context
stringlengths
2.52k
185k
gt
stringclasses
1 value
#region PDFsharp - A .NET library for processing PDF // // Authors: // Stefan Lange (mailto:Stefan.Lange@pdfsharp.com) // // Copyright (c) 2005-2009 empira Software GmbH, Cologne (Germany) // // http://www.pdfsharp.com // http://sourceforge.net/projects/pdfsharp // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion using System; using System.Diagnostics; using System.Collections.Generic; using System.Globalization; using System.ComponentModel; using System.IO; using System.Runtime.InteropServices; #if GDI using System.Drawing; using System.Drawing.Text; #endif #if WPF using System.Windows.Media; #endif using PdfSharp.Internal; using PdfSharp.Fonts.OpenType; namespace PdfSharp.Drawing { ///<summary> /// Makes fonts that are not installed on the system available within the current application domain. /// </summary> public sealed class XPrivateFontCollection : IDisposable { /// <summary> /// Initializes a new instance of the <see cref="XPrivateFontCollection"/> class. /// </summary> public XPrivateFontCollection() { //// HACK: Use one global PrivateFontCollection in GDI+ //// TODO: Make a list of it //if (s_global != null) // throw new InvalidOperationException("Because of limitations in GDI+ you can only have one instance of XPrivateFontCollection in your application."); } internal static XPrivateFontCollection s_global = new XPrivateFontCollection(); //static XPrivateFontCollection() //{ // // HACK: Use one global PrivateFontCollection in GDI+ // // TODO: Make a list of it // if (global != null) // throw new InvalidOperationException("Because of limitations in GDI+ you can only have one instance of XPrivateFontCollection in your application."); // global = this; //} //internal static XPrivateFontCollection global; /// <summary> /// Disposes all fonts from the collection. /// </summary> public void Dispose() { #if GDI //privateFonts.Clear(); this.privateFontCollection.Dispose(); this.privateFontCollection = new PrivateFontCollection(); #endif s_global = null; //GC.SuppressFinalize(this); } #if GDI internal static PrivateFontCollection GlobalPrivateFontCollection { get { return s_global != null ? s_global.privateFontCollection : null; } } #endif #if GDI //internal PrivateFontCollection PrivateFontCollection //{ // get { return privateFontCollection; } // set { privateFontCollection = value; } //} // PrivateFontCollection of GDI+ PrivateFontCollection privateFontCollection = new PrivateFontCollection(); #endif /// <summary> /// Gets the global font collection. /// </summary> public static XPrivateFontCollection Global { get { return s_global; } } /// <summary> /// Sets a new global font collection and returns the previous one, or null if no previous one exists. /// </summary> public static XPrivateFontCollection SetGlobalFontCollection(XPrivateFontCollection fontCollection) { if (fontCollection==null) throw new ArgumentNullException("fontCollection"); XPrivateFontCollection old = s_global; s_global = fontCollection; return old; } #if GDI /// <summary> /// Adds the font data to the font collections. /// </summary> public void AddFont(byte[] data, string familyName) { if (String.IsNullOrEmpty(familyName)) throw new ArgumentNullException("familyName"); //if (glyphTypeface == null) // throw new ArgumentNullException("glyphTypeface"); // Add to GDI+ PrivateFontCollection int length = data.Length; // Copy data without unsafe code IntPtr ip = Marshal.AllocCoTaskMem(length); Marshal.Copy(data, 0, ip, length); this.privateFontCollection.AddMemoryFont(ip, length); Marshal.FreeCoTaskMem(ip); //privateFonts.Add(glyphTypeface); } #endif // /// <summary> // /// Adds the glyph typeface to this collection. // /// </summary> // public void AddGlyphTypeface(XGlyphTypeface glyphTypeface) // { // if (glyphTypeface == null) // throw new ArgumentNullException("glyphTypeface"); //#if GDI // // Add to GDI+ PrivateFontCollection // byte[] data = glyphTypeface.FontData.Data; // int length = data.Length; // // Do it w/o unsafe code (do it like VB programmers do): // IntPtr ip = Marshal.AllocCoTaskMem(length); // Marshal.Copy(data, 0, ip, length); // this.privateFontCollection.AddMemoryFont(ip, length); // Marshal.FreeCoTaskMem(ip); // privateFonts.Add(glyphTypeface); //#endif // } #if GDI /// <summary> /// HACK: to be removed. /// </summary> //[Obsolete("Just make QBX compile. Will be removed when Private Fonts are working.", false)] public void AddFont(byte[] data, string fontName, bool bold, bool italic) { throw new NotImplementedException("AddFont"); //AddGlyphTypeface(new XGlyphTypeface(data)); } /// <summary> /// Adds a font from the specified file to this collection. /// </summary> public void AddFont(string filename) { throw new NotImplementedException("AddFont"); //AddGlyphTypeface(new XGlyphTypeface(filename)); } /// <summary> /// Adds a font from memory to this collection. /// </summary> public void AddFont(byte[] data) { throw new NotImplementedException("AddFont"); //AddGlyphTypeface(new XGlyphTypeface(data)); } #endif #if WPF /// <summary> /// Initializes a new instance of the FontFamily class from the specified font family name and an optional base uniform resource identifier (URI) value. /// Sample: Add(new Uri("pack://application:,,,/"), "./myFonts/#FontFamilyName");) /// </summary> /// <param name="baseUri">Specifies the base URI that is used to resolve familyName.</param> /// <param name="familyName">The family name or names that comprise the new FontFamily. Multiple family names should be separated by commas.</param> public void Add(Uri baseUri, string familyName) { // TODO: What means 'Multiple family names should be separated by commas.'? // does not work if (String.IsNullOrEmpty(familyName)) throw new ArgumentNullException("familyName"); if (familyName.Contains(",")) throw new NotImplementedException("Only one family name is supported."); // family name starts right of '#' int idxHash = familyName.IndexOf('#'); if (idxHash < 0) throw new ArgumentException("Family name must contain a '#'. Example './#MyFontFamilyName'", "familyName"); string key = familyName.Substring(idxHash + 1); if (String.IsNullOrEmpty(key)) throw new ArgumentException("familyName has invalid format."); if (this.fontFamilies.ContainsKey(key)) throw new ArgumentException("An entry with the specified family name already exists."); #if !SILVERLIGHT System.Windows.Media.FontFamily fontFamily = new System.Windows.Media.FontFamily(baseUri, familyName); #else System.Windows.Media.FontFamily fontFamily = new System.Windows.Media.FontFamily(familyName); #endif // Check whether font data realy exists #if DEBUG && !SILVERLIGHT ICollection<Typeface> list = fontFamily.GetTypefaces(); foreach (Typeface typeFace in list) { //Debug.WriteLine(String.Format("{0}, {1}, {2}, {3}", typeFace.FaceNames.Values.First(), typeFace.Style, typeFace.Weight, typeFace.Stretch)); GlyphTypeface glyphTypeface; if (!typeFace.TryGetGlyphTypeface(out glyphTypeface)) throw new ArgumentException("Font with the specified family name does not exist."); } #endif this.fontFamilies.Add(key, fontFamily); } #endif #if GDI internal static Font TryFindPrivateFont(string name, double size, FontStyle style) { try { PrivateFontCollection pfc = GlobalPrivateFontCollection; if (pfc == null) return null; foreach (System.Drawing.FontFamily family in pfc.Families) { if (String.Compare(family.Name, name, true) == 0) return new Font(family, (float)size, style, GraphicsUnit.World); } } catch { #if DEBUG #endif } return null; } #endif #if WPF internal static Typeface TryFindTypeface(string name, XFontStyle style, out System.Windows.Media.FontFamily fontFamily) { if (s_global.fontFamilies.TryGetValue(name, out fontFamily)) { Typeface typeface = FontHelper.CreateTypeface(fontFamily, style); return typeface; } return null; } #endif #if GDI___ internal XGlyphTypeface FindFont(string fontName, bool bold, bool italic) { //if (privateFonts != null) { for (int i = 0; i < 3; ++i) { // We make 4 passes. // On second pass, we ignore Italic. // On third pass, we ignore Bold. // On fourth pass, we ignore Bold and Italic foreach (XGlyphTypeface pf in privateFonts) { if (string.Compare(pf.FamilyName, fontName, StringComparison.InvariantCultureIgnoreCase) == 0) { switch (i) { case 0: if (pf.IsBold == bold && pf.IsItalic == italic) return pf; break; case 1: if (pf.IsBold == bold /*&& pf.Italic == italic*/) return pf; break; case 2: if (/*pf.Bold == bold &&*/ pf.IsItalic == italic) return pf; break; case 3: //if (pf.Bold == bold && pf.Italic == italic) return pf; } } } } } return null; } #endif #if GDI //List<XGlyphTypeface> privateFonts = new List<XGlyphTypeface>(); #endif #if WPF readonly Dictionary<string, System.Windows.Media.FontFamily> fontFamilies = new Dictionary<string, System.Windows.Media.FontFamily>(StringComparer.InvariantCultureIgnoreCase); #endif } }
namespace android.media { [global::MonoJavaBridge.JavaClass()] public partial class ToneGenerator : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static ToneGenerator() { InitJNI(); } protected ToneGenerator(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _finalize5117; protected override void finalize() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.media.ToneGenerator._finalize5117); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.ToneGenerator.staticClass, global::android.media.ToneGenerator._finalize5117); } internal static global::MonoJavaBridge.MethodId _release5118; public virtual void release() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.media.ToneGenerator._release5118); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.ToneGenerator.staticClass, global::android.media.ToneGenerator._release5118); } internal static global::MonoJavaBridge.MethodId _startTone5119; public virtual bool startTone(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.media.ToneGenerator._startTone5119, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.media.ToneGenerator.staticClass, global::android.media.ToneGenerator._startTone5119, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _startTone5120; public virtual bool startTone(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.media.ToneGenerator._startTone5120, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.media.ToneGenerator.staticClass, global::android.media.ToneGenerator._startTone5120, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _stopTone5121; public virtual void stopTone() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.media.ToneGenerator._stopTone5121); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.ToneGenerator.staticClass, global::android.media.ToneGenerator._stopTone5121); } internal static global::MonoJavaBridge.MethodId _ToneGenerator5122; public ToneGenerator(int arg0, int arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.media.ToneGenerator.staticClass, global::android.media.ToneGenerator._ToneGenerator5122, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } public static int TONE_DTMF_0 { get { return 0; } } public static int TONE_DTMF_1 { get { return 1; } } public static int TONE_DTMF_2 { get { return 2; } } public static int TONE_DTMF_3 { get { return 3; } } public static int TONE_DTMF_4 { get { return 4; } } public static int TONE_DTMF_5 { get { return 5; } } public static int TONE_DTMF_6 { get { return 6; } } public static int TONE_DTMF_7 { get { return 7; } } public static int TONE_DTMF_8 { get { return 8; } } public static int TONE_DTMF_9 { get { return 9; } } public static int TONE_DTMF_S { get { return 10; } } public static int TONE_DTMF_P { get { return 11; } } public static int TONE_DTMF_A { get { return 12; } } public static int TONE_DTMF_B { get { return 13; } } public static int TONE_DTMF_C { get { return 14; } } public static int TONE_DTMF_D { get { return 15; } } public static int TONE_SUP_DIAL { get { return 16; } } public static int TONE_SUP_BUSY { get { return 17; } } public static int TONE_SUP_CONGESTION { get { return 18; } } public static int TONE_SUP_RADIO_ACK { get { return 19; } } public static int TONE_SUP_RADIO_NOTAVAIL { get { return 20; } } public static int TONE_SUP_ERROR { get { return 21; } } public static int TONE_SUP_CALL_WAITING { get { return 22; } } public static int TONE_SUP_RINGTONE { get { return 23; } } public static int TONE_PROP_BEEP { get { return 24; } } public static int TONE_PROP_ACK { get { return 25; } } public static int TONE_PROP_NACK { get { return 26; } } public static int TONE_PROP_PROMPT { get { return 27; } } public static int TONE_PROP_BEEP2 { get { return 28; } } public static int TONE_SUP_INTERCEPT { get { return 29; } } public static int TONE_SUP_INTERCEPT_ABBREV { get { return 30; } } public static int TONE_SUP_CONGESTION_ABBREV { get { return 31; } } public static int TONE_SUP_CONFIRM { get { return 32; } } public static int TONE_SUP_PIP { get { return 33; } } public static int TONE_CDMA_DIAL_TONE_LITE { get { return 34; } } public static int TONE_CDMA_NETWORK_USA_RINGBACK { get { return 35; } } public static int TONE_CDMA_INTERCEPT { get { return 36; } } public static int TONE_CDMA_ABBR_INTERCEPT { get { return 37; } } public static int TONE_CDMA_REORDER { get { return 38; } } public static int TONE_CDMA_ABBR_REORDER { get { return 39; } } public static int TONE_CDMA_NETWORK_BUSY { get { return 40; } } public static int TONE_CDMA_CONFIRM { get { return 41; } } public static int TONE_CDMA_ANSWER { get { return 42; } } public static int TONE_CDMA_NETWORK_CALLWAITING { get { return 43; } } public static int TONE_CDMA_PIP { get { return 44; } } public static int TONE_CDMA_CALL_SIGNAL_ISDN_NORMAL { get { return 45; } } public static int TONE_CDMA_CALL_SIGNAL_ISDN_INTERGROUP { get { return 46; } } public static int TONE_CDMA_CALL_SIGNAL_ISDN_SP_PRI { get { return 47; } } public static int TONE_CDMA_CALL_SIGNAL_ISDN_PAT3 { get { return 48; } } public static int TONE_CDMA_CALL_SIGNAL_ISDN_PING_RING { get { return 49; } } public static int TONE_CDMA_CALL_SIGNAL_ISDN_PAT5 { get { return 50; } } public static int TONE_CDMA_CALL_SIGNAL_ISDN_PAT6 { get { return 51; } } public static int TONE_CDMA_CALL_SIGNAL_ISDN_PAT7 { get { return 52; } } public static int TONE_CDMA_HIGH_L { get { return 53; } } public static int TONE_CDMA_MED_L { get { return 54; } } public static int TONE_CDMA_LOW_L { get { return 55; } } public static int TONE_CDMA_HIGH_SS { get { return 56; } } public static int TONE_CDMA_MED_SS { get { return 57; } } public static int TONE_CDMA_LOW_SS { get { return 58; } } public static int TONE_CDMA_HIGH_SSL { get { return 59; } } public static int TONE_CDMA_MED_SSL { get { return 60; } } public static int TONE_CDMA_LOW_SSL { get { return 61; } } public static int TONE_CDMA_HIGH_SS_2 { get { return 62; } } public static int TONE_CDMA_MED_SS_2 { get { return 63; } } public static int TONE_CDMA_LOW_SS_2 { get { return 64; } } public static int TONE_CDMA_HIGH_SLS { get { return 65; } } public static int TONE_CDMA_MED_SLS { get { return 66; } } public static int TONE_CDMA_LOW_SLS { get { return 67; } } public static int TONE_CDMA_HIGH_S_X4 { get { return 68; } } public static int TONE_CDMA_MED_S_X4 { get { return 69; } } public static int TONE_CDMA_LOW_S_X4 { get { return 70; } } public static int TONE_CDMA_HIGH_PBX_L { get { return 71; } } public static int TONE_CDMA_MED_PBX_L { get { return 72; } } public static int TONE_CDMA_LOW_PBX_L { get { return 73; } } public static int TONE_CDMA_HIGH_PBX_SS { get { return 74; } } public static int TONE_CDMA_MED_PBX_SS { get { return 75; } } public static int TONE_CDMA_LOW_PBX_SS { get { return 76; } } public static int TONE_CDMA_HIGH_PBX_SSL { get { return 77; } } public static int TONE_CDMA_MED_PBX_SSL { get { return 78; } } public static int TONE_CDMA_LOW_PBX_SSL { get { return 79; } } public static int TONE_CDMA_HIGH_PBX_SLS { get { return 80; } } public static int TONE_CDMA_MED_PBX_SLS { get { return 81; } } public static int TONE_CDMA_LOW_PBX_SLS { get { return 82; } } public static int TONE_CDMA_HIGH_PBX_S_X4 { get { return 83; } } public static int TONE_CDMA_MED_PBX_S_X4 { get { return 84; } } public static int TONE_CDMA_LOW_PBX_S_X4 { get { return 85; } } public static int TONE_CDMA_ALERT_NETWORK_LITE { get { return 86; } } public static int TONE_CDMA_ALERT_AUTOREDIAL_LITE { get { return 87; } } public static int TONE_CDMA_ONE_MIN_BEEP { get { return 88; } } public static int TONE_CDMA_KEYPAD_VOLUME_KEY_LITE { get { return 89; } } public static int TONE_CDMA_PRESSHOLDKEY_LITE { get { return 90; } } public static int TONE_CDMA_ALERT_INCALL_LITE { get { return 91; } } public static int TONE_CDMA_EMERGENCY_RINGBACK { get { return 92; } } public static int TONE_CDMA_ALERT_CALL_GUARD { get { return 93; } } public static int TONE_CDMA_SOFT_ERROR_LITE { get { return 94; } } public static int TONE_CDMA_CALLDROP_LITE { get { return 95; } } public static int TONE_CDMA_NETWORK_BUSY_ONE_SHOT { get { return 96; } } public static int TONE_CDMA_ABBR_ALERT { get { return 97; } } public static int TONE_CDMA_SIGNAL_OFF { get { return 98; } } public static int MAX_VOLUME { get { return 100; } } public static int MIN_VOLUME { get { return 0; } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.media.ToneGenerator.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/media/ToneGenerator")); global::android.media.ToneGenerator._finalize5117 = @__env.GetMethodIDNoThrow(global::android.media.ToneGenerator.staticClass, "finalize", "()V"); global::android.media.ToneGenerator._release5118 = @__env.GetMethodIDNoThrow(global::android.media.ToneGenerator.staticClass, "release", "()V"); global::android.media.ToneGenerator._startTone5119 = @__env.GetMethodIDNoThrow(global::android.media.ToneGenerator.staticClass, "startTone", "(I)Z"); global::android.media.ToneGenerator._startTone5120 = @__env.GetMethodIDNoThrow(global::android.media.ToneGenerator.staticClass, "startTone", "(II)Z"); global::android.media.ToneGenerator._stopTone5121 = @__env.GetMethodIDNoThrow(global::android.media.ToneGenerator.staticClass, "stopTone", "()V"); global::android.media.ToneGenerator._ToneGenerator5122 = @__env.GetMethodIDNoThrow(global::android.media.ToneGenerator.staticClass, "<init>", "(II)V"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; using System.Web.Http.Description; using System.Web.Http.Filters; using Swashbuckle.Application; using Swashbuckle.Swagger; using WebActivatorEx; using SignInCheckIn; [assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")] namespace SignInCheckIn { public class SwaggerConfig { public static void Register() { var thisAssembly = typeof(SwaggerConfig).Assembly; GlobalConfiguration.Configuration .EnableSwagger(c => { // By default, the service root url is inferred from the request used to access the docs. // However, there may be situations (e.g. proxy and load-balanced environments) where this does not // resolve correctly. You can workaround this by providing your own code to determine the root URL. // //c.RootUrl(req => GetRootUrlFromAppConfig()); // If schemes are not explicitly provided in a Swagger 2.0 document, then the scheme used to access // the docs is taken as the default. If your API supports multiple schemes and you want to be explicit // about them, you can use the "Schemes" option as shown below. // //c.Schemes(new[] { "http", "https" }); // Use "SingleApiVersion" to describe a single version API. Swagger 2.0 includes an "Info" object to // hold additional metadata for an API. Version and title are required but you can also provide // additional fields by chaining methods off SingleApiVersion. // c.SingleApiVersion("v1", "SignInCheckIn"); // If your API has multiple versions, use "MultipleApiVersions" instead of "SingleApiVersion". // In this case, you must provide a lambda that tells Swashbuckle which actions should be // included in the docs for a given API version. Like "SingleApiVersion", each call to "Version" // returns an "Info" builder so you can provide additional metadata per API version. // //c.MultipleApiVersions( // (apiDesc, targetApiVersion) => ResolveVersionSupportByRouteConstraint(apiDesc, targetApiVersion), // (vc) => // { // vc.Version("v2", "Swashbuckle Dummy API V2"); // vc.Version("v1", "Swashbuckle Dummy API V1"); // }); // You can use "BasicAuth", "ApiKey" or "OAuth2" options to describe security schemes for the API. // See https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md for more details. // NOTE: These only define the schemes and need to be coupled with a corresponding "security" property // at the document or operation level to indicate which schemes are required for an operation. To do this, // you'll need to implement a custom IDocumentFilter and/or IOperationFilter to set these properties // according to your specific authorization implementation // //c.BasicAuth("basic") // .Description("Basic HTTP Authentication"); // //c.ApiKey("apiKey") // .Description("API Key Authentication") // .Name("userToken") // .In("header"); // //c.OAuth2("oauth2") // .Description("OAuth2 Implicit Grant") // .Flow("implicit") // .AuthorizationUrl("http://petstore.swagger.wordnik.com/api/oauth/dialog") // //.TokenUrl("https://tempuri.org/token") // .Scopes(scopes => // { // scopes.Add("read", "Read access to protected resources"); // scopes.Add("write", "Write access to protected resources"); // }); c.OperationFilter<AuthorizationHeaderFilter>(); c.OperationFilter<ClientApiKeyFilter>(); c.OperationFilter<SiteConfigFilter>(); // Set this flag to omit descriptions for any actions decorated with the Obsolete attribute //c.IgnoreObsoleteActions(); // Each operation be assigned one or more tags which are then used by consumers for various reasons. // For example, the swagger-ui groups operations according to the first tag of each operation. // By default, this will be controller name but you can use the "GroupActionsBy" option to // override with any value. // //c.GroupActionsBy(apiDesc => apiDesc.HttpMethod.ToString()); // You can also specify a custom sort order for groups (as defined by "GroupActionsBy") to dictate // the order in which operations are listed. For example, if the default grouping is in place // (controller name) and you specify a descending alphabetic sort order, then actions from a // ProductsController will be listed before those from a CustomersController. This is typically // used to customize the order of groupings in the swagger-ui. // //c.OrderActionGroupsBy(new DescendingAlphabeticComparer()); // Swashbuckle makes a best attempt at generating Swagger compliant JSON schemas for the various types // exposed in your API. However, there may be occasions when more control of the output is needed. // This is supported through the "MapType" and "SchemaFilter" options: // // Use the "MapType" option to override the Schema generation for a specific type. // It should be noted that the resulting Schema will be placed "inline" for any applicable Operations. // While Swagger 2.0 supports inline definitions for "all" Schema types, the swagger-ui tool does not. // It expects "complex" Schemas to be defined separately and referenced. For this reason, you should only // use the "MapType" option when the resulting Schema is a primitive or array type. If you need to alter a // complex Schema, use a Schema filter. // //c.MapType<ProductType>(() => new Schema { type = "integer", format = "int32" }); // // If you want to post-modify "complex" Schemas once they've been generated, across the board or for a // specific type, you can wire up one or more Schema filters. // //c.SchemaFilter<ApplySchemaVendorExtensions>(); // Set this flag to omit schema property descriptions for any type properties decorated with the // Obsolete attribute //c.IgnoreObsoleteProperties(); // In a Swagger 2.0 document, complex types are typically declared globally and referenced by unique // Schema Id. By default, Swashbuckle does NOT use the full type name in Schema Ids. In most cases, this // works well because it prevents the "implementation detail" of type namespaces from leaking into your // Swagger docs and UI. However, if you have multiple types in your API with the same class name, you'll // need to opt out of this behavior to avoid Schema Id conflicts. // //c.UseFullTypeNameInSchemaIds(); // In accordance with the built in JsonSerializer, Swashbuckle will, by default, describe enums as integers. // You can change the serializer behavior by configuring the StringToEnumConverter globally or for a given // enum type. Swashbuckle will honor this change out-of-the-box. However, if you use a different // approach to serialize enums as strings, you can also force Swashbuckle to describe them as strings. // //c.DescribeAllEnumsAsStrings(); // Similar to Schema filters, Swashbuckle also supports Operation and Document filters: // // Post-modify Operation descriptions once they've been generated by wiring up one or more // Operation filters. // //c.OperationFilter<AddDefaultResponse>(); // // If you've defined an OAuth2 flow as described above, you could use a custom filter // to inspect some attribute on each action and infer which (if any) OAuth2 scopes are required // to execute the operation // //c.OperationFilter<AssignOAuth2SecurityRequirements>(); // Post-modify the entire Swagger document by wiring up one or more Document filters. // This gives full control to modify the final SwaggerDocument. You should have a good understanding of // the Swagger 2.0 spec. - https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md // before using this option. // //c.DocumentFilter<ApplyDocumentVendorExtensions>(); // If you annonate Controllers and API Types with // Xml comments (http://msdn.microsoft.com/en-us/library/b2s063f7(v=vs.110).aspx), you can incorporate // those comments into the generated docs and UI. You can enable this by providing the path to one or // more Xml comment files. // c.IncludeXmlComments(GetXmlCommentsPath()); // In contrast to WebApi, Swagger 2.0 does not include the query string component when mapping a URL // to an action. As a result, Swashbuckle will raise an exception if it encounters multiple actions // with the same path (sans query string) and HTTP method. You can workaround this by providing a // custom strategy to pick a winner or merge the descriptions for the purposes of the Swagger docs // //c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First()); }) .EnableSwaggerUi(c => { // Use the "InjectStylesheet" option to enrich the UI with one or more additional CSS stylesheets. // The file must be included in your project as an "Embedded Resource", and then the resource's // "Logical Name" is passed to the method as shown below. // //c.InjectStylesheet(containingAssembly, "Swashbuckle.Dummy.SwaggerExtensions.testStyles1.css"); // Use the "InjectJavaScript" option to invoke one or more custom JavaScripts after the swagger-ui // has loaded. The file must be included in your project as an "Embedded Resource", and then the resource's // "Logical Name" is passed to the method as shown above. // //c.InjectJavaScript(thisAssembly, "Swashbuckle.Dummy.SwaggerExtensions.testScript1.js"); // The swagger-ui renders boolean data types as a dropdown. By default, it provides "true" and "false" // strings as the possible choices. You can use this option to change these to something else, // for example 0 and 1. // //c.BooleanValues(new[] { "0", "1" }); // By default, swagger-ui will validate specs against swagger.io's online validator and display the result // in a badge at the bottom of the page. Use these options to set a different validator URL or to disable the // feature entirely. //c.SetValidatorUrl("http://localhost/validator"); //c.DisableValidator(); // Use this option to control how the Operation listing is displayed. // It can be set to "None" (default), "List" (shows operations for each resource), // or "Full" (fully expanded: shows operations and their details). // c.DocExpansion(DocExpansion.None); // Use the CustomAsset option to provide your own version of assets used in the swagger-ui. // It's typically used to instruct Swashbuckle to return your version instead of the default // when a request is made for "index.html". As with all custom content, the file must be included // in your project as an "Embedded Resource", and then the resource's "Logical Name" is passed to // the method as shown below. // //c.CustomAsset("index", containingAssembly, "YourWebApiProject.SwaggerExtensions.index.html"); // If your API has multiple versions and you've applied the MultipleApiVersions setting // as described above, you can also enable a select box in the swagger-ui, that displays // a discovery URL for each version. This provides a convenient way for users to browse documentation // for different API versions. // //c.EnableDiscoveryUrlSelector(); // If your API supports the OAuth2 Implicit flow, and you've described it correctly, according to // the Swagger 2.0 specification, you can enable UI support as shown below. // //c.EnableOAuth2Support("test-client-id", "test-realm", "Swagger UI"); }); } protected static string GetXmlCommentsPath() { return $@"{AppDomain.CurrentDomain.BaseDirectory}\bin\SignInCheckIn.xml"; } } public class RequiresAuthorization : ActionFilterAttribute { } public class AuthorizationHeaderFilter : IOperationFilter { public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription) { var filterPipeline = apiDescription.ActionDescriptor.GetFilterPipeline(); var isAuthorized = filterPipeline.Select(filterInfo => filterInfo.Instance).Any(filter => filter is RequiresAuthorization); var allowAnonymous = apiDescription.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any(); if (isAuthorized && !allowAnonymous) { // Setup parameters if the endpoint doesn't have any. This prevents // a null pointer exception when adding the new authorization parameter. if (operation.parameters == null) { operation.parameters = new List<Parameter>(); } operation.parameters.Add(new Parameter { name = "Authorization", @in = "header", description = "access token", required = true, type = "string" }); } } } public class ClientApiKeyFilter : IOperationFilter { public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription) { // Setup parameters if the endpoint doesn't have any. This prevents // a null pointer exception when adding the new authorization parameter. if (operation.parameters == null) { operation.parameters = new List<Parameter>(); } operation.parameters.Add(new Parameter { name = "Crds-Api-Key", @in = "header", description = "Domain-Locked Client API Key", required = false, type = "string" }); } } public class SiteConfigFilter : IOperationFilter { public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription) { // Setup parameters if the endpoint doesn't have any. This prevents // a null pointer exception when adding the new authorization parameter. if (operation.parameters == null) { operation.parameters = new List<Parameter>(); } // TODO - Would be nice to default these to the values from the machine_config_details cookie on the client (if one exists). // I think this would require a customized Swagger index.html. operation.parameters.Add(new Parameter { name = "Crds-Site-Id", @in = "header", description = "The site (congregation) ID", required = false, type = "string" }); operation.parameters.Add(new Parameter { name = "Crds-Kiosk-Identifier", @in = "header", description = "The Kiosk Configuration ID", required = false, type = "string" }); } } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion // SSCLI 1.0 has no support for ADO.NET #if !SSCLI using System; using System.Collections; using System.Configuration; using System.Data; using System.IO; using Ctrip.Log4.Util; using Ctrip.Log4.Layout; using Ctrip.Log4.Core; namespace Ctrip.Log4.Appender { /// <summary> /// Appender that logs to a database. /// </summary> /// <remarks> /// <para> /// <see cref="AdoNetAppender"/> appends logging events to a table within a /// database. The appender can be configured to specify the connection /// string by setting the <see cref="ConnectionString"/> property. /// The connection type (provider) can be specified by setting the <see cref="ConnectionType"/> /// property. For more information on database connection strings for /// your specific database see <a href="http://www.connectionstrings.com/">http://www.connectionstrings.com/</a>. /// </para> /// <para> /// Records are written into the database either using a prepared /// statement or a stored procedure. The <see cref="CommandType"/> property /// is set to <see cref="System.Data.CommandType.Text"/> (<c>System.Data.CommandType.Text</c>) to specify a prepared statement /// or to <see cref="System.Data.CommandType.StoredProcedure"/> (<c>System.Data.CommandType.StoredProcedure</c>) to specify a stored /// procedure. /// </para> /// <para> /// The prepared statement text or the name of the stored procedure /// must be set in the <see cref="CommandText"/> property. /// </para> /// <para> /// The prepared statement or stored procedure can take a number /// of parameters. Parameters are added using the <see cref="AddParameter"/> /// method. This adds a single <see cref="AdoNetAppenderParameter"/> to the /// ordered list of parameters. The <see cref="AdoNetAppenderParameter"/> /// type may be subclassed if required to provide database specific /// functionality. The <see cref="AdoNetAppenderParameter"/> specifies /// the parameter name, database type, size, and how the value should /// be generated using a <see cref="ILayout"/>. /// </para> /// </remarks> /// <example> /// An example of a SQL Server table that could be logged to: /// <code lang="SQL"> /// CREATE TABLE [dbo].[Log] ( /// [ID] [int] IDENTITY (1, 1) NOT NULL , /// [Date] [datetime] NOT NULL , /// [Thread] [varchar] (255) NOT NULL , /// [Level] [varchar] (20) NOT NULL , /// [Logger] [varchar] (255) NOT NULL , /// [Message] [varchar] (4000) NOT NULL /// ) ON [PRIMARY] /// </code> /// </example> /// <example> /// An example configuration to log to the above table: /// <code lang="XML" escaped="true"> /// <appender name="AdoNetAppender_SqlServer" type="Ctrip.Log4.Appender.AdoNetAppender" > /// <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> /// <connectionString value="data source=SQLSVR;initial catalog=test_log4net;integrated security=false;persist security info=True;User ID=sa;Password=sa" /> /// <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message]) VALUES (@log_date, @thread, @log_level, @logger, @message)" /> /// <parameter> /// <parameterName value="@log_date" /> /// <dbType value="DateTime" /> /// <layout type="Ctrip.Log4.Layout.PatternLayout" value="%date{yyyy'-'MM'-'dd HH':'mm':'ss'.'fff}" /> /// </parameter> /// <parameter> /// <parameterName value="@thread" /> /// <dbType value="String" /> /// <size value="255" /> /// <layout type="Ctrip.Log4.Layout.PatternLayout" value="%thread" /> /// </parameter> /// <parameter> /// <parameterName value="@log_level" /> /// <dbType value="String" /> /// <size value="50" /> /// <layout type="Ctrip.Log4.Layout.PatternLayout" value="%level" /> /// </parameter> /// <parameter> /// <parameterName value="@logger" /> /// <dbType value="String" /> /// <size value="255" /> /// <layout type="Ctrip.Log4.Layout.PatternLayout" value="%logger" /> /// </parameter> /// <parameter> /// <parameterName value="@message" /> /// <dbType value="String" /> /// <size value="4000" /> /// <layout type="Ctrip.Log4.Layout.PatternLayout" value="%message" /> /// </parameter> /// </appender> /// </code> /// </example> /// <author>Julian Biddle</author> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> /// <author>Lance Nehring</author> public class AdoNetAppender : BufferingAppenderSkeleton { #region Public Instance Constructors /// <summary> /// Initializes a new instance of the <see cref="AdoNetAppender" /> class. /// </summary> /// <remarks> /// Public default constructor to initialize a new instance of this class. /// </remarks> public AdoNetAppender() { m_connectionType = "System.Data.OleDb.OleDbConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; m_useTransactions = true; m_commandType = System.Data.CommandType.Text; m_parameters = new ArrayList(); m_reconnectOnError = false; } #endregion // Public Instance Constructors #region Public Instance Properties /// <summary> /// Gets or sets the database connection string that is used to connect to /// the database. /// </summary> /// <value> /// The database connection string used to connect to the database. /// </value> /// <remarks> /// <para> /// The connections string is specific to the connection type. /// See <see cref="ConnectionType"/> for more information. /// </para> /// </remarks> /// <example>Connection string for MS Access via ODBC: /// <code>"DSN=MS Access Database;UID=admin;PWD=;SystemDB=C:\data\System.mdw;SafeTransactions = 0;FIL=MS Access;DriverID = 25;DBQ=C:\data\train33.mdb"</code> /// </example> /// <example>Another connection string for MS Access via ODBC: /// <code>"Driver={Microsoft Access Driver (*.mdb)};DBQ=C:\Work\cvs_root\Ctrip-1.2\access.mdb;UID=;PWD=;"</code> /// </example> /// <example>Connection string for MS Access via OLE DB: /// <code>"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Work\cvs_root\Ctrip-1.2\access.mdb;User Id=;Password=;"</code> /// </example> public string ConnectionString { get { return m_connectionString; } set { m_connectionString = value; } } /// <summary> /// The appSettings key from App.Config that contains the connection string. /// </summary> public string AppSettingsKey { get { return m_appSettingsKey; } set { m_appSettingsKey = value; } } #if NET_2_0 /// <summary> /// The connectionStrings key from App.Config that contains the connection string. /// </summary> /// <remarks> /// This property requires at least .NET 2.0. /// </remarks> public string ConnectionStringName { get { return m_connectionStringName; } set { m_connectionStringName = value; } } #endif /// <summary> /// Gets or sets the type name of the <see cref="IDbConnection"/> connection /// that should be created. /// </summary> /// <value> /// The type name of the <see cref="IDbConnection"/> connection. /// </value> /// <remarks> /// <para> /// The type name of the ADO.NET provider to use. /// </para> /// <para> /// The default is to use the OLE DB provider. /// </para> /// </remarks> /// <example>Use the OLE DB Provider. This is the default value. /// <code>System.Data.OleDb.OleDbConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</code> /// </example> /// <example>Use the MS SQL Server Provider. /// <code>System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</code> /// </example> /// <example>Use the ODBC Provider. /// <code>Microsoft.Data.Odbc.OdbcConnection,Microsoft.Data.Odbc,version=1.0.3300.0,publicKeyToken=b77a5c561934e089,culture=neutral</code> /// This is an optional package that you can download from /// <a href="http://msdn.microsoft.com/downloads">http://msdn.microsoft.com/downloads</a> /// search for <b>ODBC .NET Data Provider</b>. /// </example> /// <example>Use the Oracle Provider. /// <code>System.Data.OracleClient.OracleConnection, System.Data.OracleClient, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</code> /// This is an optional package that you can download from /// <a href="http://msdn.microsoft.com/downloads">http://msdn.microsoft.com/downloads</a> /// search for <b>.NET Managed Provider for Oracle</b>. /// </example> public string ConnectionType { get { return m_connectionType; } set { m_connectionType = value; } } /// <summary> /// Gets or sets the command text that is used to insert logging events /// into the database. /// </summary> /// <value> /// The command text used to insert logging events into the database. /// </value> /// <remarks> /// <para> /// Either the text of the prepared statement or the /// name of the stored procedure to execute to write into /// the database. /// </para> /// <para> /// The <see cref="CommandType"/> property determines if /// this text is a prepared statement or a stored procedure. /// </para> /// </remarks> public string CommandText { get { return m_commandText; } set { m_commandText = value; } } /// <summary> /// Gets or sets the command type to execute. /// </summary> /// <value> /// The command type to execute. /// </value> /// <remarks> /// <para> /// This value may be either <see cref="System.Data.CommandType.Text"/> (<c>System.Data.CommandType.Text</c>) to specify /// that the <see cref="CommandText"/> is a prepared statement to execute, /// or <see cref="System.Data.CommandType.StoredProcedure"/> (<c>System.Data.CommandType.StoredProcedure</c>) to specify that the /// <see cref="CommandText"/> property is the name of a stored procedure /// to execute. /// </para> /// <para> /// The default value is <see cref="System.Data.CommandType.Text"/> (<c>System.Data.CommandType.Text</c>). /// </para> /// </remarks> public CommandType CommandType { get { return m_commandType; } set { m_commandType = value; } } /// <summary> /// Should transactions be used to insert logging events in the database. /// </summary> /// <value> /// <c>true</c> if transactions should be used to insert logging events in /// the database, otherwise <c>false</c>. The default value is <c>true</c>. /// </value> /// <remarks> /// <para> /// Gets or sets a value that indicates whether transactions should be used /// to insert logging events in the database. /// </para> /// <para> /// When set a single transaction will be used to insert the buffered events /// into the database. Otherwise each event will be inserted without using /// an explicit transaction. /// </para> /// </remarks> public bool UseTransactions { get { return m_useTransactions; } set { m_useTransactions = value; } } /// <summary> /// Gets or sets the <see cref="SecurityContext"/> used to call the NetSend method. /// </summary> /// <value> /// The <see cref="SecurityContext"/> used to call the NetSend method. /// </value> /// <remarks> /// <para> /// Unless a <see cref="SecurityContext"/> specified here for this appender /// the <see cref="SecurityContextProvider.DefaultProvider"/> is queried for the /// security context to use. The default behavior is to use the security context /// of the current thread. /// </para> /// </remarks> public SecurityContext SecurityContext { get { return m_securityContext; } set { m_securityContext = value; } } /// <summary> /// Should this appender try to reconnect to the database on error. /// </summary> /// <value> /// <c>true</c> if the appender should try to reconnect to the database after an /// error has occurred, otherwise <c>false</c>. The default value is <c>false</c>, /// i.e. not to try to reconnect. /// </value> /// <remarks> /// <para> /// The default behaviour is for the appender not to try to reconnect to the /// database if an error occurs. Subsequent logging events are discarded. /// </para> /// <para> /// To force the appender to attempt to reconnect to the database set this /// property to <c>true</c>. /// </para> /// <note> /// When the appender attempts to connect to the database there may be a /// delay of up to the connection timeout specified in the connection string. /// This delay will block the calling application's thread. /// Until the connection can be reestablished this potential delay may occur multiple times. /// </note> /// </remarks> public bool ReconnectOnError { get { return m_reconnectOnError; } set { m_reconnectOnError = value; } } #endregion // Public Instance Properties #region Protected Instance Properties /// <summary> /// Gets or sets the underlying <see cref="IDbConnection" />. /// </summary> /// <value> /// The underlying <see cref="IDbConnection" />. /// </value> /// <remarks> /// <see cref="AdoNetAppender" /> creates a <see cref="IDbConnection" /> to insert /// logging events into a database. Classes deriving from <see cref="AdoNetAppender" /> /// can use this property to get or set this <see cref="IDbConnection" />. Use the /// underlying <see cref="IDbConnection" /> returned from <see cref="Connection" /> if /// you require access beyond that which <see cref="AdoNetAppender" /> provides. /// </remarks> protected IDbConnection Connection { get { return m_dbConnection; } set { m_dbConnection = value; } } #endregion // Protected Instance Properties #region Implementation of IOptionHandler /// <summary> /// Initialize the appender based on the options set /// </summary> /// <remarks> /// <para> /// This is part of the <see cref="IOptionHandler"/> delayed object /// activation scheme. The <see cref="ActivateOptions"/> method must /// be called on this object after the configuration properties have /// been set. Until <see cref="ActivateOptions"/> is called this /// object is in an undefined state and must not be used. /// </para> /// <para> /// If any of the configuration properties are modified then /// <see cref="ActivateOptions"/> must be called again. /// </para> /// </remarks> override public void ActivateOptions() { base.ActivateOptions(); // Are we using a command object m_usePreparedCommand = (m_commandText != null && m_commandText.Length > 0); if (m_securityContext == null) { m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this); } InitializeDatabaseConnection(); InitializeDatabaseCommand(); } #endregion #region Override implementation of AppenderSkeleton /// <summary> /// Override the parent method to close the database /// </summary> /// <remarks> /// <para> /// Closes the database command and database connection. /// </para> /// </remarks> override protected void OnClose() { base.OnClose(); DisposeCommand(false); DiposeConnection(); } #endregion #region Override implementation of BufferingAppenderSkeleton /// <summary> /// Inserts the events into the database. /// </summary> /// <param name="events">The events to insert into the database.</param> /// <remarks> /// <para> /// Insert all the events specified in the <paramref name="events"/> /// array into the database. /// </para> /// </remarks> override protected void SendBuffer(LoggingEvent[] events) { if (m_reconnectOnError && (m_dbConnection == null || m_dbConnection.State != ConnectionState.Open)) { LogLog.Debug(declaringType, "Attempting to reconnect to database. Current Connection State: " + ((m_dbConnection==null)?SystemInfo.NullText:m_dbConnection.State.ToString()) ); InitializeDatabaseConnection(); InitializeDatabaseCommand(); } // Check that the connection exists and is open if (m_dbConnection != null && m_dbConnection.State == ConnectionState.Open) { if (m_useTransactions) { // Create transaction // NJC - Do this on 2 lines because it can confuse the debugger IDbTransaction dbTran = null; try { dbTran = m_dbConnection.BeginTransaction(); SendBuffer(dbTran, events); // commit transaction dbTran.Commit(); } catch(Exception ex) { // rollback the transaction if (dbTran != null) { try { dbTran.Rollback(); } catch(Exception) { // Ignore exception } } // Can't insert into the database. That's a bad thing ErrorHandler.Error("Exception while writing to database", ex); } } else { // Send without transaction SendBuffer(null, events); } } } #endregion // Override implementation of BufferingAppenderSkeleton #region Public Instance Methods /// <summary> /// Adds a parameter to the command. /// </summary> /// <param name="parameter">The parameter to add to the command.</param> /// <remarks> /// <para> /// Adds a parameter to the ordered list of command parameters. /// </para> /// </remarks> public void AddParameter(AdoNetAppenderParameter parameter) { m_parameters.Add(parameter); } #endregion // Public Instance Methods #region Protected Instance Methods /// <summary> /// Writes the events to the database using the transaction specified. /// </summary> /// <param name="dbTran">The transaction that the events will be executed under.</param> /// <param name="events">The array of events to insert into the database.</param> /// <remarks> /// <para> /// The transaction argument can be <c>null</c> if the appender has been /// configured not to use transactions. See <see cref="UseTransactions"/> /// property for more information. /// </para> /// </remarks> virtual protected void SendBuffer(IDbTransaction dbTran, LoggingEvent[] events) { if (m_usePreparedCommand) { // Send buffer using the prepared command object if (m_dbCommand != null) { if (dbTran != null) { m_dbCommand.Transaction = dbTran; } // run for all events foreach(LoggingEvent e in events) { // Set the parameter values foreach(AdoNetAppenderParameter param in m_parameters) { param.FormatValue(m_dbCommand, e); } // Execute the query m_dbCommand.ExecuteNonQuery(); } } } else { // create a new command using(IDbCommand dbCmd = m_dbConnection.CreateCommand()) { if (dbTran != null) { dbCmd.Transaction = dbTran; } // run for all events foreach(LoggingEvent e in events) { // Get the command text from the Layout string logStatement = GetLogStatement(e); LogLog.Debug(declaringType, "LogStatement ["+logStatement+"]"); dbCmd.CommandText = logStatement; dbCmd.ExecuteNonQuery(); } } } } /// <summary> /// Formats the log message into database statement text. /// </summary> /// <param name="logEvent">The event being logged.</param> /// <remarks> /// This method can be overridden by subclasses to provide /// more control over the format of the database statement. /// </remarks> /// <returns> /// Text that can be passed to a <see cref="System.Data.IDbCommand"/>. /// </returns> virtual protected string GetLogStatement(LoggingEvent logEvent) { if (Layout == null) { ErrorHandler.Error("AdoNetAppender: No Layout specified."); return ""; } else { StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); Layout.Format(writer, logEvent); return writer.ToString(); } } /// <summary> /// Creates an <see cref="IDbConnection"/> instance used to connect to the database. /// </summary> /// <remarks> /// This method is called whenever a new IDbConnection is needed (i.e. when a reconnect is necessary). /// </remarks> /// <param name="connectionType">The <see cref="Type"/> of the <see cref="IDbConnection"/> object.</param> /// <param name="connectionString">The connectionString output from the ResolveConnectionString method.</param> /// <returns>An <see cref="IDbConnection"/> instance with a valid connection string.</returns> virtual protected IDbConnection CreateConnection(Type connectionType, string connectionString) { IDbConnection connection = (IDbConnection)Activator.CreateInstance(connectionType); connection.ConnectionString = connectionString; return connection; } /// <summary> /// Resolves the connection string from the ConnectionString, ConnectionStringName, or AppSettingsKey /// property. /// </summary> /// <remarks> /// ConnectiongStringName is only supported on .NET 2.0 and higher. /// </remarks> /// <param name="connectionStringContext">Additional information describing the connection string.</param> /// <returns>A connection string used to connect to the database.</returns> virtual protected string ResolveConnectionString(out string connectionStringContext) { if (m_connectionString != null && m_connectionString.Length > 0) { connectionStringContext = "ConnectionString"; return m_connectionString; } #if NET_2_0 if (!String.IsNullOrEmpty(m_connectionStringName)) { ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings[m_connectionStringName]; if (settings != null) { connectionStringContext = "ConnectionStringName"; return settings.ConnectionString; } else { throw new LogException("Unable to find [" + m_connectionStringName + "] ConfigurationManager.ConnectionStrings item"); } } #endif if (m_appSettingsKey != null && m_appSettingsKey.Length > 0) { connectionStringContext = "AppSettingsKey"; string appSettingsConnectionString = SystemInfo.GetAppSetting(m_appSettingsKey); if (appSettingsConnectionString == null || appSettingsConnectionString.Length == 0) { throw new LogException("Unable to find [" + m_appSettingsKey + "] AppSettings key."); } return appSettingsConnectionString; } connectionStringContext = "Unable to resolve connection string from ConnectionString, ConnectionStrings, or AppSettings."; return string.Empty; } /// <summary> /// Retrieves the class type of the ADO.NET provider. /// </summary> /// <remarks> /// <para> /// Gets the Type of the ADO.NET provider to use to connect to the /// database. This method resolves the type specified in the /// <see cref="ConnectionType"/> property. /// </para> /// <para> /// Subclasses can override this method to return a different type /// if necessary. /// </para> /// </remarks> /// <returns>The <see cref="Type"/> of the ADO.NET provider</returns> virtual protected Type ResolveConnectionType() { try { return SystemInfo.GetTypeFromString(m_connectionType, true, false); } catch(Exception ex) { ErrorHandler.Error("Failed to load connection type ["+m_connectionType+"]", ex); throw; } } #endregion // Protected Instance Methods #region Private Instance Methods /// <summary> /// Prepares the database command and initialize the parameters. /// </summary> private void InitializeDatabaseCommand() { if (m_dbConnection != null && m_usePreparedCommand) { try { DisposeCommand(false); // Create the command object m_dbCommand = m_dbConnection.CreateCommand(); // Set the command string m_dbCommand.CommandText = m_commandText; // Set the command type m_dbCommand.CommandType = m_commandType; } catch (Exception e) { ErrorHandler.Error("Could not create database command [" + m_commandText + "]", e); DisposeCommand(true); } if (m_dbCommand != null) { try { foreach (AdoNetAppenderParameter param in m_parameters) { try { param.Prepare(m_dbCommand); } catch (Exception e) { ErrorHandler.Error("Could not add database command parameter [" + param.ParameterName + "]", e); throw; } } } catch { DisposeCommand(true); } } if (m_dbCommand != null) { try { // Prepare the command statement. m_dbCommand.Prepare(); } catch (Exception e) { ErrorHandler.Error("Could not prepare database command [" + m_commandText + "]", e); DisposeCommand(true); } } } } /// <summary> /// Connects to the database. /// </summary> private void InitializeDatabaseConnection() { string connectionStringContext = "Unable to determine connection string context."; string resolvedConnectionString = string.Empty; try { DisposeCommand(true); DiposeConnection(); // Set the connection string resolvedConnectionString = ResolveConnectionString(out connectionStringContext); m_dbConnection = CreateConnection(ResolveConnectionType(), resolvedConnectionString); using (SecurityContext.Impersonate(this)) { // Open the database connection m_dbConnection.Open(); } } catch (Exception e) { // Sadly, your connection string is bad. ErrorHandler.Error("Could not open database connection [" + resolvedConnectionString + "]. Connection string context [" + connectionStringContext + "].", e); m_dbConnection = null; } } /// <summary> /// Cleanup the existing command. /// </summary> /// <param name="ignoreException"> /// If true, a message will be written using LogLog.Warn if an exception is encountered when calling Dispose. /// </param> private void DisposeCommand(bool ignoreException) { // Cleanup any existing command or connection if (m_dbCommand != null) { try { m_dbCommand.Dispose(); } catch (Exception ex) { if (!ignoreException) { LogLog.Warn(declaringType, "Exception while disposing cached command object", ex); } } m_dbCommand = null; } } /// <summary> /// Cleanup the existing connection. /// </summary> /// <remarks> /// Calls the IDbConnection's <see cref="IDbConnection.Close"/> method. /// </remarks> private void DiposeConnection() { if (m_dbConnection != null) { try { m_dbConnection.Close(); } catch (Exception ex) { LogLog.Warn(declaringType, "Exception while disposing cached connection object", ex); } m_dbConnection = null; } } #endregion // Private Instance Methods #region Protected Instance Fields /// <summary> /// Flag to indicate if we are using a command object /// </summary> /// <remarks> /// <para> /// Set to <c>true</c> when the appender is to use a prepared /// statement or stored procedure to insert into the database. /// </para> /// </remarks> protected bool m_usePreparedCommand; /// <summary> /// The list of <see cref="AdoNetAppenderParameter"/> objects. /// </summary> /// <remarks> /// <para> /// The list of <see cref="AdoNetAppenderParameter"/> objects. /// </para> /// </remarks> protected ArrayList m_parameters; #endregion // Protected Instance Fields #region Private Instance Fields /// <summary> /// The security context to use for privileged calls /// </summary> private SecurityContext m_securityContext; /// <summary> /// The <see cref="IDbConnection" /> that will be used /// to insert logging events into a database. /// </summary> private IDbConnection m_dbConnection; /// <summary> /// The database command. /// </summary> private IDbCommand m_dbCommand; /// <summary> /// Database connection string. /// </summary> private string m_connectionString; /// <summary> /// The appSettings key from App.Config that contains the connection string. /// </summary> private string m_appSettingsKey; #if NET_2_0 /// <summary> /// The connectionStrings key from App.Config that contains the connection string. /// </summary> private string m_connectionStringName; #endif /// <summary> /// String type name of the <see cref="IDbConnection"/> type name. /// </summary> private string m_connectionType; /// <summary> /// The text of the command. /// </summary> private string m_commandText; /// <summary> /// The command type. /// </summary> private CommandType m_commandType; /// <summary> /// Indicates whether to use transactions when writing to the database. /// </summary> private bool m_useTransactions; /// <summary> /// Indicates whether to use transactions when writing to the database. /// </summary> private bool m_reconnectOnError; #endregion // Private Instance Fields #region Private Static Fields /// <summary> /// The fully qualified type of the AdoNetAppender class. /// </summary> /// <remarks> /// Used by the internal logger to record the Type of the /// log message. /// </remarks> private readonly static Type declaringType = typeof(AdoNetAppender); #endregion Private Static Fields } /// <summary> /// Parameter type used by the <see cref="AdoNetAppender"/>. /// </summary> /// <remarks> /// <para> /// This class provides the basic database parameter properties /// as defined by the <see cref="System.Data.IDbDataParameter"/> interface. /// </para> /// <para>This type can be subclassed to provide database specific /// functionality. The two methods that are called externally are /// <see cref="Prepare"/> and <see cref="FormatValue"/>. /// </para> /// </remarks> public class AdoNetAppenderParameter { #region Public Instance Constructors /// <summary> /// Initializes a new instance of the <see cref="AdoNetAppenderParameter" /> class. /// </summary> /// <remarks> /// Default constructor for the AdoNetAppenderParameter class. /// </remarks> public AdoNetAppenderParameter() { m_precision = 0; m_scale = 0; m_size = 0; } #endregion // Public Instance Constructors #region Public Instance Properties /// <summary> /// Gets or sets the name of this parameter. /// </summary> /// <value> /// The name of this parameter. /// </value> /// <remarks> /// <para> /// The name of this parameter. The parameter name /// must match up to a named parameter to the SQL stored procedure /// or prepared statement. /// </para> /// </remarks> public string ParameterName { get { return m_parameterName; } set { m_parameterName = value; } } /// <summary> /// Gets or sets the database type for this parameter. /// </summary> /// <value> /// The database type for this parameter. /// </value> /// <remarks> /// <para> /// The database type for this parameter. This property should /// be set to the database type from the <see cref="DbType"/> /// enumeration. See <see cref="IDataParameter.DbType"/>. /// </para> /// <para> /// This property is optional. If not specified the ADO.NET provider /// will attempt to infer the type from the value. /// </para> /// </remarks> /// <seealso cref="IDataParameter.DbType" /> public DbType DbType { get { return m_dbType; } set { m_dbType = value; m_inferType = false; } } /// <summary> /// Gets or sets the precision for this parameter. /// </summary> /// <value> /// The precision for this parameter. /// </value> /// <remarks> /// <para> /// The maximum number of digits used to represent the Value. /// </para> /// <para> /// This property is optional. If not specified the ADO.NET provider /// will attempt to infer the precision from the value. /// </para> /// </remarks> /// <seealso cref="IDbDataParameter.Precision" /> public byte Precision { get { return m_precision; } set { m_precision = value; } } /// <summary> /// Gets or sets the scale for this parameter. /// </summary> /// <value> /// The scale for this parameter. /// </value> /// <remarks> /// <para> /// The number of decimal places to which Value is resolved. /// </para> /// <para> /// This property is optional. If not specified the ADO.NET provider /// will attempt to infer the scale from the value. /// </para> /// </remarks> /// <seealso cref="IDbDataParameter.Scale" /> public byte Scale { get { return m_scale; } set { m_scale = value; } } /// <summary> /// Gets or sets the size for this parameter. /// </summary> /// <value> /// The size for this parameter. /// </value> /// <remarks> /// <para> /// The maximum size, in bytes, of the data within the column. /// </para> /// <para> /// This property is optional. If not specified the ADO.NET provider /// will attempt to infer the size from the value. /// </para> /// <para> /// For BLOB data types like VARCHAR(max) it may be impossible to infer the value automatically, use -1 as the size in this case. /// </para> /// </remarks> /// <seealso cref="IDbDataParameter.Size" /> public int Size { get { return m_size; } set { m_size = value; } } /// <summary> /// Gets or sets the <see cref="IRawLayout"/> to use to /// render the logging event into an object for this /// parameter. /// </summary> /// <value> /// The <see cref="IRawLayout"/> used to render the /// logging event into an object for this parameter. /// </value> /// <remarks> /// <para> /// The <see cref="IRawLayout"/> that renders the value for this /// parameter. /// </para> /// <para> /// The <see cref="RawLayoutConverter"/> can be used to adapt /// any <see cref="ILayout"/> into a <see cref="IRawLayout"/> /// for use in the property. /// </para> /// </remarks> public IRawLayout Layout { get { return m_layout; } set { m_layout = value; } } #endregion // Public Instance Properties #region Public Instance Methods /// <summary> /// Prepare the specified database command object. /// </summary> /// <param name="command">The command to prepare.</param> /// <remarks> /// <para> /// Prepares the database command object by adding /// this parameter to its collection of parameters. /// </para> /// </remarks> virtual public void Prepare(IDbCommand command) { // Create a new parameter IDbDataParameter param = command.CreateParameter(); // Set the parameter properties param.ParameterName = m_parameterName; if (!m_inferType) { param.DbType = m_dbType; } if (m_precision != 0) { param.Precision = m_precision; } if (m_scale != 0) { param.Scale = m_scale; } if (m_size != 0) { param.Size = m_size; } // Add the parameter to the collection of params command.Parameters.Add(param); } /// <summary> /// Renders the logging event and set the parameter value in the command. /// </summary> /// <param name="command">The command containing the parameter.</param> /// <param name="loggingEvent">The event to be rendered.</param> /// <remarks> /// <para> /// Renders the logging event using this parameters layout /// object. Sets the value of the parameter on the command object. /// </para> /// </remarks> virtual public void FormatValue(IDbCommand command, LoggingEvent loggingEvent) { // Lookup the parameter IDbDataParameter param = (IDbDataParameter)command.Parameters[m_parameterName]; // Format the value object formattedValue = Layout.Format(loggingEvent); // If the value is null then convert to a DBNull if (formattedValue == null) { formattedValue = DBNull.Value; } param.Value = formattedValue; } #endregion // Public Instance Methods #region Private Instance Fields /// <summary> /// The name of this parameter. /// </summary> private string m_parameterName; /// <summary> /// The database type for this parameter. /// </summary> private DbType m_dbType; /// <summary> /// Flag to infer type rather than use the DbType /// </summary> private bool m_inferType = true; /// <summary> /// The precision for this parameter. /// </summary> private byte m_precision; /// <summary> /// The scale for this parameter. /// </summary> private byte m_scale; /// <summary> /// The size for this parameter. /// </summary> private int m_size; /// <summary> /// The <see cref="IRawLayout"/> to use to render the /// logging event into an object for this parameter. /// </summary> private IRawLayout m_layout; #endregion // Private Instance Fields } } #endif // !SSCLI
// // MRCombatSheetData.cs // // Author: // Steve Jakab <> // // Copyright (c) 2014 Steve Jakab // // 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 UnityEngine; using System; using System.Collections; using System.Collections.Generic; namespace PortableRealm { public class MRCombatSheetData { #region Subclasses public class MRCharacterCombatData { public MRWeapon weapon; public MRArmor shield; public MRArmor breastplate; public MRArmor helmet; public MRArmor fullArmor; public MRFightChit attackChit; public MRMoveChit maneuverChit; public MRSpell spell; public MRMagicChit spellMagic; public MRIColorSource spellColor; public List<MRISpellTarget> spellTargets = new List<MRISpellTarget>(); public MRCombatManager.eAttackType attackType = MRCombatManager.eAttackType.None; public MRCombatManager.eDefenseType maneuverType = MRCombatManager.eDefenseType.None; public MRCombatManager.eAttackType shieldType = MRCombatManager.eAttackType.None; public int pendingWounds; } public class AttackerData { public MRDenizen attacker; public MRCombatManager.eAttackType attackType; public AttackerData(MRDenizen _attacker, MRCombatManager.eAttackType _attackType) { attacker = _attacker; attackType = _attackType; } } public class DefenderData { public MRDenizen defender; public MRCombatManager.eDefenseType defenseType; public DefenderData(MRDenizen _defender, MRCombatManager.eDefenseType _defenseType) { defender = _defender; defenseType = _defenseType; } } #endregion #region Methods /// <summary> /// Adds an attacker to an attack square. /// </summary> /// <param name="attacker">Attacker.</param> /// <param name="slot">Slot to put the attacker on.</param> public void AddAttacker(MRDenizen attacker, MRCombatManager.eAttackType slot) { if (attacker.CombatSheet != null) attacker.CombatSheet.RemoveCombatant(attacker); attacker.CombatSheet = this; Attackers.Insert(0, new AttackerData(attacker, slot)); } /// <summary> /// Adds a defender to a defense square. Will add it to a random one, but try to keep all squares evenly filled. /// </summary> /// <param name="defender">Defender.</param> public void AddDefender(MRDenizen defender) { // get the number of defenders in each slot IDictionary<MRCombatManager.eDefenseType, int> slots = new Dictionary<MRCombatManager.eDefenseType, int>(); slots[MRCombatManager.eDefenseType.Charge] = 0; slots[MRCombatManager.eDefenseType.Dodge] = 0; slots[MRCombatManager.eDefenseType.Duck] = 0; foreach (DefenderData data in Defenders) { ++slots[data.defenseType]; } if (defender is MRMonster && ((MRMonster)defender).OwnedBy != null) { // prevent head/club from being placed in the same slot as its owner foreach (DefenderData data in Defenders) { if (((MRMonster)defender).OwnedBy == data.defender) slots[data.defenseType] = int.MaxValue; } } int lowestCount = int.MaxValue; foreach (int value in slots.Values) { if (value < lowestCount) lowestCount = value; } MRCombatManager.eDefenseType pick = MRCombatManager.eDefenseType.None; do { Debug.Log("Pick random defense location roll"); int rnd = MRRandom.Range(0, Enum.GetValues(typeof(MRCombatManager.eDefenseType)).Length); pick = (MRCombatManager.eDefenseType)Enum.GetValues(typeof(MRCombatManager.eDefenseType)).GetValue(rnd); } while (pick == MRCombatManager.eDefenseType.None || slots[pick] != lowestCount); AddDefender(defender, pick); if (defender is MRMonster && ((MRMonster)defender).Owns != null) { // add a monster's head/club to the same sheet it's on AddDefender(((MRMonster)defender).Owns); } } /// <summary> /// Adds a defender to a defense square. /// </summary> /// <param name="defender">Defender.</param> /// <param name="slot">Slot to put the defender on.</param> public void AddDefender(MRDenizen defender, MRCombatManager.eDefenseType slot) { if (defender.CombatSheet != null) defender.CombatSheet.RemoveCombatant(defender); defender.CombatSheet = this; Defenders.Insert(0, new DefenderData(defender, slot)); } public void AddDefenderTarget(MRDenizen target, MRCombatManager.eDefenseType slot) { if (DefenderTarget != null) { Debug.LogError("Tried to add defender target to defender with existing target"); return; } if (target.CombatSheet != null) target.CombatSheet.RemoveCombatant(target); target.CombatSheet = this; DefenderTarget = new DefenderData(target, slot); } public AttackerData FindAttacker(MRDenizen attacker) { foreach (AttackerData data in Attackers) { if (data.attacker == attacker) return data; } return null; } public DefenderData FindDefender(MRDenizen target) { foreach (DefenderData data in Defenders) { if (data.defender == target) return data; } if (DefenderTarget != null && DefenderTarget.defender == target) return DefenderTarget; return null; } /// <summary> /// Removes a combatant from the sheet. /// </summary> /// <param name="combatant">The combatant to remove.</param> public void RemoveCombatant(MRIControllable combatant) { if (combatant.CombatSheet != this) return; combatant.CombatSheet = null; foreach (DefenderData data in Defenders) { if (data.defender == combatant) { Defenders.Remove(data); return; } } foreach (AttackerData data in Attackers) { if (data.attacker == combatant) { Attackers.Remove(data); return; } } if (DefenderTarget.defender == combatant) DefenderTarget = null; } /// <summary> /// Removes all combatants from this sheet. /// </summary> public void RemoveCombatants() { foreach (DefenderData data in Defenders) { data.defender.CombatSheet = null; } foreach (AttackerData data in Attackers) { data.attacker.CombatSheet = null; } if (DefenderTarget != null) DefenderTarget.defender.CombatSheet = null; Defenders.Clear(); Attackers.Clear(); DefenderTarget = null; } /// <summary> /// Returns he character's armor hit by a given attack direction. /// </summary> /// <returns>The armor for attack.</returns> /// <param name="attack">Attack.</param> public MRArmor CharacterArmorForAttack(MRCombatManager.eAttackType attack) { if (CharacterData == null) return null; if (CharacterData.shield != null && CharacterData.shieldType == attack) return CharacterData.shield; if (CharacterData.breastplate != null && (attack == MRCombatManager.eAttackType.Thrust || attack == MRCombatManager.eAttackType.Swing)) { return CharacterData.breastplate; } if (CharacterData.helmet != null && attack == MRCombatManager.eAttackType.Smash) return CharacterData.helmet; if (CharacterData.fullArmor != null) return CharacterData.fullArmor; return null; } #endregion #region Members public MRControllable SheetOwner; public MRCharacterCombatData CharacterData; public IList<AttackerData> Attackers = new List<AttackerData>(); public IList<DefenderData> Defenders = new List<DefenderData>(); // the target of a defending denizen on their own sheet public DefenderData DefenderTarget; #endregion } }
// Copyright 2017 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections.Generic; using System.IO; using UnityEditor; using UnityEngine; using PolyToolkit; using PolyToolkitInternal; using System; using System.Text.RegularExpressions; namespace PolyToolkitEditor { /// <summary> /// Window that allows the user to browse and import Poly models. /// /// Note that EditorWindow objects are created and deleted when the window is opened or closed, so this /// object can't be responsible for any background logic like importing assets, etc. It should only deal /// with UI. For all background logic and and real work, we rely on AssetBrowserManager. /// </summary> public class AssetBrowserWindow : EditorWindow { /// <summary> /// Title of the window (shown in the Unity UI). /// </summary> private const string WINDOW_TITLE = "Poly Toolkit"; /// <summary> /// URL of the user's profile page. /// </summary> private const string USER_PROFILE_URL = "https://poly.google.com/user"; /// <summary> /// Width and height of each asset thumbnail image in the grid. /// </summary> private const int THUMBNAIL_WIDTH = 128; private const int THUMBNAIL_HEIGHT = 96; /// <summary> /// Width of each grid cell in the assets grid. /// </summary> private const int CELL_WIDTH = THUMBNAIL_WIDTH; /// <summary> /// Spacing between grid cells in the assets grid. /// </summary> private const int CELL_SPACING = 5; /// <summary> /// Height of the title bar at the top of the window. /// </summary> private const int TITLE_BAR_HEIGHT = 64; /// <summary> /// Height of the bar that contains the back button. /// </summary> private const int BACK_BUTTON_BAR_HEIGHT = 28; /// <summary> /// Height of the title image. /// </summary> private const int TITLE_IMAGE_HEIGHT = 40; /// <summary> /// Padding around title image. /// </summary> private const int TITLE_IMAGE_PADDING = 12; /// <summary> /// Margin from the top where the UI begins. /// This does not account for the back button bar. /// </summary> private const int TOP_MARGIN_BASE = TITLE_BAR_HEIGHT + 10; /// <summary> /// Padding around the window. /// </summary> private const int PADDING = 5; /// <summary> /// Size of the user's profile picture. /// </summary> private const int PROFILE_PICTURE_SIZE = 40; /// <summary> /// Size of the left column (labels), in pixels. /// </summary> private const int LEFT_COL_WIDTH = 140; /// <summary> /// Height of the "successfully imported" box. /// </summary> private const int IMPORT_SUCCESS_BOX_HEIGHT = 120; /// <summary> /// Texture to use for the title bar. /// </summary> private const string TITLE_TEX = "Editor/Textures/PolyToolkitTitle.png"; /// <summary> /// Texture to use for the back button (back arrow) if the skin is Unity pro. /// </summary> private const string BACK_ARROW_LIGHT_TEX = "Editor/Textures/BackArrow.png"; /// <summary> /// Texture to use for the back button (back arrow) if the skin is Unity personal. /// </summary> private const string BACK_ARROW_DARK_TEX = "Editor/Textures/BackArrowDark.png"; /// <summary> /// Texture to use for the back button bar background if the skin is Unity pro. /// </summary> private const string DARK_GREY_TEX = "Editor/Textures/DarkGrey.png"; /// <summary> /// Texture to use for the back button bar background if the skin is Unity personal. /// </summary> private const string LIGHT_GREY_TEX = "Editor/Textures/LightGrey.png"; /// <summary> /// Category key corresponding to selecting the "FEATURED" section. /// </summary> private const string KEY_FEATURED = "_featured"; /// <summary> /// Category key corresponding to selecting the "Your Uploads" section. /// </summary> private const string KEY_YOUR_UPLOADS = "_your_uploads"; /// <summary> /// Category key corresponding to selecting the "Your Uploads" section. /// </summary> private const string KEY_YOUR_LIKES = "_your_likes"; /// <summary> /// Index of the "FEATURED" category below. /// </summary> private const int CATEGORY_FEATURED = 0; /// <summary> /// Categories that the user can choose to browse. /// </summary> private static readonly CategoryInfo[] CATEGORIES = { new CategoryInfo(KEY_FEATURED, "Featured", PolyCategory.UNSPECIFIED), new CategoryInfo(KEY_YOUR_UPLOADS, "Your Uploads", PolyCategory.UNSPECIFIED), new CategoryInfo(KEY_YOUR_LIKES, "Your Likes", PolyCategory.UNSPECIFIED), new CategoryInfo("animals", "Animals and Creatures", PolyCategory.ANIMALS), new CategoryInfo("architecture", "Architecture", PolyCategory.ARCHITECTURE), new CategoryInfo("art", "Art", PolyCategory.ART), new CategoryInfo("food", "Food and Drink", PolyCategory.FOOD), new CategoryInfo("nature", "Nature", PolyCategory.NATURE), new CategoryInfo("objects", "Objects", PolyCategory.OBJECTS), new CategoryInfo("people", "People and Characters", PolyCategory.PEOPLE), new CategoryInfo("places", "Places and Scenes", PolyCategory.PLACES), new CategoryInfo("tech", "Technology", PolyCategory.TECH), new CategoryInfo("transport", "Transport", PolyCategory.TRANSPORT), }; /// <summary> /// Represent the several modes that the UI can be in. /// </summary> private enum UiMode { // Browsing assets by category/type (default mode). BROWSE, // Searching for assets by keyword (search box open). SEARCH, // Viewing the details of a particular asset. DETAILS, }; /// <summary> /// Current UI mode. /// </summary> private UiMode mode = UiMode.BROWSE; /// <summary> /// The previous UI mode. /// </summary> private UiMode previousMode = UiMode.BROWSE; /// <summary> /// Index of the category that is currently selected (in CATEGORIES[]). /// </summary> private int selectedCategory = 0; /// <summary> /// The search terms the user has typed in the search box. /// </summary> private string searchTerms = ""; /// <summary> /// The texture to use in place of a thumbnail when loading the thumbnail. /// </summary> private Texture2D loadingTex = null; /// <summary> /// The texture to use for the back button (back arrow). /// </summary> private Texture2D backArrowTex = null; /// <summary> /// Texture used for back button bar background. /// </summary> private Texture2D backBarBackgroundTex = null; /// <summary> /// Reference to the AssetBrowserManager. /// </summary> private AssetBrowserManager manager; /// <summary> /// Current scrolling position of the scroll view with the list of assets. /// </summary> private Vector2 assetListScrollPos; /// <summary> /// Current scrolling position of the details window. /// </summary> private Vector2 detailsScrollPos; /// <summary> /// If non-null, we're showing the details page for the given asset. If null, /// we are showing the grid screen that shows all assets. /// </summary> private PolyAsset selectedAsset = null; /// <summary> /// Indicates whether the query we're currently showing requires authentication. /// </summary> private bool queryRequiresAuth = false; /// <summary> /// The selected asset path in the "Import" section of the details page. /// </summary> private string ptAssetLocalPath = ""; /// <summary> /// Current asset type filter (indicates the type of asset that the user wishes to see). /// </summary> private PolyFormatFilter? assetTypeFilter = null; /// <summary> /// Texture for the title bar. /// </summary> private Texture2D titleTex; /// <summary> /// The style we use for the asset title in the details page. /// </summary> private GUIStyle detailsTitleStyle; /// <summary> /// GUI helper that keeps track of our open layouts. /// </summary> private GUIHelper guiHelper = new GUIHelper(); /// <summary> /// Currently selected import options. /// </summary> private EditTimeImportOptions importOptions; /// <summary> /// If true, the currently displayed asset was just imported successfully. /// </summary> private bool justImported; /// <summary> /// Shows the browser window. /// </summary> [MenuItem("Poly/Browse Assets...")] public static void BrowsePolyAssets() { GetWindow<AssetBrowserWindow>(WINDOW_TITLE, /* focus */ true); PtAnalytics.SendEvent(PtAnalytics.Action.MENU_BROWSE_ASSETS); } /// <summary> /// Shows the browser window. /// </summary> [MenuItem("Window/Poly: Browse Assets...")] public static void BrowsePolyAssets2() { BrowsePolyAssets(); } /// <summary> /// Notifies this window that the given asset was just imported successfully /// (so we can show this state in the UI). /// </summary> /// <param name="assetId">The ID of the asset that was just imported.</param> public void HandleAssetImported(string assetId) { if (selectedAsset != null && assetId == selectedAsset.name) { justImported = true; } } /// <summary> /// Performs one-time initialization. /// </summary> private void Initialize() { PtDebug.Log("ABW: initializing."); if (manager == null) { manager = new AssetBrowserManager(); manager.SetRefreshCallback(UpdateUi); } loadingTex = new Texture2D(1,1); titleTex = PtUtils.LoadTexture2DFromRelativePath(TITLE_TEX); backArrowTex = PtUtils.LoadTexture2DFromRelativePath( EditorGUIUtility.isProSkin ? BACK_ARROW_LIGHT_TEX : BACK_ARROW_DARK_TEX); backBarBackgroundTex = PtUtils.LoadTexture2DFromRelativePath( EditorGUIUtility.isProSkin ? DARK_GREY_TEX : LIGHT_GREY_TEX); detailsTitleStyle = new GUIStyle(EditorStyles.wordWrappedLabel); detailsTitleStyle.fontSize = 15; detailsTitleStyle.fontStyle = FontStyle.Bold; } private void SetUiMode(UiMode newMode) { if (newMode != mode) { previousMode = mode; mode = newMode; } PtDebug.Log("ABW: changed UI mode to " + newMode); } /// <summary> /// Renders the window GUI (invoked by Unity). /// </summary> public void OnGUI() { if (Application.isPlaying) { DrawTitleBar(/* withSignInUi */ false); GUILayout.Space(TOP_MARGIN_BASE); guiHelper.BeginHorizontal(); GUILayout.FlexibleSpace(); GUILayout.Label("(This window doesn't work in Play mode)", EditorStyles.wordWrappedLabel); GUILayout.FlexibleSpace(); guiHelper.EndHorizontal(); return; } if (manager == null) { // Initialize, if we haven't yet. We delay this to OnGUI instead of earlier because we need // the Unity GUI system to be completely initialized (so we can create styles, for instance), which // only happens on OnGUI(). PolyRequest request = BuildRequest(); manager = new AssetBrowserManager(request); manager.SetRefreshCallback(UpdateUi); Initialize(); } // We have to check if Poly is ready every time (it's cheap to check). This is because Poly can be // unloaded and wiped every time we enter or exit play mode. manager.EnsurePolyIsReady(); int topMargin; if (!DrawHeader(out topMargin)) { // Abort rendering because a button was pressed (for example, the back button). return; } guiHelper.BeginArea(new Rect(PADDING, PADDING, position.width - 2 * PADDING, position.height - 2 * PADDING)); GUILayout.Space(topMargin); switch (mode) { case UiMode.BROWSE: DrawBrowseUi(); break; case UiMode.SEARCH: DrawSearchUi(); break; case UiMode.DETAILS: DrawDetailsUi(); break; default: throw new System.Exception("Invalid UI mode: " + mode); } guiHelper.EndArea(); guiHelper.FinishAndCheck(); } /// <summary> /// Draws the header and handles header-related events (like the back button). /// </summary> /// <param name="topMargin">(Out param). The top margin at which the rest of the content /// should be rendered. Only valid if this method returns true.</param> /// <returns>True if the header was successfully drawn and rendering should continue. /// False if it was aborted due to a back button press.</returns> private bool DrawHeader(out int topMargin) { DrawTitleBar(withSignInUi: true); bool hasBackButtonBar = HasBackButtonBar(); topMargin = TOP_MARGIN_BASE; if (hasBackButtonBar) { bool backButtonClicked = DrawBackButtonBar(); if (backButtonClicked) { HandleBackButton(); return false; } // Increase the top margin of the content to account for the back button bar. topMargin += BACK_BUTTON_BAR_HEIGHT; } return true; } /// <summary> /// Draws the title bar at the top of the window. /// The title bar includes the user's profile picture and the Sign In/Out UI. /// <param name="withSignInUi">If true, also include the sign in/sign out UI.</param> /// </summary> private void DrawTitleBar(bool withSignInUi) { GUI.DrawTexture(new Rect(0, 0, position.width, TITLE_BAR_HEIGHT), Texture2D.whiteTexture); GUIStyle titleStyle = new GUIStyle (GUI.skin.label); titleStyle.margin = new RectOffset(TITLE_IMAGE_PADDING, TITLE_IMAGE_PADDING, TITLE_IMAGE_PADDING, TITLE_IMAGE_PADDING); if (GUILayout.Button(titleTex, titleStyle, GUILayout.Width(titleTex.width * TITLE_IMAGE_HEIGHT / titleTex.height), GUILayout.Height(TITLE_IMAGE_HEIGHT))) { // Clicked title image. Return to the featured assets page. SetUiMode(UiMode.BROWSE); selectedCategory = CATEGORY_FEATURED; StartRequest(); } if (!withSignInUi) return; guiHelper.BeginArea(new Rect(TITLE_IMAGE_PADDING, TITLE_IMAGE_PADDING, position.width - 2 * TITLE_IMAGE_PADDING, TITLE_BAR_HEIGHT)); if (PolyApi.IsAuthenticated) { // User is authenticated, so show the profie picture. guiHelper.BeginHorizontal(); GUILayout.FlexibleSpace(); Texture2D userTex = PolyApi.UserIcon != null && PolyApi.UserIcon.texture != null ? PolyApi.UserIcon.texture : loadingTex; if (GUILayout.Button(new GUIContent(userTex, /* tooltip */ PolyApi.UserName), GUIStyle.none, GUILayout.Width(PROFILE_PICTURE_SIZE), GUILayout.Height(PROFILE_PICTURE_SIZE))) { // Clicked profile picture. Show the dropdown menu. ShowProfileDropdownMenu(); } guiHelper.EndHorizontal(); } else if (PolyApi.IsAuthenticating) { guiHelper.BeginHorizontal(); GUILayout.FlexibleSpace(); GUILayout.Label("Signing in... Please wait."); guiHelper.EndHorizontal(); guiHelper.BeginHorizontal(); GUILayout.FlexibleSpace(); bool cancelSignInClicked = GUILayout.Button("Cancel", EditorStyles.miniButton); guiHelper.EndHorizontal(); if (cancelSignInClicked) { PtAnalytics.SendEvent(PtAnalytics.Action.ACCOUNT_SIGN_IN_CANCEL); manager.CancelSignIn(); } } else { // Not signed in. Show "Sign In" button. GUILayout.Space(30); guiHelper.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Sign in")) { PtAnalytics.SendEvent(PtAnalytics.Action.ACCOUNT_SIGN_IN_START); manager.LaunchSignInFlow(); } guiHelper.EndHorizontal(); } guiHelper.EndArea(); } /// <summary> /// Draws the "browse" UI. The main UI allows the user to select a category to browse and set filters, /// and allows them to browse the assets grid. When they click on an asset, they go to the details UI. /// </summary> private void DrawBrowseUi() { guiHelper.BeginHorizontal(); GUILayout.FlexibleSpace(); bool searchClicked = GUILayout.Button("Search..."); guiHelper.EndHorizontal(); if (searchClicked) { SetUiMode(UiMode.SEARCH); PtAnalytics.SendEvent(PtAnalytics.Action.BROWSE_SEARCH_CLICKED); manager.ClearRequest(); return; } guiHelper.BeginHorizontal(); // Draw the category dropdowns. GUILayout.Label("Show:", GUILayout.Width(LEFT_COL_WIDTH)); if (EditorGUILayout.DropdownButton(new GUIContent(CATEGORIES[selectedCategory].title), FocusType.Keyboard)) { GenericMenu menu = new GenericMenu(); for (int i = 0; i < CATEGORIES.Length; i++) { if (i == 3) menu.AddSeparator(""); menu.AddItem(new GUIContent(CATEGORIES[i].title), i == selectedCategory, DropdownMenuCallback, i); } menu.ShowAsContext(); } guiHelper.EndHorizontal(); // Draw the "Asset type" toggles. bool showAssetTypeFilter = (CATEGORIES[selectedCategory].key != KEY_YOUR_LIKES); if (showAssetTypeFilter) { guiHelper.BeginHorizontal(); GUILayout.Label("Asset type:", GUILayout.Width(LEFT_COL_WIDTH)); bool blocksToggle = GUILayout.Toggle(assetTypeFilter == PolyFormatFilter.BLOCKS, "Blocks", "Button"); bool tiltBrushToggle = GUILayout.Toggle(assetTypeFilter == PolyFormatFilter.TILT, "Tilt Brush", "Button"); bool allToggle = GUILayout.Toggle(assetTypeFilter == null, "All", "Button"); guiHelper.EndHorizontal(); GUILayout.Space(10); if (blocksToggle && assetTypeFilter != PolyFormatFilter.BLOCKS) { assetTypeFilter = PolyFormatFilter.BLOCKS; PtAnalytics.SendEvent(PtAnalytics.Action.BROWSE_ASSET_TYPE_SELECTED, assetTypeFilter.ToString()); StartRequest(); return; } else if (tiltBrushToggle && assetTypeFilter != PolyFormatFilter.TILT) { assetTypeFilter = PolyFormatFilter.TILT; PtAnalytics.SendEvent(PtAnalytics.Action.BROWSE_ASSET_TYPE_SELECTED, assetTypeFilter.ToString()); StartRequest(); return; } else if (allToggle && assetTypeFilter != null) { assetTypeFilter = null; PtAnalytics.SendEvent(PtAnalytics.Action.BROWSE_ASSET_TYPE_SELECTED, assetTypeFilter.ToString()); StartRequest(); return; } } DrawResultsGrid(); } private void HandleBackButton() { switch (mode) { case UiMode.SEARCH: SetUiMode(UiMode.BROWSE); StartRequest(); return; case UiMode.DETAILS: selectedAsset = null; justImported = false; manager.ClearCurrentAssetResult(); SetUiMode(previousMode); return; default: throw new Exception("Invalid UI mode for back button: " + mode); } } private void DrawSearchUi() { bool searchClicked = false; // Pressing ENTER in the search terms box is the same as clicking "Search". We have to check // this BEFORE we draw the text field, otherwise it will consume the event and we won't see it. if (Event.current != null && Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Return && GUI.GetNameOfFocusedControl() == "searchTerms") { searchClicked = true; } GUILayout.Space(10); GUILayout.Label("Search", EditorStyles.boldLabel); GUILayout.Label("Enter search terms (or a Poly URL) below:", EditorStyles.wordWrappedLabel); GUI.SetNextControlName("searchTerms"); searchTerms = EditorGUILayout.TextField(searchTerms, EditorStyles.textArea); guiHelper.BeginHorizontal(); GUILayout.FlexibleSpace(); searchClicked = GUILayout.Button("Search") || searchClicked; guiHelper.EndHorizontal(); if (searchClicked && searchTerms.Trim().Length > 0) { // Note: for privacy reasons we don't log the search terms, just the fact that a search was made. PtAnalytics.SendEvent(PtAnalytics.Action.BROWSE_SEARCHED); string assetId; if (SearchTermIsAssetPage(searchTerms, out assetId)) { manager.StartRequestForSpecificAsset(assetId); SetUiMode(UiMode.DETAILS); return; } StartRequest(); } DrawResultsGrid(); } /// <summary> /// Returns true if the url was a valid asset url, false if not. /// </summary> /// <param name="url">The url of the asset to get.</param> /// <param name="assetId">The id of the asset to get from the url, null if the url is invalid.</param> private bool SearchTermIsAssetPage(string url, out string assetId) { Regex regex = new Regex("^(http[s]?:\\/\\/)?.*\\/view\\/([^?]+)"); Match match = regex.Match(url); if (match.Success) { assetId = match.Groups[2].ToString(); assetId = assetId.Trim(); return true; } assetId = null; return false; } /// <summary> /// Draws the query results grid, using the current query results as reported by /// the AssetsBrowserManager. /// </summary> private void DrawResultsGrid() { if (manager.IsQuerying) { GUILayout.Space(30); GUILayout.Label("Fetching assets. Please wait..."); return; } if (manager.CurrentResult == null) { return; } if (manager.CurrentResult != null && !manager.CurrentResult.Status.ok) { GUILayout.Space(30); GUILayout.Label("There was a problem with that request! Please try again later.", EditorStyles.wordWrappedLabel); guiHelper.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Retry")) { // Retry the previous request. manager.ClearCaches(); StartRequest(); } GUILayout.FlexibleSpace(); guiHelper.EndHorizontal(); return; } if (manager.CurrentResult.Value.assets == null || manager.CurrentResult.Value.assets.Count == 0) { GUILayout.Space(30); GUILayout.Label("No results."); return; } PolyListAssetsResult result = manager.CurrentResult.Value; if (!result.status.ok) { GUILayout.Space(30); GUILayout.Label("*** ERROR fetching results. Try again.."); return; } guiHelper.BeginHorizontal(); string resultCountLabel; resultCountLabel = string.Format("{0} assets found.", result.totalSize); if (result.assets.Count < result.totalSize) { resultCountLabel += string.Format(" (showing 1-{0}).", result.assets.Count); } GUILayout.Label(resultCountLabel, EditorStyles.miniLabel); GUILayout.FlexibleSpace(); bool refreshClicked = GUILayout.Button("Refresh"); guiHelper.EndHorizontal(); GUILayout.Space(5); if (refreshClicked) { PtAnalytics.SendEvent(PtAnalytics.Action.BROWSE_REFRESH_CLICKED); manager.ClearCaches(); StartRequest(); return; } // Calculate how many assets we want to show on each row, based on the window width. // This allows the user to dynamically resize the window and have the assets grid // automatically reflow. int assetsPerRow = Mathf.Clamp( Mathf.FloorToInt((position.width - 40) / (CELL_WIDTH + CELL_SPACING)), 1, 8); int assetsThisRow = 0; // The assets grid is in a scroll view. assetListScrollPos = guiHelper.BeginScrollView(assetListScrollPos); GUILayout.Space(5); guiHelper.BeginVertical(); guiHelper.BeginHorizontal(); PolyAsset clickedAsset = null; foreach (PolyAsset asset in result.assets) { if (assetsThisRow >= assetsPerRow) { // Begin new row. guiHelper.EndHorizontal(); GUILayout.Space(20); guiHelper.BeginHorizontal(); assetsThisRow = 0; } if (assetsThisRow > 0) GUILayout.Space(CELL_SPACING); guiHelper.BeginVertical(); if (GUILayout.Button(asset.thumbnailTexture ?? loadingTex, GUILayout.Width(THUMBNAIL_WIDTH), GUILayout.Height(THUMBNAIL_HEIGHT))) { clickedAsset = asset; } GUILayout.Label(asset.displayName, EditorStyles.boldLabel, GUILayout.Width(CELL_WIDTH)); GUILayout.Label(asset.authorName, GUILayout.Width(CELL_WIDTH)); guiHelper.EndVertical(); assetsThisRow++; } // Complete last row with dummy cells. if (assetsThisRow > 0) { while (assetsThisRow < assetsPerRow) { guiHelper.BeginVertical(); GUILayout.Label("", GUILayout.Width(CELL_WIDTH), GUILayout.Height(THUMBNAIL_HEIGHT)); GUILayout.Label("", EditorStyles.boldLabel, GUILayout.Width(CELL_WIDTH)); GUILayout.Label("", GUILayout.Width(CELL_WIDTH)); guiHelper.EndVertical(); assetsThisRow++; } } guiHelper.EndHorizontal(); GUILayout.Space(10); bool loadMoreClicked = false; if (manager.resultHasMorePages) { // If the current response has at least another page of results left, show the load more button. guiHelper.BeginHorizontal(); GUILayout.FlexibleSpace(); loadMoreClicked = GUILayout.Button("Load more"); GUILayout.FlexibleSpace(); guiHelper.EndHorizontal(); } GUILayout.Space(5); guiHelper.EndVertical(); guiHelper.EndScrollView(); if (loadMoreClicked) { manager.GetNextPageRequest(); return; } if (clickedAsset != null) { PrepareDetailsUi(clickedAsset); PtAnalytics.SendEvent(PtAnalytics.Action.BROWSE_ASSET_DETAILS_CLICKED, GetAssetFormatDescription(selectedAsset)); SetUiMode(UiMode.DETAILS); } } /// <summary> /// Called as a callback by AssetBrowserManager whenever something interesting changes which /// requires us to update our UI. /// </summary> private void UpdateUi() { // Tell Unity to repaint this window, which will invoke OnGUI(). Repaint(); } /// <summary> /// Returns whether or not the given category requires authentication. /// </summary> private bool CategoryRequiresAuth(int category) { string key = CATEGORIES[category].key; return (key == KEY_YOUR_UPLOADS || key == KEY_YOUR_LIKES); } /// <summary> /// Shows the profile dropdown menu (the dropdown menu that appears when the user clicks their profile /// picture). /// </summary> private void ShowProfileDropdownMenu() { GenericMenu menu = new GenericMenu(); menu.AddItem(new GUIContent("My Profile (web)"), /* on */ false, () => { PtAnalytics.SendEvent(PtAnalytics.Action.ACCOUNT_VIEW_PROFILE); Application.OpenURL(USER_PROFILE_URL); }); menu.AddSeparator(""); menu.AddItem(new GUIContent("Sign Out"), /* on */ false, () => { PolyApi.SignOut(); PtAnalytics.SendEvent(PtAnalytics.Action.ACCOUNT_SIGN_OUT); // If the user was viewing a category that requires sign in, reset back to the home page. if (queryRequiresAuth) { selectedCategory = CATEGORY_FEATURED; StartRequest(); } }); menu.ShowAsContext(); } /// <summary> /// Callback invoked when the user picks a new category from the category dropdown. /// </summary> /// <param name="userData">The index of the selected category.</param> private void DropdownMenuCallback(object userData) { int selection = (int)userData; if (selection == selectedCategory) return; // If the user picked a category that requires authentication, and they are not authenticated, // tell them why they can't view it. if (CategoryRequiresAuth(selection) && !PolyApi.IsAuthenticated) { PtAnalytics.SendEvent(PtAnalytics.Action.BROWSE_MISSING_AUTH); EditorUtility.DisplayDialog("Sign in required", "To view your uploads or likes, you must sign in first.", "OK"); return; } selectedCategory = (int)userData; PtAnalytics.SendEvent(PtAnalytics.Action.BROWSE_CATEGORY_SELECTED, CATEGORIES[selectedCategory].key); StartRequest(); } /// <summary> /// Builds and returns a PolyRequest from the current state of the AssetBrowswerWindow variables. /// </summary> private PolyRequest BuildRequest() { CategoryInfo info = CATEGORIES[selectedCategory]; if (info.key == KEY_YOUR_UPLOADS) { PolyListUserAssetsRequest listUserAssetsRequest = PolyListUserAssetsRequest.MyNewest(); listUserAssetsRequest.formatFilter = assetTypeFilter; return listUserAssetsRequest; } if (info.key == KEY_YOUR_LIKES) { PolyListLikedAssetsRequest listLikedAssetsRequest = PolyListLikedAssetsRequest.MyLiked(); return listLikedAssetsRequest; } PolyListAssetsRequest listAssetsRequest; if (info.key == KEY_FEATURED) { listAssetsRequest = PolyListAssetsRequest.Featured(); } else { listAssetsRequest = new PolyListAssetsRequest(); listAssetsRequest.category = info.polyCategory; } listAssetsRequest.formatFilter = assetTypeFilter; // Only show curated results. listAssetsRequest.curated = true; return listAssetsRequest; } /// <summary> /// Sends a list assets request to the assets service according to the parameters currently selected in the UI. /// When the request is done, AssetBrowserManager will inform us through the callback. /// </summary> private void StartRequest() { if (mode == UiMode.BROWSE) { PolyRequest request = BuildRequest(); queryRequiresAuth = CategoryRequiresAuth(selectedCategory); if (!queryRequiresAuth || PolyApi.IsAuthenticated) { manager.StartRequest(request); } } else if (mode == UiMode.SEARCH) { PolyListAssetsRequest request = new PolyListAssetsRequest(); request.keywords = searchTerms; manager.StartRequest(request); } else { throw new System.Exception("Unexpected UI mode for StartQuery: " + mode); } // Reset scroll bar position. assetListScrollPos = Vector2.zero; } /// <summary> /// Set the variables of the details ui page for the newly selected asset. /// </summary> private void PrepareDetailsUi(PolyAsset newSelectedAsset) { selectedAsset = newSelectedAsset; ptAssetLocalPath = PtUtils.GetDefaultPtAssetPath(selectedAsset); detailsScrollPos = Vector2.zero; importOptions = PtSettings.Instance.defaultImportOptions; } /// <summary> /// Draws the asset details page. This is the page that shows the details about the selected asset /// and allows the user to click to import it. /// </summary> private void DrawDetailsUi() { if (manager.IsQuerying) { // Check if manager is querying for a specific asset. GUILayout.Space(30); GUILayout.Label("Fetching asset. Please wait..."); selectedAsset = null; return; } // If we just got the specific asset result, set the details ui import options to the relevant // variables at first. if (manager.CurrentAssetResult != null && selectedAsset == null) { PrepareDetailsUi(manager.CurrentAssetResult); } // Check if the user selected something in the PtAsset picker. if (Event.current != null && Event.current.commandName == "ObjectSelectorUpdated") { UnityEngine.Object picked = EditorGUIUtility.GetObjectPickerObject(); ptAssetLocalPath = (picked != null && picked is PtAsset) ? AssetDatabase.GetAssetPath(picked) : PtUtils.GetDefaultPtAssetPath(selectedAsset); PtAnalytics.SendEvent(PtAnalytics.Action.IMPORT_LOCATION_CHANGED); } if (selectedAsset == null) { manager.ClearCurrentAssetResult(); GUILayout.Space(20); GUILayout.Label("Asset not found."); return; } detailsScrollPos = guiHelper.BeginScrollView(detailsScrollPos); const float width = 150; guiHelper.BeginHorizontal(); GUILayout.Label(selectedAsset.displayName, detailsTitleStyle); guiHelper.EndHorizontal(); guiHelper.BeginHorizontal(); GUILayout.Label(selectedAsset.authorName, EditorStyles.wordWrappedLabel); GUILayout.FlexibleSpace(); if (GUILayout.Button("View on Web", GUILayout.MaxWidth(100))) { PtAnalytics.SendEvent(PtAnalytics.Action.BROWSE_VIEW_ON_WEB); Application.OpenURL(selectedAsset.Url); } GUILayout.Space(5); guiHelper.EndHorizontal(); GUILayout.Space(10); Texture2D image = selectedAsset.thumbnailTexture ?? loadingTex; float displayWidth = position.width - 40; float displayHeight = image.height * displayWidth / image.width; displayHeight = Mathf.Min(image.height, displayHeight); displayWidth = Mathf.Min(image.width, displayWidth); GUILayout.Label(image, GUILayout.Width(displayWidth), GUILayout.Height(displayHeight)); if (manager.IsDownloadingAsset(selectedAsset)) { guiHelper.BeginHorizontal(); GUILayout.FlexibleSpace(); GUILayout.Label("Downloading asset. Please wait..."); GUILayout.FlexibleSpace(); guiHelper.EndHorizontal(); guiHelper.EndScrollView(); return; } else if (justImported) { Rect lastRect = GUILayoutUtility.GetLastRect(); Rect boxRect = new Rect(PADDING, lastRect.yMax + PADDING, position.width - 2 * PADDING, IMPORT_SUCCESS_BOX_HEIGHT); GUI.DrawTexture(boxRect, backBarBackgroundTex); GUILayout.Space(20); guiHelper.BeginHorizontal(); GUILayout.FlexibleSpace(); guiHelper.BeginVertical(); GUILayout.Label("Asset successfully imported."); GUILayout.Label("Saved to: " + PtSettings.Instance.assetObjectsPath); GUILayout.Space(10); if (GUILayout.Button("OK")) { // Dismiss. justImported = false; } guiHelper.EndVertical(); GUILayout.FlexibleSpace(); guiHelper.EndHorizontal(); guiHelper.EndScrollView(); return; } GUILayout.Space(5); GUILayout.Label("Import Options", EditorStyles.boldLabel); GUILayout.Space(5); guiHelper.BeginHorizontal(); GUILayout.Space(12); GUILayout.Label("Import Location", GUILayout.Width(width)); GUILayout.FlexibleSpace(); GUILayout.Label(ptAssetLocalPath, EditorStyles.wordWrappedLabel); GUILayout.Space(5); guiHelper.EndHorizontal(); guiHelper.BeginHorizontal(); GUILayout.Space(width - 10); GUILayout.FlexibleSpace(); if (GUILayout.Button("Replace existing...")) { PtAsset current = AssetDatabase.LoadAssetAtPath<PtAsset>(ptAssetLocalPath); EditorGUIUtility.ShowObjectPicker<PtAsset>(current, /* allowSceneObjects */ false, PtAsset.FilterString, 0); } GUILayout.Space(5); guiHelper.EndHorizontal(); EditTimeImportOptions oldOptions = importOptions; importOptions = ImportOptionsGui.ImportOptionsField(importOptions); if (oldOptions.alsoInstantiate != importOptions.alsoInstantiate) { // Persist 'always instantiate' option if it was changed. PtSettings.Instance.defaultImportOptions.alsoInstantiate = importOptions.alsoInstantiate; } SendImportOptionMutationAnalytics(oldOptions, importOptions); GUILayout.Space(10); GUILayout.Box("", GUILayout.ExpandWidth(true), GUILayout.Height(1)); GUILayout.Space(10); guiHelper.BeginHorizontal(); GUIStyle buttonStyle = new GUIStyle(GUI.skin.button); buttonStyle.fontStyle = FontStyle.Bold; buttonStyle.padding = new RectOffset(10, 10, 8, 8); bool importButtonClicked = GUILayout.Button("Import into Project", buttonStyle); GUILayout.FlexibleSpace(); guiHelper.EndHorizontal(); GUILayout.Space(5); if (!File.Exists(PtUtils.ToAbsolutePath(ptAssetLocalPath))) { GUILayout.Label(PolyInternalUtils.ATTRIBUTION_NOTICE, EditorStyles.wordWrappedLabel); } else { GUILayout.Label("WARNING: The indicated asset already exists and will be OVERWRITTEN by " + "the new asset. Existing instances of the old asset will be automatically updated " + "to the new asset.", EditorStyles.wordWrappedLabel); } guiHelper.EndScrollView(); if (importButtonClicked) { if (!ptAssetLocalPath.StartsWith("Assets/") || !ptAssetLocalPath.EndsWith(".asset")) { EditorUtility.DisplayDialog("Invalid import path", "The import path must begin with Assets/ and have the .asset extension.", "OK"); return; } string errorString; if (!ValidateImportOptions(importOptions.baseOptions, out errorString)) { EditorUtility.DisplayDialog("Invalid import options", errorString, "OK"); return; } PtAnalytics.SendEvent(PtAnalytics.Action.IMPORT_STARTED, GetAssetFormatDescription(selectedAsset)); if (previousMode == UiMode.SEARCH) { PtAnalytics.SendEvent(PtAnalytics.Action.IMPORT_STARTED_FROM_SEARCH, GetAssetFormatDescription(selectedAsset)); } manager.StartDownloadAndImport(selectedAsset, ptAssetLocalPath, importOptions); } } /// <summary> /// Returns whether the import options are valid and, if not, a relevant error message to display. /// </summary> private bool ValidateImportOptions(PolyImportOptions options, out string errorString) { switch (options.rescalingMode) { case PolyImportOptions.RescalingMode.CONVERT: if (options.scaleFactor == 0.0f) { errorString = "Scale factor must not be 0."; return false; } break; case PolyImportOptions.RescalingMode.FIT: if (options.desiredSize == 0.0f) { errorString = "Desired size must not be 0."; return false; } break; default: throw new System.Exception("Import options must hvae a valid rescaling mode"); } errorString = null; return true; } /// <summary> /// Returns true if the current UI mode has a back button bar. /// </summary> /// <returns>True if the current UI mode has a back button bar, false otherwise.</returns> private bool HasBackButtonBar() { return mode == UiMode.DETAILS || mode == UiMode.SEARCH; } /// <summary> /// Draws the "Back" button bar. /// </summary> /// <returns>True if the back button was clicked, false otherwise.</returns> private bool DrawBackButtonBar() { guiHelper.BeginArea(new Rect(0, TITLE_BAR_HEIGHT, position.width, BACK_BUTTON_BAR_HEIGHT)); GUI.DrawTexture(new Rect(0, 0, position.width, BACK_BUTTON_BAR_HEIGHT), backBarBackgroundTex); guiHelper.BeginHorizontal(); GUILayout.Space(PADDING); bool backButtonClicked = GUILayout.Button(new GUIContent("Back", backArrowTex), EditorStyles.miniLabel); GUILayout.FlexibleSpace(); guiHelper.EndHorizontal(); guiHelper.EndArea(); return backButtonClicked; } /// <summary> /// Returns a string with all the asset formats of the given asset. /// </summary> /// <param name="asset">The asset.</param> /// <returns>A string with all the comma-separated asset formats of the given asset.</returns> private string GetAssetFormatDescription(PolyAsset asset) { List<string> formatTypes = new List<string>(); if (asset.formats != null) { foreach (PolyFormat format in asset.formats) { formatTypes.Add(format.formatType.ToString()); } } else { // Shouldn't happen [tm]. formatTypes.Add("NULL"); } formatTypes.Sort(); return string.Join(",", formatTypes.ToArray()); } /// <summary> /// Sends Analytics events for mutations in the given import options. /// </summary> /// <param name="before">The options before the mutation.</param> /// <param name="after">The options after the mutation.</param> private void SendImportOptionMutationAnalytics(EditTimeImportOptions before, EditTimeImportOptions after) { if (before.alsoInstantiate != after.alsoInstantiate) { PtAnalytics.SendEvent(PtAnalytics.Action.IMPORT_INSTANTIATE_TOGGLED, after.alsoInstantiate.ToString()); } if (before.baseOptions.desiredSize != after.baseOptions.desiredSize) { PtAnalytics.SendEvent(PtAnalytics.Action.IMPORT_DESIRED_SIZE_SET, after.baseOptions.desiredSize.ToString()); } if (before.baseOptions.recenter != after.baseOptions.recenter) { PtAnalytics.SendEvent(PtAnalytics.Action.IMPORT_RECENTER_TOGGLED, after.baseOptions.recenter.ToString()); } if (before.baseOptions.rescalingMode != after.baseOptions.rescalingMode) { PtAnalytics.SendEvent(PtAnalytics.Action.IMPORT_SCALE_MODE_CHANGED, after.baseOptions.rescalingMode.ToString()); } if (before.baseOptions.scaleFactor != after.baseOptions.scaleFactor) { PtAnalytics.SendEvent(PtAnalytics.Action.IMPORT_SCALE_FACTOR_CHANGED, after.baseOptions.scaleFactor.ToString()); } } private void OnDestroy() { PtDebug.Log("ABW: destroying."); manager.SetRefreshCallback(null); } private struct CategoryInfo { public string key; public string title; public PolyCategory polyCategory; public CategoryInfo(string key, string title, PolyCategory polyCategory = PolyCategory.UNSPECIFIED) { this.key = key; this.title = title; this.polyCategory = polyCategory; } } } }
// 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.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue { internal sealed class StatementSyntaxComparer : SyntaxComparer { internal static readonly StatementSyntaxComparer Default = new StatementSyntaxComparer(); private readonly SyntaxNode _oldRootChild; private readonly SyntaxNode _newRootChild; private readonly SyntaxNode _oldRoot; private readonly SyntaxNode _newRoot; private StatementSyntaxComparer() { } internal StatementSyntaxComparer(SyntaxNode oldRootChild, SyntaxNode newRootChild) { _oldRootChild = oldRootChild; _newRootChild = newRootChild; _oldRoot = oldRootChild.Parent; _newRoot = newRootChild.Parent; } #region Tree Traversal protected internal override bool TryGetParent(SyntaxNode node, out SyntaxNode parent) { parent = node.Parent; while (parent != null && !HasLabel(parent)) { parent = parent.Parent; } return parent != null; } protected internal override IEnumerable<SyntaxNode> GetChildren(SyntaxNode node) { Debug.Assert(HasLabel(node)); if (node == _oldRoot || node == _newRoot) { return EnumerateRootChildren(node); } return IsLeaf(node) ? null : EnumerateNonRootChildren(node); } private IEnumerable<SyntaxNode> EnumerateNonRootChildren(SyntaxNode node) { foreach (var child in node.ChildNodes()) { if (LambdaUtilities.IsLambdaBodyStatementOrExpression(child)) { continue; } if (HasLabel(child)) { yield return child; } else { foreach (var descendant in child.DescendantNodes(DescendIntoChildren)) { if (HasLabel(descendant)) { yield return descendant; } } } } } private IEnumerable<SyntaxNode> EnumerateRootChildren(SyntaxNode root) { Debug.Assert(_oldRoot != null && _newRoot != null); var child = (root == _oldRoot) ? _oldRootChild : _newRootChild; if (GetLabelImpl(child) != Label.Ignored) { yield return child; } else { foreach (var descendant in child.DescendantNodes(DescendIntoChildren)) { if (HasLabel(descendant)) { yield return descendant; } } } } private bool DescendIntoChildren(SyntaxNode node) { return !LambdaUtilities.IsLambdaBodyStatementOrExpression(node) && !HasLabel(node); } protected internal sealed override IEnumerable<SyntaxNode> GetDescendants(SyntaxNode node) { if (node == _oldRoot || node == _newRoot) { Debug.Assert(_oldRoot != null && _newRoot != null); var rootChild = (node == _oldRoot) ? _oldRootChild : _newRootChild; if (HasLabel(rootChild)) { yield return rootChild; } node = rootChild; } // TODO: avoid allocation of closure foreach (var descendant in node.DescendantNodes(descendIntoChildren: c => !IsLeaf(c) && (c == node || !LambdaUtilities.IsLambdaBodyStatementOrExpression(c)))) { if (!LambdaUtilities.IsLambdaBodyStatementOrExpression(descendant) && HasLabel(descendant)) { yield return descendant; } } } private static bool IsLeaf(SyntaxNode node) { bool isLeaf; Classify(node.Kind(), node, out isLeaf); return isLeaf; } #endregion #region Labels // Assumptions: // - Each listed label corresponds to one or more syntax kinds. // - Nodes with same labels might produce Update edits, nodes with different labels don't. // - If IsTiedToParent(label) is true for a label then all its possible parent labels must precede the label. // (i.e. both MethodDeclaration and TypeDeclaration must precede TypeParameter label). internal enum Label { ConstructorDeclaration, Block, CheckedStatement, UnsafeStatement, TryStatement, CatchClause, // tied to parent CatchDeclaration, // tied to parent CatchFilterClause, // tied to parent FinallyClause, // tied to parent ForStatement, ForStatementPart, // tied to parent ForEachStatement, ForEachComponentStatement, UsingStatement, FixedStatement, LockStatement, WhileStatement, DoStatement, IfStatement, ElseClause, // tied to parent SwitchStatement, SwitchSection, YieldStatement, // tied to parent GotoStatement, GotoCaseStatement, BreakContinueStatement, ReturnThrowStatement, ExpressionStatement, LabeledStatement, // TODO: // Ideally we could declare LocalVariableDeclarator tied to the first enclosing node that defines local scope (block, foreach, etc.) // Also consider handling LocalDeclarationStatement as just a bag of variable declarators, // so that variable declarators contained in one can be matched with variable declarators contained in the other. LocalDeclarationStatement, // tied to parent LocalVariableDeclaration, // tied to parent LocalVariableDeclarator, // tied to parent AwaitExpression, LocalFunction, Lambda, FromClause, QueryBody, FromClauseLambda, // tied to parent LetClauseLambda, // tied to parent WhereClauseLambda, // tied to parent OrderByClause, // tied to parent OrderingLambda, // tied to parent SelectClauseLambda, // tied to parent JoinClauseLambda, // tied to parent JoinIntoClause, // tied to parent GroupClauseLambda, // tied to parent QueryContinuation, // tied to parent // helpers: Count, Ignored = IgnoredNode } private static int TiedToAncestor(Label label) { switch (label) { case Label.LocalDeclarationStatement: case Label.LocalVariableDeclaration: case Label.LocalVariableDeclarator: case Label.GotoCaseStatement: case Label.BreakContinueStatement: case Label.ElseClause: case Label.CatchClause: case Label.CatchDeclaration: case Label.CatchFilterClause: case Label.FinallyClause: case Label.ForStatementPart: case Label.YieldStatement: case Label.LocalFunction: case Label.FromClauseLambda: case Label.LetClauseLambda: case Label.WhereClauseLambda: case Label.OrderByClause: case Label.OrderingLambda: case Label.SelectClauseLambda: case Label.JoinClauseLambda: case Label.JoinIntoClause: case Label.GroupClauseLambda: case Label.QueryContinuation: return 1; default: return 0; } } /// <summary> /// <paramref name="nodeOpt"/> is null only when comparing value equality of a tree node. /// </summary> internal static Label Classify(SyntaxKind kind, SyntaxNode nodeOpt, out bool isLeaf) { // Notes: // A descendant of a leaf node may be a labeled node that we don't want to visit if // we are comparing its parent node (used for lambda bodies). // // Expressions are ignored but they may contain nodes that should be matched by tree comparer. // (e.g. lambdas, declaration expressions). Descending to these nodes is handled in EnumerateChildren. isLeaf = false; // If the node is a for loop Initializer, Condition, or Incrementor expression we label it as "ForStatementPart". // We need to capture it in the match since these expressions can be "active statements" and as such we need to map them. // // The parent is not available only when comparing nodes for value equality. if (nodeOpt != null && nodeOpt.Parent.IsKind(SyntaxKind.ForStatement) && nodeOpt is ExpressionSyntax) { return Label.ForStatementPart; } switch (kind) { case SyntaxKind.ConstructorDeclaration: // Root when matching constructor bodies. return Label.ConstructorDeclaration; case SyntaxKind.Block: return Label.Block; case SyntaxKind.LocalDeclarationStatement: return Label.LocalDeclarationStatement; case SyntaxKind.VariableDeclaration: return Label.LocalVariableDeclaration; case SyntaxKind.VariableDeclarator: return Label.LocalVariableDeclarator; case SyntaxKind.LabeledStatement: return Label.LabeledStatement; case SyntaxKind.EmptyStatement: isLeaf = true; return Label.Ignored; case SyntaxKind.GotoStatement: isLeaf = true; return Label.GotoStatement; case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoDefaultStatement: isLeaf = true; return Label.GotoCaseStatement; case SyntaxKind.BreakStatement: case SyntaxKind.ContinueStatement: isLeaf = true; return Label.BreakContinueStatement; case SyntaxKind.ReturnStatement: case SyntaxKind.ThrowStatement: return Label.ReturnThrowStatement; case SyntaxKind.ExpressionStatement: return Label.ExpressionStatement; case SyntaxKind.YieldBreakStatement: case SyntaxKind.YieldReturnStatement: return Label.YieldStatement; case SyntaxKind.DoStatement: return Label.DoStatement; case SyntaxKind.WhileStatement: return Label.WhileStatement; case SyntaxKind.ForStatement: return Label.ForStatement; case SyntaxKind.ForEachStatement: return Label.ForEachStatement; case SyntaxKind.ForEachVariableStatement: return Label.ForEachComponentStatement; case SyntaxKind.UsingStatement: return Label.UsingStatement; case SyntaxKind.FixedStatement: return Label.FixedStatement; case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: return Label.CheckedStatement; case SyntaxKind.UnsafeStatement: return Label.UnsafeStatement; case SyntaxKind.LockStatement: return Label.LockStatement; case SyntaxKind.IfStatement: return Label.IfStatement; case SyntaxKind.ElseClause: return Label.ElseClause; case SyntaxKind.SwitchStatement: return Label.SwitchStatement; case SyntaxKind.SwitchSection: return Label.SwitchSection; case SyntaxKind.CaseSwitchLabel: case SyntaxKind.DefaultSwitchLabel: // Switch labels are included in the "value" of the containing switch section. // We don't need to analyze case expressions. isLeaf = true; return Label.Ignored; case SyntaxKind.TryStatement: return Label.TryStatement; case SyntaxKind.CatchClause: return Label.CatchClause; case SyntaxKind.CatchDeclaration: // the declarator of the exception variable return Label.CatchDeclaration; case SyntaxKind.CatchFilterClause: return Label.CatchFilterClause; case SyntaxKind.FinallyClause: return Label.FinallyClause; case SyntaxKind.LocalFunctionStatement: return Label.LocalFunction; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.AnonymousMethodExpression: return Label.Lambda; case SyntaxKind.FromClause: // The first from clause of a query is not a lambda. // We have to assign it a label different from "FromClauseLambda" // so that we won't match lambda-from to non-lambda-from. // // Since FromClause declares range variables we need to include it in the map, // so that we are able to map range variable declarations. // Therefore we assign it a dedicated label. // // The parent is not available only when comparing nodes for value equality. // In that case it doesn't matter what label the node has as long as it has some. if (nodeOpt == null || nodeOpt.Parent.IsKind(SyntaxKind.QueryExpression)) { return Label.FromClause; } return Label.FromClauseLambda; case SyntaxKind.QueryBody: return Label.QueryBody; case SyntaxKind.QueryContinuation: return Label.QueryContinuation; case SyntaxKind.LetClause: return Label.LetClauseLambda; case SyntaxKind.WhereClause: return Label.WhereClauseLambda; case SyntaxKind.OrderByClause: return Label.OrderByClause; case SyntaxKind.AscendingOrdering: case SyntaxKind.DescendingOrdering: return Label.OrderingLambda; case SyntaxKind.SelectClause: return Label.SelectClauseLambda; case SyntaxKind.JoinClause: return Label.JoinClauseLambda; case SyntaxKind.JoinIntoClause: return Label.JoinIntoClause; case SyntaxKind.GroupClause: return Label.GroupClauseLambda; case SyntaxKind.IdentifierName: case SyntaxKind.QualifiedName: case SyntaxKind.GenericName: case SyntaxKind.TypeArgumentList: case SyntaxKind.AliasQualifiedName: case SyntaxKind.PredefinedType: case SyntaxKind.ArrayType: case SyntaxKind.ArrayRankSpecifier: case SyntaxKind.PointerType: case SyntaxKind.NullableType: case SyntaxKind.OmittedTypeArgument: case SyntaxKind.NameColon: case SyntaxKind.StackAllocArrayCreationExpression: case SyntaxKind.OmittedArraySizeExpression: case SyntaxKind.ThisExpression: case SyntaxKind.BaseExpression: case SyntaxKind.ArgListExpression: case SyntaxKind.NumericLiteralExpression: case SyntaxKind.StringLiteralExpression: case SyntaxKind.CharacterLiteralExpression: case SyntaxKind.TrueLiteralExpression: case SyntaxKind.FalseLiteralExpression: case SyntaxKind.NullLiteralExpression: case SyntaxKind.TypeOfExpression: case SyntaxKind.SizeOfExpression: case SyntaxKind.DefaultExpression: // can't contain a lambda/await/anonymous type: isLeaf = true; return Label.Ignored; case SyntaxKind.AwaitExpression: return Label.AwaitExpression; default: // any other node may contain a lambda: return Label.Ignored; } } protected internal override int GetLabel(SyntaxNode node) { return (int)GetLabelImpl(node); } internal static Label GetLabelImpl(SyntaxNode node) { bool isLeaf; return Classify(node.Kind(), node, out isLeaf); } internal static bool HasLabel(SyntaxNode node) { return GetLabelImpl(node) != Label.Ignored; } protected internal override int LabelCount { get { return (int)Label.Count; } } protected internal override int TiedToAncestor(int label) { return TiedToAncestor((Label)label); } #endregion #region Comparisons internal static bool IgnoreLabeledChild(SyntaxKind kind) { // In most cases we can determine Label based on child kind. // The only cases when we can't are // - for Initializer, Condition and Incrementor expressions in ForStatement. // - first from clause of a query expression. bool isLeaf; return Classify(kind, null, out isLeaf) != Label.Ignored; } public override bool ValuesEqual(SyntaxNode left, SyntaxNode right) { // only called from the tree matching alg, which only operates on nodes that are labeled. Debug.Assert(HasLabel(left)); Debug.Assert(HasLabel(right)); Func<SyntaxKind, bool> ignoreChildNode; switch (left.Kind()) { case SyntaxKind.SwitchSection: return Equal((SwitchSectionSyntax)left, (SwitchSectionSyntax)right); case SyntaxKind.ForStatement: // The only children of ForStatement are labeled nodes and punctuation. return true; default: // When comparing the value of a node with its partner we are deciding whether to add an Update edit for the pair. // If the actual change is under a descendant labeled node we don't want to attribute it to the node being compared, // so we skip all labeled children when recursively checking for equivalence. if (IsLeaf(left)) { ignoreChildNode = null; } else { ignoreChildNode = IgnoreLabeledChild; } break; } return SyntaxFactory.AreEquivalent(left, right, ignoreChildNode); } private bool Equal(SwitchSectionSyntax left, SwitchSectionSyntax right) { return SyntaxFactory.AreEquivalent(left.Labels, right.Labels, null) && SyntaxFactory.AreEquivalent(left.Statements, right.Statements, ignoreChildNode: IgnoreLabeledChild); } protected override bool TryComputeWeightedDistance(SyntaxNode leftNode, SyntaxNode rightNode, out double distance) { switch (leftNode.Kind()) { case SyntaxKind.VariableDeclarator: distance = ComputeDistance( ((VariableDeclaratorSyntax)leftNode).Identifier, ((VariableDeclaratorSyntax)rightNode).Identifier); return true; case SyntaxKind.ForStatement: var leftFor = (ForStatementSyntax)leftNode; var rightFor = (ForStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftFor, rightFor); return true; case SyntaxKind.ForEachStatement: { var leftForEach = (ForEachStatementSyntax)leftNode; var rightForEach = (ForEachStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftForEach, rightForEach); return true; } case SyntaxKind.UsingStatement: var leftUsing = (UsingStatementSyntax)leftNode; var rightUsing = (UsingStatementSyntax)rightNode; if (leftUsing.Declaration != null && rightUsing.Declaration != null) { distance = ComputeWeightedDistance( leftUsing.Declaration, leftUsing.Statement, rightUsing.Declaration, rightUsing.Statement); } else { distance = ComputeWeightedDistance( (SyntaxNode)leftUsing.Expression ?? leftUsing.Declaration, leftUsing.Statement, (SyntaxNode)rightUsing.Expression ?? rightUsing.Declaration, rightUsing.Statement); } return true; case SyntaxKind.LockStatement: var leftLock = (LockStatementSyntax)leftNode; var rightLock = (LockStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftLock.Expression, leftLock.Statement, rightLock.Expression, rightLock.Statement); return true; case SyntaxKind.FixedStatement: var leftFixed = (FixedStatementSyntax)leftNode; var rightFixed = (FixedStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftFixed.Declaration, leftFixed.Statement, rightFixed.Declaration, rightFixed.Statement); return true; case SyntaxKind.WhileStatement: var leftWhile = (WhileStatementSyntax)leftNode; var rightWhile = (WhileStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftWhile.Condition, leftWhile.Statement, rightWhile.Condition, rightWhile.Statement); return true; case SyntaxKind.DoStatement: var leftDo = (DoStatementSyntax)leftNode; var rightDo = (DoStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftDo.Condition, leftDo.Statement, rightDo.Condition, rightDo.Statement); return true; case SyntaxKind.IfStatement: var leftIf = (IfStatementSyntax)leftNode; var rightIf = (IfStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftIf.Condition, leftIf.Statement, rightIf.Condition, rightIf.Statement); return true; case SyntaxKind.Block: BlockSyntax leftBlock = (BlockSyntax)leftNode; BlockSyntax rightBlock = (BlockSyntax)rightNode; return TryComputeWeightedDistance(leftBlock, rightBlock, out distance); case SyntaxKind.CatchClause: distance = ComputeWeightedDistance((CatchClauseSyntax)leftNode, (CatchClauseSyntax)rightNode); return true; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.AnonymousMethodExpression: distance = ComputeWeightedDistanceOfLambdas(leftNode, rightNode); return true; case SyntaxKind.LocalFunctionStatement: distance = ComputeWeightedDistanceOfLocalFunctions((LocalFunctionStatementSyntax)leftNode, (LocalFunctionStatementSyntax)rightNode); return true; case SyntaxKind.YieldBreakStatement: case SyntaxKind.YieldReturnStatement: // Ignore the expression of yield return. The structure of the state machine is more important than the yielded values. distance = (leftNode.RawKind == rightNode.RawKind) ? 0.0 : 0.1; return true; default: distance = 0; return false; } } private static double ComputeWeightedDistanceOfLocalFunctions(LocalFunctionStatementSyntax leftNode, LocalFunctionStatementSyntax rightNode) { double modifierDistance = ComputeDistance(leftNode.Modifiers, rightNode.Modifiers); double returnTypeDistance = ComputeDistance(leftNode.ReturnType, rightNode.ReturnType); double identifierDistance = ComputeDistance(leftNode.Identifier, rightNode.Identifier); double typeParameterDistance = ComputeDistance(leftNode.TypeParameterList, rightNode.TypeParameterList); double parameterDistance = ComputeDistance(leftNode.ParameterList.Parameters, rightNode.ParameterList.Parameters); double bodyDistance = ComputeDistance((SyntaxNode)leftNode.Body ?? leftNode.ExpressionBody, (SyntaxNode)rightNode.Body ?? rightNode.ExpressionBody); return modifierDistance * 0.1 + returnTypeDistance * 0.1 + identifierDistance * 0.2 + typeParameterDistance * 0.2 + parameterDistance * 0.2 + bodyDistance * 0.2; } private static double ComputeWeightedDistanceOfLambdas(SyntaxNode leftNode, SyntaxNode rightNode) { IEnumerable<SyntaxToken> leftParameters, rightParameters; SyntaxToken leftAsync, rightAsync; SyntaxNode leftBody, rightBody; GetLambdaParts(leftNode, out leftParameters, out leftAsync, out leftBody); GetLambdaParts(rightNode, out rightParameters, out rightAsync, out rightBody); if ((leftAsync.Kind() == SyntaxKind.AsyncKeyword) != (rightAsync.Kind() == SyntaxKind.AsyncKeyword)) { return 1.0; } double parameterDistance = ComputeDistance(leftParameters, rightParameters); double bodyDistance = ComputeDistance(leftBody, rightBody); return parameterDistance * 0.6 + bodyDistance * 0.4; } private static void GetLambdaParts(SyntaxNode lambda, out IEnumerable<SyntaxToken> parameters, out SyntaxToken asyncKeyword, out SyntaxNode body) { switch (lambda.Kind()) { case SyntaxKind.SimpleLambdaExpression: var simple = (SimpleLambdaExpressionSyntax)lambda; parameters = simple.Parameter.DescendantTokens(); asyncKeyword = simple.AsyncKeyword; body = simple.Body; break; case SyntaxKind.ParenthesizedLambdaExpression: var parenthesized = (ParenthesizedLambdaExpressionSyntax)lambda; parameters = GetDescendantTokensIgnoringSeparators(parenthesized.ParameterList.Parameters); asyncKeyword = parenthesized.AsyncKeyword; body = parenthesized.Body; break; case SyntaxKind.AnonymousMethodExpression: var anonymous = (AnonymousMethodExpressionSyntax)lambda; if (anonymous.ParameterList != null) { parameters = GetDescendantTokensIgnoringSeparators(anonymous.ParameterList.Parameters); } else { parameters = SpecializedCollections.EmptyEnumerable<SyntaxToken>(); } asyncKeyword = anonymous.AsyncKeyword; body = anonymous.Block; break; default: throw ExceptionUtilities.Unreachable; } } private bool TryComputeWeightedDistance(BlockSyntax leftBlock, BlockSyntax rightBlock, out double distance) { // No block can be matched with the root block. // Note that in constructors the root is the constructor declaration, since we need to include // the constructor initializer in the match. if (leftBlock.Parent == null || rightBlock.Parent == null || leftBlock.Parent.IsKind(SyntaxKind.ConstructorDeclaration) || rightBlock.Parent.IsKind(SyntaxKind.ConstructorDeclaration)) { distance = 0.0; return true; } if (leftBlock.Parent.Kind() != rightBlock.Parent.Kind()) { distance = 0.2 + 0.8 * ComputeWeightedBlockDistance(leftBlock, rightBlock); return true; } switch (leftBlock.Parent.Kind()) { case SyntaxKind.IfStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: case SyntaxKind.ForStatement: case SyntaxKind.WhileStatement: case SyntaxKind.DoStatement: case SyntaxKind.FixedStatement: case SyntaxKind.LockStatement: case SyntaxKind.UsingStatement: case SyntaxKind.SwitchSection: case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.AnonymousMethodExpression: // value distance of the block body is included: distance = GetDistance(leftBlock.Parent, rightBlock.Parent); return true; case SyntaxKind.CatchClause: var leftCatch = (CatchClauseSyntax)leftBlock.Parent; var rightCatch = (CatchClauseSyntax)rightBlock.Parent; if (leftCatch.Declaration == null && leftCatch.Filter == null && rightCatch.Declaration == null && rightCatch.Filter == null) { var leftTry = (TryStatementSyntax)leftCatch.Parent; var rightTry = (TryStatementSyntax)rightCatch.Parent; distance = 0.5 * ComputeValueDistance(leftTry.Block, rightTry.Block) + 0.5 * ComputeValueDistance(leftBlock, rightBlock); } else { // value distance of the block body is included: distance = GetDistance(leftBlock.Parent, rightBlock.Parent); } return true; case SyntaxKind.Block: case SyntaxKind.LabeledStatement: distance = ComputeWeightedBlockDistance(leftBlock, rightBlock); return true; case SyntaxKind.UnsafeStatement: case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: case SyntaxKind.ElseClause: case SyntaxKind.FinallyClause: case SyntaxKind.TryStatement: distance = 0.2 * ComputeValueDistance(leftBlock, rightBlock); return true; default: throw ExceptionUtilities.Unreachable; } } private static double ComputeWeightedBlockDistance(BlockSyntax leftBlock, BlockSyntax rightBlock) { double distance; if (TryComputeLocalsDistance(leftBlock, rightBlock, out distance)) { return distance; } return ComputeValueDistance(leftBlock, rightBlock); } private static double ComputeWeightedDistance(CatchClauseSyntax left, CatchClauseSyntax right) { double blockDistance = ComputeDistance(left.Block, right.Block); double distance = CombineOptional(blockDistance, left.Declaration, right.Declaration, left.Filter, right.Filter); return AdjustForLocalsInBlock(distance, left.Block, right.Block, localsWeight: 0.3); } private static double ComputeWeightedDistance(ForEachStatementSyntax left, ForEachStatementSyntax right) { double statementDistance = ComputeDistance(left.Statement, right.Statement); double expressionDistance = ComputeDistance(left.Expression, right.Expression); double identifierDistance = ComputeDistance(left.Identifier, right.Identifier); double distance = identifierDistance * 0.7 + expressionDistance * 0.2 + statementDistance * 0.1; return AdjustForLocalsInBlock(distance, left.Statement, right.Statement, localsWeight: 0.6); } private static double ComputeWeightedDistance(ForStatementSyntax left, ForStatementSyntax right) { double statementDistance = ComputeDistance(left.Statement, right.Statement); double conditionDistance = ComputeDistance(left.Condition, right.Condition); double incDistance = ComputeDistance( GetDescendantTokensIgnoringSeparators(left.Incrementors), GetDescendantTokensIgnoringSeparators(right.Incrementors)); double distance = conditionDistance * 0.3 + incDistance * 0.3 + statementDistance * 0.4; double localsDistance; if (TryComputeLocalsDistance(left.Declaration, right.Declaration, out localsDistance)) { distance = distance * 0.4 + localsDistance * 0.6; } return distance; } private static double ComputeWeightedDistance( VariableDeclarationSyntax leftVariables, StatementSyntax leftStatement, VariableDeclarationSyntax rightVariables, StatementSyntax rightStatement) { double distance = ComputeDistance(leftStatement, rightStatement); // Put maximum weight behind the variables declared in the header of the statement. double localsDistance; if (TryComputeLocalsDistance(leftVariables, rightVariables, out localsDistance)) { distance = distance * 0.4 + localsDistance * 0.6; } // If the statement is a block that declares local variables, // weight them more than the rest of the statement. return AdjustForLocalsInBlock(distance, leftStatement, rightStatement, localsWeight: 0.2); } private static double ComputeWeightedDistance( SyntaxNode leftHeaderOpt, StatementSyntax leftStatement, SyntaxNode rightHeaderOpt, StatementSyntax rightStatement) { Debug.Assert(leftStatement != null); Debug.Assert(rightStatement != null); double headerDistance = ComputeDistance(leftHeaderOpt, rightHeaderOpt); double statementDistance = ComputeDistance(leftStatement, rightStatement); double distance = headerDistance * 0.6 + statementDistance * 0.4; return AdjustForLocalsInBlock(distance, leftStatement, rightStatement, localsWeight: 0.5); } private static double AdjustForLocalsInBlock( double distance, StatementSyntax leftStatement, StatementSyntax rightStatement, double localsWeight) { // If the statement is a block that declares local variables, // weight them more than the rest of the statement. if (leftStatement.Kind() == SyntaxKind.Block && rightStatement.Kind() == SyntaxKind.Block) { double localsDistance; if (TryComputeLocalsDistance((BlockSyntax)leftStatement, (BlockSyntax)rightStatement, out localsDistance)) { return localsDistance * localsWeight + distance * (1 - localsWeight); } } return distance; } private static bool TryComputeLocalsDistance(VariableDeclarationSyntax leftOpt, VariableDeclarationSyntax rightOpt, out double distance) { List<SyntaxToken> leftLocals = null; List<SyntaxToken> rightLocals = null; if (leftOpt != null) { GetLocalNames(leftOpt, ref leftLocals); } if (rightOpt != null) { GetLocalNames(rightOpt, ref rightLocals); } if (leftLocals == null || rightLocals == null) { distance = 0; return false; } distance = ComputeDistance(leftLocals, rightLocals); return true; } private static bool TryComputeLocalsDistance(BlockSyntax left, BlockSyntax right, out double distance) { List<SyntaxToken> leftLocals = null; List<SyntaxToken> rightLocals = null; GetLocalNames(left, ref leftLocals); GetLocalNames(right, ref rightLocals); if (leftLocals == null || rightLocals == null) { distance = 0; return false; } distance = ComputeDistance(leftLocals, rightLocals); return true; } // doesn't include variables declared in declaration expressions private static void GetLocalNames(BlockSyntax block, ref List<SyntaxToken> result) { foreach (var child in block.ChildNodes()) { if (child.IsKind(SyntaxKind.LocalDeclarationStatement)) { GetLocalNames(((LocalDeclarationStatementSyntax)child).Declaration, ref result); } } } // doesn't include variables declared in declaration expressions private static void GetLocalNames(VariableDeclarationSyntax localDeclaration, ref List<SyntaxToken> result) { foreach (var local in localDeclaration.Variables) { if (result == null) { result = new List<SyntaxToken>(); } result.Add(local.Identifier); } } private static double CombineOptional( double distance0, SyntaxNode leftOpt1, SyntaxNode rightOpt1, SyntaxNode leftOpt2, SyntaxNode rightOpt2, double weight0 = 0.8, double weight1 = 0.5) { bool one = leftOpt1 != null || rightOpt1 != null; bool two = leftOpt2 != null || rightOpt2 != null; if (!one && !two) { return distance0; } double distance1 = ComputeDistance(leftOpt1, rightOpt1); double distance2 = ComputeDistance(leftOpt2, rightOpt2); double d; if (one && two) { d = distance1 * weight1 + distance2 * (1 - weight1); } else if (one) { d = distance1; } else { d = distance2; } return distance0 * weight0 + d * (1 - weight0); } #endregion } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: A1026Response.txt #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.ProtocolBuffers; using pbc = global::Google.ProtocolBuffers.Collections; using pbd = global::Google.ProtocolBuffers.Descriptors; using scg = global::System.Collections.Generic; namespace DolphinServer.ProtoEntity { namespace Proto { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class A1026Response { #region Extension registration public static void RegisterAllExtensions(pb::ExtensionRegistry registry) { } #endregion #region Static variables internal static pbd::MessageDescriptor internal__static_A1026Response__Descriptor; internal static pb::FieldAccess.FieldAccessorTable<global::DolphinServer.ProtoEntity.A1026Response, global::DolphinServer.ProtoEntity.A1026Response.Builder> internal__static_A1026Response__FieldAccessorTable; internal static pbd::MessageDescriptor internal__static_A1026GameResult__Descriptor; internal static pb::FieldAccess.FieldAccessorTable<global::DolphinServer.ProtoEntity.A1026GameResult, global::DolphinServer.ProtoEntity.A1026GameResult.Builder> internal__static_A1026GameResult__FieldAccessorTable; #endregion #region Descriptor public static pbd::FileDescriptor Descriptor { get { return descriptor; } } private static pbd::FileDescriptor descriptor; static A1026Response() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChFBMTAyNlJlc3BvbnNlLnR4dCJYCg1BMTAyNlJlc3BvbnNlEhEKCUVycm9y", "SW5mbxgBIAEoCRIRCglFcnJvckNvZGUYAiABKAUSIQoHR1Jlc3VsdBgDIAMo", "CzIQLkExMDI2R2FtZVJlc3VsdCJKCg9BMTAyNkdhbWVSZXN1bHQSFgoOUmVz", "dWx0QWN0aW9uSWQYASABKAkSDQoFU2NvcmUYAiABKAUSEAoIRGF0ZVRpbWUY", "AyABKAlCHKoCGURvbHBoaW5TZXJ2ZXIuUHJvdG9FbnRpdHk=")); pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) { descriptor = root; internal__static_A1026Response__Descriptor = Descriptor.MessageTypes[0]; internal__static_A1026Response__FieldAccessorTable = new pb::FieldAccess.FieldAccessorTable<global::DolphinServer.ProtoEntity.A1026Response, global::DolphinServer.ProtoEntity.A1026Response.Builder>(internal__static_A1026Response__Descriptor, new string[] { "ErrorInfo", "ErrorCode", "GResult", }); internal__static_A1026GameResult__Descriptor = Descriptor.MessageTypes[1]; internal__static_A1026GameResult__FieldAccessorTable = new pb::FieldAccess.FieldAccessorTable<global::DolphinServer.ProtoEntity.A1026GameResult, global::DolphinServer.ProtoEntity.A1026GameResult.Builder>(internal__static_A1026GameResult__Descriptor, new string[] { "ResultActionId", "Score", "DateTime", }); pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance(); RegisterAllExtensions(registry); return registry; }; pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, new pbd::FileDescriptor[] { }, assigner); } #endregion } } #region Messages [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class A1026Response : pb::GeneratedMessage<A1026Response, A1026Response.Builder> { private A1026Response() { } private static readonly A1026Response defaultInstance = new A1026Response().MakeReadOnly(); private static readonly string[] _a1026ResponseFieldNames = new string[] { "ErrorCode", "ErrorInfo", "GResult" }; private static readonly uint[] _a1026ResponseFieldTags = new uint[] { 16, 10, 26 }; public static A1026Response DefaultInstance { get { return defaultInstance; } } public override A1026Response DefaultInstanceForType { get { return DefaultInstance; } } protected override A1026Response ThisMessage { get { return this; } } public static pbd::MessageDescriptor Descriptor { get { return global::DolphinServer.ProtoEntity.Proto.A1026Response.internal__static_A1026Response__Descriptor; } } protected override pb::FieldAccess.FieldAccessorTable<A1026Response, A1026Response.Builder> InternalFieldAccessors { get { return global::DolphinServer.ProtoEntity.Proto.A1026Response.internal__static_A1026Response__FieldAccessorTable; } } public const int ErrorInfoFieldNumber = 1; private bool hasErrorInfo; private string errorInfo_ = ""; public bool HasErrorInfo { get { return hasErrorInfo; } } public string ErrorInfo { get { return errorInfo_; } } public const int ErrorCodeFieldNumber = 2; private bool hasErrorCode; private int errorCode_; public bool HasErrorCode { get { return hasErrorCode; } } public int ErrorCode { get { return errorCode_; } } public const int GResultFieldNumber = 3; private pbc::PopsicleList<global::DolphinServer.ProtoEntity.A1026GameResult> gResult_ = new pbc::PopsicleList<global::DolphinServer.ProtoEntity.A1026GameResult>(); public scg::IList<global::DolphinServer.ProtoEntity.A1026GameResult> GResultList { get { return gResult_; } } public int GResultCount { get { return gResult_.Count; } } public global::DolphinServer.ProtoEntity.A1026GameResult GetGResult(int index) { return gResult_[index]; } public override bool IsInitialized { get { return true; } } public override void WriteTo(pb::ICodedOutputStream output) { CalcSerializedSize(); string[] field_names = _a1026ResponseFieldNames; if (hasErrorInfo) { output.WriteString(1, field_names[1], ErrorInfo); } if (hasErrorCode) { output.WriteInt32(2, field_names[0], ErrorCode); } if (gResult_.Count > 0) { output.WriteMessageArray(3, field_names[2], gResult_); } UnknownFields.WriteTo(output); } private int memoizedSerializedSize = -1; public override int SerializedSize { get { int size = memoizedSerializedSize; if (size != -1) return size; return CalcSerializedSize(); } } private int CalcSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasErrorInfo) { size += pb::CodedOutputStream.ComputeStringSize(1, ErrorInfo); } if (hasErrorCode) { size += pb::CodedOutputStream.ComputeInt32Size(2, ErrorCode); } foreach (global::DolphinServer.ProtoEntity.A1026GameResult element in GResultList) { size += pb::CodedOutputStream.ComputeMessageSize(3, element); } size += UnknownFields.SerializedSize; memoizedSerializedSize = size; return size; } public static A1026Response ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static A1026Response ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static A1026Response ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static A1026Response ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static A1026Response ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static A1026Response ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static A1026Response ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static A1026Response ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static A1026Response ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static A1026Response ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private A1026Response MakeReadOnly() { gResult_.MakeReadOnly(); return this; } public static Builder CreateBuilder() { return new Builder(); } public override Builder ToBuilder() { return CreateBuilder(this); } public override Builder CreateBuilderForType() { return new Builder(); } public static Builder CreateBuilder(A1026Response prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::GeneratedBuilder<A1026Response, Builder> { protected override Builder ThisBuilder { get { return this; } } public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(A1026Response cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } private bool resultIsReadOnly; private A1026Response result; private A1026Response PrepareBuilder() { if (resultIsReadOnly) { A1026Response original = result; result = new A1026Response(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override bool IsInitialized { get { return result.IsInitialized; } } protected override A1026Response MessageBeingBuilt { get { return PrepareBuilder(); } } public override Builder Clear() { result = DefaultInstance; resultIsReadOnly = true; return this; } public override Builder Clone() { if (resultIsReadOnly) { return new Builder(result); } else { return new Builder().MergeFrom(result); } } public override pbd::MessageDescriptor DescriptorForType { get { return global::DolphinServer.ProtoEntity.A1026Response.Descriptor; } } public override A1026Response DefaultInstanceForType { get { return global::DolphinServer.ProtoEntity.A1026Response.DefaultInstance; } } public override A1026Response BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessage other) { if (other is A1026Response) { return MergeFrom((A1026Response) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(A1026Response other) { if (other == global::DolphinServer.ProtoEntity.A1026Response.DefaultInstance) return this; PrepareBuilder(); if (other.HasErrorInfo) { ErrorInfo = other.ErrorInfo; } if (other.HasErrorCode) { ErrorCode = other.ErrorCode; } if (other.gResult_.Count != 0) { result.gResult_.Add(other.gResult_); } this.MergeUnknownFields(other.UnknownFields); return this; } public override Builder MergeFrom(pb::ICodedInputStream input) { return MergeFrom(input, pb::ExtensionRegistry.Empty); } public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { PrepareBuilder(); pb::UnknownFieldSet.Builder unknownFields = null; uint tag; string field_name; while (input.ReadTag(out tag, out field_name)) { if(tag == 0 && field_name != null) { int field_ordinal = global::System.Array.BinarySearch(_a1026ResponseFieldNames, field_name, global::System.StringComparer.Ordinal); if(field_ordinal >= 0) tag = _a1026ResponseFieldTags[field_ordinal]; else { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); continue; } } switch (tag) { case 0: { throw pb::InvalidProtocolBufferException.InvalidTag(); } default: { if (pb::WireFormat.IsEndGroupTag(tag)) { if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); break; } case 10: { result.hasErrorInfo = input.ReadString(ref result.errorInfo_); break; } case 16: { result.hasErrorCode = input.ReadInt32(ref result.errorCode_); break; } case 26: { input.ReadMessageArray(tag, field_name, result.gResult_, global::DolphinServer.ProtoEntity.A1026GameResult.DefaultInstance, extensionRegistry); break; } } } if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } public bool HasErrorInfo { get { return result.hasErrorInfo; } } public string ErrorInfo { get { return result.ErrorInfo; } set { SetErrorInfo(value); } } public Builder SetErrorInfo(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasErrorInfo = true; result.errorInfo_ = value; return this; } public Builder ClearErrorInfo() { PrepareBuilder(); result.hasErrorInfo = false; result.errorInfo_ = ""; return this; } public bool HasErrorCode { get { return result.hasErrorCode; } } public int ErrorCode { get { return result.ErrorCode; } set { SetErrorCode(value); } } public Builder SetErrorCode(int value) { PrepareBuilder(); result.hasErrorCode = true; result.errorCode_ = value; return this; } public Builder ClearErrorCode() { PrepareBuilder(); result.hasErrorCode = false; result.errorCode_ = 0; return this; } public pbc::IPopsicleList<global::DolphinServer.ProtoEntity.A1026GameResult> GResultList { get { return PrepareBuilder().gResult_; } } public int GResultCount { get { return result.GResultCount; } } public global::DolphinServer.ProtoEntity.A1026GameResult GetGResult(int index) { return result.GetGResult(index); } public Builder SetGResult(int index, global::DolphinServer.ProtoEntity.A1026GameResult value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.gResult_[index] = value; return this; } public Builder SetGResult(int index, global::DolphinServer.ProtoEntity.A1026GameResult.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.gResult_[index] = builderForValue.Build(); return this; } public Builder AddGResult(global::DolphinServer.ProtoEntity.A1026GameResult value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.gResult_.Add(value); return this; } public Builder AddGResult(global::DolphinServer.ProtoEntity.A1026GameResult.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.gResult_.Add(builderForValue.Build()); return this; } public Builder AddRangeGResult(scg::IEnumerable<global::DolphinServer.ProtoEntity.A1026GameResult> values) { PrepareBuilder(); result.gResult_.Add(values); return this; } public Builder ClearGResult() { PrepareBuilder(); result.gResult_.Clear(); return this; } } static A1026Response() { object.ReferenceEquals(global::DolphinServer.ProtoEntity.Proto.A1026Response.Descriptor, null); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class A1026GameResult : pb::GeneratedMessage<A1026GameResult, A1026GameResult.Builder> { private A1026GameResult() { } private static readonly A1026GameResult defaultInstance = new A1026GameResult().MakeReadOnly(); private static readonly string[] _a1026GameResultFieldNames = new string[] { "DateTime", "ResultActionId", "Score" }; private static readonly uint[] _a1026GameResultFieldTags = new uint[] { 26, 10, 16 }; public static A1026GameResult DefaultInstance { get { return defaultInstance; } } public override A1026GameResult DefaultInstanceForType { get { return DefaultInstance; } } protected override A1026GameResult ThisMessage { get { return this; } } public static pbd::MessageDescriptor Descriptor { get { return global::DolphinServer.ProtoEntity.Proto.A1026Response.internal__static_A1026GameResult__Descriptor; } } protected override pb::FieldAccess.FieldAccessorTable<A1026GameResult, A1026GameResult.Builder> InternalFieldAccessors { get { return global::DolphinServer.ProtoEntity.Proto.A1026Response.internal__static_A1026GameResult__FieldAccessorTable; } } public const int ResultActionIdFieldNumber = 1; private bool hasResultActionId; private string resultActionId_ = ""; public bool HasResultActionId { get { return hasResultActionId; } } public string ResultActionId { get { return resultActionId_; } } public const int ScoreFieldNumber = 2; private bool hasScore; private int score_; public bool HasScore { get { return hasScore; } } public int Score { get { return score_; } } public const int DateTimeFieldNumber = 3; private bool hasDateTime; private string dateTime_ = ""; public bool HasDateTime { get { return hasDateTime; } } public string DateTime { get { return dateTime_; } } public override bool IsInitialized { get { return true; } } public override void WriteTo(pb::ICodedOutputStream output) { CalcSerializedSize(); string[] field_names = _a1026GameResultFieldNames; if (hasResultActionId) { output.WriteString(1, field_names[1], ResultActionId); } if (hasScore) { output.WriteInt32(2, field_names[2], Score); } if (hasDateTime) { output.WriteString(3, field_names[0], DateTime); } UnknownFields.WriteTo(output); } private int memoizedSerializedSize = -1; public override int SerializedSize { get { int size = memoizedSerializedSize; if (size != -1) return size; return CalcSerializedSize(); } } private int CalcSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasResultActionId) { size += pb::CodedOutputStream.ComputeStringSize(1, ResultActionId); } if (hasScore) { size += pb::CodedOutputStream.ComputeInt32Size(2, Score); } if (hasDateTime) { size += pb::CodedOutputStream.ComputeStringSize(3, DateTime); } size += UnknownFields.SerializedSize; memoizedSerializedSize = size; return size; } public static A1026GameResult ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static A1026GameResult ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static A1026GameResult ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static A1026GameResult ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static A1026GameResult ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static A1026GameResult ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static A1026GameResult ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static A1026GameResult ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static A1026GameResult ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static A1026GameResult ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private A1026GameResult MakeReadOnly() { return this; } public static Builder CreateBuilder() { return new Builder(); } public override Builder ToBuilder() { return CreateBuilder(this); } public override Builder CreateBuilderForType() { return new Builder(); } public static Builder CreateBuilder(A1026GameResult prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::GeneratedBuilder<A1026GameResult, Builder> { protected override Builder ThisBuilder { get { return this; } } public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(A1026GameResult cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } private bool resultIsReadOnly; private A1026GameResult result; private A1026GameResult PrepareBuilder() { if (resultIsReadOnly) { A1026GameResult original = result; result = new A1026GameResult(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override bool IsInitialized { get { return result.IsInitialized; } } protected override A1026GameResult MessageBeingBuilt { get { return PrepareBuilder(); } } public override Builder Clear() { result = DefaultInstance; resultIsReadOnly = true; return this; } public override Builder Clone() { if (resultIsReadOnly) { return new Builder(result); } else { return new Builder().MergeFrom(result); } } public override pbd::MessageDescriptor DescriptorForType { get { return global::DolphinServer.ProtoEntity.A1026GameResult.Descriptor; } } public override A1026GameResult DefaultInstanceForType { get { return global::DolphinServer.ProtoEntity.A1026GameResult.DefaultInstance; } } public override A1026GameResult BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessage other) { if (other is A1026GameResult) { return MergeFrom((A1026GameResult) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(A1026GameResult other) { if (other == global::DolphinServer.ProtoEntity.A1026GameResult.DefaultInstance) return this; PrepareBuilder(); if (other.HasResultActionId) { ResultActionId = other.ResultActionId; } if (other.HasScore) { Score = other.Score; } if (other.HasDateTime) { DateTime = other.DateTime; } this.MergeUnknownFields(other.UnknownFields); return this; } public override Builder MergeFrom(pb::ICodedInputStream input) { return MergeFrom(input, pb::ExtensionRegistry.Empty); } public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { PrepareBuilder(); pb::UnknownFieldSet.Builder unknownFields = null; uint tag; string field_name; while (input.ReadTag(out tag, out field_name)) { if(tag == 0 && field_name != null) { int field_ordinal = global::System.Array.BinarySearch(_a1026GameResultFieldNames, field_name, global::System.StringComparer.Ordinal); if(field_ordinal >= 0) tag = _a1026GameResultFieldTags[field_ordinal]; else { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); continue; } } switch (tag) { case 0: { throw pb::InvalidProtocolBufferException.InvalidTag(); } default: { if (pb::WireFormat.IsEndGroupTag(tag)) { if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); break; } case 10: { result.hasResultActionId = input.ReadString(ref result.resultActionId_); break; } case 16: { result.hasScore = input.ReadInt32(ref result.score_); break; } case 26: { result.hasDateTime = input.ReadString(ref result.dateTime_); break; } } } if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } public bool HasResultActionId { get { return result.hasResultActionId; } } public string ResultActionId { get { return result.ResultActionId; } set { SetResultActionId(value); } } public Builder SetResultActionId(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasResultActionId = true; result.resultActionId_ = value; return this; } public Builder ClearResultActionId() { PrepareBuilder(); result.hasResultActionId = false; result.resultActionId_ = ""; return this; } public bool HasScore { get { return result.hasScore; } } public int Score { get { return result.Score; } set { SetScore(value); } } public Builder SetScore(int value) { PrepareBuilder(); result.hasScore = true; result.score_ = value; return this; } public Builder ClearScore() { PrepareBuilder(); result.hasScore = false; result.score_ = 0; return this; } public bool HasDateTime { get { return result.hasDateTime; } } public string DateTime { get { return result.DateTime; } set { SetDateTime(value); } } public Builder SetDateTime(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasDateTime = true; result.dateTime_ = value; return this; } public Builder ClearDateTime() { PrepareBuilder(); result.hasDateTime = false; result.dateTime_ = ""; return this; } } static A1026GameResult() { object.ReferenceEquals(global::DolphinServer.ProtoEntity.Proto.A1026Response.Descriptor, null); } } #endregion } #endregion Designer generated code
// Copyright (c) 2010-2013 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.Runtime.InteropServices; using SharpDX.DXGI; using SharpDX.Direct3D11; namespace SharpDX.Toolkit.Graphics { /// <summary> /// A RenderTarget2D front end to <see cref="SharpDX.Direct3D11.Texture2D"/>. /// </summary> /// <remarks> /// This class instantiates a <see cref="Texture2D"/> with the binding flags <see cref="BindFlags.RenderTarget"/>. /// This class is also castable to <see cref="Direct3D11.RenderTargetView"/>. /// </remarks> public class RenderTarget2D : Texture2DBase { private bool pureRenderTarget; private RenderTargetView customRenderTargetView; internal RenderTarget2D(GraphicsDevice device, Texture2DDescription description2D) : base(device.MainDevice, description2D) { Initialize(Resource); } internal RenderTarget2D(GraphicsDevice device, Direct3D11.Texture2D texture, RenderTargetView renderTargetView = null, bool pureRenderTarget = false) : base(device.MainDevice, texture) { this.pureRenderTarget = pureRenderTarget; this.customRenderTargetView = renderTargetView; Initialize(Resource); } /// <summary> /// RenderTargetView casting operator. /// </summary> /// <param name="from">Source for the.</param> public static implicit operator RenderTargetView(RenderTarget2D from) { return from == null ? null : from.renderTargetViews != null ? from.renderTargetViews[0] : null; } protected override void InitializeViews() { if ((this.Description.BindFlags & BindFlags.RenderTarget) != 0) { this.renderTargetViews = new TextureView[GetViewCount()]; } if (pureRenderTarget) { renderTargetViews[0] = new TextureView(this, customRenderTargetView); } else { // Perform default initialization base.InitializeViews(); if ((this.Description.BindFlags & BindFlags.RenderTarget) != 0) { GetRenderTargetView(ViewType.Full, 0, 0); } } } internal override TextureView GetRenderTargetView(ViewType viewType, int arrayOrDepthSlice, int mipIndex) { if ((this.Description.BindFlags & BindFlags.RenderTarget) == 0) return null; if (viewType == ViewType.MipBand) throw new NotSupportedException("ViewSlice.MipBand is not supported for render targets"); int arrayCount; int mipCount; GetViewSliceBounds(viewType, ref arrayOrDepthSlice, ref mipIndex, out arrayCount, out mipCount); var rtvIndex = GetViewIndex(viewType, arrayOrDepthSlice, mipIndex); lock (this.renderTargetViews) { var rtv = this.renderTargetViews[rtvIndex]; // Creates the shader resource view if (rtv == null) { // Create the render target view var rtvDescription = new RenderTargetViewDescription() { Format = this.Description.Format }; if (this.Description.ArraySize > 1) { rtvDescription.Dimension = this.Description.SampleDescription.Count > 1 ? RenderTargetViewDimension.Texture2DMultisampledArray : RenderTargetViewDimension.Texture2DArray; if (this.Description.SampleDescription.Count > 1) { rtvDescription.Texture2DMSArray.ArraySize = arrayCount; rtvDescription.Texture2DMSArray.FirstArraySlice = arrayOrDepthSlice; } else { rtvDescription.Texture2DArray.ArraySize = arrayCount; rtvDescription.Texture2DArray.FirstArraySlice = arrayOrDepthSlice; rtvDescription.Texture2DArray.MipSlice = mipIndex; } } else { rtvDescription.Dimension = this.Description.SampleDescription.Count > 1 ? RenderTargetViewDimension.Texture2DMultisampled : RenderTargetViewDimension.Texture2D; if (this.Description.SampleDescription.Count <= 1) rtvDescription.Texture2D.MipSlice = mipIndex; } rtv = new TextureView(this, new RenderTargetView(GraphicsDevice, Resource, rtvDescription)); this.renderTargetViews[rtvIndex] = ToDispose(rtv); } return rtv; } } public override Texture Clone() { return new RenderTarget2D(GraphicsDevice, this.Description); } /// <summary> /// Creates a new <see cref="RenderTarget2D"/> from a <see cref="Texture2DDescription"/>. /// </summary> /// <param name="device">The <see cref="GraphicsDevice"/>.</param> /// <param name="description">The description.</param> /// <returns> /// A new instance of <see cref="RenderTarget2D"/> class. /// </returns> /// <msdn-id>ff476521</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short> public static RenderTarget2D New(GraphicsDevice device, Texture2DDescription description) { return new RenderTarget2D(device, description); } /// <summary> /// Creates a new <see cref="RenderTarget2D"/> from a <see cref="Direct3D11.Texture2D"/>. /// </summary> /// <param name="device">The <see cref="GraphicsDevice"/>.</param> /// <param name="texture">The native texture <see cref="Direct3D11.Texture2D"/>.</param> /// <returns> /// A new instance of <see cref="RenderTarget2D"/> class. /// </returns> /// <msdn-id>ff476521</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short> public static RenderTarget2D New(GraphicsDevice device, Direct3D11.Texture2D texture) { return new RenderTarget2D(device, texture); } /// <summary> /// Creates a new <see cref="RenderTarget2D"/> from a <see cref="RenderTargetView"/>. /// </summary> /// <param name="device">The <see cref="GraphicsDevice"/>.</param> /// <param name="renderTargetView">The native texture <see cref="RenderTargetView"/>.</param> /// <returns> /// A new instance of <see cref="RenderTarget2D"/> class. /// </returns> /// <msdn-id>ff476521</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short> public static RenderTarget2D New(GraphicsDevice device, RenderTargetView renderTargetView, bool pureRenderTarget = false) { using (var resource = renderTargetView.Resource) { return new RenderTarget2D(device, resource.QueryInterface<Direct3D11.Texture2D>(), renderTargetView, pureRenderTarget); } } /// <summary> /// Creates a new <see cref="RenderTarget2D" /> with a single mipmap. /// </summary> /// <param name="device">The <see cref="GraphicsDevice"/>.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="format">Describes the format to use.</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="RenderTarget2D" /> class.</returns> /// <msdn-id>ff476521</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short> public static RenderTarget2D New(GraphicsDevice device, int width, int height, PixelFormat format, TextureFlags flags = TextureFlags.RenderTarget | TextureFlags.ShaderResource, int arraySize = 1) { return New(device, width, height, false, format, flags, arraySize); } /// <summary> /// Creates a new <see cref="RenderTarget2D" />. /// </summary> /// <param name="device">The <see cref="GraphicsDevice"/>.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</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="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="RenderTarget2D" /> class.</returns> /// <msdn-id>ff476521</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short> public static RenderTarget2D New(GraphicsDevice device, int width, int height, MipMapCount mipCount, PixelFormat format, TextureFlags flags = TextureFlags.RenderTarget | TextureFlags.ShaderResource, int arraySize = 1) { return new RenderTarget2D(device, CreateDescription(device.MainDevice, width, height, format, flags, mipCount, arraySize, MSAALevel.None)); } /// <summary> /// Creates a new <see cref="RenderTarget2D" /> using multisampling. /// </summary> /// <param name="device">The <see cref="GraphicsDevice"/>.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="format">Describes the format to use.</param> /// <param name="arraySize">Size of the texture 2D array, default to 1.</param> /// <param name="multiSampleCount">The multisample count.</param> /// <returns>A new instance of <see cref="RenderTarget2D" /> class.</returns> /// <msdn-id>ff476521</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short> public static RenderTarget2D New(GraphicsDevice device, int width, int height, MSAALevel multiSampleCount, PixelFormat format, int arraySize = 1) { if (multiSampleCount == MSAALevel.None) { throw new ArgumentException("Cannot declare a MSAA RenderTarget with MSAALevel.None. Use other non-MSAA constructors", "multiSampleCount"); } return new RenderTarget2D(device, CreateDescription(device.MainDevice, width, height, format, TextureFlags.RenderTarget, 1, arraySize, multiSampleCount)); } /// <summary> /// Creates a new texture description for a <see cref="RenderTarget2D" /> with a single mipmap. /// </summary> /// <param name="device">The <see cref="GraphicsDevice"/>.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="format">Describes the format to use.</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="RenderTarget2D" /> class.</returns> /// <msdn-id>ff476521</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short> public static Texture2DDescription CreateDescription(GraphicsDevice device, int width, int height, PixelFormat format, TextureFlags flags = TextureFlags.RenderTarget | TextureFlags.ShaderResource, int arraySize = 1) { return CreateDescription(device, width, height, false, format, flags, arraySize); } /// <summary> /// Creates a new texture description <see cref="RenderTarget2D" />. /// </summary> /// <param name="device">The <see cref="GraphicsDevice"/>.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</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="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="RenderTarget2D" /> class.</returns> /// <msdn-id>ff476521</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short> public static Texture2DDescription CreateDescription(GraphicsDevice device, int width, int height, MipMapCount mipCount, PixelFormat format, TextureFlags flags = TextureFlags.RenderTarget | TextureFlags.ShaderResource, int arraySize = 1) { return CreateDescription(device.MainDevice, width, height, format, flags, mipCount, arraySize, MSAALevel.None); } /// <summary> /// Creates a new texture description <see cref="RenderTarget2D" /> using multisampling. /// </summary> /// <param name="device">The <see cref="GraphicsDevice"/>.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="format">Describes the format to use.</param> /// <param name="arraySize">Size of the texture 2D array, default to 1.</param> /// <param name="multiSampleCount">The multisample count.</param> /// <returns>A new instance of <see cref="RenderTarget2D" /> class.</returns> /// <msdn-id>ff476521</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short> public static Texture2DDescription CreateDescription(GraphicsDevice device, int width, int height, MSAALevel multiSampleCount, PixelFormat format, int arraySize = 1) { if (multiSampleCount == MSAALevel.None) { throw new ArgumentException("Cannot declare a MSAA RenderTarget with MSAALevel.None. Use other non-MSAA constructors", "multiSampleCount"); } return CreateDescription(device.MainDevice, width, height, format, TextureFlags.RenderTarget, 1, arraySize, multiSampleCount); } /// <summary> /// <see cref="SharpDX.Direct3D11.Texture2D"/> casting operator. /// </summary> /// <param name="from">From the Texture1D.</param> public static implicit operator SharpDX.Direct3D11.Texture2D(RenderTarget2D from) { // Don't bother with multithreading here return from == null ? null : from.Resource; } /// <summary> /// Implicit casting operator to <see cref="Direct3D11.Resource"/> /// </summary> /// <param name="from">The GraphicsResource to convert from.</param> public static implicit operator SharpDX.Direct3D11.Resource(RenderTarget2D from) { return from == null ? null : (SharpDX.Direct3D11.Resource)from.Resource; } internal static Texture2DDescription CreateDescription(GraphicsDevice device, int width, int height, PixelFormat format, TextureFlags textureFlags, int mipCount, int arraySize, MSAALevel multiSampleCount) { // Make sure that the texture to create is a render target textureFlags |= TextureFlags.RenderTarget; var desc = Texture2DBase.NewDescription(width, height, format, textureFlags, mipCount, arraySize, ResourceUsage.Default); // Sets the MSAALevel int maximumMSAA = (int)device.Features[format].MSAALevelMax; desc.SampleDescription.Count = Math.Max(1, Math.Min((int)multiSampleCount, maximumMSAA)); return desc; } } }
// Copyright (c) Cloud Native Foundation. // Licensed under the Apache 2.0 license. // See LICENSE file in the project root for full license information. using CloudNative.CloudEvents.UnitTests; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net.Mime; using System.Text; using System.Text.Json; using System.Text.Json.Serialization; using System.Threading.Tasks; using Xunit; using static CloudNative.CloudEvents.UnitTests.TestHelpers; // JObject is a really handy way of creating JSON which we can then parse with System.Text.Json using JObject = Newtonsoft.Json.Linq.JObject; using JArray = Newtonsoft.Json.Linq.JArray; using CloudNative.CloudEvents.Core; namespace CloudNative.CloudEvents.SystemTextJson.UnitTests { public class JsonEventFormatterTest { private static readonly ContentType s_jsonCloudEventContentType = new ContentType("application/cloudevents+json; charset=utf-8"); private static readonly ContentType s_jsonCloudEventBatchContentType = new ContentType("application/cloudevents-batch+json; charset=utf-8"); private const string NonAsciiValue = "GBP=\u00a3"; /// <summary> /// A simple test that populates all known v1.0 attributes, so we don't need to test that /// aspect in the future. /// </summary> [Fact] public void EncodeStructuredModeMessage_V1Attributes() { var cloudEvent = new CloudEvent(CloudEventsSpecVersion.V1_0) { Data = "text", // Just so that it's reasonable to have a DataContentType DataContentType = "text/plain", DataSchema = new Uri("https://data-schema"), Id = "event-id", Source = new Uri("https://event-source"), Subject = "event-subject", Time = new DateTimeOffset(2021, 2, 19, 12, 34, 56, 789, TimeSpan.FromHours(1)), Type = "event-type" }; var encoded = new JsonEventFormatter().EncodeStructuredModeMessage(cloudEvent, out var contentType); Assert.Equal("application/cloudevents+json; charset=utf-8", contentType.ToString()); JsonElement obj = ParseJson(encoded); var asserter = new JsonElementAsserter { { "data", JsonValueKind.String, "text" }, { "datacontenttype", JsonValueKind.String, "text/plain" }, { "dataschema", JsonValueKind.String, "https://data-schema" }, { "id", JsonValueKind.String, "event-id" }, { "source", JsonValueKind.String, "https://event-source" }, { "specversion", JsonValueKind.String, "1.0" }, { "subject", JsonValueKind.String, "event-subject" }, { "time", JsonValueKind.String, "2021-02-19T12:34:56.789+01:00" }, { "type", JsonValueKind.String, "event-type" }, }; asserter.AssertProperties(obj, assertCount: true); } [Fact] public void EncodeStructuredModeMessage_AllAttributeTypes() { var cloudEvent = new CloudEvent(AllTypesExtensions) { ["binary"] = SampleBinaryData, ["boolean"] = true, ["integer"] = 10, ["string"] = "text", ["timestamp"] = SampleTimestamp, ["uri"] = SampleUri, ["urireference"] = SampleUriReference }; // We're not going to check these. cloudEvent.PopulateRequiredAttributes(); JsonElement element = EncodeAndParseStructured(cloudEvent); var asserter = new JsonElementAsserter { { "binary", JsonValueKind.String, SampleBinaryDataBase64 }, { "boolean", JsonValueKind.True, true }, { "integer", JsonValueKind.Number, 10 }, { "string", JsonValueKind.String, "text" }, { "timestamp", JsonValueKind.String, SampleTimestampText }, { "uri", JsonValueKind.String, SampleUriText }, { "urireference", JsonValueKind.String, SampleUriReferenceText }, }; asserter.AssertProperties(element, assertCount: false); } [Fact] public void EncodeStructuredModeMessage_JsonDataType_ObjectSerialization() { var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); cloudEvent.Data = new { Text = "simple text" }; cloudEvent.DataContentType = "application/json"; JsonElement element = EncodeAndParseStructured(cloudEvent); JsonElement dataProperty = element.GetProperty("data"); var asserter = new JsonElementAsserter { { "Text", JsonValueKind.String, "simple text" } }; asserter.AssertProperties(dataProperty, assertCount: true); } [Fact] public void EncodeStructuredModeMessage_JsonDataType_NumberSerialization() { var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); cloudEvent.Data = 10; cloudEvent.DataContentType = "application/json"; JsonElement element = EncodeAndParseStructured(cloudEvent); var asserter = new JsonElementAsserter { { "data", JsonValueKind.Number, 10 } }; asserter.AssertProperties(element, assertCount: false); } [Fact] public void EncodeStructuredModeMessage_JsonDataType_CustomSerializerOptions() { var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); cloudEvent.Data = new { DateValue = new DateTime(2021, 2, 19, 12, 49, 34, DateTimeKind.Utc) }; cloudEvent.DataContentType = "application/json"; var serializerOptions = new JsonSerializerOptions { Converters = { new YearMonthDayConverter() }, }; var formatter = new JsonEventFormatter(serializerOptions, default); var encoded = formatter.EncodeStructuredModeMessage(cloudEvent, out _); JsonElement element = ParseJson(encoded); JsonElement dataProperty = element.GetProperty("data"); var asserter = new JsonElementAsserter { { "DateValue", JsonValueKind.String, "2021-02-19" } }; asserter.AssertProperties(dataProperty, assertCount: true); } [Fact] public void EncodeStructuredModeMessage_JsonDataType_AttributedModel() { var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); cloudEvent.Data = new AttributedModel { AttributedProperty = "simple text" }; cloudEvent.DataContentType = "application/json"; JsonElement element = EncodeAndParseStructured(cloudEvent); JsonElement dataProperty = element.GetProperty("data"); var asserter = new JsonElementAsserter { { AttributedModel.JsonPropertyName, JsonValueKind.String, "simple text" } }; asserter.AssertProperties(dataProperty, assertCount: true); } [Fact] public void EncodeStructuredModeMessage_JsonDataType_JsonElementObject() { var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); cloudEvent.Data = ParseJson("{ \"value\": { \"Key\": \"value\" } }").GetProperty("value"); cloudEvent.DataContentType = "application/json"; JsonElement element = EncodeAndParseStructured(cloudEvent); JsonElement data = element.GetProperty("data"); var asserter = new JsonElementAsserter { { "Key", JsonValueKind.String, "value" } }; asserter.AssertProperties(data, assertCount: true); } [Fact] public void EncodeStructuredModeMessage_JsonDataType_JsonElementString() { var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); cloudEvent.Data = ParseJson("{ \"value\": \"text\" }").GetProperty("value"); cloudEvent.DataContentType = "application/json"; JsonElement element = EncodeAndParseStructured(cloudEvent); JsonElement data = element.GetProperty("data"); Assert.Equal(JsonValueKind.String, data.ValueKind); Assert.Equal("text", data.GetString()); } [Fact] public void EncodeStructuredModeMessage_JsonDataType_JsonElementNull() { var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); cloudEvent.Data = ParseJson("{ \"value\": null }").GetProperty("value"); cloudEvent.DataContentType = "application/json"; JsonElement element = EncodeAndParseStructured(cloudEvent); JsonElement data = element.GetProperty("data"); Assert.Equal(JsonValueKind.Null, data.ValueKind); } [Fact] public void EncodeStructuredModeMessage_JsonDataType_JsonElementNumeric() { var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); cloudEvent.Data = ParseJson("{ \"value\": 100 }").GetProperty("value"); cloudEvent.DataContentType = "application/json"; JsonElement element = EncodeAndParseStructured(cloudEvent); JsonElement data = element.GetProperty("data"); Assert.Equal(JsonValueKind.Number, data.ValueKind); Assert.Equal(100, data.GetInt32()); } [Fact] public void EncodeStructuredModeMessage_JsonDataType_NullValue() { var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); cloudEvent.Data = null; cloudEvent.DataContentType = "application/json"; JsonElement element = EncodeAndParseStructured(cloudEvent); Assert.False(element.TryGetProperty("data", out _)); } [Fact] public void EncodeStructuredModeMessage_TextType_String() { var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); cloudEvent.Data = "some text"; cloudEvent.DataContentType = "text/anything"; JsonElement element = EncodeAndParseStructured(cloudEvent); var dataProperty = element.GetProperty("data"); Assert.Equal(JsonValueKind.String, dataProperty.ValueKind); Assert.Equal("some text", dataProperty.GetString()); } // A text content type with bytes as data is serialized like any other bytes. [Fact] public void EncodeStructuredModeMessage_TextType_Bytes() { var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); cloudEvent.Data = SampleBinaryData; cloudEvent.DataContentType = "text/anything"; JsonElement element = EncodeAndParseStructured(cloudEvent); Assert.False(element.TryGetProperty("data", out _)); var dataBase64 = element.GetProperty("data_base64"); Assert.Equal(JsonValueKind.String, dataBase64.ValueKind); Assert.Equal(SampleBinaryDataBase64, dataBase64.GetString()); } [Fact] public void EncodeStructuredModeMessage_TextType_NotStringOrBytes() { var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); cloudEvent.Data = new object(); cloudEvent.DataContentType = "text/anything"; var formatter = new JsonEventFormatter(); Assert.Throws<ArgumentException>(() => formatter.EncodeStructuredModeMessage(cloudEvent, out _)); } [Fact] public void EncodeStructuredModeMessage_ArbitraryType_Bytes() { var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); cloudEvent.Data = SampleBinaryData; cloudEvent.DataContentType = "not_text/or_json"; JsonElement element = EncodeAndParseStructured(cloudEvent); Assert.False(element.TryGetProperty("data", out _)); var dataBase64 = element.GetProperty("data_base64"); Assert.Equal(JsonValueKind.String, dataBase64.ValueKind); Assert.Equal(SampleBinaryDataBase64, dataBase64.GetString()); } [Fact] public void EncodeStructuredModeMessage_ArbitraryType_NotBytes() { var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); cloudEvent.Data = new object(); cloudEvent.DataContentType = "not_text/or_json"; var formatter = new JsonEventFormatter(); Assert.Throws<ArgumentException>(() => formatter.EncodeStructuredModeMessage(cloudEvent, out _)); } [Fact] public void EncodeBinaryModeEventData_JsonDataType_ObjectSerialization() { var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); cloudEvent.Data = new { Text = "simple text" }; cloudEvent.DataContentType = "application/json"; var bytes = new JsonEventFormatter().EncodeBinaryModeEventData(cloudEvent); JsonElement data = ParseJson(bytes); var asserter = new JsonElementAsserter { { "Text", JsonValueKind.String, "simple text" } }; asserter.AssertProperties(data, assertCount: true); } [Fact] public void EncodeBinaryModeEventData_JsonDataType_CustomSerializer() { var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); cloudEvent.Data = new { DateValue = new DateTime(2021, 2, 19, 12, 49, 34, DateTimeKind.Utc) }; cloudEvent.DataContentType = "application/json"; var serializerOptions = new JsonSerializerOptions { Converters = { new YearMonthDayConverter() }, }; var formatter = new JsonEventFormatter(serializerOptions, default); var bytes = formatter.EncodeBinaryModeEventData(cloudEvent); JsonElement data = ParseJson(bytes); var asserter = new JsonElementAsserter { { "DateValue", JsonValueKind.String, "2021-02-19" } }; asserter.AssertProperties(data, assertCount: true); } [Fact] public void EncodeBinaryModeEventData_JsonDataType_AttributedModel() { var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); cloudEvent.Data = new AttributedModel { AttributedProperty = "simple text" }; cloudEvent.DataContentType = "application/json"; var bytes = new JsonEventFormatter().EncodeBinaryModeEventData(cloudEvent); JsonElement data = ParseJson(bytes); var asserter = new JsonElementAsserter { { AttributedModel.JsonPropertyName, JsonValueKind.String, "simple text" } }; asserter.AssertProperties(data, assertCount: true); } [Theory] [InlineData("utf-8")] [InlineData("utf-16")] public void EncodeBinaryModeEventData_JsonDataType_JsonElement(string charset) { // This would definitely be an odd thing to do, admittedly... var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); cloudEvent.Data = ParseJson($"{{ \"value\": \"some text\" }}").GetProperty("value"); cloudEvent.DataContentType = $"application/json; charset={charset}"; var bytes = new JsonEventFormatter().EncodeBinaryModeEventData(cloudEvent); Assert.Equal("\"some text\"", BinaryDataUtilities.GetString(bytes, Encoding.GetEncoding(charset))); } [Fact] public void EncodeBinaryModeEventData_JsonDataType_NullValue() { var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); cloudEvent.Data = null; cloudEvent.DataContentType = "application/json"; var bytes = new JsonEventFormatter().EncodeBinaryModeEventData(cloudEvent); Assert.True(bytes.IsEmpty); } [Theory] [InlineData("utf-8")] [InlineData("iso-8859-1")] public void EncodeBinaryModeEventData_TextType_String(string charset) { var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); cloudEvent.Data = "some text"; cloudEvent.DataContentType = $"text/anything; charset={charset}"; var bytes = new JsonEventFormatter().EncodeBinaryModeEventData(cloudEvent); Assert.Equal("some text", BinaryDataUtilities.GetString(bytes, Encoding.GetEncoding(charset))); } // A text content type with bytes as data is serialized like any other bytes. [Fact] public void EncodeBinaryModeEventData_TextType_Bytes() { var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); cloudEvent.Data = SampleBinaryData; cloudEvent.DataContentType = "text/anything"; var bytes = new JsonEventFormatter().EncodeBinaryModeEventData(cloudEvent); Assert.Equal(SampleBinaryData, bytes); } [Fact] public void EncodeBinaryModeEventData_TextType_NotStringOrBytes() { var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); cloudEvent.Data = new object(); cloudEvent.DataContentType = "text/anything"; var formatter = new JsonEventFormatter(); Assert.Throws<ArgumentException>(() => formatter.EncodeBinaryModeEventData(cloudEvent)); } [Fact] public void EncodeBinaryModeEventData_ArbitraryType_Bytes() { var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); cloudEvent.Data = SampleBinaryData; cloudEvent.DataContentType = "not_text/or_json"; var bytes = new JsonEventFormatter().EncodeBinaryModeEventData(cloudEvent); Assert.Equal(SampleBinaryData, bytes); } [Fact] public void EncodeBinaryModeEventData_ArbitraryType_NotBytes() { var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); cloudEvent.Data = new object(); cloudEvent.DataContentType = "not_text/or_json"; var formatter = new JsonEventFormatter(); Assert.Throws<ArgumentException>(() => formatter.EncodeBinaryModeEventData(cloudEvent)); } [Fact] public void EncodeBinaryModeEventData_NoContentType_ConvertsStringToJson() { var cloudEvent = new CloudEvent { Data = "some text" }.PopulateRequiredAttributes(); // EncodeBinaryModeEventData doesn't actually populate the content type of the CloudEvent, // but treat the data as if we'd explicitly specified application/json. var data = new JsonEventFormatter().EncodeBinaryModeEventData(cloudEvent); string text = BinaryDataUtilities.GetString(data, Encoding.UTF8); Assert.Equal("\"some text\"", text); } [Fact] public void EncodeBinaryModeEventData_NoContentType_LeavesBinaryData() { var cloudEvent = new CloudEvent { Data = SampleBinaryData }.PopulateRequiredAttributes(); // EncodeBinaryModeEventData does *not* implicitly encode binary data as JSON. var data = new JsonEventFormatter().EncodeBinaryModeEventData(cloudEvent); var array = BinaryDataUtilities.AsArray(data); Assert.Equal(array, SampleBinaryData); } // Note: batch mode testing is restricted to the batch aspects; we assume that the // per-CloudEvent implementation is shared with structured mode, so we rely on // structured mode testing for things like custom serialization. [Fact] public void EncodeBatchModeMessage_Empty() { var cloudEvents = new CloudEvent[0]; var formatter = new JsonEventFormatter(); var bytes = formatter.EncodeBatchModeMessage(cloudEvents, out var contentType); Assert.Equal("application/cloudevents-batch+json; charset=utf-8", contentType.ToString()); var array = ParseJson(bytes); Assert.Equal(JsonValueKind.Array, array.ValueKind); Assert.Equal(0, array.GetArrayLength()); } [Fact] public void EncodeBatchModeMessage_TwoEvents() { var event1 = new CloudEvent().PopulateRequiredAttributes(); event1.Id = "event1"; event1.Data = "simple text"; event1.DataContentType = "text/plain"; var event2 = new CloudEvent().PopulateRequiredAttributes(); event2.Id = "event2"; var cloudEvents = new[] { event1, event2 }; var formatter = new JsonEventFormatter(); var bytes = formatter.EncodeBatchModeMessage(cloudEvents, out var contentType); Assert.Equal("application/cloudevents-batch+json; charset=utf-8", contentType.ToString()); var array = ParseJson(bytes).EnumerateArray().ToList(); Assert.Equal(2, array.Count); var asserter1 = new JsonElementAsserter { { "specversion", JsonValueKind.String, "1.0" }, { "id", JsonValueKind.String, event1.Id }, { "type", JsonValueKind.String, event1.Type }, { "source", JsonValueKind.String, "//test" }, { "data", JsonValueKind.String, "simple text" }, { "datacontenttype", JsonValueKind.String, event1.DataContentType } }; asserter1.AssertProperties(array[0], assertCount: true); var asserter2 = new JsonElementAsserter { { "specversion", JsonValueKind.String, "1.0" }, { "id", JsonValueKind.String, event2.Id }, { "type", JsonValueKind.String, event2.Type }, { "source", JsonValueKind.String, "//test" }, }; asserter2.AssertProperties(array[1], assertCount: true); } [Fact] public void EncodeBatchModeMessage_Invalid() { var formatter = new JsonEventFormatter(); // Invalid CloudEvent Assert.Throws<ArgumentException>(() => formatter.EncodeBatchModeMessage(new[] { new CloudEvent() }, out _)); // Null argument Assert.Throws<ArgumentNullException>(() => formatter.EncodeBatchModeMessage(null!, out _)); // Null value within the argument. Arguably this should throw ArgumentException instead of // ArgumentNullException, but it's unlikely to cause confusion. Assert.Throws<ArgumentNullException>(() => formatter.EncodeBatchModeMessage(new CloudEvent[1], out _)); } [Fact] public void DecodeStructuredModeMessage_NotJson() { var formatter = new JsonEventFormatter(); Assert.ThrowsAny<JsonException>(() => formatter.DecodeStructuredModeMessage(new byte[10], new ContentType("application/json"), null)); } // Just a single test for the code that parses asynchronously... the guts are all the same. [Theory] [InlineData("utf-8")] [InlineData("iso-8859-1")] public async Task DecodeStructuredModeMessageAsync_Minimal(string charset) { // Note: just using Json.NET to get the JSON in a simple way... var obj = new JObject { ["specversion"] = "1.0", ["type"] = "test-type", ["id"] = "test-id", ["source"] = SampleUriText, ["text"] = NonAsciiValue }; var bytes = Encoding.GetEncoding(charset).GetBytes(obj.ToString()); var stream = new MemoryStream(bytes); var formatter = new JsonEventFormatter(); var cloudEvent = await formatter.DecodeStructuredModeMessageAsync(stream, new ContentType($"application/cloudevents+json; charset={charset}"), null); Assert.Equal("test-type", cloudEvent.Type); Assert.Equal("test-id", cloudEvent.Id); Assert.Equal(SampleUri, cloudEvent.Source); Assert.Equal(NonAsciiValue, cloudEvent["text"]); } [Theory] [InlineData("utf-8")] [InlineData("iso-8859-1")] public void DecodeStructuredModeMessage_Minimal(string charset) { var obj = new JObject { ["specversion"] = "1.0", ["type"] = "test-type", ["id"] = "test-id", ["source"] = SampleUriText, ["text"] = NonAsciiValue }; var bytes = Encoding.GetEncoding(charset).GetBytes(obj.ToString()); var stream = new MemoryStream(bytes); var formatter = new JsonEventFormatter(); var cloudEvent = formatter.DecodeStructuredModeMessage(stream, new ContentType($"application/cloudevents+json; charset={charset}"), null); Assert.Equal("test-type", cloudEvent.Type); Assert.Equal("test-id", cloudEvent.Id); Assert.Equal(SampleUri, cloudEvent.Source); } [Fact] public void DecodeStructuredModeMessage_NoSpecVersion() { var obj = new JObject { ["type"] = "test-type", ["id"] = "test-id", ["source"] = SampleUriText, }; Assert.Throws<ArgumentException>(() => DecodeStructuredModeMessage(obj)); } [Fact] public void DecodeStructuredModeMessage_UnknownSpecVersion() { var obj = new JObject { ["specversion"] = "0.5", ["type"] = "test-type", ["id"] = "test-id", ["source"] = SampleUriText, }; Assert.Throws<ArgumentException>(() => DecodeStructuredModeMessage(obj)); } [Fact] public void DecodeStructuredModeMessage_MissingRequiredAttributes() { var obj = new JObject { ["specversion"] = "1.0", ["type"] = "test-type", ["id"] = "test-id" // Source is missing }; Assert.Throws<ArgumentException>(() => DecodeStructuredModeMessage(obj)); } [Fact] public void DecodeStructuredModeMessage_SpecVersionNotString() { var obj = new JObject { ["specversion"] = 1, ["type"] = "test-type", ["id"] = "test-id", ["source"] = SampleUriText, }; Assert.Throws<ArgumentException>(() => DecodeStructuredModeMessage(obj)); } [Fact] public void DecodeStructuredModeMessage_TypeNotString() { var obj = new JObject { ["specversion"] = "1.0", ["type"] = 1, ["id"] = "test-id", ["source"] = SampleUriText, }; Assert.Throws<ArgumentException>(() => DecodeStructuredModeMessage(obj)); } [Fact] public void DecodeStructuredModeMessage_V1Attributes() { var obj = new JObject { ["specversion"] = "1.0", ["type"] = "test-type", ["id"] = "test-id", ["data"] = "text", // Just so that it's reasonable to have a DataContentType, ["datacontenttype"] = "text/plain", ["dataschema"] = "https://data-schema", ["subject"] = "event-subject", ["source"] = "//event-source", ["time"] = SampleTimestampText }; var cloudEvent = DecodeStructuredModeMessage(obj); Assert.Equal(CloudEventsSpecVersion.V1_0, cloudEvent.SpecVersion); Assert.Equal("test-type", cloudEvent.Type); Assert.Equal("test-id", cloudEvent.Id); Assert.Equal("text/plain", cloudEvent.DataContentType); Assert.Equal(new Uri("https://data-schema"), cloudEvent.DataSchema); Assert.Equal("event-subject", cloudEvent.Subject); Assert.Equal(new Uri("//event-source", UriKind.RelativeOrAbsolute), cloudEvent.Source); AssertTimestampsEqual(SampleTimestamp, cloudEvent.Time); } [Fact] public void DecodeStructuredModeMessage_AllAttributeTypes() { var obj = new JObject { // Required attributes ["specversion"] = "1.0", ["type"] = "test-type", ["id"] = "test-id", ["source"] = "//source", // Extension attributes ["binary"] = SampleBinaryDataBase64, ["boolean"] = true, ["integer"] = 10, ["string"] = "text", ["timestamp"] = SampleTimestampText, ["uri"] = SampleUriText, ["urireference"] = SampleUriReferenceText }; var bytes = Encoding.UTF8.GetBytes(obj.ToString()); var formatter = new JsonEventFormatter(); var cloudEvent = formatter.DecodeStructuredModeMessage(bytes, s_jsonCloudEventContentType, AllTypesExtensions); Assert.Equal(SampleBinaryData, cloudEvent["binary"]); Assert.True((bool)cloudEvent["boolean"]!); Assert.Equal(10, cloudEvent["integer"]); Assert.Equal("text", cloudEvent["string"]); AssertTimestampsEqual(SampleTimestamp, (DateTimeOffset)cloudEvent["timestamp"]!); Assert.Equal(SampleUri, cloudEvent["uri"]); Assert.Equal(SampleUriReference, cloudEvent["urireference"]); } [Fact] public void DecodeStructuredModeMessage_IncorrectExtensionTypeWithValidValue() { var obj = new JObject { ["specversion"] = "1.0", ["type"] = "test-type", ["id"] = "test-id", ["source"] = "//source", // Incorrect type, but is a valid value for the extension ["integer"] = "10", }; // Decode the event, providing the extension with the correct type. var bytes = Encoding.UTF8.GetBytes(obj.ToString()); var formatter = new JsonEventFormatter(); var cloudEvent = formatter.DecodeStructuredModeMessage(bytes, s_jsonCloudEventContentType, AllTypesExtensions); // The value will have been decoded according to the extension. Assert.Equal(10, cloudEvent["integer"]); } // There are other invalid token types as well; this is just one of them. [Fact] public void DecodeStructuredModeMessage_AttributeValueAsArrayToken() { var obj = CreateMinimalValidJObject(); obj["attr"] = new Newtonsoft.Json.Linq.JArray(); Assert.Throws<ArgumentException>(() => DecodeStructuredModeMessage(obj)); } [Fact] public void DecodeStructuredModeMessage_Null() { var obj = CreateMinimalValidJObject(); obj["attr"] = Newtonsoft.Json.Linq.JValue.CreateNull(); var cloudEvent = DecodeStructuredModeMessage(obj); // The JSON event format spec demands that we ignore null values, so we shouldn't // have created an extension attribute. Assert.Null(cloudEvent.GetAttribute("attr")); } [Theory] [InlineData(null)] [InlineData("application/json")] [InlineData("text/plain")] [InlineData("application/binary")] public void DecodeStructuredModeMessage_NoData(string contentType) { var obj = CreateMinimalValidJObject(); if (contentType is object) { obj["datacontenttype"] = contentType; } var cloudEvent = DecodeStructuredModeMessage(obj); Assert.Null(cloudEvent.Data); } [Fact] public void DecodeStructuredModeMessage_BothDataAndDataBase64() { var obj = CreateMinimalValidJObject(); obj["data"] = "text"; obj["data_base64"] = SampleBinaryDataBase64; Assert.Throws<ArgumentException>(() => DecodeStructuredModeMessage(obj)); } [Fact] public void DecodeStructuredModeMessage_DataBase64NonString() { var obj = CreateMinimalValidJObject(); obj["data_base64"] = 10; Assert.Throws<ArgumentException>(() => DecodeStructuredModeMessage(obj)); } // data_base64 always ends up as bytes, regardless of content type. [Theory] [InlineData(null)] [InlineData("application/json")] [InlineData("text/plain")] [InlineData("application/binary")] public void DecodeStructuredModeMessage_Base64(string contentType) { var obj = CreateMinimalValidJObject(); if (contentType is object) { obj["datacontenttype"] = contentType; } obj["data_base64"] = SampleBinaryDataBase64; var cloudEvent = DecodeStructuredModeMessage(obj); Assert.Equal(SampleBinaryData, cloudEvent.Data); } [Theory] [InlineData("text/plain")] [InlineData("image/png")] public void DecodeStructuredModeMessage_NonJsonContentType_JsonStringToken(string contentType) { var obj = CreateMinimalValidJObject(); obj["datacontenttype"] = contentType; obj["data"] = "some text"; var cloudEvent = DecodeStructuredModeMessage(obj); Assert.Equal("some text", cloudEvent.Data); } [Theory] [InlineData(null)] [InlineData("application/json")] public void DecodeStructuredModeMessage_JsonContentType_JsonStringToken(string contentType) { var obj = CreateMinimalValidJObject(); if (contentType is object) { obj["datacontenttype"] = contentType; } obj["data"] = "text"; var cloudEvent = DecodeStructuredModeMessage(obj); var element = (JsonElement) cloudEvent.Data!; Assert.Equal(JsonValueKind.String, element.ValueKind); Assert.Equal("text", element.GetString()); } [Theory] [InlineData(null)] [InlineData("application/json")] [InlineData("application/xyz+json")] public void DecodeStructuredModeMessage_JsonContentType_NonStringValue(string contentType) { var obj = CreateMinimalValidJObject(); if (contentType is object) { obj["datacontenttype"] = contentType; } obj["data"] = 10; var cloudEvent = DecodeStructuredModeMessage(obj); var element = (JsonElement) cloudEvent.Data!; Assert.Equal(JsonValueKind.Number, element.ValueKind); Assert.Equal(10, element.GetInt32()); } [Fact] public void DecodeStructuredModeMessage_NonJsonContentType_NonStringValue() { var obj = CreateMinimalValidJObject(); obj["datacontenttype"] = "text/plain"; obj["data"] = 10; Assert.Throws<ArgumentException>(() => DecodeStructuredModeMessage(obj)); } [Fact] public void DecodeStructuredModeMessage_NullDataBase64Ignored() { var obj = CreateMinimalValidJObject(); obj["data_base64"] = Newtonsoft.Json.Linq.JValue.CreateNull(); obj["data"] = "some text"; obj["datacontenttype"] = "text/plain"; var cloudEvent = DecodeStructuredModeMessage(obj); Assert.Equal("some text", cloudEvent.Data); } [Fact] public void DecodeStructuredModeMessage_NullDataIgnored() { var obj = CreateMinimalValidJObject(); obj["data_base64"] = SampleBinaryDataBase64; obj["data"] = Newtonsoft.Json.Linq.JValue.CreateNull(); obj["datacontenttype"] = "application/binary"; var cloudEvent = DecodeStructuredModeMessage(obj); Assert.Equal(SampleBinaryData, cloudEvent.Data); } [Fact] public void DecodeBinaryModeEventData_EmptyData_JsonContentType() { var data = DecodeBinaryModeEventData(new byte[0], "application/json"); Assert.Null(data); } [Fact] public void DecodeBinaryModeEventData_EmptyData_TextContentType() { var data = DecodeBinaryModeEventData(new byte[0], "text/plain"); var text = Assert.IsType<string>(data); Assert.Equal("", text); } [Fact] public void DecodeBinaryModeEventData_EmptyData_OtherContentType() { var data = DecodeBinaryModeEventData(new byte[0], "application/binary"); var byteArray = Assert.IsType<byte[]>(data); Assert.Empty(byteArray); } [Theory] [InlineData("utf-8")] [InlineData("utf-16")] public void DecodeBinaryModeEventData_Json(string charset) { var encoding = Encoding.GetEncoding(charset); var bytes = encoding.GetBytes(new JObject { ["test"] = "some text" }.ToString()); var data = DecodeBinaryModeEventData(bytes, $"application/json; charset={charset}"); var element = Assert.IsType<JsonElement>(data); var asserter = new JsonElementAsserter { { "test", JsonValueKind.String, "some text"} }; asserter.AssertProperties(element, assertCount: true); } [Theory] [InlineData("utf-8")] [InlineData("iso-8859-1")] public void DecodeBinaryModeEventData_Text(string charset) { var encoding = Encoding.GetEncoding(charset); var bytes = encoding.GetBytes(NonAsciiValue); var data = DecodeBinaryModeEventData(bytes, $"text/plain; charset={charset}"); var text = Assert.IsType<string>(data); Assert.Equal(NonAsciiValue, text); } [Fact] public void DecodeBinaryModeEventData_Binary() { byte[] bytes = { 0, 1, 2, 3 }; var data = DecodeBinaryModeEventData(bytes, "application/binary"); Assert.Equal(bytes, data); } [Fact] public void DecodeBatchMode_NotArray() { var formatter = new JsonEventFormatter(); var data = Encoding.UTF8.GetBytes(CreateMinimalValidJObject().ToString()); Assert.Throws<ArgumentException>(() => formatter.DecodeBatchModeMessage(data, s_jsonCloudEventBatchContentType, extensionAttributes: null)); } [Fact] public void DecodeBatchMode_ArrayContainingNonObject() { var formatter = new JsonEventFormatter(); var array = new JArray { CreateMinimalValidJObject(), "text" }; var data = Encoding.UTF8.GetBytes(array.ToString()); Assert.Throws<ArgumentException>(() => formatter.DecodeBatchModeMessage(data, s_jsonCloudEventBatchContentType, extensionAttributes: null)); } [Fact] public void DecodeBatchMode_Empty() { var cloudEvents = DecodeBatchModeMessage(new JArray()); Assert.Empty(cloudEvents); } [Fact] public void DecodeBatchMode_Minimal() { var cloudEvents = DecodeBatchModeMessage(new JArray { CreateMinimalValidJObject() }); var cloudEvent = Assert.Single(cloudEvents); Assert.Equal("event-type", cloudEvent.Type); Assert.Equal("event-id", cloudEvent.Id); Assert.Equal(new Uri("//event-source", UriKind.RelativeOrAbsolute), cloudEvent.Source); } [Fact] public void DecodeBatchMode_Minimal_WithStream() { var array = new JArray { CreateMinimalValidJObject() }; var bytes = Encoding.UTF8.GetBytes(array.ToString()); var formatter = new JsonEventFormatter(); var cloudEvents = formatter.DecodeBatchModeMessage(new MemoryStream(bytes), s_jsonCloudEventBatchContentType, null); var cloudEvent = Assert.Single(cloudEvents); Assert.Equal("event-type", cloudEvent.Type); Assert.Equal("event-id", cloudEvent.Id); Assert.Equal(new Uri("//event-source", UriKind.RelativeOrAbsolute), cloudEvent.Source); } // Just a single test for the code that parses asynchronously... the guts are all the same. [Fact] public async Task DecodeBatchModeMessageAsync_Minimal() { var obj = new JObject { ["specversion"] = "1.0", ["type"] = "test-type", ["id"] = "test-id", ["source"] = SampleUriText, }; var bytes = Encoding.UTF8.GetBytes(new JArray { obj }.ToString()); var stream = new MemoryStream(bytes); var formatter = new JsonEventFormatter(); var cloudEvents = await formatter.DecodeBatchModeMessageAsync(stream, s_jsonCloudEventBatchContentType, null); var cloudEvent = Assert.Single(cloudEvents); Assert.Equal("test-type", cloudEvent.Type); Assert.Equal("test-id", cloudEvent.Id); Assert.Equal(SampleUri, cloudEvent.Source); } [Fact] public void DecodeBatchMode_Multiple() { var array = new JArray { new JObject { ["specversion"] = "1.0", ["type"] = "type1", ["id"] = "event1", ["source"] = "//event-source1", ["data"] = "simple text", ["datacontenttype"] = "text/plain" }, new JObject { ["specversion"] = "1.0", ["type"] = "type2", ["id"] = "event2", ["source"] = "//event-source2" }, }; var cloudEvents = DecodeBatchModeMessage(array); Assert.Equal(2, cloudEvents.Count); var event1 = cloudEvents[0]; Assert.Equal("type1", event1.Type); Assert.Equal("event1", event1.Id); Assert.Equal(new Uri("//event-source1", UriKind.RelativeOrAbsolute), event1.Source); Assert.Equal("simple text", event1.Data); Assert.Equal("text/plain", event1.DataContentType); var event2 = cloudEvents[1]; Assert.Equal("type2", event2.Type); Assert.Equal("event2", event2.Id); Assert.Equal(new Uri("//event-source2", UriKind.RelativeOrAbsolute), event2.Source); Assert.Null(event2.Data); Assert.Null(event2.DataContentType); } // Additional tests for the changes/clarifications in https://github.com/cloudevents/spec/pull/861 [Fact] public void EncodeStructured_DefaultContentTypeToApplicationJson() { var cloudEvent = new CloudEvent { Data = new { Key = "value" } }.PopulateRequiredAttributes(); var encoded = new JsonEventFormatter().EncodeStructuredModeMessage(cloudEvent, out var contentType); Assert.Equal("application/cloudevents+json; charset=utf-8", contentType.ToString()); JsonElement obj = ParseJson(encoded); var asserter = new JsonElementAsserter { { "data", JsonValueKind.Object, cloudEvent.Data }, { "datacontenttype", JsonValueKind.String, "application/json" }, { "id", JsonValueKind.String, "test-id" }, { "source", JsonValueKind.String, "//test" }, { "specversion", JsonValueKind.String, "1.0" }, { "type", JsonValueKind.String, "test-type" }, }; asserter.AssertProperties(obj, assertCount: true); } [Fact] public void EncodeStructured_BinaryData_DefaultContentTypeIsNotImplied() { var cloudEvent = new CloudEvent { Data = SampleBinaryData }.PopulateRequiredAttributes(); // If a CloudEvent to have binary data but no data content type, // the spec says the data should be placed in data_base64, but the content type // should *not* be defaulted to application/json, as clarified in https://github.com/cloudevents/spec/issues/933 var encoded = new JsonEventFormatter().EncodeStructuredModeMessage(cloudEvent, out var contentType); Assert.Equal("application/cloudevents+json; charset=utf-8", contentType.ToString()); JsonElement obj = ParseJson(encoded); var asserter = new JsonElementAsserter { { "data_base64", JsonValueKind.String, SampleBinaryDataBase64 }, { "id", JsonValueKind.String, "test-id" }, { "source", JsonValueKind.String, "//test" }, { "specversion", JsonValueKind.String, "1.0" }, { "type", JsonValueKind.String, "test-type" }, }; asserter.AssertProperties(obj, assertCount: true); } [Fact] public void DecodeStructured_DefaultContentTypeToApplicationJson() { var obj = new JObject { ["specversion"] = "1.0", ["type"] = "test-type", ["id"] = "test-id", ["source"] = SampleUriText, ["data"] = "some text" }; var cloudEvent = DecodeStructuredModeMessage(obj); Assert.Equal("application/json", cloudEvent.DataContentType); var jsonData = Assert.IsType<JsonElement>(cloudEvent.Data); Assert.Equal(JsonValueKind.String, jsonData.ValueKind); Assert.Equal("some text", jsonData.GetString()); } // Utility methods private static object DecodeBinaryModeEventData(byte[] bytes, string contentType) { var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); cloudEvent.DataContentType = contentType; new JsonEventFormatter().DecodeBinaryModeEventData(bytes, cloudEvent); return cloudEvent.Data!; } internal static JObject CreateMinimalValidJObject() => new JObject { ["specversion"] = "1.0", ["type"] = "event-type", ["id"] = "event-id", ["source"] = "//event-source" }; /// <summary> /// Parses JSON as a JsonElement. /// </summary> internal static JsonElement ParseJson(string text) { using var document = JsonDocument.Parse(text); return document.RootElement.Clone(); } /// <summary> /// Parses JSON as a JsonElement. /// </summary> internal static JsonElement ParseJson(ReadOnlyMemory<byte> data) { using var document = JsonDocument.Parse(data); return document.RootElement.Clone(); } /// <summary> /// Convenience method to format a CloudEvent with the default JsonEventFormatter in /// structured mode, then parse the result as a JObject. /// </summary> private static JsonElement EncodeAndParseStructured(CloudEvent cloudEvent) { var formatter = new JsonEventFormatter(); var encoded = formatter.EncodeStructuredModeMessage(cloudEvent, out _); return ParseJson(encoded); } /// <summary> /// Convenience method to serialize a JObject to bytes, then /// decode it as a structured event with the default (System.Text.Json) JsonEventFormatter and no extension attributes. /// </summary> private static CloudEvent DecodeStructuredModeMessage(Newtonsoft.Json.Linq.JObject obj) { var bytes = Encoding.UTF8.GetBytes(obj.ToString()); var formatter = new JsonEventFormatter(); return formatter.DecodeStructuredModeMessage(bytes, s_jsonCloudEventContentType, null); } /// <summary> /// Convenience method to serialize a JArray to bytes, then /// decode it as a structured event with the default (System.Text.Json) JsonEventFormatter and no extension attributes. /// </summary> private static IReadOnlyList<CloudEvent> DecodeBatchModeMessage(Newtonsoft.Json.Linq.JArray array) { var bytes = Encoding.UTF8.GetBytes(array.ToString()); var formatter = new JsonEventFormatter(); return formatter.DecodeBatchModeMessage(bytes, s_jsonCloudEventBatchContentType, null); } private class YearMonthDayConverter : JsonConverter<DateTime> { public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => DateTime.ParseExact(reader.GetString()!, "yyyy-MM-dd", CultureInfo.InvariantCulture); public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) => writer.WriteStringValue(value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)); } } }
using System; using System.Text; using System.Collections; using System.Text.RegularExpressions; using System.Security.Cryptography.X509Certificates; using System.Net; using System.IO; using AppUtil; using Vim25Api; using System.Collections.Generic; namespace ColdMigration { ///<summary> ///This sample puts VM files in specified Datacenter and Datastore ///and register and reconfigure the particular VM. ///</summary> ///<param name="vmname">Name of the virtual machine</param> ///<param name="localpath">localpath to copy files</param> ///<param name="datacentername">Name of the datacenter</param> ///<param name="datastorename">Name of the datastore</param> ///<remarks> ///--url [webserviceurl] ///--username [username]--password [password] --vmname [vmname] --localpath[localpath] ///--datacentername [datacentername] --datastorename [datastorename] ///</remarks> class ColdMigration { private static AppUtil.AppUtil cb = null; static VimService _service; static ServiceContent _sic; private ArrayList vdiskName = new ArrayList(); /// <summary> /// Gets virtual machine name. /// </summary> /// <returns>Returns string type vmName</returns> private String getVmName() { return cb.get_option("vmname"); } /// <summary> /// Gets local path. /// </summary> /// <returns>Returns string type localpath</returns> private String getLocalPath() { return cb.get_option("localpath"); } /// <summary> /// Gets datacenter name. /// </summary> /// <returns>Returns string type datacentername.</returns> private String getDataCenter() { return cb.get_option("datacentername"); } /// <summary> /// Gets datastore name. /// </summary> /// <returns>Returns string type datastorename.</returns> private String getDataStore() { return cb.get_option("datastorename"); } ///<summary> ///The function gets cookies of url. ///</summary> ///<returns>Returns the string type cookie string.</returns> private String getCookie() { Cookie cookie = cb._connection._service.CookieContainer.GetCookies( new Uri(cb.get_option("url")))[0]; String cookieString = cookie.ToString(); return cookieString; } /// <summary> /// Dump the data, register the virtual machine and do reconfig if specified. /// File greater than 500 MB is not supported. /// </summary> private void coldMigration() { _service = cb.getConnection()._service; _sic = cb.getConnection()._sic; Boolean validated = customValidation(); if(validated) { String[] listOfDir = getSubDirectories(getLocalPath()); if(listOfDir != null && listOfDir.Length != 0) { Boolean bSize = false; // Dumping All The Data for(int i=0; i<listOfDir.Length; i++) { bSize = copyDir(listOfDir[i]); } if (bSize.ToString() == "True") { // Register The Virtual Machine Boolean regFlag = registerVirtualMachine(); //Reconfig All The Stuff Back if (regFlag) { reconfigVirtualMachine(); } } else { Console.WriteLine("Only copying files less than 500 MB is supported"); } } else { Console.WriteLine("There are no VM Directories" +" available on Specified locations"); } } else { // DO NOTHING } } /// <summary> /// Copying the directory. /// </summary> /// <param name="dirName"></param> /// <returns>Returns the boolean value true or false.</returns> private Boolean copyDir(String dirName) { Console.WriteLine("Copying The Virtual Machine To Host.........."); // dirName = getLocalPath() + "/" + dirName; String [] listOfFiles = getDirFiles(dirName); long fileSize = 0; for(int i=0; i<listOfFiles.Length; i++) { System.IO.FileInfo info = new System.IO.FileInfo(listOfFiles[i].ToString()); fileSize = info.Length; if (fileSize > 524288000) { return false; } String remoteFilePath = "/"+getVmName()+"/"+listOfFiles[i].Substring(listOfFiles[i].LastIndexOf("\\")+1); String localFilePath = dirName + "\\" + listOfFiles[i].Substring(listOfFiles[i].LastIndexOf("\\") + 1); if(localFilePath.IndexOf("vdisk") != -1) { String dataStoreName = dirName.Substring(dirName.LastIndexOf("#")+1); remoteFilePath = "/" + getVmName() + "/" + dataStoreName + "/" + listOfFiles[i].Substring(listOfFiles[i].LastIndexOf("\\") + 1); if(localFilePath.IndexOf("flat") == -1) { vdiskName.Add(dataStoreName+"/"+listOfFiles[i]); } } else { remoteFilePath = "/"+getVmName()+"/"+listOfFiles[i].Substring(listOfFiles[i].LastIndexOf("\\")+1); } putVMFiles(remoteFilePath,localFilePath); } Console.WriteLine("Copying The Virtual Machine To Host..........Done"); return true; } /// <summary> /// Upload the VM files from local path. /// </summary> /// <param name="remoteFilePath"></param> /// <param name="localFilePath"></param> private void putVMFiles(String remoteFilePath, String localFilePath) { try { String serviceUrl = cb.getServiceUrl(); serviceUrl = serviceUrl.Substring(0, serviceUrl.LastIndexOf("sdk") - 1); String httpUrl = serviceUrl + "/folder" + remoteFilePath + "?dcPath=" + getDataCenter() + "&dsName=" + getDataStore(); httpUrl = httpUrl.Replace("\\ ", "%20"); Console.WriteLine("Putting VM File " + httpUrl); WebClient client = new WebClient(); NetworkCredential nwCred = new NetworkCredential(); nwCred.UserName = cb.get_option("username"); nwCred.Password = cb.get_option("password"); client.Credentials = nwCred; client.Headers.Add(HttpRequestHeader.Cookie, getCookie()); client.UploadFile(httpUrl, "PUT", localFilePath); } catch (Exception e) { Console.WriteLine(e.Message.ToString()); } } /// <summary> /// Gets datacenter for particular vm managed object reference. /// </summary> /// <param name="vmmor"></param> /// <returns>Returns string value dcName.</returns> private String getDataCenter(ManagedObjectReference vmmor) { ManagedObjectReference morParent = cb.getServiceUtil().GetMoRefProp(vmmor,"parent"); morParent = cb.getServiceUtil().GetMoRefProp(morParent, "parent"); Object objdcName = cb.getServiceUtil().GetDynamicProperty(morParent, "name"); String dcName = objdcName.ToString(); return dcName; } /// <summary> /// Register the virtual machine. /// </summary> /// <returns>Returns the boolean value true or false.</returns> private Boolean registerVirtualMachine() { Boolean registered = false; Console.WriteLine("Registering The Virtual Machine .........."); // Get datacenter var serviceUtil = cb.getServiceUtil(); var dataCenterMoref = serviceUtil.GetDecendentMoRef(_sic.rootFolder, "Datacenter", getDataCenter()); var vmFolderMoref = (ManagedObjectReference)serviceUtil.GetDynamicProperty(dataCenterMoref, "vmFolder"); // Get datastore var datastoreMorefs = (ManagedObjectReference[])serviceUtil.GetDynamicProperty(dataCenterMoref, "datastore"); var dirSize = getDirSize(getLocalPath()); ManagedObjectReference targetDatastoreMoref = null; foreach (var datastoreMoref in datastoreMorefs) { var datastoreSummary = (DatastoreSummary)serviceUtil.GetDynamicProperty(datastoreMoref, "summary"); if (datastoreSummary.name.Equals(getDataStore(), StringComparison.CurrentCultureIgnoreCase)) { var datastoreInfo = (DatastoreInfo)serviceUtil.GetDynamicProperty(datastoreMoref, "info"); if (datastoreInfo.freeSpace > dirSize) { targetDatastoreMoref = datastoreMoref; break; } } } if (targetDatastoreMoref == null) { Console.WriteLine("Could not find user entered datastore."); return registered; } // Select the first accessible host attached to the datastore var datastoreHostMounts = (DatastoreHostMount[])serviceUtil.GetDynamicProperty(targetDatastoreMoref, "host"); ManagedObjectReference targetHostSystemMoref = null; foreach (var datastoreHostMount in datastoreHostMounts) { if (datastoreHostMount.mountInfo.accessible) targetHostSystemMoref = datastoreHostMount.key; } if (targetHostSystemMoref == null) { Console.WriteLine( "No accessible host found in datacenter that has the specified datastore and free space."); return registered; } else { // Get vmx path var vmxPath = "[" + getDataStore() + "] " + getVmName() + "/" + getVmName() + ".vmx"; // The parent of a host system is either ComputeResource or ClusterComputeResource var computeResourceRef = (ManagedObjectReference)serviceUtil.GetDynamicProperty(targetHostSystemMoref, "parent"); // Get resource pool of the compute resource var resourcePoolMoref = (ManagedObjectReference)serviceUtil.GetMoRefProp(computeResourceRef, "resourcePool"); // Registering the virtual machine var taskmor = _service.RegisterVM_Task( vmFolderMoref, vmxPath, getVmName(), false, resourcePoolMoref, targetHostSystemMoref); string result = serviceUtil.WaitForTask(taskmor); if (result.Equals("sucess")) { Console.WriteLine("Registering The Virtual Machine ..........Done"); registered = true; } else { Console.WriteLine("Some Exception While Registering The VM"); registered = false; } return registered; } } /// <summary> /// Reconfig the virtual machine. /// </summary> private void reconfigVirtualMachine() { Console.WriteLine("ReConfigure The Virtual Machine .........."); VirtualMachineFileInfo vmFileInfo = new VirtualMachineFileInfo(); vmFileInfo.logDirectory = "["+getDataStore()+"]"+getVmName(); vmFileInfo.snapshotDirectory= "["+getDataStore()+"]"+getVmName(); vmFileInfo.suspendDirectory= "["+getDataStore()+"]"+getVmName(); vmFileInfo.vmPathName= "["+getDataStore() +"]"+getVmName()+"/"+getVmName()+".vmx"; VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); vmConfigSpec.files =vmFileInfo; ManagedObjectReference taskmor = _service.ReconfigVM_Task( getVmMor(getVmName()),vmConfigSpec); Object[] result = cb.getServiceUtil().WaitForValues( taskmor, new String[] { "info.state", "info.error" }, new String[] { "state" }, new Object[][] { new Object[] { TaskInfoState.success, TaskInfoState.error }} ); if (result[0].Equals(TaskInfoState.success)) { Console.WriteLine("ReConfigure The Virtual Machine .......... Done"); } else { Console.WriteLine("Some Exception While Reconfiguring The VM " + result[0]); } } /// <summary> /// Gets the managed object reference of particular virtual machine. /// </summary> /// <param name="vmName"></param> /// <returns>Returns the mor.</returns> private ManagedObjectReference getVmMor(String vmName) { ManagedObjectReference vmmor = cb.getServiceUtil().GetDecendentMoRef(null, "VirtualMachine", getVmName()); return vmmor; } /// <summary> /// Gets the sub directory of any local directory. /// </summary> /// <param name="localDir"></param> /// <returns>Returns the string array.</returns> private String[] getSubDirectories(String localDir) { String[] listOfDirectories = Directory.GetDirectories(localDir); if (listOfDirectories != null) { return listOfDirectories; } else { Console.WriteLine("Local Path Doesn't Exist"); return null; } } /// <summary> /// Gets the directory files. /// </summary> /// <param name="localDir"></param> /// <returns>Returns the string array.</returns> private String [] getDirFiles(String localDir) { String[] listOfFiles = Directory.GetFiles(localDir); if(listOfFiles != null) { return listOfFiles; } else { Console.WriteLine("Local Path Doesn't Exist"); return null; } } /// <summary> /// Gets the directory size. /// </summary> /// <param name="localDir"></param> /// <returns>Returns size.</returns> private long getDirSize(String localDir) { String[] fileList = Directory.GetFiles(localDir); long size = 0; if(fileList.Length != 0) { for(int i=0; i<fileList.Length; i++) { System.IO.FileInfo temp = new System.IO.FileInfo(localDir + "/" + fileList[i]); temp.Create(); if(temp.Exists) { size = size + getDirSize(temp.Directory.FullName); } else { size = size + temp.Length; } } } else { // DO NOTHING } return size; } /// <summary> /// Does the custom validation. /// </summary> /// <returns>Returns the boolean type true or false.</returns> private Boolean customValidation() { Boolean validate = false; String datacenterName = getDataCenter(); String datastoreName = getDataStore(); if(datacenterName.Length != 0 && datacenterName != null && datastoreName.Length != 0 && datastoreName != null) { ManagedObjectReference dcmor = cb.getServiceUtil().GetDecendentMoRef(null, "Datacenter", datacenterName); if(dcmor != null) { ManagedObjectReference [] datastores = (ManagedObjectReference []) cb.getServiceUtil().GetDynamicProperty(dcmor,"datastore"); if(datastores.Length != 0) { for(int i=0; i<datastores.Length; i++) { DatastoreSummary dsSummary = (DatastoreSummary) cb.getServiceUtil().GetDynamicProperty(datastores[i], "summary"); if(dsSummary.name.Equals(datastoreName)) { i = datastores.Length + 1; validate = true; } } if(!validate) { Console.WriteLine("Specified Datastore is not" +" found in specified Datacenter"); } return validate; } else { Console.WriteLine("No Datastore found in specified Datacenter"); return validate; } } else { Console.WriteLine("Specified Datacenter Not Found"); return validate; } } return validate; } ///<summary> ///This method is used to add application specific user options ///</summary> ///<returns> Array of OptionSpec containing the details of application specific user options ///</returns> public static OptionSpec[] constructOptions() { OptionSpec[] useroptions = new OptionSpec[4]; useroptions[0] = new OptionSpec("vmname", "String", 1 , "Name of the virtual machine" , null); useroptions[1] = new OptionSpec("localpath", "String", 1, "Localpath to copy files", null); useroptions[2] = new OptionSpec("datacentername", "String", 1, "Name of the datacenter", null); useroptions[3] = new OptionSpec("datastorename", "String", 1, "Name of the datastore", null); return useroptions; } /// <summary> /// The main entry point for the application. /// </summary> public static void Main(String[] args) { ColdMigration obj = new ColdMigration(); cb = AppUtil.AppUtil.initialize("ColdMigration" , ColdMigration.constructOptions() , args); cb.connect(); obj.coldMigration(); cb.disConnect(); Console.WriteLine("Please enter any key to exit: "); Console.Read(); } } }
using UnityEngine; using System.Collections; using System.Runtime.InteropServices; using System.IO; using System; //Dive Head Tracking // copyright by Shoogee GmbH & Co. KG Refer to LICENCE.txt //[ExecuteInEditMode] public class OpenDiveSensor : MonoBehaviour { // This is used for rotating the camera with another object //for example tilting the camera while going along a racetrack or rollercoaster public bool add_rotation_gameobject=false; public GameObject rotation_gameobject; // mouse emulation public bool emulateMouseInEditor=true; public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 } public RotationAxes axes = RotationAxes.MouseXAndY; public Texture nogyrotexture; /// Offset projection for 2 cameras in VR private float offset =0.0f; private float max_offset=0.002f; //public float max_offcenter_warp=0.1f; public Camera cameraleft; public Camera cameraright; public float zoom=0.1f; private float IPDCorrection=0.0f; private float aspectRatio; public float znear=0.1f; public float zfar=10000.0f; private float time_since_last_fullscreen=0; private int is_tablet; AndroidJavaObject mConfig; AndroidJavaObject mWindowManager; private float q0,q1,q2,q3; private float m0,m1,m2; Quaternion rot; private bool show_gyro_error_message=false; string errormessage; #if UNITY_EDITOR private float sensitivityX = 15F; private float sensitivityY = 15F; private float minimumX = -360F; private float maximumX = 360F; private float minimumY = -90F; private float maximumY = 90F; float rotationY = 0F; #elif UNITY_ANDROID private static AndroidJavaClass javadivepluginclass; private static AndroidJavaClass javaunityplayerclass; private static AndroidJavaObject currentactivity; private static AndroidJavaObject javadiveplugininstance; [DllImport("divesensor")] private static extern void initialize_sensors(); [DllImport("divesensor")] private static extern int get_q(ref float q0,ref float q1,ref float q2,ref float q3); [DllImport("divesensor")] private static extern int get_m(ref float m0,ref float m1,ref float m2); [DllImport("divesensor")] private static extern int get_error(); [DllImport("divesensor")] private static extern void dive_command(string command); #elif UNITY_IPHONE [DllImport("__Internal")] private static extern void initialize_sensors(); [DllImport("__Internal")] private static extern float get_q0(); [DllImport("__Internal")] private static extern float get_q1(); [DllImport("__Internal")] private static extern float get_q2(); [DllImport("__Internal")] private static extern float get_q3(); [DllImport("__Internal")] private static extern void DiveUpdateGyroData(); [DllImport("__Internal")] private static extern int get_q(ref float q0,ref float q1,ref float q2,ref float q3); #endif public static void divecommand(string command){ #if UNITY_EDITOR #elif UNITY_ANDROID dive_command(command); #elif UNITY_IPHONE #endif } public static void setFullscreen(){ #if UNITY_EDITOR #elif UNITY_ANDROID String answer; answer= javadiveplugininstance.Call<string>("setFullscreen"); #elif UNITY_IPHONE #endif return; } void Start () { rot=Quaternion.identity; // Disable screen dimming Screen.sleepTimeout = SleepTimeout.NeverSleep; Application.targetFrameRate = 60; #if UNITY_EDITOR if (GetComponent<Rigidbody>()) GetComponent<Rigidbody>().freezeRotation = true; #elif UNITY_ANDROID // Java part javadivepluginclass = new AndroidJavaClass("com.shoogee.divejava.divejava") ; javaunityplayerclass= new AndroidJavaClass("com.unity3d.player.UnityPlayer"); currentactivity = javaunityplayerclass.GetStatic<AndroidJavaObject>("currentActivity"); javadiveplugininstance = javadivepluginclass.CallStatic<AndroidJavaObject>("instance"); object[] args={currentactivity}; javadiveplugininstance.Call<string>("set_activity",args); initialize_sensors (); String answer; answer= javadiveplugininstance.Call<string>("initializeDive"); answer= javadiveplugininstance.Call<string>("getDeviceType"); if (answer=="Tablet"){ is_tablet=1; Debug.Log("Dive Unity Tablet Mode activated"); } else{ Debug.Log("Dive Phone Mode activated "+answer); } answer= javadiveplugininstance.Call<string>("setFullscreen"); show_gyro_error_message=true; Network.logLevel = NetworkLogLevel.Full; int err = get_error(); if (err==0){ errormessage=""; show_gyro_error_message=false; } if (err==1){ show_gyro_error_message=true; errormessage="ERROR: Dive needs a Gyroscope and your telephone has none, we are trying to go to Accelerometer compatibility mode. Dont expect too much."; } #elif UNITY_IPHONE initialize_sensors(); #endif float tabletcorrection=-0.028f; //is_tablet=0; if (is_tablet==1) { Debug.Log ("Is tablet, using tabletcorrection"); IPDCorrection=tabletcorrection; } else { IPDCorrection=IPDCorrection; } //setIPDCorrection(IPDCorrection); } void Update () { aspectRatio=(Screen.height*2.0f)/Screen.width; setIPDCorrection(IPDCorrection); //Debug.Log ("Divecamera"+cameraleft.aspect+"1/asp "+1/cameraleft.aspect+" Screen Width/Height "+ aspectRatio); #if UNITY_EDITOR #elif UNITY_ANDROID time_since_last_fullscreen+=Time.deltaTime; if (time_since_last_fullscreen >8){ setFullscreen (); time_since_last_fullscreen=0; } get_q(ref q0,ref q1,ref q2,ref q3); //get_m(ref m0,ref m1,ref m2); rot.x=-q2;rot.y=q3;rot.z=-q1;rot.w=q0; if (add_rotation_gameobject){ transform.rotation =rotation_gameobject.transform.rotation* rot; } else { transform.rotation = rot; if (is_tablet==1)transform.rotation=rot*Quaternion.AngleAxis(90,Vector3.forward); } #elif UNITY_IPHONE DiveUpdateGyroData(); get_q(ref q0,ref q1,ref q2,ref q3); rot.x=-q2; rot.y=q3; rot.z=-q1; rot.w=q0; transform.rotation = rot; if (add_rotation_gameobject){ transform.rotation =rotation_gameobject.transform.rotation* rot; } else { transform.rotation = rot; if (is_tablet==1)transform.rotation=rot*Quaternion.AngleAxis(90,Vector3.forward); } #endif #if UNITY_EDITOR if (emulateMouseInEditor){ if (axes == RotationAxes.MouseXAndY) { float rotationX = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * sensitivityX; rotationY += Input.GetAxis("Mouse Y") * sensitivityY; rotationY = Mathf.Clamp (rotationY, minimumY, maximumY); transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0); } else if (axes == RotationAxes.MouseX) { transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityX, 0); } else { rotationY += Input.GetAxis("Mouse Y ") * sensitivityY; rotationY = Mathf.Clamp (rotationY, minimumY, maximumY); transform.localEulerAngles = new Vector3(-rotationY, transform.localEulerAngles.y, 0); } } #endif } void OnGUI () { /* if (GUI.Button(new Rect(Screen.width/4-150, Screen.height-100, 300,100), "+IPD")){ Debug.Log("Clicked the button with an image"); IPDCorrection=IPDCorrection+0.01f; setIPDCorrection(IPDCorrection); } if (GUI.Button(new Rect(Screen.width-Screen.width/4-150, Screen.height-100, 300,100), "-IPD")){ Debug.Log("Clicked the button with an image"); IPDCorrection=IPDCorrection-0.01f; setIPDCorrection(IPDCorrection); } */ if (show_gyro_error_message) { if(GUI.Button(new Rect(0,0, Screen.width, Screen.height) , "Error: \n\n No Gyro detected \n \n Touch screen to continue anyway")) { show_gyro_error_message=false; } GUI.DrawTexture(new Rect(Screen.width/2-320, Screen.height/2-240, 640, 480), nogyrotexture, ScaleMode.ScaleToFit, true, 0); return; } } void setIPDCorrection(float correction) { // not using camera nearclipplane value because that leads to problems with field of view in different projects cameraleft.projectionMatrix = PerspectiveOffCenter((-zoom+correction)*(znear/0.1f), (zoom+correction)*(znear/0.1f), -zoom*(znear/0.1f)*aspectRatio, zoom*(znear/0.1f)*aspectRatio, znear, zfar);; cameraright.projectionMatrix = PerspectiveOffCenter((-zoom-correction)*(znear/0.1f), (zoom-correction)*(znear/0.1f), -zoom*(znear/0.1f)*aspectRatio, zoom*(znear/0.1f)*aspectRatio, znear, zfar);; } static Matrix4x4 PerspectiveOffCenter(float left, float right, float bottom, float top, float near, float far) { float x = 2.0F * near / (right - left); float y = 2.0F * near / (top - bottom); float a = (right + left) / (right - left); float b = (top + bottom) / (top - bottom); float c = -(far + near) / (far - near); float d = -(2.0F * far * near) / (far - near); float e = -1.0F; Matrix4x4 m = new Matrix4x4(); m[0, 0] = x; m[0, 1] = 0; m[0, 2] = a; m[0, 3] = 0; m[1, 0] = 0; m[1, 1] = y; m[1, 2] = b; m[1, 3] = 0; m[2, 0] = 0; m[2, 1] = 0; m[2, 2] = c; m[2, 3] = d; m[3, 0] = 0; m[3, 1] = 0; m[3, 2] = e; m[3, 3] = 0; return m; } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Protocols.TestTools.StackSdk.Compression.Mppc; using Microsoft.Protocols.TestTools.ExtendedLogging; namespace Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpbcgr { public class StaticVirtualChannelName { public static string RDPEDYC = "DRDYNVC"; } /// <summary> /// Send SVC Data /// </summary> /// <param name="channelId">Static virtual channel ID</param> /// <param name="channelHeader">Channel_PDU_Header</param> /// <param name="SVCData">Static virtual channel data to be sent</param> public delegate void SendSVCData(UInt16 channelId, CHANNEL_PDU_HEADER channelHeader, byte[] SVCData); /// <summary> /// Process received data /// </summary> /// <param name="data"></param> public delegate void ReceiveData(byte[] data); /// <summary> /// Base class for Static Virtual Channel /// </summary> public abstract class StaticVirtualChannel { #region Variables /// <summary> /// Channel ID of this static virtual channel /// </summary> protected UInt16 channelId; /// <summary> /// Channel Name of this static virtual channel /// </summary> protected string channelName; /// <summary> /// Channel options /// </summary> protected Channel_Options channelOptions; protected Compressor mppcCompressor; protected Decompressor mppcDecompressor; /// <summary> /// Method used to send SVC data /// </summary> protected SendSVCData Sender; /// <summary> /// How much data could be put into a chunk /// </summary> protected uint maxChunkSize; /// <summary> /// Contains the decompressed data. /// </summary> protected List<byte> decompressedBuffer; #endregion Variables #region Properties /// <summary> /// Channel ID /// </summary> public UInt16 ChannelId { get { return channelId; } } /// <summary> /// Channel Name /// </summary> public string ChannelName { get { return channelName; } } /// <summary> /// Channel Options /// </summary> public Channel_Options ChannelOptions { get { return channelOptions; } } #endregion Properties #region Constructor /// <summary> /// Constructor /// </summary> /// <param name="id">Channel ID</param> /// <param name="name">Channel Name</param> /// <param name="options">Channel Options</param> /// <param name="chunkSize">Max chunk size</param> /// <param name="compressType">Compress Type</param> /// <param name="decompressType">Decompress Type</param> /// <param name="sender">Method used to send packet</param> public StaticVirtualChannel(UInt16 id, string name, Channel_Options options, uint chunkSize, CompressionType compressType, CompressionType decompressType, SendSVCData sender) { this.channelId = id; this.channelName = name; this.channelOptions = options; this.maxChunkSize = chunkSize; this.decompressedBuffer = new List<byte>(); if (compressType != CompressionType.PACKET_COMPR_TYPE_NONE) { mppcCompressor = new Compressor((SlidingWindowSize)compressType); } if (decompressType != CompressionType.PACKET_COMPR_TYPE_NONE) { mppcDecompressor = new Decompressor((SlidingWindowSize)decompressType); } this.Sender = sender; } #endregion Constructor #region Public methods /// <summary> /// Send data from this channel /// </summary> /// <param name="data"></param> public void Send(byte[] data) { if (data == null || data.Length == 0) { return; } ChannelChunk[] chunks = SplitToChunks(data); foreach (ChannelChunk chunk in chunks) { Sender(ChannelId, chunk.channelPduHeader, chunk.chunkData); } // ETW Provider Dump message string messageName = "RDPBCGR:SVC Sent Data"; ExtendedLogger.DumpMessage(messageName, RdpbcgrUtility.DumpLevel_Layer1, "RDPBCGR: Static Virtual Channel Sent Data", data); } /// <summary> /// Event called when received SVC data /// </summary> public event ReceiveData Received; /// <summary> /// Process received static virtual channel packet /// </summary> /// <param name="packet"></param> public abstract void ReceivePackets(StackPacket packet); #endregion Public methods #region Protected Methods /// <summary> /// Process Static virtual channel data /// </summary> /// <param name="data"></param> protected void ProcessSVCData(byte[] data) { if (this.Received != null) { Received(data); } // ETW Provider Dump message string messageName = "RDPBCGR:SVC Received Data"; ExtendedLogger.DumpMessage(messageName, RdpbcgrUtility.DumpLevel_Layer1, "RDPBCGR: Static Virtual Channel Received Data", data); } #endregion Protected Methods #region Internal Methods /// <summary> /// Split and compress the complete virtual channel data into chunk data. /// </summary> /// <param name="completeData">The compete virtual channel data. This argument can be null.</param> /// <returns>The splitted chunk data.</returns> internal ChannelChunk[] SplitToChunks(byte[] completeData) { if (completeData == null || completeData.Length <= 0) { return null; } // calculate the number of the chunks int chunkNum = (int)(completeData.Length / maxChunkSize); if ((completeData.Length % maxChunkSize) != 0) { chunkNum++; } ChannelChunk[] chunks = new ChannelChunk[chunkNum]; uint chunkSize = maxChunkSize; // fill the chunks except the last one for (int i = 0; i < chunkNum; i++) { if (i == chunkNum - 1) // the last chunk { chunkSize = (uint)(completeData.Length - maxChunkSize * i); } byte[] chunkData = new byte[chunkSize]; Array.Copy(completeData, maxChunkSize * i, chunkData, 0, chunkSize); chunks[i].channelPduHeader.length = (uint)completeData.Length; if (mppcCompressor != null && channelOptions == Channel_Options.COMPRESS) // has compression { CompressMode flag; chunks[i].chunkData = mppcCompressor.Compress(chunkData, out flag); if ((flag & CompressMode.Compressed) == CompressMode.Compressed) { chunks[i].channelPduHeader.flags |= CHANNEL_PDU_HEADER_flags_Values.CHANNEL_PACKET_COMPRESSED; } if ((flag & CompressMode.Flush) == CompressMode.Flush) { chunks[i].channelPduHeader.flags |= CHANNEL_PDU_HEADER_flags_Values.CHANNEL_PACKET_FLUSHED; } if ((flag & CompressMode.SetToFront) == CompressMode.SetToFront) { chunks[i].channelPduHeader.flags |= CHANNEL_PDU_HEADER_flags_Values.CHANNEL_PACKET_AT_FRONT; } } else // no compression { chunks[i].chunkData = chunkData; } } // set the first chunk CHANNEL_FLAG_FIRST chunks[0].channelPduHeader.flags |= CHANNEL_PDU_HEADER_flags_Values.CHANNEL_FLAG_FIRST; // the last chunk chunks[chunkNum - 1].channelPduHeader.flags |= CHANNEL_PDU_HEADER_flags_Values.CHANNEL_FLAG_LAST; return chunks; } #endregion Internal Methods } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace WebHost.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; namespace System.Numerics.Tests { public static class MyBigIntImp { public static BigInteger outParam = 0; public static BigInteger DoUnaryOperatorMine(BigInteger num1, string op) { List<byte> bytes1 = new List<byte>(num1.ToByteArray()); int factor; double result; switch (op) { case "uSign": if (IsZero(bytes1)) { return new BigInteger(0); } if (IsZero(Max(bytes1, new List<byte>(new byte[] { 0 })))) { return new BigInteger(-1); } return new BigInteger(1); case "u~": return new BigInteger(Not(bytes1).ToArray()); case "uLog10": factor = unchecked((int)BigInteger.Log(num1, 10)); if (factor > 100) { for (int i = 0; i < factor - 100; i++) { num1 = num1 / 10; } } result = Math.Log10((double)num1); if (factor > 100) { for (int i = 0; i < factor - 100; i++) { result = result + 1; } } return ApproximateBigInteger(result); case "uLog": factor = unchecked((int)BigInteger.Log(num1, 10)); if (factor > 100) { for (int i = 0; i < factor - 100; i++) { num1 = num1 / 10; } } result = Math.Log((double)num1); if (factor > 100) { for (int i = 0; i < factor - 100; i++) { result = result + Math.Log(10); } } return ApproximateBigInteger(result); case "uAbs": if ((bytes1[bytes1.Count - 1] & 0x80) != 0) { bytes1 = Negate(bytes1); } return new BigInteger(bytes1.ToArray()); case "u--": return new BigInteger(Add(bytes1, new List<byte>(new byte[] { 0xff })).ToArray()); case "u++": return new BigInteger(Add(bytes1, new List<byte>(new byte[] { 1 })).ToArray()); case "uNegate": case "u-": return new BigInteger(Negate(bytes1).ToArray()); case "u+": return num1; case "uMultiply": case "u*": return new BigInteger(Multiply(bytes1, bytes1).ToArray()); default: throw new ArgumentException(String.Format("Invalid operation found: {0}", op)); } } public static BigInteger DoBinaryOperatorMine(BigInteger num1, BigInteger num2, string op) { List<byte> bytes1 = new List<byte>(num1.ToByteArray()); List<byte> bytes2 = new List<byte>(num2.ToByteArray()); switch (op) { case "bMin": return new BigInteger(Negate(Max(Negate(bytes1), Negate(bytes2))).ToArray()); case "bMax": return new BigInteger(Max(bytes1, bytes2).ToArray()); case "b>>": return new BigInteger(ShiftLeft(bytes1, Negate(bytes2)).ToArray()); case "b<<": return new BigInteger(ShiftLeft(bytes1, bytes2).ToArray()); case "b^": return new BigInteger(Xor(bytes1, bytes2).ToArray()); case "b|": return new BigInteger(Or(bytes1, bytes2).ToArray()); case "b&": return new BigInteger(And(bytes1, bytes2).ToArray()); case "bLog": return ApproximateBigInteger(Math.Log((double)num1, (double)num2)); case "bGCD": return new BigInteger(GCD(bytes1, bytes2).ToArray()); case "bPow": int arg2 = (int)num2; bytes2 = new List<byte>(new BigInteger(arg2).ToByteArray()); return new BigInteger(Pow(bytes1, bytes2).ToArray()); case "bDivRem": BigInteger ret = new BigInteger(Divide(bytes1, bytes2).ToArray()); bytes1 = new List<byte>(num1.ToByteArray()); bytes2 = new List<byte>(num2.ToByteArray()); outParam = new BigInteger(Remainder(bytes1, bytes2).ToArray()); return ret; case "bRemainder": case "b%": return new BigInteger(Remainder(bytes1, bytes2).ToArray()); case "bDivide": case "b/": return new BigInteger(Divide(bytes1, bytes2).ToArray()); case "bMultiply": case "b*": return new BigInteger(Multiply(bytes1, bytes2).ToArray()); case "bSubtract": case "b-": bytes2 = Negate(bytes2); goto case "bAdd"; case "bAdd": case "b+": return new BigInteger(Add(bytes1, bytes2).ToArray()); default: throw new ArgumentException(String.Format("Invalid operation found: {0}", op)); } } public static BigInteger DoTertanaryOperatorMine(BigInteger num1, BigInteger num2, BigInteger num3, string op) { List<byte> bytes1 = new List<byte>(num1.ToByteArray()); List<byte> bytes2 = new List<byte>(num2.ToByteArray()); List<byte> bytes3 = new List<byte>(num3.ToByteArray()); switch (op) { case "tModPow": return new BigInteger(ModPow(bytes1, bytes2, bytes3).ToArray()); default: throw new ArgumentException(String.Format("Invalid operation found: {0}", op)); } } public static List<byte> Add(List<byte> bytes1, List<byte> bytes2) { List<byte> bnew = new List<byte>(); bool num1neg = (bytes1[bytes1.Count - 1] & 0x80) != 0; bool num2neg = (bytes2[bytes2.Count - 1] & 0x80) != 0; byte extender = 0; bool bnewneg; bool carry; NormalizeLengths(bytes1, bytes2); carry = false; for (int i = 0; i < bytes1.Count; i++) { int temp = bytes1[i] + bytes2[i]; if (carry) { temp++; } carry = false; if (temp > byte.MaxValue) { temp -= byte.MaxValue + 1; carry = true; } bnew.Add((byte)temp); } bnewneg = (bnew[bnew.Count - 1] & 0x80) != 0; if ((num1neg == num2neg) & (num1neg != bnewneg)) { if (num1neg) { extender = 0xff; } bnew.Add(extender); } return bnew; } public static List<byte> Negate(List<byte> bytes) { bool carry; List<byte> bnew = new List<byte>(); bool bsame; for (int i = 0; i < bytes.Count; i++) { bytes[i] ^= 0xFF; } carry = false; for (int i = 0; i < bytes.Count; i++) { int temp = (i == 0 ? 0x01 : 0x00) + bytes[i]; if (carry) { temp++; } carry = false; if (temp > byte.MaxValue) { temp -= byte.MaxValue + 1; carry = true; } bnew.Add((byte)temp); } bsame = ((bnew[bnew.Count - 1] & 0x80) != 0); bsame &= ((bnew[bnew.Count - 1] & 0x7f) == 0); for (int i = bnew.Count - 2; i >= 0; i--) { bsame &= (bnew[i] == 0); } if (bsame) { bnew.Add((byte)0); } return bnew; } public static List<byte> Multiply(List<byte> bytes1, List<byte> bytes2) { NormalizeLengths(bytes1, bytes2); List<byte> bresult = new List<byte>(); for (int i = 0; i < bytes1.Count; i++) { bresult.Add((byte)0x00); bresult.Add((byte)0x00); } NormalizeLengths(bytes2, bresult); NormalizeLengths(bytes1, bresult); BitArray ba2 = new BitArray(bytes2.ToArray()); for (int i = ba2.Length - 1; i >= 0; i--) { if (ba2[i]) { bresult = Add(bytes1, bresult); } if (i != 0) { bresult = ShiftLeftDrop(bresult); } } bresult = SetLength(bresult, bytes2.Count); return bresult; } public static List<byte> Divide(List<byte> bytes1, List<byte> bytes2) { bool numPos = ((bytes1[bytes1.Count - 1] & 0x80) == 0); bool denPos = ((bytes2[bytes2.Count - 1] & 0x80) == 0); if (!numPos) { bytes1 = Negate(bytes1); } if (!denPos) { bytes2 = Negate(bytes2); } bool qPos = (numPos == denPos); Trim(bytes1); Trim(bytes2); BitArray ba1 = new BitArray(bytes1.ToArray()); BitArray ba2 = new BitArray(bytes2.ToArray()); int ba11loc = 0; for (int i = ba1.Length - 1; i >= 0; i--) { if (ba1[i]) { ba11loc = i; break; } } int ba21loc = 0; for (int i = ba2.Length - 1; i >= 0; i--) { if (ba2[i]) { ba21loc = i; break; } } int shift = ba11loc - ba21loc; if (shift < 0) { return new List<byte>(new byte[] { (byte)0 }); } BitArray br = new BitArray(shift + 1, false); for (int i = 0; i < shift; i++) { bytes2 = ShiftLeftGrow(bytes2); } while (shift >= 0) { bytes2 = Negate(bytes2); bytes1 = Add(bytes1, bytes2); bytes2 = Negate(bytes2); if (bytes1[bytes1.Count - 1] < 128) { br[shift] = true; } else { bytes1 = Add(bytes1, bytes2); } bytes2 = ShiftRight(bytes2); shift--; } List<byte> result = GetBytes(br); if (!qPos) { result = Negate(result); } return result; } public static List<byte> Remainder(List<byte> bytes1, List<byte> bytes2) { bool numPos = ((bytes1[bytes1.Count - 1] & 0x80) == 0); bool denPos = ((bytes2[bytes2.Count - 1] & 0x80) == 0); if (!numPos) { bytes1 = Negate(bytes1); } if (!denPos) { bytes2 = Negate(bytes2); } Trim(bytes1); Trim(bytes2); BitArray ba1 = new BitArray(bytes1.ToArray()); BitArray ba2 = new BitArray(bytes2.ToArray()); int ba11loc = 0; for (int i = ba1.Length - 1; i >= 0; i--) { if (ba1[i]) { ba11loc = i; break; } } int ba21loc = 0; for (int i = ba2.Length - 1; i >= 0; i--) { if (ba2[i]) { ba21loc = i; break; } } int shift = ba11loc - ba21loc; if (shift < 0) { if (!numPos) { bytes1 = Negate(bytes1); } return bytes1; } BitArray br = new BitArray(shift + 1, false); for (int i = 0; i < shift; i++) { bytes2 = ShiftLeftGrow(bytes2); } while (shift >= 0) { bytes2 = Negate(bytes2); bytes1 = Add(bytes1, bytes2); bytes2 = Negate(bytes2); if (bytes1[bytes1.Count - 1] < 128) { br[shift] = true; } else { bytes1 = Add(bytes1, bytes2); } bytes2 = ShiftRight(bytes2); shift--; } if (!numPos) { bytes1 = Negate(bytes1); } return bytes1; } public static List<byte> Pow(List<byte> bytes1, List<byte> bytes2) { if (IsZero(bytes2)) { return new List<byte>(new byte[] { 1 }); } BitArray ba2 = new BitArray(bytes2.ToArray()); int last1 = 0; List<byte> result = null; for (int i = ba2.Length - 1; i >= 0; i--) { if (ba2[i]) { last1 = i; break; } } for (int i = 0; i <= last1; i++) { if (ba2[i]) { if (result == null) { result = bytes1; } else { result = Multiply(result, bytes1); } Trim(bytes1); Trim(result); } if (i != last1) { bytes1 = Multiply(bytes1, bytes1); Trim(bytes1); } } return (result == null) ? new List<byte>(new byte[] { 1 }) : result; } public static List<byte> ModPow(List<byte> bytes1, List<byte> bytes2, List<byte> bytes3) { if (IsZero(bytes2)) { return Remainder(new List<byte>(new byte[] { 1 }), bytes3); } BitArray ba2 = new BitArray(bytes2.ToArray()); int last1 = 0; List<byte> result = null; for (int i = ba2.Length - 1; i >= 0; i--) { if (ba2[i]) { last1 = i; break; } } bytes1 = Remainder(bytes1, Copy(bytes3)); for (int i = 0; i <= last1; i++) { if (ba2[i]) { if (result == null) { result = bytes1; } else { result = Multiply(result, bytes1); result = Remainder(result, Copy(bytes3)); } Trim(bytes1); Trim(result); } if (i != last1) { bytes1 = Multiply(bytes1, bytes1); bytes1 = Remainder(bytes1, Copy(bytes3)); Trim(bytes1); } } return (result == null) ? Remainder(new List<byte>(new byte[] { 1 }), bytes3) : result; } public static List<byte> GCD(List<byte> bytes1, List<byte> bytes2) { List<byte> temp; bool numPos = ((bytes1[bytes1.Count - 1] & 0x80) == 0); bool denPos = ((bytes2[bytes2.Count - 1] & 0x80) == 0); if (!numPos) { bytes1 = Negate(bytes1); } if (!denPos) { bytes2 = Negate(bytes2); } Trim(bytes1); Trim(bytes2); while (!IsZero(bytes2)) { temp = Copy(bytes2); bytes2 = Remainder(bytes1, bytes2); bytes1 = temp; } return bytes1; } public static List<byte> Max(List<byte> bytes1, List<byte> bytes2) { bool b1Pos = ((bytes1[bytes1.Count - 1] & 0x80) == 0); bool b2Pos = ((bytes2[bytes2.Count - 1] & 0x80) == 0); if (b1Pos != b2Pos) { if (b1Pos) { return bytes1; } if (b2Pos) { return bytes2; } } List<byte> sum = Add(bytes1, Negate(Copy(bytes2))); if ((sum[sum.Count - 1] & 0x80) != 0) { return bytes2; } return bytes1; } public static List<byte> And(List<byte> bytes1, List<byte> bytes2) { List<byte> bnew = new List<byte>(); NormalizeLengths(bytes1, bytes2); for (int i = 0; i < bytes1.Count; i++) { bnew.Add((byte)(bytes1[i] & bytes2[i])); } return bnew; } public static List<byte> Or(List<byte> bytes1, List<byte> bytes2) { List<byte> bnew = new List<byte>(); NormalizeLengths(bytes1, bytes2); for (int i = 0; i < bytes1.Count; i++) { bnew.Add((byte)(bytes1[i] | bytes2[i])); } return bnew; } public static List<byte> Xor(List<byte> bytes1, List<byte> bytes2) { List<byte> bnew = new List<byte>(); NormalizeLengths(bytes1, bytes2); for (int i = 0; i < bytes1.Count; i++) { bnew.Add((byte)(bytes1[i] ^ bytes2[i])); } return bnew; } public static List<byte> Not(List<byte> bytes) { List<byte> bnew = new List<byte>(); for (int i = 0; i < bytes.Count; i++) { bnew.Add((byte)(bytes[i] ^ 0xFF)); } return bnew; } public static List<byte> ShiftLeft(List<byte> bytes1, List<byte> bytes2) { int byteShift = (int)new BigInteger(Divide(Copy(bytes2), new List<byte>(new byte[] { 8 })).ToArray()); sbyte bitShift = (sbyte)new BigInteger(Remainder(bytes2, new List<byte>(new byte[] { 8 })).ToArray()); for (int i = 0; i < Math.Abs(bitShift); i++) { if (bitShift < 0) { bytes1 = ShiftRight(bytes1); } else { bytes1 = ShiftLeftGrow(bytes1); } } if (byteShift < 0) { byteShift = -byteShift; if (byteShift >= bytes1.Count) { if ((bytes1[bytes1.Count - 1] & 0x80) != 0) { bytes1 = new List<byte>(new byte[] { 0xFF }); } else { bytes1 = new List<byte>(new byte[] { 0 }); } } else { List<byte> temp = new List<byte>(); for (int i = byteShift; i < bytes1.Count; i++) { temp.Add(bytes1[i]); } bytes1 = temp; } } else { List<byte> temp = new List<byte>(); for (int i = 0; i < byteShift; i++) { temp.Add((byte)0); } for (int i = 0; i < bytes1.Count; i++) { temp.Add(bytes1[i]); } bytes1 = temp; } return bytes1; } public static List<byte> ShiftLeftGrow(List<byte> bytes) { List<byte> bresult = new List<byte>(); for (int i = 0; i < bytes.Count; i++) { byte newbyte = bytes[i]; if (newbyte > 127) { newbyte -= 128; } newbyte = (byte)(newbyte * 2); if ((i != 0) && (bytes[i - 1] >= 128)) { newbyte++; } bresult.Add(newbyte); } if ((bytes[bytes.Count - 1] > 63) && (bytes[bytes.Count - 1] < 128)) { bresult.Add((byte)0); } if ((bytes[bytes.Count - 1] > 127) && (bytes[bytes.Count - 1] < 192)) { bresult.Add((byte)0xFF); } return bresult; } public static List<byte> ShiftLeftDrop(List<byte> bytes) { List<byte> bresult = new List<byte>(); for (int i = 0; i < bytes.Count; i++) { byte newbyte = bytes[i]; if (newbyte > 127) { newbyte -= 128; } newbyte = (byte)(newbyte * 2); if ((i != 0) && (bytes[i - 1] >= 128)) { newbyte++; } bresult.Add(newbyte); } return bresult; } public static List<byte> ShiftRight(List<byte> bytes) { List<byte> bresult = new List<byte>(); for (int i = 0; i < bytes.Count; i++) { byte newbyte = bytes[i]; newbyte = (byte)(newbyte / 2); if ((i != (bytes.Count - 1)) && ((bytes[i + 1] & 0x01) == 1)) { newbyte += 128; } if ((i == (bytes.Count - 1)) && ((bytes[bytes.Count - 1] & 0x80) != 0)) { newbyte += 128; } bresult.Add(newbyte); } return bresult; } public static List<byte> SetLength(List<byte> bytes, int size) { List<byte> bresult = new List<byte>(); for (int i = 0; i < size; i++) { bresult.Add(bytes[i]); } return bresult; } public static List<byte> Copy(List<byte> bytes) { List<byte> ret = new List<byte>(); for (int i = 0; i < bytes.Count; i++) { ret.Add(bytes[i]); } return ret; } public static void NormalizeLengths(List<byte> bytes1, List<byte> bytes2) { bool num1neg = (bytes1[bytes1.Count - 1] & 0x80) != 0; bool num2neg = (bytes2[bytes2.Count - 1] & 0x80) != 0; byte extender = 0; if (bytes1.Count < bytes2.Count) { if (num1neg) { extender = 0xff; } while (bytes1.Count < bytes2.Count) { bytes1.Add(extender); } } if (bytes2.Count < bytes1.Count) { if (num2neg) { extender = 0xff; } while (bytes2.Count < bytes1.Count) { bytes2.Add(extender); } } } public static void Trim(List<byte> bytes) { while (bytes.Count > 1) { if ((bytes[bytes.Count - 1] & 0x80) == 0) { if ((bytes[bytes.Count - 1] == 0) & ((bytes[bytes.Count - 2] & 0x80) == 0)) { bytes.RemoveAt(bytes.Count - 1); } else { break; } } else { if ((bytes[bytes.Count - 1] == 0xFF) & ((bytes[bytes.Count - 2] & 0x80) != 0)) { bytes.RemoveAt(bytes.Count - 1); } else { break; } } } } public static List<byte> GetBytes(BitArray ba) { int length = ((ba.Length) / 8) + 1; List<byte> mask = new List<byte>(new byte[] { 0 }); for (int i = length - 1; i >= 0; i--) { for (int j = 7; j >= 0; j--) { mask = ShiftLeftGrow(mask); if ((8 * i + j < ba.Length) && (ba[8 * i + j])) { mask[0] |= (byte)1; } } } return mask; } public static String Print(byte[] bytes) { String ret = "make "; for (int i = 0; i < bytes.Length; i++) { ret += bytes[i] + " "; } ret += "endmake "; return ret; } public static String PrintFormatX(byte[] bytes) { string ret = String.Empty; for (int i = 0; i < bytes.Length; i++) { ret += bytes[i].ToString("x"); } return ret; } public static String PrintFormatX2(byte[] bytes) { string ret = String.Empty; for (int i = 0; i < bytes.Length; i++) { ret += bytes[i].ToString("x2") + " "; } return ret; } public static bool IsZero(List<byte> list) { return IsZero(list.ToArray()); } public static bool IsZero(byte[] value) { for (int i = 0; i < value.Length; i++) { if (value[i] != 0) { return false; } } return true; } public static byte[] GetNonZeroRandomByteArray(Random random, int size) { byte[] value = new byte[size]; while (IsZero(value)) { random.NextBytes(value); } return value; } public static byte[] GetRandomByteArray(Random random, int size) { byte[] value = new byte[size]; random.NextBytes(value); return value; } public static BigInteger ApproximateBigInteger(double value) { //Special case values; if (Double.IsNaN(value)) { return new BigInteger(-101); } if (Double.IsNegativeInfinity(value)) { return new BigInteger(-102); } if (Double.IsPositiveInfinity(value)) { return new BigInteger(-103); } BigInteger result = new BigInteger(Math.Round(value, 0)); if (result != 0) { bool pos = (value > 0); if (!pos) { value = -value; } int size = (int)Math.Floor(Math.Log10(value)); //keep only the first 17 significant digits; if (size > 17) { result = result - (result % BigInteger.Pow(10, size - 17)); } if (!pos) { value = -value; } } return result; } } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; namespace UnityEditor.CountlyXCodeEditor { public class PBXParser { public const string PBX_HEADER_TOKEN = "// !$*UTF8*$!\n"; public const char WHITESPACE_SPACE = ' '; public const char WHITESPACE_TAB = '\t'; public const char WHITESPACE_NEWLINE = '\n'; public const char WHITESPACE_CARRIAGE_RETURN = '\r'; public const char ARRAY_BEGIN_TOKEN = '('; public const char ARRAY_END_TOKEN = ')'; public const char ARRAY_ITEM_DELIMITER_TOKEN = ','; public const char DICTIONARY_BEGIN_TOKEN = '{'; public const char DICTIONARY_END_TOKEN = '}'; public const char DICTIONARY_ASSIGN_TOKEN = '='; public const char DICTIONARY_ITEM_DELIMITER_TOKEN = ';'; public const char QUOTEDSTRING_BEGIN_TOKEN = '"'; public const char QUOTEDSTRING_END_TOKEN = '"'; public const char QUOTEDSTRING_ESCAPE_TOKEN = '\\'; public const char END_OF_FILE = (char)0x1A; public const string COMMENT_BEGIN_TOKEN = "/*"; public const string COMMENT_END_TOKEN = "*/"; public const string COMMENT_LINE_TOKEN = "//"; private const int BUILDER_CAPACITY = 20000; // private char[] data; private int index; // public bool success; // private int indent; public PBXDictionary Decode( string data ) { // success = true; if( !data.StartsWith( PBX_HEADER_TOKEN ) ) { Debug.Log( "Wrong file format." ); return null; } data = data.Substring( 13 ); this.data = data.ToCharArray(); index = 0; return (PBXDictionary)ParseValue(); } public string Encode( PBXDictionary pbxData, bool readable = false ) { // indent = 0; StringBuilder builder = new StringBuilder( PBX_HEADER_TOKEN, BUILDER_CAPACITY ); bool success = SerializeValue( pbxData, builder, readable ); return ( success ? builder.ToString() : null ); } #region Move private char NextToken() { SkipWhitespaces(); return StepForeward(); } private string Peek( int step = 1 ) { string sneak = string.Empty; for( int i = 1; i <= step; i++ ) { if( data.Length - 1 < index + i ) { break; } sneak += data[ index + i ]; } return sneak; } private bool SkipWhitespaces() { bool whitespace = false; while( Regex.IsMatch( StepForeward().ToString(), @"\s" ) ) whitespace = true; StepBackward(); if( SkipComments() ) { whitespace = true; SkipWhitespaces(); } return whitespace; } private bool SkipComments() { string s = string.Empty; string tag = Peek( 2 ); switch( tag ) { case COMMENT_BEGIN_TOKEN: { while( Peek( 2 ).CompareTo( COMMENT_END_TOKEN ) != 0 ) { s += StepForeward(); } s += StepForeward( 2 ); break; } case COMMENT_LINE_TOKEN: { while( !Regex.IsMatch( StepForeward().ToString(), @"\n" ) ) continue; break; } default: return false; } return true; } private char StepForeward( int step = 1 ) { index = Math.Min( data.Length, index + step ); return data[ index ]; } private char StepBackward( int step = 1 ) { index = Math.Max( 0, index - step ); return data[ index ]; } #endregion #region Parse private object ParseValue() { switch( NextToken() ) { case END_OF_FILE: Debug.Log( "End of file" ); return null; case DICTIONARY_BEGIN_TOKEN: return ParseDictionary(); case ARRAY_BEGIN_TOKEN: return ParseArray(); case QUOTEDSTRING_BEGIN_TOKEN: return ParseString(); default: StepBackward(); return ParseEntity(); } } // private T Convert<T>( PBXDictionary dictionary ) // { // if( dictionary.ContainsKey( "isa" ) ){ //// ((string)dictionary["isa"]).CompareTo( // Type targetType = Type.GetType( (string)dictionary["isa"] ); // if( targetType.IsSubclassOf( typeof(PBXObject) ) ) { // Debug.Log( "ok" ); // T converted = (T)Activator.CreateInstance( targetType ); // return converted; // } // else { // Debug.Log( "Warning: unknown PBX type: " + targetType.Name ); // return default(T); // } // // } // return default(T); // // } private PBXDictionary ParseDictionary() { SkipWhitespaces(); PBXDictionary dictionary = new PBXDictionary(); string keyString = string.Empty; object valueObject = null; bool complete = false; while( !complete ) { switch( NextToken() ) { case END_OF_FILE: Debug.Log( "Error: reached end of file inside a dictionary: " + index ); complete = true; break; case DICTIONARY_ITEM_DELIMITER_TOKEN: keyString = string.Empty; valueObject = null; break; case DICTIONARY_END_TOKEN: keyString = string.Empty; valueObject = null; complete = true; break; case DICTIONARY_ASSIGN_TOKEN: valueObject = ParseValue(); dictionary.Add( keyString, valueObject ); break; default: StepBackward(); keyString = ParseValue() as string; break; } } return dictionary; } private PBXList ParseArray() { PBXList list = new PBXList(); bool complete = false; while( !complete ) { switch( NextToken() ) { case END_OF_FILE: Debug.Log( "Error: Reached end of file inside a list: " + list ); complete = true; break; case ARRAY_END_TOKEN: complete = true; break; case ARRAY_ITEM_DELIMITER_TOKEN: break; default: StepBackward(); list.Add( ParseValue() ); break; } } return list; } private object ParseString() { string s = string.Empty; char c = StepForeward(); while( c != QUOTEDSTRING_END_TOKEN ) { s += c; if( c == QUOTEDSTRING_ESCAPE_TOKEN ) s += StepForeward(); c = StepForeward(); } return s; } private object ParseEntity() { string word = string.Empty; while( !Regex.IsMatch( Peek(), @"[;,\s=]" ) ) { word += StepForeward(); } if( word.Length != 24 && Regex.IsMatch( word, @"^\d+$" ) ) { return Int32.Parse( word ); } return word; } #endregion #region Serialize private bool SerializeValue( object value, StringBuilder builder, bool readable = false ) { if( value == null ) { builder.Append( "null" ); } else if( value is PBXObject ) { SerializeDictionary( ((PBXObject)value).data, builder, readable ); } else if( value is Dictionary<string, object> ) { SerializeDictionary( (Dictionary<string, object>)value, builder, readable ); } else if( value.GetType().IsArray ) { SerializeArray( new ArrayList( (ICollection)value ), builder, readable ); } else if( value is ArrayList ) { SerializeArray( (ArrayList)value, builder, readable ); } else if( value is string ) { SerializeString( (string)value, builder, readable ); } else if( value is Char ) { SerializeString( Convert.ToString( (char)value ), builder, readable ); } else if( value is bool ) { builder.Append( Convert.ToInt32( value ).ToString() ); } else if( value.GetType().IsPrimitive ) { builder.Append( Convert.ToString( value ) ); } // else if( value is Hashtable ) // { // serializeObject( (Hashtable)value, builder ); // } // else if( ( value is Boolean ) && ( (Boolean)value == true ) ) // { // builder.Append( "NO" ); // } // else if( ( value is Boolean ) && ( (Boolean)value == false ) ) // { // builder.Append( "YES" ); // } else { Debug.LogWarning( "Error: unknown object of type " + value.GetType().Name ); return false; } return true; } private bool SerializeDictionary( Dictionary<string, object> dictionary, StringBuilder builder, bool readable = false ) { builder.Append( DICTIONARY_BEGIN_TOKEN ); foreach( KeyValuePair<string, object> pair in dictionary ) { SerializeString( pair.Key, builder ); builder.Append( DICTIONARY_ASSIGN_TOKEN ); SerializeValue( pair.Value, builder ); builder.Append( DICTIONARY_ITEM_DELIMITER_TOKEN ); } builder.Append( DICTIONARY_END_TOKEN ); return true; } private bool SerializeArray( ArrayList anArray, StringBuilder builder, bool readable = false ) { builder.Append( ARRAY_BEGIN_TOKEN ); for( int i = 0; i < anArray.Count; i++ ) { object value = anArray[i]; if( !SerializeValue( value, builder ) ) { return false; } builder.Append( ARRAY_ITEM_DELIMITER_TOKEN ); } builder.Append( ARRAY_END_TOKEN ); return true; } private bool SerializeString( string aString, StringBuilder builder, bool useQuotes = false, bool readable = false ) { // Is a GUID? if( Regex.IsMatch( aString, @"^[A-F0-9]{24}$" ) ) { builder.Append( aString ); return true; } // Is an empty string? if( string.IsNullOrEmpty( aString ) ) { builder.Append( QUOTEDSTRING_BEGIN_TOKEN ); builder.Append( QUOTEDSTRING_END_TOKEN ); return true; } if( !Regex.IsMatch( aString, @"^[A-Za-z0-9_.]+$" ) ) { useQuotes = true; } if( useQuotes ) builder.Append( QUOTEDSTRING_BEGIN_TOKEN ); builder.Append( aString ); if( useQuotes ) builder.Append( QUOTEDSTRING_END_TOKEN ); return true; } #endregion } }
namespace SimpleECS.Internal { using System.IO; /// <summary> /// Generates the entity create and query foreach functions /// Use to increase the default limits /// </summary> public static class CodeGenerator { static string Pattern(string value, int count, bool comma_sep = true) { string result = ""; for (int i = 1; i < count; ++i) { result += value.Replace("#", i.ToString()); if (comma_sep) result += ", "; } result += value.Replace("#", (count).ToString()); return result; } /// <summary> /// Generates all world.CreateEntity functions /// </summary> /// <param name="count">Maximum number of components that can be used in CreateEntity Functions</param> /// <param name="output_path">Path to EntityCreateFunctions.cs</param> public static void CreateEntityFunctions(int count, string output_path) { using (StreamWriter writer = new StreamWriter(output_path)) { writer.WriteLine($"namespace {nameof(SimpleECS)}"); writer.WriteLine("{"); writer.WriteLine(" using Internal;"); writer.WriteLine(" public partial struct World"); writer.WriteLine(" {"); for (int i = 1; i < count + 1; ++i) { writer.WriteLine($" public Entity CreateEntity<{Pattern("C#", i)}>({Pattern("C# c#", i)})"); writer.WriteLine(" {"); writer.WriteLine(" if (this.TryGetWorldInfo(out var data))"); writer.WriteLine(" {"); writer.WriteLine($" data.buffer_signature.Clear(){Pattern(".Add<C#>()", i, false)};"); writer.WriteLine(" var archetype = data.GetArchetypeData(data.buffer_signature);"); writer.WriteLine(" return data.StructureEvents.CreateEntity(archetype)"); writer.WriteLine($" {Pattern(".Set(c#)", i, false)};"); writer.WriteLine(" }"); writer.WriteLine(" return default;"); writer.WriteLine(" }"); } writer.WriteLine(" }"); writer.WriteLine("}"); } } /// <summary> /// Generates all query.Foreach functions /// </summary> /// <param name="world_data_count">Maximum number of world data that can be used in queries</param> /// <param name="component_count">Maximum number of components that can be used in queries</param> /// <param name="output_path">Path to QueryForeachFunctions.cs</param> public static void CreateQueryFunctions(int world_data_count, int component_count, string output_path) { using (StreamWriter writer = new StreamWriter(output_path)) { writer.WriteLine($"namespace {nameof(SimpleECS)}"); writer.WriteLine("{"); writer.WriteLine(" public partial class Query"); writer.WriteLine(" {"); for (int c = 1; c < component_count + 1; ++c) // components { string c_val = Pattern("C#", c); var arch_get = Pattern("&& archetype.TryGetArray(out C#[] c#)", c, false); writer.WriteLine($" public delegate void c{c}_query<{c_val}>({Pattern("ref C# c#", c)});"); WriteDocumentation(); writer.WriteLine($" public void Foreach<{c_val}>(in c{c}_query<{c_val}> action)"); writer.WriteLine(" {"); writer.WriteLine(" if (Update(out var world_info))"); writer.WriteLine(" {"); writer.WriteLine(" world_info.StructureEvents.EnqueueEvents++;"); writer.WriteLine(" for (int archetype_index = 0; archetype_index < archetype_count; ++archetype_index)"); writer.WriteLine(" {"); writer.WriteLine(" var archetype = world_info.archetypes[matching_archetypes[archetype_index]].data;"); writer.WriteLine(" int count = archetype.entity_count;"); writer.WriteLine($" if (count > 0 {arch_get})"); writer.WriteLine(" {"); writer.WriteLine(" for (int e = 0; e < count; ++e)"); writer.WriteLine($" action({Pattern("ref c#[e]", c)});"); writer.WriteLine(" }"); writer.WriteLine(" }"); writer.WriteLine(" world_info.StructureEvents.EnqueueEvents--;"); writer.WriteLine(" }"); writer.WriteLine(" }"); } for (int c = 1; c < component_count + 1; ++c) // entity and components { string c_val = Pattern("C#", c); var arch_get = Pattern("&& archetype.TryGetArray(out C#[] c#)", c, false); writer.WriteLine($" public delegate void ec{c}_query<{c_val}>(Entity entity, {Pattern("ref C# c#", c)});"); WriteDocumentation(); writer.WriteLine($" public void Foreach<{c_val}>(in ec{c}_query<{c_val}> action)"); writer.WriteLine(" {"); writer.WriteLine(" if (Update(out var world_info))"); writer.WriteLine(" {"); writer.WriteLine(" world_info.StructureEvents.EnqueueEvents++;"); writer.WriteLine(" for (int archetype_index = 0; archetype_index < archetype_count; ++archetype_index)"); writer.WriteLine(" {"); writer.WriteLine(" var archetype = world_info.archetypes[matching_archetypes[archetype_index]].data;"); writer.WriteLine(" int count = archetype.entity_count;"); writer.WriteLine(" var entities = archetype.entities;"); writer.WriteLine($" if (count > 0 {arch_get})"); writer.WriteLine(" {"); writer.WriteLine(" for (int e = 0; e < count; ++e)"); writer.WriteLine($" action(entities[e], {Pattern("ref c#[e]", c)});"); writer.WriteLine(" }"); writer.WriteLine(" }"); writer.WriteLine(" world_info.StructureEvents.EnqueueEvents--;"); writer.WriteLine(" }"); writer.WriteLine(" }"); } for (int c = 1; c < component_count + 1; ++c) // world data and components for (int w = 1; w < world_data_count + 1; ++w) { string c_val = Pattern("C#", c); string w_val = Pattern("W#", w); var arch_get = Pattern("&& archetype.TryGetArray(out C#[] c#)", c, false); writer.WriteLine($" public delegate void w{w}c{c}_query<{w_val},{c_val}>({Pattern("in W# w#", w)}, {Pattern("ref C# c#", c)});"); WriteDocumentation(); writer.WriteLine($" public void Foreach<{w_val},{c_val}>(in w{w}c{c}_query<{w_val},{c_val}> action)"); writer.WriteLine(" {"); writer.WriteLine(" if (Update(out var world_info))"); writer.WriteLine(" {"); writer.WriteLine($"{Pattern(" ref W# w# = ref world.GetData<W#>();\n", w, false)}"); writer.WriteLine(" world_info.StructureEvents.EnqueueEvents++;"); writer.WriteLine(" for (int archetype_index = 0; archetype_index < archetype_count; ++archetype_index)"); writer.WriteLine(" {"); writer.WriteLine(" var archetype = world_info.archetypes[matching_archetypes[archetype_index]].data;"); writer.WriteLine(" int count = archetype.entity_count;"); writer.WriteLine($" if (count > 0 {arch_get})"); writer.WriteLine(" {"); writer.WriteLine(" for (int e = 0; e < count; ++e)"); writer.WriteLine($" action({Pattern("in w#", w)}, {Pattern("ref c#[e]", c)});"); writer.WriteLine(" }"); writer.WriteLine(" }"); writer.WriteLine(" world_info.StructureEvents.EnqueueEvents--;"); writer.WriteLine(" }"); writer.WriteLine(" }"); } for (int c = 1; c < component_count + 1; ++c) // world data, entity and components for (int w = 1; w < world_data_count + 1; ++w) { string c_val = Pattern("C#", c); string w_val = Pattern("W#", w); var arch_get = Pattern("&& archetype.TryGetArray(out C#[] c#)", c, false); writer.WriteLine($" public delegate void w{w}ec{c}_query<{w_val},{c_val}>({Pattern("in W# w#", w)}, Entity entity, {Pattern("ref C# c#", c)});"); WriteDocumentation(); writer.WriteLine($" public void Foreach<{w_val},{c_val}>(in w{w}ec{c}_query<{w_val},{c_val}> action)"); writer.WriteLine(" {"); writer.WriteLine(" if (Update(out var world_info))"); writer.WriteLine(" {"); writer.WriteLine($"{Pattern(" ref W# w# = ref world.GetData<W#>();\n", w, false)}"); writer.WriteLine(" world_info.StructureEvents.EnqueueEvents++;"); writer.WriteLine(" for (int archetype_index = 0; archetype_index < archetype_count; ++archetype_index)"); writer.WriteLine(" {"); writer.WriteLine(" var archetype = world_info.archetypes[matching_archetypes[archetype_index]].data;"); writer.WriteLine(" int count = archetype.entity_count;"); writer.WriteLine(" var entities = archetype.entities;"); writer.WriteLine($" if (count > 0 {arch_get})"); writer.WriteLine(" {"); writer.WriteLine(" for (int e = 0; e < count; ++e)"); writer.WriteLine($" action({Pattern("in w#", w)}, entities[e], {Pattern("ref c#[e]", c)});"); writer.WriteLine(" }"); writer.WriteLine(" }"); writer.WriteLine(" world_info.StructureEvents.EnqueueEvents--;"); writer.WriteLine(" }"); writer.WriteLine(" }"); } writer.WriteLine(" }"); writer.WriteLine("}"); void WriteDocumentation() { writer.WriteLine(" /// <summary>"); writer.WriteLine(" /// performs the action on all entities that match the query."); writer.WriteLine(" /// query must be in the form of '(in world_data', entity, ref components)'."); writer.WriteLine($" /// query can add up to {world_data_count} world data and {component_count} components"); writer.WriteLine(" /// </summary>"); } } } } }
// Copyright 2011 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Microsoft.Data.OData.Atom { /// <summary> /// Constant values related to the ATOM format. /// </summary> internal static class AtomConstants { #region Xml constants ----------------------------------------------------------------------------------------- /// <summary>'http://www.w3.org/2000/xmlns/' - namespace for namespace declarations.</summary> internal const string XmlNamespacesNamespace = "http://www.w3.org/2000/xmlns/"; /// <summary>Attribute use to add xml: namespaces specific attributes.</summary> internal const string XmlNamespace = "http://www.w3.org/XML/1998/namespace"; /// <summary> Schema Namespace prefix For xmlns.</summary> internal const string XmlnsNamespacePrefix = "xmlns"; /// <summary> Schema Namespace prefix For xml.</summary> internal const string XmlNamespacePrefix = "xml"; /// <summary>XML attribute value to indicate the base URI for a document or element.</summary> internal const string XmlBaseAttributeName = "base"; /// <summary>Name of the xml:lang attribute.</summary> internal const string XmlLangAttributeName = "lang"; /// <summary>Name of the xml:space attribute.</summary> internal const string XmlSpaceAttributeName = "space"; /// <summary>'preserve' value for the xml:space attribute.</summary> internal const string XmlPreserveSpaceAttributeValue = "preserve"; #endregion Xml constants #region OData constants --------------------------------------------------------------------------------------- /// <summary>XML namespace for data service annotations.</summary> internal const string ODataMetadataNamespace = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"; /// <summary>XML namespace prefix for data service annotations.</summary> internal const string ODataMetadataNamespacePrefix = "m"; /// <summary>XML namespace for data services.</summary> internal const string ODataNamespace = "http://schemas.microsoft.com/ado/2007/08/dataservices"; /// <summary>Prefix for data services namespace.</summary> internal const string ODataNamespacePrefix = "d"; /// <summary>OData attribute which indicates the etag value for the declaring entry element.</summary> internal const string ODataETagAttributeName = "etag"; /// <summary>OData attribute which indicates the null value for the element.</summary> internal const string ODataNullAttributeName = "null"; /// <summary>OData element name for the 'count' element</summary> internal const string ODataCountElementName = "count"; /// <summary>OData scheme namespace for data services category scheme in atom:category elements.</summary> internal const string ODataSchemeNamespace = "http://schemas.microsoft.com/ado/2007/08/dataservices/scheme"; /// <summary>OData stream property 'mediaresource' Uri segment name used in named stream link relations.</summary> internal const string ODataStreamPropertyMediaResourceSegmentName = "mediaresource"; /// <summary>OData stream property 'edit-media' Uri segment name used in named stream link relations.</summary> internal const string ODataStreamPropertyEditMediaSegmentName = "edit-media"; /// <summary>OData stream property prefix for named stream 'mediaresource' related link relations.</summary> internal const string ODataStreamPropertyMediaResourceRelatedLinkRelationPrefix = ODataNamespace + "/" + ODataStreamPropertyMediaResourceSegmentName + "/"; /// <summary>OData stream property prefix for named stream 'edit-media' related link relations.</summary> internal const string ODataStreamPropertyEditMediaRelatedLinkRelationPrefix = ODataNamespace + "/" + ODataStreamPropertyEditMediaSegmentName + "/"; /// <summary>OData navigation properties 'related' Uri segment name used in navigation link relations.</summary> internal const string ODataNavigationPropertiesRelatedSegmentName = "related"; /// <summary>OData navigation properties prefix for navigation link relations.</summary> internal const string ODataNavigationPropertiesRelatedLinkRelationPrefix = ODataNamespace + "/" + ODataNavigationPropertiesRelatedSegmentName + "/"; /// <summary>OData navigation properties 'relatedlinks' Uri segment name used in association link relations.</summary> internal const string ODataNavigationPropertiesAssociationRelatedSegmentName = "relatedlinks"; /// <summary>OData association link prefix for relation attribute.</summary> internal const string ODataNavigationPropertiesAssociationLinkRelationPrefix = ODataNamespace + "/" + ODataNavigationPropertiesAssociationRelatedSegmentName + "/"; /// <summary>'Inline' - wrapping element for inlined entry/feed content.</summary> internal const string ODataInlineElementName = "inline"; /// <summary>Name of the error element for Xml error responses.</summary> internal const string ODataErrorElementName = "error"; /// <summary>Name of the error code element for Xml error responses.</summary> internal const string ODataErrorCodeElementName = "code"; /// <summary>Name of the error message element for Xml error responses.</summary> internal const string ODataErrorMessageElementName = "message"; /// <summary>Name of the inner error message element for Xml error responses.</summary> internal const string ODataInnerErrorElementName = "innererror"; /// <summary>Name of the message element in inner errors for Xml error responses.</summary> internal const string ODataInnerErrorMessageElementName = "message"; /// <summary>Name of the type element in inner errors for Xml error responses.</summary> internal const string ODataInnerErrorTypeElementName = "type"; /// <summary>Name of the stack trace element in inner errors for Xml error responses.</summary> internal const string ODataInnerErrorStackTraceElementName = "stacktrace"; /// <summary>Name of the inner error element nested in inner errors for Xml error responses.</summary> internal const string ODataInnerErrorInnerErrorElementName = "internalexception"; /// <summary>Element name for the items in a collection.</summary> internal const string ODataCollectionItemElementName = "element"; /// <summary>Element name for m:action.</summary> internal const string ODataActionElementName = "action"; /// <summary>Element name for m:function.</summary> internal const string ODataFunctionElementName = "function"; /// <summary>Attribute name for m:action|m:function/@metadata.</summary> internal const string ODataOperationMetadataAttribute = "metadata"; /// <summary>Attribute name for m:action|m:function/@title.</summary> internal const string ODataOperationTitleAttribute = "title"; /// <summary>Attribute name for m:action|m:function/@target.</summary> internal const string ODataOperationTargetAttribute = "target"; /// <summary>XML element name for the wrapper 'links' element around a sequence of Uris in response to a $links request.</summary> internal const string ODataLinksElementName = "links"; /// <summary>XML element name for a Uri response to a $links request.</summary> internal const string ODataUriElementName = "uri"; /// <summary>XML element name for a next link in a response to a $links request.</summary> internal const string ODataNextLinkElementName = "next"; #endregion OData constants #region Atom Format constants --------------------------------------------------------------------------------- /// <summary>Schema namespace for Atom.</summary> internal const string AtomNamespace = "http://www.w3.org/2005/Atom"; /// <summary>Prefix for the Atom namespace - empty since it is the default namespace.</summary> internal const string AtomNamespacePrefix = ""; /// <summary>Prefix for the Atom namespace used in cases where we need a non-empty prefix.</summary> internal const string NonEmptyAtomNamespacePrefix = "atom"; /// <summary>XML element name to mark entry element in Atom.</summary> internal const string AtomEntryElementName = "entry"; /// <summary>XML element name to mark feed element in Atom.</summary> internal const string AtomFeedElementName = "feed"; /// <summary>XML element name to mark content element in Atom.</summary> internal const string AtomContentElementName = "content"; /// <summary>XML element name to mark type attribute in Atom.</summary> internal const string AtomTypeAttributeName = "type"; /// <summary>Element containing property values when 'content' is used for media link entries</summary> internal const string AtomPropertiesElementName = "properties"; /// <summary>XML element name to mark id element in Atom.</summary> internal const string AtomIdElementName = "id"; /// <summary>XML element name to mark title element in Atom.</summary> internal const string AtomTitleElementName = "title"; /// <summary>XML element name to mark the subtitle element in Atom.</summary> internal const string AtomSubtitleElementName = "subtitle"; /// <summary>XML element name to mark the summary element in Atom.</summary> internal const string AtomSummaryElementName = "summary"; /// <summary>XML element name to mark the 'published' element in Atom.</summary> internal const string AtomPublishedElementName = "published"; /// <summary>XML element name to mark the 'source' element in Atom.</summary> internal const string AtomSourceElementName = "source"; /// <summary>XML element name to mark the 'rights' element in Atom.</summary> internal const string AtomRightsElementName = "rights"; /// <summary>XML element name to mark the 'logo' element in Atom.</summary> internal const string AtomLogoElementName = "logo"; /// <summary>XML element name to mark the 'author' element in Atom.</summary> internal const string AtomAuthorElementName = "author"; /// <summary>XML element name to mark the 'author name' element in Atom.</summary> internal const string AtomAuthorNameElementName = "name"; /// <summary>XML element name to mark the 'contributor' element in Atom.</summary> internal const string AtomContributorElementName = "contributor"; /// <summary>XML element name to mark the 'generator' element in Atom.</summary> internal const string AtomGeneratorElementName = "generator"; /// <summary>XML attribute name of the 'uri' attribute of a 'generator' element in Atom.</summary> internal const string AtomGeneratorUriAttributeName = "uri"; /// <summary>XML attribute name of the 'version' attribute of a 'generator' element in Atom.</summary> internal const string AtomGeneratorVersionAttributeName = "version"; /// <summary>XML element name to mark the 'icon' element in Atom.</summary> internal const string AtomIconElementName = "icon"; /// <summary>XML element name to mark the 'name' element in an Atom person construct.</summary> internal const string AtomPersonNameElementName = "name"; /// <summary>XML element name to mark the 'uri' element in an Atom person construct.</summary> internal const string AtomPersonUriElementName = "uri"; /// <summary>XML element name to mark the 'email' element in an Atom person construct.</summary> internal const string AtomPersonEmailElementName = "email"; /// <summary>'updated' - XML element name for ATOM 'updated' element for entries.</summary> internal const string AtomUpdatedElementName = "updated"; /// <summary>'category' - XML element name for ATOM 'category' element for entries.</summary> internal const string AtomCategoryElementName = "category"; /// <summary>'term' - XML attribute name for ATOM 'term' attribute for categories.</summary> internal const string AtomCategoryTermAttributeName = "term"; /// <summary>'scheme' - XML attribute name for ATOM 'scheme' attribute for categories.</summary> internal const string AtomCategorySchemeAttributeName = "scheme"; /// <summary>'scheme' - XML attribute name for ATOM 'label' attribute for categories.</summary> internal const string AtomCategoryLabelAttributeName = "label"; /// <summary> Atom link relation attribute value for edit links.</summary> internal const string AtomEditRelationAttributeValue = "edit"; /// <summary> Atom link relation attribute value for self links.</summary> internal const string AtomSelfRelationAttributeValue = "self"; /// <summary>XML element name to mark link element in Atom.</summary> internal const string AtomLinkElementName = "link"; /// <summary>XML attribute name of the link relation attribute in Atom.</summary> internal const string AtomLinkRelationAttributeName = "rel"; /// <summary>XML attribute name of the type attribute of a link in Atom.</summary> internal const string AtomLinkTypeAttributeName = "type"; /// <summary>XML attribute name of the href attribute of a link in Atom.</summary> internal const string AtomLinkHrefAttributeName = "href"; /// <summary>XML attribute name of the hreflang attribute of a link in Atom.</summary> internal const string AtomLinkHrefLangAttributeName = "hreflang"; /// <summary>XML attribute name of the title attribute of a link in Atom.</summary> internal const string AtomLinkTitleAttributeName = "title"; /// <summary>XML attribute name of the length attribute of a link in Atom.</summary> internal const string AtomLinkLengthAttributeName = "length"; /// <summary>XML element name to mark href attribute element in Atom.</summary> internal const string AtomHRefAttributeName = "href"; /// <summary>Atom source attribute name for the content of media link entries.</summary> internal const string MediaLinkEntryContentSourceAttributeName = "src"; /// <summary>Atom link relation attribute value for edit-media links.</summary> internal const string AtomEditMediaRelationAttributeValue = "edit-media"; /// <summary>XML attribute value of the link relation attribute for next page links in Atom.</summary> internal const string AtomNextRelationAttributeValue = "next"; /// <summary>Link relation: alternate - refers to a substitute for this context.</summary> internal const string AtomAlternateRelationAttributeValue = "alternate"; /// <summary>Link relation: related - identifies a related resource.</summary> internal const string AtomRelatedRelationAttributeValue = "related"; /// <summary>Link relation: enclosure - identifies a related resource that is potentially large and might require special handling.</summary> internal const string AtomEnclosureRelationAttributeValue = "enclosure"; /// <summary>Link relation: via - identifies a resource that is the source of the information in the link's context.</summary> internal const string AtomViaRelationAttributeValue = "via"; /// <summary>Link relation: describedby - refers to a resource providing information about the link's context.</summary> internal const string AtomDescribedByRelationAttributeValue = "describedby"; /// <summary>Link relation: service - indicates a URI that can be used to retrieve a service document.</summary> internal const string AtomServiceRelationAttributeValue = "service"; /// <summary>Atom metadata text construct kind: plain text</summary> internal const string AtomTextConstructTextKind = "text"; /// <summary>Atom metadata text construct kind: html</summary> internal const string AtomTextConstructHtmlKind = "html"; /// <summary>Atom metadata text construct kind: xhtml</summary> internal const string AtomTextConstructXHtmlKind = "xhtml"; /// <summary>Default title for service document workspaces.</summary> internal const string AtomWorkspaceDefaultTitle = "Default"; /// <summary>'true' literal</summary> internal const string AtomTrueLiteral = "true"; /// <summary>'false' literal</summary> internal const string AtomFalseLiteral = "false"; /// <summary>IANA link relations namespace.</summary> internal const string IanaLinkRelationsNamespace = "http://www.iana.org/assignments/relation/"; #endregion Atom Format constants #region Atom Publishing Protocol constants ------------------------------------------------------------ /// <summary>The Atom Publishing Protocol (APP) namespace: 'http://www.w3.org/2007/app'.</summary> internal const string AtomPublishingNamespace = "http://www.w3.org/2007/app"; /// <summary>The name of the top-level 'service' element when writing service documents in Xml format.</summary> internal const string AtomPublishingServiceElementName = "service"; /// <summary>The name of the 'workspace' element when writing service documents in Xml format.</summary> internal const string AtomPublishingWorkspaceElementName = "workspace"; /// <summary>The name of the 'collection' element when writing service documents in Xml format.</summary> internal const string AtomPublishingCollectionElementName = "collection"; /// <summary>The name of the 'categories' element encountered while reading a service document in XML format.</summary> internal const string AtomPublishingCategoriesElementName = "categories"; /// <summary>The name of the 'accept' element encountered while reading a service document in XML format.</summary> internal const string AtomPublishingAcceptElementName = "accept"; /// <summary>The name of the 'fixed' attribute of an inline categories element in APP.</summary> internal const string AtomPublishingFixedAttributeName = "fixed"; /// <summary>The value 'yes' of the 'fixed' attribute of an inline categories element in APP.</summary> internal const string AtomPublishingFixedYesValue = "yes"; /// <summary>The value 'no' of the 'fixed' attribute of an inline categories element in APP.</summary> internal const string AtomPublishingFixedNoValue = "no"; #endregion #region Spatial constants ------------------------------------------------------------------------------------- /// <summary>XML namespace for GeoRss format</summary> internal const string GeoRssNamespace = "http://www.georss.org/georss"; /// <summary>XML namespace prefix for GeoRss format</summary> internal const string GeoRssPrefix = "georss"; /// <summary>XML namespace for GML format</summary> internal const string GmlNamespace = "http://www.opengis.net/gml"; /// <summary>XML namespace prefix for GML format</summary> internal const string GmlPrefix = "gml"; #endregion } }
// // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; namespace Mono.System.Xml { /// <summary> /// http://www.w3.org/TR/REC-xml /// </summary> /// <remarks> /// Includes code and Ideas from org.apache.xerces.util.XMLChar class of Xerces 2.0.1 /// However, No surrogate support is included in this class. /// This class is currently public. Make it internal after testing completes /// </remarks> internal class XmlConstructs { internal static readonly char [] WhitespaceChars = {' ', '\n', '\t', '\r'}; /** Character flags. */ internal static readonly byte [] CHARS = new byte [1 << 16]; /** Valid character mask. */ internal const int VALID = 0x01; /** Space character mask. */ internal const int SPACE = 0x02; /** Name start character mask. */ internal const int NAME_START = 0x04; /** Name character mask. */ internal const int NAME = 0x08; /** Pubid character mask. */ internal const int PUBID = 0x10; /** * Content character mask. Special characters are those that can * be considered the start of markup, such as '&lt;' and '&amp;'. * The various newline characters are considered special as well. * All other valid XML characters can be considered content. * <p> * This is an optimization for the inner loop of character scanning. */ internal const int CONTENT = 0x20; /** NCName start character mask. */ internal const int NCNAME_START = 0x40; /** NCName character mask. */ internal const int NCNAME = 0x80; static XmlConstructs () { // // [2] Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | // [#xE000-#xFFFD] | [#x10000-#x10FFFF] // int[] charRange = { 0x0009, 0x000A, 0x000D, 0x000D, 0x0020, 0xD7FF, 0xE000, 0xFFFD, }; // // [3] S ::= (#x20 | #x9 | #xD | #xA)+ // int[] spaceChar = { 0x0020, 0x0009, 0x000D, 0x000A, }; // // [4] NameChar ::= Letter | Digit | '.' | '-' | '_' | ':' | // CombiningChar | Extender // int[] nameChar = { 0x002D, 0x002E, // '-' and '.' }; // // [5] Name ::= (Letter | '_' | ':') (NameChar)* // int[] nameStartChar = { 0x003A, 0x005F, // ':' and '_' }; // // [13] PubidChar ::= #x20 | 0xD | 0xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%] // int[] pubidChar = { 0x000A, 0x000D, 0x0020, 0x0021, 0x0023, 0x0024, 0x0025, 0x003D, 0x005F }; int[] pubidRange = { 0x0027, 0x003B, 0x003F, 0x005A, 0x0061, 0x007A }; // // [84] Letter ::= BaseChar | Ideographic // int[] letterRange = { // BaseChar 0x0041, 0x005A, 0x0061, 0x007A, 0x00C0, 0x00D6, 0x00D8, 0x00F6, 0x00F8, 0x0131, 0x0134, 0x013E, 0x0141, 0x0148, 0x014A, 0x017E, 0x0180, 0x01C3, 0x01CD, 0x01F0, 0x01F4, 0x01F5, 0x01FA, 0x0217, 0x0250, 0x02A8, 0x02BB, 0x02C1, 0x0388, 0x038A, 0x038E, 0x03A1, 0x03A3, 0x03CE, 0x03D0, 0x03D6, 0x03E2, 0x03F3, 0x0401, 0x040C, 0x040E, 0x044F, 0x0451, 0x045C, 0x045E, 0x0481, 0x0490, 0x04C4, 0x04C7, 0x04C8, 0x04CB, 0x04CC, 0x04D0, 0x04EB, 0x04EE, 0x04F5, 0x04F8, 0x04F9, 0x0531, 0x0556, 0x0561, 0x0586, 0x05D0, 0x05EA, 0x05F0, 0x05F2, 0x0621, 0x063A, 0x0641, 0x064A, 0x0671, 0x06B7, 0x06BA, 0x06BE, 0x06C0, 0x06CE, 0x06D0, 0x06D3, 0x06E5, 0x06E6, 0x0905, 0x0939, 0x0958, 0x0961, 0x0985, 0x098C, 0x098F, 0x0990, 0x0993, 0x09A8, 0x09AA, 0x09B0, 0x09B6, 0x09B9, 0x09DC, 0x09DD, 0x09DF, 0x09E1, 0x09F0, 0x09F1, 0x0A05, 0x0A0A, 0x0A0F, 0x0A10, 0x0A13, 0x0A28, 0x0A2A, 0x0A30, 0x0A32, 0x0A33, 0x0A35, 0x0A36, 0x0A38, 0x0A39, 0x0A59, 0x0A5C, 0x0A72, 0x0A74, 0x0A85, 0x0A8B, 0x0A8F, 0x0A91, 0x0A93, 0x0AA8, 0x0AAA, 0x0AB0, 0x0AB2, 0x0AB3, 0x0AB5, 0x0AB9, 0x0B05, 0x0B0C, 0x0B0F, 0x0B10, 0x0B13, 0x0B28, 0x0B2A, 0x0B30, 0x0B32, 0x0B33, 0x0B36, 0x0B39, 0x0B5C, 0x0B5D, 0x0B5F, 0x0B61, 0x0B85, 0x0B8A, 0x0B8E, 0x0B90, 0x0B92, 0x0B95, 0x0B99, 0x0B9A, 0x0B9E, 0x0B9F, 0x0BA3, 0x0BA4, 0x0BA8, 0x0BAA, 0x0BAE, 0x0BB5, 0x0BB7, 0x0BB9, 0x0C05, 0x0C0C, 0x0C0E, 0x0C10, 0x0C12, 0x0C28, 0x0C2A, 0x0C33, 0x0C35, 0x0C39, 0x0C60, 0x0C61, 0x0C85, 0x0C8C, 0x0C8E, 0x0C90, 0x0C92, 0x0CA8, 0x0CAA, 0x0CB3, 0x0CB5, 0x0CB9, 0x0CE0, 0x0CE1, 0x0D05, 0x0D0C, 0x0D0E, 0x0D10, 0x0D12, 0x0D28, 0x0D2A, 0x0D39, 0x0D60, 0x0D61, 0x0E01, 0x0E2E, 0x0E32, 0x0E33, 0x0E40, 0x0E45, 0x0E81, 0x0E82, 0x0E87, 0x0E88, 0x0E94, 0x0E97, 0x0E99, 0x0E9F, 0x0EA1, 0x0EA3, 0x0EAA, 0x0EAB, 0x0EAD, 0x0EAE, 0x0EB2, 0x0EB3, 0x0EC0, 0x0EC4, 0x0F40, 0x0F47, 0x0F49, 0x0F69, 0x10A0, 0x10C5, 0x10D0, 0x10F6, 0x1102, 0x1103, 0x1105, 0x1107, 0x110B, 0x110C, 0x110E, 0x1112, 0x1154, 0x1155, 0x115F, 0x1161, 0x116D, 0x116E, 0x1172, 0x1173, 0x11AE, 0x11AF, 0x11B7, 0x11B8, 0x11BC, 0x11C2, 0x1E00, 0x1E9B, 0x1EA0, 0x1EF9, 0x1F00, 0x1F15, 0x1F18, 0x1F1D, 0x1F20, 0x1F45, 0x1F48, 0x1F4D, 0x1F50, 0x1F57, 0x1F5F, 0x1F7D, 0x1F80, 0x1FB4, 0x1FB6, 0x1FBC, 0x1FC2, 0x1FC4, 0x1FC6, 0x1FCC, 0x1FD0, 0x1FD3, 0x1FD6, 0x1FDB, 0x1FE0, 0x1FEC, 0x1FF2, 0x1FF4, 0x1FF6, 0x1FFC, 0x212A, 0x212B, 0x2180, 0x2182, 0x3041, 0x3094, 0x30A1, 0x30FA, 0x3105, 0x312C, 0xAC00, 0xD7A3, // Ideographic 0x3021, 0x3029, 0x4E00, 0x9FA5, }; int[] letterChar = { // BaseChar 0x0386, 0x038C, 0x03DA, 0x03DC, 0x03DE, 0x03E0, 0x0559, 0x06D5, 0x093D, 0x09B2, 0x0A5E, 0x0A8D, 0x0ABD, 0x0AE0, 0x0B3D, 0x0B9C, 0x0CDE, 0x0E30, 0x0E84, 0x0E8A, 0x0E8D, 0x0EA5, 0x0EA7, 0x0EB0, 0x0EBD, 0x1100, 0x1109, 0x113C, 0x113E, 0x1140, 0x114C, 0x114E, 0x1150, 0x1159, 0x1163, 0x1165, 0x1167, 0x1169, 0x1175, 0x119E, 0x11A8, 0x11AB, 0x11BA, 0x11EB, 0x11F0, 0x11F9, 0x1F59, 0x1F5B, 0x1F5D, 0x1FBE, 0x2126, 0x212E, // Ideographic 0x3007, }; // // [87] CombiningChar ::= ... // int[] combiningCharRange = { 0x0300, 0x0345, 0x0360, 0x0361, 0x0483, 0x0486, 0x0591, 0x05A1, 0x05A3, 0x05B9, 0x05BB, 0x05BD, 0x05C1, 0x05C2, 0x064B, 0x0652, 0x06D6, 0x06DC, 0x06DD, 0x06DF, 0x06E0, 0x06E4, 0x06E7, 0x06E8, 0x06EA, 0x06ED, 0x0901, 0x0903, 0x093E, 0x094C, 0x0951, 0x0954, 0x0962, 0x0963, 0x0981, 0x0983, 0x09C0, 0x09C4, 0x09C7, 0x09C8, 0x09CB, 0x09CD, 0x09E2, 0x09E3, 0x0A40, 0x0A42, 0x0A47, 0x0A48, 0x0A4B, 0x0A4D, 0x0A70, 0x0A71, 0x0A81, 0x0A83, 0x0ABE, 0x0AC5, 0x0AC7, 0x0AC9, 0x0ACB, 0x0ACD, 0x0B01, 0x0B03, 0x0B3E, 0x0B43, 0x0B47, 0x0B48, 0x0B4B, 0x0B4D, 0x0B56, 0x0B57, 0x0B82, 0x0B83, 0x0BBE, 0x0BC2, 0x0BC6, 0x0BC8, 0x0BCA, 0x0BCD, 0x0C01, 0x0C03, 0x0C3E, 0x0C44, 0x0C46, 0x0C48, 0x0C4A, 0x0C4D, 0x0C55, 0x0C56, 0x0C82, 0x0C83, 0x0CBE, 0x0CC4, 0x0CC6, 0x0CC8, 0x0CCA, 0x0CCD, 0x0CD5, 0x0CD6, 0x0D02, 0x0D03, 0x0D3E, 0x0D43, 0x0D46, 0x0D48, 0x0D4A, 0x0D4D, 0x0E34, 0x0E3A, 0x0E47, 0x0E4E, 0x0EB4, 0x0EB9, 0x0EBB, 0x0EBC, 0x0EC8, 0x0ECD, 0x0F18, 0x0F19, 0x0F71, 0x0F84, 0x0F86, 0x0F8B, 0x0F90, 0x0F95, 0x0F99, 0x0FAD, 0x0FB1, 0x0FB7, 0x20D0, 0x20DC, 0x302A, 0x302F, }; int[] combiningCharChar = { 0x05BF, 0x05C4, 0x0670, 0x093C, 0x094D, 0x09BC, 0x09BE, 0x09BF, 0x09D7, 0x0A02, 0x0A3C, 0x0A3E, 0x0A3F, 0x0ABC, 0x0B3C, 0x0BD7, 0x0D57, 0x0E31, 0x0EB1, 0x0F35, 0x0F37, 0x0F39, 0x0F3E, 0x0F3F, 0x0F97, 0x0FB9, 0x20E1, 0x3099, 0x309A, }; // // [88] Digit ::= ... // int[] digitRange = { 0x0030, 0x0039, 0x0660, 0x0669, 0x06F0, 0x06F9, 0x0966, 0x096F, 0x09E6, 0x09EF, 0x0A66, 0x0A6F, 0x0AE6, 0x0AEF, 0x0B66, 0x0B6F, 0x0BE7, 0x0BEF, 0x0C66, 0x0C6F, 0x0CE6, 0x0CEF, 0x0D66, 0x0D6F, 0x0E50, 0x0E59, 0x0ED0, 0x0ED9, 0x0F20, 0x0F29, }; // // [89] Extender ::= ... // int[] extenderRange = { 0x3031, 0x3035, 0x309D, 0x309E, 0x30FC, 0x30FE, }; int[] extenderChar = { 0x00B7, 0x02D0, 0x02D1, 0x0387, 0x0640, 0x0E46, 0x0EC6, 0x3005, }; // // SpecialChar ::= '<', '&', '\n', '\r', ']' // int[] specialChar = { '<', '&', '\n', '\r', ']', }; // // Initialize // // set valid characters for (int i = 0; i < charRange.Length; i += 2) { for (int j = charRange[i]; j <= charRange[i + 1]; j++) { CHARS[j] = (byte)(CHARS[j] | VALID | CONTENT); } } // remove special characters for (int i = 0; i < specialChar.Length; i++) { CHARS[specialChar[i]] = (byte)(CHARS[specialChar[i]] & ~CONTENT); } // set space characters for (int i = 0; i < spaceChar.Length; i++) { CHARS[spaceChar[i]] = (byte)(CHARS[spaceChar[i]] | SPACE); } // set name start characters for (int i = 0; i < nameStartChar.Length; i++) { CHARS[nameStartChar[i]] = (byte)(CHARS[nameStartChar[i]] | NAME_START | NAME | NCNAME_START | NCNAME); } for (int i = 0; i < letterRange.Length; i += 2) { for (int j = letterRange[i]; j <= letterRange[i + 1]; j++) { CHARS[j] = (byte)(CHARS[j] | NAME_START | NAME | NCNAME_START | NCNAME); } } for (int i = 0; i < letterChar.Length; i++) { CHARS[letterChar[i]] = (byte)(CHARS[letterChar[i]] | NAME_START | NAME | NCNAME_START | NCNAME); } // set name characters for (int i = 0; i < nameChar.Length; i++) { CHARS[nameChar[i]] = (byte)(CHARS[nameChar[i]] | NAME | NCNAME); } for (int i = 0; i < digitRange.Length; i += 2) { for (int j = digitRange[i]; j <= digitRange[i + 1]; j++) { CHARS[j] = (byte)(CHARS[j] | NAME | NCNAME); } } for (int i = 0; i < combiningCharRange.Length; i += 2) { for (int j = combiningCharRange[i]; j <= combiningCharRange[i + 1]; j++) { CHARS[j] = (byte)(CHARS[j] | NAME | NCNAME); } } for (int i = 0; i < combiningCharChar.Length; i++) { CHARS[combiningCharChar[i]] = (byte)(CHARS[combiningCharChar[i]] | NAME | NCNAME); } for (int i = 0; i < extenderRange.Length; i += 2) { for (int j = extenderRange[i]; j <= extenderRange[i + 1]; j++) { CHARS[j] = (byte)(CHARS[j] | NAME | NCNAME); } } for (int i = 0; i < extenderChar.Length; i++) { CHARS[extenderChar[i]] = (byte)(CHARS[extenderChar[i]] | NAME | NCNAME); } // remove ':' from allowable NCNAME_START and NCNAME chars CHARS[':'] = (byte)(CHARS[':'] & ~(NCNAME_START | NCNAME)); // set Pubid characters for (int i = 0; i < pubidChar.Length; i++) { CHARS[pubidChar[i]] = (byte)(CHARS[pubidChar[i]] | PUBID); } for (int i = 0; i < pubidRange.Length; i += 2) { for (int j = pubidRange[i]; j <= pubidRange[i + 1]; j++) { CHARS[j] = (byte)(CHARS[j] | PUBID); } } } //Static Methods /// <summary> /// Returns true if the specified character is valid. /// </summary> /// <param name="c">The character to check.</param> public static bool IsValid(char c) { return c > 0 && ((CHARS[c] & VALID) != 0); } public static bool IsValid (int c) { if (c > 0xffff) return c < 0x110000; return c > 0 && ((CHARS[c] & VALID) != 0); } /// <summary> /// Returns true if the specified character is invalid. /// </summary> /// <param name="c">The character to check.</param> public static bool IsInvalid(char c) { return !IsValid(c); } public static bool IsInvalid(int c) { return !IsValid(c); } /// <summary> /// Returns true if the specified character can be considered content. /// </summary> /// <param name="c">The character to check.</param> public static bool IsContent(char c) { return (CHARS[c] & CONTENT) != 0; } public static bool IsContent(int c) { return c > 0 && c < CHARS.Length && (CHARS[c] & CONTENT) != 0; } /// <summary> /// Returns true if the specified character can be considered markup. /// Markup characters include '&lt;', '&amp;', and '%'. /// </summary> /// <param name="c">The character to check.</param> public static bool IsMarkup(char c) { return c == '<' || c == '&' || c == '%'; } public static bool IsMarkup(int c) { return c > 0 && c < CHARS.Length && (c == '<' || c == '&' || c == '%'); } /// <summary> /// Returns true if the specified character is a space character /// as defined by production [3] in the XML 1.0 specification. /// </summary> /// <param name="c">The character to check.</param> /// <returns></returns> public static bool IsWhitespace (char c) { return (CHARS[c] & SPACE) != 0; } public static bool IsWhitespace (int c) { return c > 0 && c < CHARS.Length && (CHARS[c] & SPACE) != 0; } /// <summary> /// Returns true if the specified character is a valid name start /// character as defined by production [5] in the XML 1.0 specification. /// </summary> /// <param name="c">The character to check.</param> public static bool IsFirstNameChar (char c) { return (CHARS[c] & NAME_START) != 0; } public static bool IsFirstNameChar (int c) { return c > 0 && c < CHARS.Length && (CHARS[c] & NAME_START) != 0; } /// <summary> /// Returns true if the specified character is a valid name /// character as defined by production [4] in the XML 1.0 specification. /// </summary> /// <param name="c">The character to check.</param> public static bool IsNameChar(char c) { return (CHARS[c] & NAME) != 0; } public static bool IsNameChar(int c) { return c > 0 && c < CHARS.Length && (CHARS[c] & NAME) != 0; } /// <summary> /// Returns true if the specified character is a valid NCName start /// character as defined by production [4] in Namespaces in XML /// recommendation. /// </summary> /// <param name="c">The character to check.</param> /// <returns></returns> public static bool IsNCNameStart(char c) { return (CHARS[c] & NCNAME_START) != 0; } public static bool IsNCNameStart(int c) { return c > 0 && c < CHARS.Length && (CHARS[c] & NCNAME_START) != 0; } /// <summary> /// Returns true if the specified character is a valid NCName /// character as defined by production [5] in Namespaces in XML /// recommendation. /// </summary> /// <param name="c"></param> /// <returns></returns> public static bool IsNCNameChar(char c) { return (CHARS[c] & NCNAME) != 0; } public static bool IsNCNameChar(int c) { return c > 0 && c < CHARS.Length && (CHARS[c] & NCNAME) != 0; } /// <summary> /// Returns true if the specified character is a valid Pubid /// character as defined by production [13] in the XML 1.0 specification. /// </summary> /// <param name="c">The character to check</param> public static bool IsPubidChar (char c) { return (CHARS[c] & PUBID) != 0; } public static bool IsPubidChar (int c) { return c > 0 && c < CHARS.Length && (CHARS[c] & PUBID) != 0; } /// <summary> /// Check to see if a string is a valid Name according to [5] /// in the XML 1.0 Recommendation /// </summary> /// <param name="name">The string to check</param> public static bool IsValidName(String name, out Exception err) { err = null; if (name.Length == 0) { err = new XmlException("Name can not be an empty string",null); return false; } char ch = name[0]; if( IsFirstNameChar (ch) == false) { err = new XmlException("The character '"+ch+"' cannot start a Name",null); return false; } for (int i = 1; i < name.Length; i++ ) { ch = name[i]; if( IsNameChar (ch) == false ) { err = new XmlException("The character '"+ch+"' is not allowed in a Name",null); return false; } } return true; } public static int IsValidName (string name) { if (name.Length == 0) return 0; if (!IsFirstNameChar (name [0])) return 0; for (int i=1; i<name.Length; i++) if (!IsNameChar (name [i])) return i; return -1; } /// <summary> /// Check to see if a string is a valid NCName according to [4] /// from the XML Namespaces 1.0 Recommendation /// </summary> /// <param name="ncName">The string to check</param> public static bool IsValidNCName(String ncName, out Exception err) { err = null; if (ncName.Length == 0) { err = new XmlException("NCName can not be an empty string",null); return false; } char ch = ncName[0]; if( IsNCNameStart(ch) == false) { err = new XmlException("The character '"+ch+"' cannot start a NCName",null); return false; } for (int i = 1; i < ncName.Length; i++ ) { ch = ncName[i]; if( IsNCNameChar (ch) == false ) { err = new XmlException("The character '"+ch+"' is not allowed in a NCName",null); return false; } } return true; } /// <summary> /// Check to see if a string is a valid Nmtoken according to [7] /// in the XML 1.0 Recommendation /// </summary> /// <param name="nmtoken">The string to check.</param> public static bool IsValidNmtoken(String nmtoken, out Exception err) { err = null; if (nmtoken.Length == 0) { err = new XmlException("NMTOKEN can not be an empty string", null); return false; } for (int i = 0; i < nmtoken.Length; i++ ) { char ch = nmtoken[i]; if( ! IsNameChar (ch) ) { err = new XmlException("The character '"+ch+"' is not allowed in a NMTOKEN",null); return false; } } return true; } // encodings /// <summary> /// Returns true if the encoding name is a valid IANA encoding. /// This method does not verify that there is a decoder available /// for this encoding, only that the characters are valid for an /// IANA encoding name. /// </summary> /// <param name="ianaEncoding">The encoding to check.</param> /// <returns></returns> public static bool IsValidIANAEncoding(String ianaEncoding) { if (ianaEncoding != null) { int length = ianaEncoding.Length; if (length > 0) { char c = ianaEncoding[0]; if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) { for (int i = 1; i < length; i++) { c = ianaEncoding[i]; if ((c < 'A' || c > 'Z') && (c < 'a' || c > 'z') && (c < '0' || c > '9') && c != '.' && c != '_' && c != '-') { return false; } } return true; } } } return false; } public static bool IsName (string str) { if (str.Length == 0) return false; if (!IsFirstNameChar (str [0])) return false; for (int i = 1; i < str.Length; i++) if (!IsNameChar (str [i])) return false; return true; } public static bool IsNCName (string str) { if (str.Length == 0) return false; if (!IsFirstNameChar (str [0])) return false; for (int i = 0; i < str.Length; i++) if (!IsNCNameChar (str [i])) return false; return true; } public static bool IsNmToken (string str) { if (str.Length == 0) return false; for (int i = 0; i < str.Length; i++) if (!IsNameChar (str [i])) return false; return true; } public static bool IsWhitespace (string str) { for (int i = 0; i < str.Length; i++) if (!IsWhitespace (str [i])) return false; return true; } public static int GetPredefinedEntity (string name) { switch (name) { case "amp": return '&'; case "lt": return '<'; case "gt": return '>'; case "quot": return '"'; case "apos": return '\''; default: return -1; } } } }
using Signum.Entities.Workflow; using Signum.Engine.Workflow; using Signum.Engine; using Signum.Engine.Operations; using Signum.Entities; using Signum.React.Facades; using System; using System.Threading; using System.Collections.Generic; using System.Linq; using Signum.Entities.Basics; using Signum.Engine.DynamicQuery; using Signum.Engine.Basics; using Signum.Engine.Authorization; using Newtonsoft.Json; using Signum.Utilities; using Signum.React.ApiControllers; using Microsoft.AspNetCore.Mvc; using Signum.React.Filters; using static Signum.React.ApiControllers.OperationController; using Signum.Entities.Reflection; using System.ComponentModel.DataAnnotations; namespace Signum.React.Workflow { [ValidateModelFilter] public class WorkflowController : Controller { [HttpGet("api/workflow/fetchForViewing/{caseActivityId}")] public EntityPackWorkflow GetEntity(string caseActivityId) { var lite = Lite.ParsePrimaryKey<CaseActivityEntity>(caseActivityId); var activity = CaseActivityLogic.RetrieveForViewing(lite); using (WorkflowActivityInfo.Scope(new WorkflowActivityInfo { CaseActivity = activity })) { var ep = SignumServer.GetEntityPack((Entity)activity.Case.MainEntity); return new EntityPackWorkflow { activity = activity, canExecuteActivity = OperationLogic.ServiceCanExecute(activity).ToDictionary(a => a.Key.Key, a => a.Value), canExecuteMainEntity = ep.canExecute, Extension = ep.extension, }; } } [HttpGet("api/workflow/tags/{caseId}")] public List<CaseTagTypeEntity> GetTags(string caseId) { var lite = Lite.ParsePrimaryKey<CaseEntity>(caseId); return Database.Query<CaseTagEntity>().Where(a => a.Case == lite).Select(a => a.TagType).ToList(); } public class EntityPackWorkflow { public CaseActivityEntity activity { get; set; } public Dictionary<string, string> canExecuteActivity { get; set; } public Dictionary<string, string> canExecuteMainEntity { get; set; } [JsonExtensionData] public Dictionary<string, object?> Extension { get; set; } = new Dictionary<string, object?>(); } [HttpGet("api/workflow/caseFlowPack/{caseActivityId}")] public EntityPackCaseFlow GetCaseFlowPack(string caseActivityId) { var lite = Lite.ParsePrimaryKey<CaseActivityEntity>(caseActivityId); var dbValues = lite.InDB(a => new { a.Case, a.WorkflowActivity }); return new EntityPackCaseFlow { pack = SignumServer.GetEntityPack(dbValues.Case), workflowActivity = dbValues.WorkflowActivity, }; } public class EntityPackCaseFlow { public EntityPackTS pack { get; set; } public IWorkflowNodeEntity workflowActivity { get; set; } } [HttpGet("api/workflow/starts")] public List<WorkflowEntity> Starts() { return WorkflowLogic.GetAllowedStarts(); } [HttpGet("api/workflow/workflowModel/{workflowId}")] public WorkflowModelAndIssues GetWorkflowModel(string workflowId) { var id = PrimaryKey.Parse(workflowId, typeof(WorkflowEntity)); var wf = Database.Retrieve<WorkflowEntity>(id); var model = WorkflowLogic.GetWorkflowModel(wf); var wb = new WorkflowBuilder(wf); List<WorkflowIssue> issues = new List<WorkflowIssue>(); wb.ValidateGraph(issues); return new WorkflowModelAndIssues(model, issues); } public class WorkflowModelAndIssues { public WorkflowModel model; public List<WorkflowIssue> issues; public WorkflowModelAndIssues(WorkflowModel model, List<WorkflowIssue> issues) { this.model = model; this.issues = issues; } } [HttpPost("api/workflow/previewChanges/{workflowId}")] public PreviewResult PreviewChanges(string workflowId, [Required, FromBody]WorkflowModel model) { var id = PrimaryKey.Parse(workflowId, typeof(WorkflowEntity)); var wf = Database.Retrieve<WorkflowEntity>(id); return WorkflowLogic.PreviewChanges(wf, model); } [HttpPost("api/workflow/save"), ValidateModelFilter] public ActionResult<EntityPackWithIssues> SaveWorkflow([Required, FromBody]EntityOperationRequest request) { WorkflowEntity entity; List<WorkflowIssue> issuesContainer = new List<WorkflowIssue>(); try { entity = ((WorkflowEntity)request.entity).Execute(WorkflowOperation.Save, (request.Args.EmptyIfNull()).And(issuesContainer).ToArray()); } catch (IntegrityCheckException ex) { GraphExplorer.SetValidationErrors(GraphExplorer.FromRoot(request.entity), ex); this.TryValidateModel(request, "request"); this.ModelState.AddModelError("workflowIssues", JsonConvert.SerializeObject(issuesContainer, SignumServer.JsonSerializerSettings)); return BadRequest(this.ModelState); } return new EntityPackWithIssues(SignumServer.GetEntityPack(entity), issuesContainer); } public class EntityPackWithIssues { public EntityPackTS entityPack; public List<WorkflowIssue> issues; public EntityPackWithIssues(EntityPackTS entityPack, List<WorkflowIssue> issues) { this.entityPack = entityPack; this.issues = issues; } } [HttpGet("api/workflow/findMainEntityType")] public List<Lite<TypeEntity>> FindMainEntityType(string subString, int count) { var list = TypeLogic.TypeToEntity .Where(kvp => typeof(ICaseMainEntity).IsAssignableFrom(kvp.Key)) .Select(kvp => kvp.Value.ToLite()); return AutocompleteUtils.Autocomplete(list, subString, count); } [HttpPost("api/workflow/findNode")] public List<Lite<IWorkflowNodeEntity>> FindNode([Required, FromBody]WorkflowFindNodeRequest request) { var workflow = Lite.Create<WorkflowEntity>(request.workflowId); return WorkflowLogic.AutocompleteNodes(workflow, request.subString, request.count, request.excludes); } public class WorkflowFindNodeRequest { public int workflowId; public string subString; public int count; public List<Lite<IWorkflowNodeEntity>> excludes; } [HttpPost("api/workflow/condition/test")] public WorkflowConditionTestResponse Test([Required, FromBody]WorkflowConditionTestRequest request) { IWorkflowConditionEvaluator evaluator; try { evaluator = request.workflowCondition.Eval.Algorithm; } catch (Exception e) { return new WorkflowConditionTestResponse { compileError = e.Message }; } try { return new WorkflowConditionTestResponse { validationResult = evaluator.EvaluateUntyped(request.exampleEntity, new WorkflowTransitionContext(null, null, null)) }; } catch (Exception e) { return new WorkflowConditionTestResponse { validationException = e.Message }; } } public class WorkflowConditionTestRequest { public WorkflowConditionEntity workflowCondition; public ICaseMainEntity exampleEntity; } public class WorkflowConditionTestResponse { public string compileError; public string validationException; public bool validationResult; } [HttpGet("api/workflow/scriptRunner/view")] public WorkflowScriptRunnerState ViewScriptRunner() { WorkflowPermission.ViewWorkflowPanel.AssertAuthorized(); WorkflowScriptRunnerState state = WorkflowScriptRunner.ExecutionState(); return state; } [HttpPost("api/workflow/scriptRunner/start")] public void StartScriptRunner() { WorkflowPermission.ViewWorkflowPanel.AssertAuthorized(); WorkflowScriptRunner.StartRunningScripts(0); Thread.Sleep(1000); } [HttpPost("api/workflow/scriptRunner/stop")] public void StopScriptRunner() { WorkflowPermission.ViewWorkflowPanel.AssertAuthorized(); WorkflowScriptRunner.Stop(); Thread.Sleep(1000); } [HttpGet("api/workflow/caseflow/{caseId}")] public CaseFlow GetCaseFlow(string caseId) { var lite = Lite.ParsePrimaryKey<CaseEntity>(caseId); return CaseFlowLogic.GetCaseFlow(lite.RetrieveAndRemember()); } [HttpPost("api/workflow/activityMonitor")] public WorkflowActivityMonitor GetWorkflowActivityMonitor([Required, FromBody]WorkflowActivityMonitorRequestTS request) { return WorkflowActivityMonitorLogic.GetWorkflowActivityMonitor(request.ToRequest()); } [HttpPost("api/workflow/nextConnections")] public List<Lite<IWorkflowNodeEntity>> GetNextJumps([Required, FromBody]NextConnectionsRequest request) { return request.workflowActivity.RetrieveAndForget() .NextConnectionsFromCache(request.connectionType) .Select(a => a.To.ToLite()) .ToList(); } } public class NextConnectionsRequest { public Lite<WorkflowActivityEntity> workflowActivity; public ConnectionType connectionType; } public class WorkflowActivityMonitorRequestTS { public Lite<WorkflowEntity> workflow; public List<FilterTS> filters; public List<ColumnTS> columns; public WorkflowActivityMonitorRequest ToRequest() { var qd = QueryLogic.Queries.QueryDescription(typeof(CaseActivityEntity)); return new WorkflowActivityMonitorRequest { Workflow = workflow, Filters = filters.Select(f => f.ToFilter(qd, true)).ToList(), Columns = columns.Select(c => c.ToColumn(qd, true)).ToList(), }; } } }
using System.Collections.Generic; using System.Linq; using ParadoxNotion; using ParadoxNotion.Serialization; using NodeCanvas.Framework.Internal; using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif namespace NodeCanvas.Framework{ /// A component that is used to control a Graph in respects to the gameobject attached to abstract public class GraphOwner : MonoBehaviour { [SerializeField] /*[HideInInspector]*/ private string boundGraphSerialization; [SerializeField] /*[HideInInspector]*/ private List<UnityEngine.Object> boundGraphObjectReferences; public enum EnableAction{ EnableBehaviour, DoNothing } public enum DisableAction{ DisableBehaviour, PauseBehaviour, DoNothing } [HideInInspector] ///What will happen OnEnable public EnableAction enableAction = EnableAction.EnableBehaviour; [HideInInspector] ///What will happen OnDisable public DisableAction disableAction = DisableAction.DisableBehaviour; ///Raised when the assigned behaviour state is changed (start/pause/stop) public static System.Action<GraphOwner> onOwnerBehaviourStateChange; private Dictionary<Graph, Graph> instances = new Dictionary<Graph, Graph>(); private bool startCalled = false; private static bool isQuiting; abstract public Graph graph{get;set;} abstract public IBlackboard blackboard{get;set;} abstract public System.Type graphType{get;} ///Is the assigned graph currently running? public bool isRunning{ get {return graph != null? graph.isRunning : false;} } ///Is the assigned graph currently paused? public bool isPaused{ get {return graph != null? graph.isPaused : false;} } ///The time is seconds the graph is running public float elapsedTime{ get {return graph != null? graph.elapsedTime : 0;} } //Gets the instance graph for this owner of the provided graph protected Graph GetInstance(Graph originalGraph){ if (originalGraph == null){ return null; } //in editor the instance is always the original #if UNITY_EDITOR if (!Application.isPlaying){ return originalGraph; } #endif //if its already an instance, return the instance if (instances.Values.Contains(originalGraph)){ return originalGraph; } Graph instance = null; //if it's not an instance but rather an asset reference which has been instantiated before, return the instance stored, //otherwise create and store a new instance. if (!instances.TryGetValue(originalGraph, out instance)){ instance = Graph.Clone<Graph>(originalGraph); instances[originalGraph] = instance; } instance.agent = this; instance.blackboard = this.blackboard; return instance; } ///Start the graph assigned public void StartBehaviour(){ graph = GetInstance(graph); if (graph != null){ graph.StartGraph(this, blackboard, true); if (onOwnerBehaviourStateChange != null){ onOwnerBehaviourStateChange(this); } } } ///Start the graph assigned providing a callback for when it's finished if at all public void StartBehaviour(System.Action<bool> callback){ graph = GetInstance(graph); if (graph != null){ graph.StartGraph(this, blackboard, true, callback); if (onOwnerBehaviourStateChange != null){ onOwnerBehaviourStateChange(this); } } } ///Pause the current running graph public void PauseBehaviour(){ if (graph != null){ graph.Pause(); if (onOwnerBehaviourStateChange != null){ onOwnerBehaviourStateChange(this); } } } ///Stop the current running graph public void StopBehaviour(){ if (graph != null){ graph.Stop(); if (onOwnerBehaviourStateChange != null){ onOwnerBehaviourStateChange(this); } } } ///Manually update the assigned graph public void UpdateBehaviour(){ if (graph != null){ graph.UpdateGraph(); } } ///Send an event through the graph (To be used with CheckEvent for example). Same as .graph.SendEvent public void SendEvent(string eventName){ SendEvent(new EventData(eventName));} public void SendEvent<T>(string eventName, T eventValue) {SendEvent(new EventData<T>(eventName, eventValue)); } public void SendEvent(EventData eventData){ if (graph != null){ graph.SendEvent(eventData); } } ///Thats the same as calling the static Graph.SendGlobalEvent public static void SendGlobalEvent(string eventName){ Graph.SendGlobalEvent( new EventData(eventName) ); } ///Thats the same as calling the static Graph.SendGlobalEvent public static void SendGlobalEvent<T>(string eventName, T eventValue){ Graph.SendGlobalEvent( new EventData<T>(eventName, eventValue) ); } //just set the quit flag protected void OnApplicationQuit(){ isQuiting = true; } //instantiate and deserialize the bound graph, or instantiate the asset graph reference protected void Awake(){ #if UNITY_EDITOR if ( !hasUpdated2_6_2 ){ Debug.LogWarning(string.Format("GraphOwner '{0}' is being used in runtime but has not been updated to version 2.6.2+ !", name), gameObject); enabled = false; return; } #endif if ( !string.IsNullOrEmpty(boundGraphSerialization) ){ //bound if (graph == null){ graph = (Graph)ScriptableObject.CreateInstance(graphType); #if UNITY_EDITOR graph.name = this.name + " " + graphType.Name; #endif graph.Deserialize(boundGraphSerialization, true, boundGraphObjectReferences); instances[graph] = graph; return; } //this is done for when instantiating a prefab with a bound graph graph.SetSerializationObjectReferences(boundGraphObjectReferences); } graph = GetInstance(graph); } //mark as startCalled and handle enable behaviour setting protected void Start(){ startCalled = true; if (enableAction == EnableAction.EnableBehaviour){ StartBehaviour(); } } //handle enable behaviour setting protected void OnEnable(){ if (startCalled && enableAction == EnableAction.EnableBehaviour){ StartBehaviour(); } } //handle disable behaviour setting protected void OnDisable(){ if (isQuiting){ return; } if (disableAction == DisableAction.DisableBehaviour){ StopBehaviour(); } if (disableAction == DisableAction.PauseBehaviour){ PauseBehaviour(); } } //Destroy instanced graphs as well protected void OnDestroy(){ if (isQuiting){ return; } StopBehaviour(); foreach (var instanceGraph in instances.Values){ foreach(var subGraph in instanceGraph.GetAllInstancedNestedGraphs()){ Destroy(subGraph); } Destroy(instanceGraph); } } //////////////////////////////////////// ///////////GUI AND EDITOR STUFF///////// //////////////////////////////////////// #if UNITY_EDITOR [SerializeField] private VersionUpdateProxyGraph versionUpdateProxyGraph; private Graph boundGraphInstance; ///Editor. Has owner been version updated? public bool hasUpdated2_6_2{ get { return versionUpdateProxyGraph == null && GetComponents(typeof(IScriptableComponent)).Cast<Graph>().Contains(this.graph) == false; } } ///Editor. Is the graph a bound one? public bool graphIsBound{ get { return boundGraphInstance != null || !string.IsNullOrEmpty(boundGraphSerialization); } } //Called in editor only after assigned graph is serialized. //If the graph is bound, we store the serialization data here. public void OnGraphSerialized(Graph serializedGraph){ if (graphIsBound && this.graph == serializedGraph){ string newSerialization = null; List<Object> newReferences = null; graph.GetSerializationData(out newSerialization, out newReferences); if (newSerialization != boundGraphSerialization || !newReferences.SequenceEqual(boundGraphObjectReferences)){ UnityEditor.Undo.RecordObject(this, "Bound Graph Change"); boundGraphSerialization = newSerialization; boundGraphObjectReferences = newReferences; EditorUtility.SetDirty(this); } } } ///Called from the editor. protected void OnValidate(){ Validate(); } public void Validate(){ if (Application.isPlaying || EditorApplication.isPlayingOrWillChangePlaymode){ return; } //check if has updated before everything else! if (!hasUpdated2_6_2){ if (graph != null){ graph.hideFlags = HideFlags.HideInInspector; } return; } //everything bellow is relevant to bound graphs only if (!graphIsBound){ return; } var prefabType = PrefabUtility.GetPrefabType(this); if (boundGraphInstance == null){ if (prefabType == PrefabType.Prefab){ if (graph == null){ graph = (Graph)ScriptableObject.CreateInstance(graphType); AssetDatabase.AddObjectToAsset(graph, this); EditorApplication.delayCall += ()=>{ AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(graph)); }; } boundGraphInstance = graph; } else { boundGraphInstance = (Graph)ScriptableObject.CreateInstance(graphType); } } boundGraphInstance.Deserialize(boundGraphSerialization, false, boundGraphObjectReferences); boundGraphInstance.hideFlags = prefabType == PrefabType.Prefab? HideFlags.None : (HideFlags.DontSaveInEditor | HideFlags.DontSaveInBuild); (boundGraphInstance as UnityEngine.Object).name = this.name + " " + graphType.Name; boundGraphInstance.Validate(); graph = boundGraphInstance; boundGraphSerialization = graph.Serialize(false, boundGraphObjectReferences); graph.agent = this; graph.blackboard = this.blackboard; } ///Editor. Handles updating bound graphs from previous versions. public void TryUpdateBoundGraphPriorToVersion2_6_2(){ if (hasUpdated2_6_2){ return; } var scriptableComponents = GetComponents(typeof(IScriptableComponent)).Where(s => s != null && s.GetType() == graphType).Cast<Graph>(); var prefabType = PrefabUtility.GetPrefabType(this); var thisTypeName = this.GetType().Name; if (prefabType == PrefabType.Prefab){ //Replace monoscript reference thus keeping object reference the same as far as prefab system works. //VersionUpdateProxyGraph uses exactly the same field names, so Unity will still deserialize values but in the new script. foreach(var scriptable in scriptableComponents){ if (scriptable == this.graph){ scriptable.Serialize(); scriptable.GetSerializationData(out boundGraphSerialization, out boundGraphObjectReferences); var monoscriptGUID = AssetDatabase.FindAssets("VersionUpdateProxyGraph")[0]; var monoScript = (MonoScript)AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(monoscriptGUID), typeof(MonoScript)); var id = scriptable.GetInstanceID(); var serObject = new SerializedObject(scriptable); var scriptProp = serObject.FindProperty("m_Script"); scriptProp.objectReferenceValue = monoScript; serObject.ApplyModifiedProperties(); #if UNITY_5_6_OR_NEWER serObject.UpdateIfRequiredOrScript(); #else serObject.UpdateIfDirtyOrScript(); #endif versionUpdateProxyGraph = (VersionUpdateProxyGraph)EditorUtility.InstanceIDToObject(id); versionUpdateProxyGraph.hideFlags = HideFlags.NotEditable; boundGraphInstance = null; graph = null; Debug.Log(string.Format("{0} '{1}' ({2}), Updated.", thisTypeName, name, prefabType), this); EditorUtility.SetDirty(this); break; } } } if (prefabType == PrefabType.PrefabInstance){ if (versionUpdateProxyGraph != null){ versionUpdateProxyGraph.GetSerializationData(out boundGraphSerialization, out boundGraphObjectReferences); Debug.Log(string.Format("{0} '{1}' (Linked {2}), Updated.", thisTypeName, name, prefabType), this); boundGraphInstance = null; graph = null; DestroyImmediate(versionUpdateProxyGraph, true); EditorUtility.SetDirty(this); } //This can happen if the graphowner (and it's bound graph) is not part of the prefab asset. foreach(var scriptable in scriptableComponents){ if (scriptable == this.graph){ scriptable.Serialize(); scriptable.GetSerializationData(out boundGraphSerialization, out boundGraphObjectReferences); Debug.Log(string.Format("{0} '{1}' ({2}), Updated.", thisTypeName, name, prefabType), this); boundGraphInstance = null; graph = null; DestroyImmediate(scriptable, true); EditorUtility.SetDirty(this); } break; } } //All other PrefabType cases. if (prefabType != PrefabType.Prefab && prefabType != PrefabType.PrefabInstance){ foreach(var scriptable in scriptableComponents){ if (scriptable == this.graph){ scriptable.Serialize(); scriptable.GetSerializationData(out boundGraphSerialization, out boundGraphObjectReferences); Debug.Log(string.Format("{0} '{1}', Updated.", thisTypeName, name), this); boundGraphInstance = null; graph = null; DestroyImmediate(scriptable, true); EditorUtility.SetDirty(this); } break; } } } ////// ////// ///Editor. Binds the target graph (null to unbind current). public void SetBoundGraphReference(Graph target){ if (Application.isPlaying || EditorApplication.isPlayingOrWillChangePlaymode){ Debug.LogError("SetBoundGraphReference method is an Editor only method!"); return; } graph = null; boundGraphInstance = null; if (target == null){ boundGraphSerialization = null; boundGraphObjectReferences = null; return; } target.Serialize(); target.GetSerializationData(out boundGraphSerialization, out boundGraphObjectReferences); Validate(); //validate to handle bound graph instance } protected void Reset(){ blackboard = gameObject.GetComponent<Blackboard>(); if (blackboard == null){ blackboard = gameObject.AddComponent<Blackboard>(); } } //forward the call protected void OnDrawGizmos(){ Gizmos.DrawIcon(transform.position, "GraphOwnerGizmo.png", true); DoGizmos(graph); } void DoGizmos(Graph targetGraph){ if (targetGraph != null){ for (var i = 0; i < targetGraph.allNodes.Count; i++){ var node = targetGraph.allNodes[i]; node.OnDrawGizmos(); if (Graph.currentSelection == node){ node.OnDrawGizmosSelected(); } var graphAssignable = node as IGraphAssignable; if (graphAssignable != null && graphAssignable.nestedGraph != null){ DoGizmos(graphAssignable.nestedGraph); } } } } #endif } ///The class where GraphOwners derive from abstract public class GraphOwner<T> : GraphOwner where T:Graph{ [SerializeField] /*[HideInInspector]*/ private T _graph; [SerializeField] /*[HideInInspector]*/ private Object _blackboard; ///The current behaviour Graph assigned sealed public override Graph graph{ get {return _graph; } set {_graph = (T)value;} } ///The current behaviour Graph assigned (same as .graph but of type T) public T behaviour{ get { return _graph; } set { _graph = value; } } ///The blackboard that the assigned behaviour will be Started with or currently using sealed public override IBlackboard blackboard{ get { if (graph != null && graph.useLocalBlackboard){ return graph.localBlackboard; } if (_blackboard == null){ _blackboard = GetComponent<Blackboard>(); } return _blackboard as IBlackboard; } set { if ( !ReferenceEquals(_blackboard, value) ){ _blackboard = (Blackboard)(object)value; if (graph != null && !graph.useLocalBlackboard){ graph.blackboard = value; } } } } ///The Graph type this Owner can be assigned sealed public override System.Type graphType{ get {return typeof(T);} } ///Start a new behaviour on this owner public void StartBehaviour(T newGraph){ SwitchBehaviour(newGraph); } ///Start a new behaviour on this owner and get a call back for when it's finished if at all public void StartBehaviour(T newGraph, System.Action<bool> callback){ SwitchBehaviour(newGraph, callback); } ///Use to switch the behaviour dynamicaly at runtime public void SwitchBehaviour(T newGraph){ SwitchBehaviour(newGraph, null); } ///Use to switch or set graphs at runtime and optionaly get a callback when it's finished if at all public void SwitchBehaviour(T newGraph, System.Action<bool> callback){ StopBehaviour(); graph = newGraph; StartBehaviour(callback); } } }
/* * 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 IOrderSourceReservationApi : IApiAccessor { #region Synchronous Operations /// <summary> /// Create an orderSourceReservation /// </summary> /// <remarks> /// Inserts a new orderSourceReservation using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">OrderSourceReservation to be inserted.</param> /// <returns>OrderSourceReservation</returns> OrderSourceReservation AddOrderSourceReservation (OrderSourceReservation body); /// <summary> /// Create an orderSourceReservation /// </summary> /// <remarks> /// Inserts a new orderSourceReservation using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">OrderSourceReservation to be inserted.</param> /// <returns>ApiResponse of OrderSourceReservation</returns> ApiResponse<OrderSourceReservation> AddOrderSourceReservationWithHttpInfo (OrderSourceReservation body); /// <summary> /// Delete an orderSourceReservation /// </summary> /// <remarks> /// Deletes the orderSourceReservation identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="orderSourceReservationId">Id of the orderSourceReservation to be deleted.</param> /// <returns></returns> void DeleteOrderSourceReservation (int? orderSourceReservationId); /// <summary> /// Delete an orderSourceReservation /// </summary> /// <remarks> /// Deletes the orderSourceReservation identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="orderSourceReservationId">Id of the orderSourceReservation to be deleted.</param> /// <returns>ApiResponse of Object(void)</returns> ApiResponse<Object> DeleteOrderSourceReservationWithHttpInfo (int? orderSourceReservationId); /// <summary> /// Search orderSourceReservations by filter /// </summary> /// <remarks> /// Returns the list of orderSourceReservations 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&lt;OrderSourceReservation&gt;</returns> List<OrderSourceReservation> GetOrderSourceReservationByFilter (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Search orderSourceReservations by filter /// </summary> /// <remarks> /// Returns the list of orderSourceReservations 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&lt;OrderSourceReservation&gt;</returns> ApiResponse<List<OrderSourceReservation>> GetOrderSourceReservationByFilterWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Get an orderSourceReservation by id /// </summary> /// <remarks> /// Returns the orderSourceReservation identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="orderSourceReservationId">Id of the orderSourceReservation to be returned.</param> /// <returns>OrderSourceReservation</returns> OrderSourceReservation GetOrderSourceReservationById (int? orderSourceReservationId); /// <summary> /// Get an orderSourceReservation by id /// </summary> /// <remarks> /// Returns the orderSourceReservation identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="orderSourceReservationId">Id of the orderSourceReservation to be returned.</param> /// <returns>ApiResponse of OrderSourceReservation</returns> ApiResponse<OrderSourceReservation> GetOrderSourceReservationByIdWithHttpInfo (int? orderSourceReservationId); /// <summary> /// Update an orderSourceReservation /// </summary> /// <remarks> /// Updates an existing orderSourceReservation using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">OrderSourceReservation to be updated.</param> /// <returns></returns> void UpdateOrderSourceReservation (OrderSourceReservation body); /// <summary> /// Update an orderSourceReservation /// </summary> /// <remarks> /// Updates an existing orderSourceReservation using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">OrderSourceReservation to be updated.</param> /// <returns>ApiResponse of Object(void)</returns> ApiResponse<Object> UpdateOrderSourceReservationWithHttpInfo (OrderSourceReservation body); #endregion Synchronous Operations #region Asynchronous Operations /// <summary> /// Create an orderSourceReservation /// </summary> /// <remarks> /// Inserts a new orderSourceReservation using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">OrderSourceReservation to be inserted.</param> /// <returns>Task of OrderSourceReservation</returns> System.Threading.Tasks.Task<OrderSourceReservation> AddOrderSourceReservationAsync (OrderSourceReservation body); /// <summary> /// Create an orderSourceReservation /// </summary> /// <remarks> /// Inserts a new orderSourceReservation using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">OrderSourceReservation to be inserted.</param> /// <returns>Task of ApiResponse (OrderSourceReservation)</returns> System.Threading.Tasks.Task<ApiResponse<OrderSourceReservation>> AddOrderSourceReservationAsyncWithHttpInfo (OrderSourceReservation body); /// <summary> /// Delete an orderSourceReservation /// </summary> /// <remarks> /// Deletes the orderSourceReservation identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="orderSourceReservationId">Id of the orderSourceReservation to be deleted.</param> /// <returns>Task of void</returns> System.Threading.Tasks.Task DeleteOrderSourceReservationAsync (int? orderSourceReservationId); /// <summary> /// Delete an orderSourceReservation /// </summary> /// <remarks> /// Deletes the orderSourceReservation identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="orderSourceReservationId">Id of the orderSourceReservation to be deleted.</param> /// <returns>Task of ApiResponse</returns> System.Threading.Tasks.Task<ApiResponse<Object>> DeleteOrderSourceReservationAsyncWithHttpInfo (int? orderSourceReservationId); /// <summary> /// Search orderSourceReservations by filter /// </summary> /// <remarks> /// Returns the list of orderSourceReservations 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&lt;OrderSourceReservation&gt;</returns> System.Threading.Tasks.Task<List<OrderSourceReservation>> GetOrderSourceReservationByFilterAsync (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Search orderSourceReservations by filter /// </summary> /// <remarks> /// Returns the list of orderSourceReservations 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&lt;OrderSourceReservation&gt;)</returns> System.Threading.Tasks.Task<ApiResponse<List<OrderSourceReservation>>> GetOrderSourceReservationByFilterAsyncWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Get an orderSourceReservation by id /// </summary> /// <remarks> /// Returns the orderSourceReservation identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="orderSourceReservationId">Id of the orderSourceReservation to be returned.</param> /// <returns>Task of OrderSourceReservation</returns> System.Threading.Tasks.Task<OrderSourceReservation> GetOrderSourceReservationByIdAsync (int? orderSourceReservationId); /// <summary> /// Get an orderSourceReservation by id /// </summary> /// <remarks> /// Returns the orderSourceReservation identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="orderSourceReservationId">Id of the orderSourceReservation to be returned.</param> /// <returns>Task of ApiResponse (OrderSourceReservation)</returns> System.Threading.Tasks.Task<ApiResponse<OrderSourceReservation>> GetOrderSourceReservationByIdAsyncWithHttpInfo (int? orderSourceReservationId); /// <summary> /// Update an orderSourceReservation /// </summary> /// <remarks> /// Updates an existing orderSourceReservation using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">OrderSourceReservation to be updated.</param> /// <returns>Task of void</returns> System.Threading.Tasks.Task UpdateOrderSourceReservationAsync (OrderSourceReservation body); /// <summary> /// Update an orderSourceReservation /// </summary> /// <remarks> /// Updates an existing orderSourceReservation using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">OrderSourceReservation to be updated.</param> /// <returns>Task of ApiResponse</returns> System.Threading.Tasks.Task<ApiResponse<Object>> UpdateOrderSourceReservationAsyncWithHttpInfo (OrderSourceReservation body); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class OrderSourceReservationApi : IOrderSourceReservationApi { private Infoplus.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="OrderSourceReservationApi"/> class. /// </summary> /// <returns></returns> public OrderSourceReservationApi(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="OrderSourceReservationApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public OrderSourceReservationApi(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 an orderSourceReservation Inserts a new orderSourceReservation using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">OrderSourceReservation to be inserted.</param> /// <returns>OrderSourceReservation</returns> public OrderSourceReservation AddOrderSourceReservation (OrderSourceReservation body) { ApiResponse<OrderSourceReservation> localVarResponse = AddOrderSourceReservationWithHttpInfo(body); return localVarResponse.Data; } /// <summary> /// Create an orderSourceReservation Inserts a new orderSourceReservation using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">OrderSourceReservation to be inserted.</param> /// <returns>ApiResponse of OrderSourceReservation</returns> public ApiResponse< OrderSourceReservation > AddOrderSourceReservationWithHttpInfo (OrderSourceReservation body) { // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling OrderSourceReservationApi->AddOrderSourceReservation"); var localVarPath = "/v1.0/orderSourceReservation"; 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("AddOrderSourceReservation", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<OrderSourceReservation>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (OrderSourceReservation) Configuration.ApiClient.Deserialize(localVarResponse, typeof(OrderSourceReservation))); } /// <summary> /// Create an orderSourceReservation Inserts a new orderSourceReservation using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">OrderSourceReservation to be inserted.</param> /// <returns>Task of OrderSourceReservation</returns> public async System.Threading.Tasks.Task<OrderSourceReservation> AddOrderSourceReservationAsync (OrderSourceReservation body) { ApiResponse<OrderSourceReservation> localVarResponse = await AddOrderSourceReservationAsyncWithHttpInfo(body); return localVarResponse.Data; } /// <summary> /// Create an orderSourceReservation Inserts a new orderSourceReservation using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">OrderSourceReservation to be inserted.</param> /// <returns>Task of ApiResponse (OrderSourceReservation)</returns> public async System.Threading.Tasks.Task<ApiResponse<OrderSourceReservation>> AddOrderSourceReservationAsyncWithHttpInfo (OrderSourceReservation body) { // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling OrderSourceReservationApi->AddOrderSourceReservation"); var localVarPath = "/v1.0/orderSourceReservation"; 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("AddOrderSourceReservation", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<OrderSourceReservation>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (OrderSourceReservation) Configuration.ApiClient.Deserialize(localVarResponse, typeof(OrderSourceReservation))); } /// <summary> /// Delete an orderSourceReservation Deletes the orderSourceReservation identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="orderSourceReservationId">Id of the orderSourceReservation to be deleted.</param> /// <returns></returns> public void DeleteOrderSourceReservation (int? orderSourceReservationId) { DeleteOrderSourceReservationWithHttpInfo(orderSourceReservationId); } /// <summary> /// Delete an orderSourceReservation Deletes the orderSourceReservation identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="orderSourceReservationId">Id of the orderSourceReservation to be deleted.</param> /// <returns>ApiResponse of Object(void)</returns> public ApiResponse<Object> DeleteOrderSourceReservationWithHttpInfo (int? orderSourceReservationId) { // verify the required parameter 'orderSourceReservationId' is set if (orderSourceReservationId == null) throw new ApiException(400, "Missing required parameter 'orderSourceReservationId' when calling OrderSourceReservationApi->DeleteOrderSourceReservation"); var localVarPath = "/v1.0/orderSourceReservation/{orderSourceReservationId}"; 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 (orderSourceReservationId != null) localVarPathParams.Add("orderSourceReservationId", Configuration.ApiClient.ParameterToString(orderSourceReservationId)); // 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("DeleteOrderSourceReservation", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Object>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null); } /// <summary> /// Delete an orderSourceReservation Deletes the orderSourceReservation identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="orderSourceReservationId">Id of the orderSourceReservation to be deleted.</param> /// <returns>Task of void</returns> public async System.Threading.Tasks.Task DeleteOrderSourceReservationAsync (int? orderSourceReservationId) { await DeleteOrderSourceReservationAsyncWithHttpInfo(orderSourceReservationId); } /// <summary> /// Delete an orderSourceReservation Deletes the orderSourceReservation identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="orderSourceReservationId">Id of the orderSourceReservation to be deleted.</param> /// <returns>Task of ApiResponse</returns> public async System.Threading.Tasks.Task<ApiResponse<Object>> DeleteOrderSourceReservationAsyncWithHttpInfo (int? orderSourceReservationId) { // verify the required parameter 'orderSourceReservationId' is set if (orderSourceReservationId == null) throw new ApiException(400, "Missing required parameter 'orderSourceReservationId' when calling OrderSourceReservationApi->DeleteOrderSourceReservation"); var localVarPath = "/v1.0/orderSourceReservation/{orderSourceReservationId}"; 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 (orderSourceReservationId != null) localVarPathParams.Add("orderSourceReservationId", Configuration.ApiClient.ParameterToString(orderSourceReservationId)); // 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("DeleteOrderSourceReservation", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Object>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null); } /// <summary> /// Search orderSourceReservations by filter Returns the list of orderSourceReservations 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&lt;OrderSourceReservation&gt;</returns> public List<OrderSourceReservation> GetOrderSourceReservationByFilter (string filter = null, int? page = null, int? limit = null, string sort = null) { ApiResponse<List<OrderSourceReservation>> localVarResponse = GetOrderSourceReservationByFilterWithHttpInfo(filter, page, limit, sort); return localVarResponse.Data; } /// <summary> /// Search orderSourceReservations by filter Returns the list of orderSourceReservations 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&lt;OrderSourceReservation&gt;</returns> public ApiResponse< List<OrderSourceReservation> > GetOrderSourceReservationByFilterWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null) { var localVarPath = "/v1.0/orderSourceReservation/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("GetOrderSourceReservationByFilter", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<List<OrderSourceReservation>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List<OrderSourceReservation>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<OrderSourceReservation>))); } /// <summary> /// Search orderSourceReservations by filter Returns the list of orderSourceReservations 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&lt;OrderSourceReservation&gt;</returns> public async System.Threading.Tasks.Task<List<OrderSourceReservation>> GetOrderSourceReservationByFilterAsync (string filter = null, int? page = null, int? limit = null, string sort = null) { ApiResponse<List<OrderSourceReservation>> localVarResponse = await GetOrderSourceReservationByFilterAsyncWithHttpInfo(filter, page, limit, sort); return localVarResponse.Data; } /// <summary> /// Search orderSourceReservations by filter Returns the list of orderSourceReservations 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&lt;OrderSourceReservation&gt;)</returns> public async System.Threading.Tasks.Task<ApiResponse<List<OrderSourceReservation>>> GetOrderSourceReservationByFilterAsyncWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null) { var localVarPath = "/v1.0/orderSourceReservation/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("GetOrderSourceReservationByFilter", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<List<OrderSourceReservation>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List<OrderSourceReservation>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<OrderSourceReservation>))); } /// <summary> /// Get an orderSourceReservation by id Returns the orderSourceReservation identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="orderSourceReservationId">Id of the orderSourceReservation to be returned.</param> /// <returns>OrderSourceReservation</returns> public OrderSourceReservation GetOrderSourceReservationById (int? orderSourceReservationId) { ApiResponse<OrderSourceReservation> localVarResponse = GetOrderSourceReservationByIdWithHttpInfo(orderSourceReservationId); return localVarResponse.Data; } /// <summary> /// Get an orderSourceReservation by id Returns the orderSourceReservation identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="orderSourceReservationId">Id of the orderSourceReservation to be returned.</param> /// <returns>ApiResponse of OrderSourceReservation</returns> public ApiResponse< OrderSourceReservation > GetOrderSourceReservationByIdWithHttpInfo (int? orderSourceReservationId) { // verify the required parameter 'orderSourceReservationId' is set if (orderSourceReservationId == null) throw new ApiException(400, "Missing required parameter 'orderSourceReservationId' when calling OrderSourceReservationApi->GetOrderSourceReservationById"); var localVarPath = "/v1.0/orderSourceReservation/{orderSourceReservationId}"; 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 (orderSourceReservationId != null) localVarPathParams.Add("orderSourceReservationId", Configuration.ApiClient.ParameterToString(orderSourceReservationId)); // 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("GetOrderSourceReservationById", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<OrderSourceReservation>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (OrderSourceReservation) Configuration.ApiClient.Deserialize(localVarResponse, typeof(OrderSourceReservation))); } /// <summary> /// Get an orderSourceReservation by id Returns the orderSourceReservation identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="orderSourceReservationId">Id of the orderSourceReservation to be returned.</param> /// <returns>Task of OrderSourceReservation</returns> public async System.Threading.Tasks.Task<OrderSourceReservation> GetOrderSourceReservationByIdAsync (int? orderSourceReservationId) { ApiResponse<OrderSourceReservation> localVarResponse = await GetOrderSourceReservationByIdAsyncWithHttpInfo(orderSourceReservationId); return localVarResponse.Data; } /// <summary> /// Get an orderSourceReservation by id Returns the orderSourceReservation identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="orderSourceReservationId">Id of the orderSourceReservation to be returned.</param> /// <returns>Task of ApiResponse (OrderSourceReservation)</returns> public async System.Threading.Tasks.Task<ApiResponse<OrderSourceReservation>> GetOrderSourceReservationByIdAsyncWithHttpInfo (int? orderSourceReservationId) { // verify the required parameter 'orderSourceReservationId' is set if (orderSourceReservationId == null) throw new ApiException(400, "Missing required parameter 'orderSourceReservationId' when calling OrderSourceReservationApi->GetOrderSourceReservationById"); var localVarPath = "/v1.0/orderSourceReservation/{orderSourceReservationId}"; 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 (orderSourceReservationId != null) localVarPathParams.Add("orderSourceReservationId", Configuration.ApiClient.ParameterToString(orderSourceReservationId)); // 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("GetOrderSourceReservationById", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<OrderSourceReservation>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (OrderSourceReservation) Configuration.ApiClient.Deserialize(localVarResponse, typeof(OrderSourceReservation))); } /// <summary> /// Update an orderSourceReservation Updates an existing orderSourceReservation using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">OrderSourceReservation to be updated.</param> /// <returns></returns> public void UpdateOrderSourceReservation (OrderSourceReservation body) { UpdateOrderSourceReservationWithHttpInfo(body); } /// <summary> /// Update an orderSourceReservation Updates an existing orderSourceReservation using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">OrderSourceReservation to be updated.</param> /// <returns>ApiResponse of Object(void)</returns> public ApiResponse<Object> UpdateOrderSourceReservationWithHttpInfo (OrderSourceReservation body) { // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling OrderSourceReservationApi->UpdateOrderSourceReservation"); var localVarPath = "/v1.0/orderSourceReservation"; 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("UpdateOrderSourceReservation", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Object>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null); } /// <summary> /// Update an orderSourceReservation Updates an existing orderSourceReservation using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">OrderSourceReservation to be updated.</param> /// <returns>Task of void</returns> public async System.Threading.Tasks.Task UpdateOrderSourceReservationAsync (OrderSourceReservation body) { await UpdateOrderSourceReservationAsyncWithHttpInfo(body); } /// <summary> /// Update an orderSourceReservation Updates an existing orderSourceReservation using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">OrderSourceReservation to be updated.</param> /// <returns>Task of ApiResponse</returns> public async System.Threading.Tasks.Task<ApiResponse<Object>> UpdateOrderSourceReservationAsyncWithHttpInfo (OrderSourceReservation body) { // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling OrderSourceReservationApi->UpdateOrderSourceReservation"); var localVarPath = "/v1.0/orderSourceReservation"; 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("UpdateOrderSourceReservation", 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. using System; using Xunit; namespace System.Linq.Expressions.Tests { public static class NonLiftedComparisonLessThanNullableTests { #region Test methods [Fact] public static void CheckNonLiftedComparisonLessThanNullableByteTest() { byte?[] values = new byte?[] { null, 0, 1, byte.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonLessThanNullableByte(values[i], values[j]); } } } [Fact] public static void CheckNonLiftedComparisonLessThanNullableCharTest() { char?[] values = new char?[] { null, '\0', '\b', 'A', '\uffff' }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonLessThanNullableChar(values[i], values[j]); } } } [Fact] public static void CheckNonLiftedComparisonLessThanNullableDecimalTest() { decimal?[] values = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonLessThanNullableDecimal(values[i], values[j]); } } } [Fact] public static void CheckNonLiftedComparisonLessThanNullableDoubleTest() { double?[] values = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonLessThanNullableDouble(values[i], values[j]); } } } [Fact] public static void CheckNonLiftedComparisonLessThanNullableFloatTest() { float?[] values = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonLessThanNullableFloat(values[i], values[j]); } } } [Fact] public static void CheckNonLiftedComparisonLessThanNullableIntTest() { int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonLessThanNullableInt(values[i], values[j]); } } } [Fact] public static void CheckNonLiftedComparisonLessThanNullableLongTest() { long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonLessThanNullableLong(values[i], values[j]); } } } [Fact] public static void CheckNonLiftedComparisonLessThanNullableSByteTest() { sbyte?[] values = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonLessThanNullableSByte(values[i], values[j]); } } } [Fact] public static void CheckNonLiftedComparisonLessThanNullableShortTest() { short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonLessThanNullableShort(values[i], values[j]); } } } [Fact] public static void CheckNonLiftedComparisonLessThanNullableUIntTest() { uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonLessThanNullableUInt(values[i], values[j]); } } } [Fact] public static void CheckNonLiftedComparisonLessThanNullableULongTest() { ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonLessThanNullableULong(values[i], values[j]); } } } [Fact] public static void CheckNonLiftedComparisonLessThanNullableUShortTest() { ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonLessThanNullableUShort(values[i], values[j]); } } } #endregion #region Test verifiers private static void VerifyComparisonLessThanNullableByte(byte? a, byte? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.LessThan( Expression.Constant(a, typeof(byte?)), Expression.Constant(b, typeof(byte?)), false, null)); Func<bool> f = e.Compile(); bool expected = a < b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonLessThanNullableChar(char? a, char? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.LessThan( Expression.Constant(a, typeof(char?)), Expression.Constant(b, typeof(char?)), false, null)); Func<bool> f = e.Compile(); bool expected = a < b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonLessThanNullableDecimal(decimal? a, decimal? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.LessThan( Expression.Constant(a, typeof(decimal?)), Expression.Constant(b, typeof(decimal?)), false, null)); Func<bool> f = e.Compile(); bool expected = a < b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonLessThanNullableDouble(double? a, double? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.LessThan( Expression.Constant(a, typeof(double?)), Expression.Constant(b, typeof(double?)), false, null)); Func<bool> f = e.Compile(); bool expected = a < b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonLessThanNullableFloat(float? a, float? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.LessThan( Expression.Constant(a, typeof(float?)), Expression.Constant(b, typeof(float?)), false, null)); Func<bool> f = e.Compile(); bool expected = a < b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonLessThanNullableInt(int? a, int? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.LessThan( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?)), false, null)); Func<bool> f = e.Compile(); bool expected = a < b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonLessThanNullableLong(long? a, long? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.LessThan( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?)), false, null)); Func<bool> f = e.Compile(); bool expected = a < b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonLessThanNullableSByte(sbyte? a, sbyte? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.LessThan( Expression.Constant(a, typeof(sbyte?)), Expression.Constant(b, typeof(sbyte?)), false, null)); Func<bool> f = e.Compile(); bool expected = a < b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonLessThanNullableShort(short? a, short? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.LessThan( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?)), false, null)); Func<bool> f = e.Compile(); bool expected = a < b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonLessThanNullableUInt(uint? a, uint? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.LessThan( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?)), false, null)); Func<bool> f = e.Compile(); bool expected = a < b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonLessThanNullableULong(ulong? a, ulong? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.LessThan( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?)), false, null)); Func<bool> f = e.Compile(); bool expected = a < b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonLessThanNullableUShort(ushort? a, ushort? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.LessThan( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?)), false, null)); Func<bool> f = e.Compile(); bool expected = a < b; bool result = f(); Assert.Equal(expected, result); } #endregion } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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. //----------------------------------------------------------------------------- //------------------------------------------------------------------------------ // Shape Editor //------------------------------------------------------------------------------ function initializeShapeEditor() { echo(" % - Initializing Shape Editor"); exec("./gui/Profiles.ed.cs"); exec("./gui/shapeEdPreviewWindow.ed.gui"); exec("./gui/shapeEdAnimWindow.ed.gui"); exec("./gui/shapeEdAdvancedWindow.ed.gui"); exec("./gui/ShapeEditorToolbar.ed.gui"); exec("./gui/shapeEdSelectWindow.ed.gui"); exec("./gui/shapeEdPropWindow.ed.gui"); exec("./scripts/shapeEditor.ed.cs"); exec("./scripts/shapeEditorHints.ed.cs"); exec("./scripts/shapeEditorActions.ed.cs"); // Add windows to editor gui ShapeEdPreviewGui.setVisible(false); ShapeEdAnimWindow.setVisible(false); ShapeEditorToolbar.setVisible(false); ShapeEdSelectWindow.setVisible(false); ShapeEdPropWindow.setVisible(false); EditorGui.add(ShapeEdPreviewGui); EditorGui.add(ShapeEdAnimWindow); EditorGui.add(ShapeEdAdvancedWindow); EditorGui.add(ShapeEditorToolbar); EditorGui.add(ShapeEdSelectWindow); EditorGui.add(ShapeEdPropWindow); new ScriptObject(ShapeEditorPlugin) { superClass = "EditorPlugin"; editorGui = ShapeEdShapeView; }; %map = new ActionMap(); %map.bindCmd( keyboard, "escape", "ToolsToolbarArray->WorldEditorInspectorPalette.performClick();", "" ); %map.bindCmd( keyboard, "1", "ShapeEditorNoneModeBtn.performClick();", "" ); %map.bindCmd( keyboard, "2", "ShapeEditorMoveModeBtn.performClick();", "" ); %map.bindCmd( keyboard, "3", "ShapeEditorRotateModeBtn.performClick();", "" ); //%map.bindCmd( keyboard, "4", "ShapeEditorScaleModeBtn.performClick();", "" ); // not needed for the shape editor %map.bindCmd( keyboard, "n", "ShapeEditorToolbar->showNodes.performClick();", "" ); %map.bindCmd( keyboard, "t", "ShapeEditorToolbar->ghostMode.performClick();", "" ); %map.bindCmd( keyboard, "r", "ShapeEditorToolbar->wireframeMode.performClick();", "" ); %map.bindCmd( keyboard, "f", "ShapeEditorToolbar->fitToShapeBtn.performClick();", "" ); %map.bindCmd( keyboard, "g", "ShapeEditorToolbar->showGridBtn.performClick();", "" ); %map.bindCmd( keyboard, "h", "ShapeEdSelectWindow->tabBook.selectPage( 2 );", "" ); // Load help tab %map.bindCmd( keyboard, "l", "ShapeEdSelectWindow->tabBook.selectPage( 1 );", "" ); // load Library Tab %map.bindCmd( keyboard, "j", "ShapeEdSelectWindow->tabBook.selectPage( 0 );", "" ); // load scene object Tab %map.bindCmd( keyboard, "SPACE", "ShapeEdAnimWindow.togglePause();", "" ); %map.bindCmd( keyboard, "i", "ShapeEdSequences.onEditSeqInOut(\"in\", ShapeEdSeqSlider.getValue());", "" ); %map.bindCmd( keyboard, "o", "ShapeEdSequences.onEditSeqInOut(\"out\", ShapeEdSeqSlider.getValue());", "" ); %map.bindCmd( keyboard, "shift -", "ShapeEdSeqSlider.setValue(ShapeEdAnimWindow-->seqIn.getText());", "" ); %map.bindCmd( keyboard, "shift =", "ShapeEdSeqSlider.setValue(ShapeEdAnimWindow-->seqOut.getText());", "" ); %map.bindCmd( keyboard, "=", "ShapeEdAnimWindow-->stepFwdBtn.performClick();", "" ); %map.bindCmd( keyboard, "-", "ShapeEdAnimWindow-->stepBkwdBtn.performClick();", "" ); ShapeEditorPlugin.map = %map; ShapeEditorPlugin.initSettings(); } function destroyShapeEditor() { } function SetToggleButtonValue(%ctrl, %value) { if ( %ctrl.getValue() != %value ) %ctrl.performClick(); } // Replace the command field in an Editor PopupMenu item (returns the original value) function ShapeEditorPlugin::replaceMenuCmd(%this, %menuTitle, %id, %newCmd) { %menu = EditorGui.findMenu( %menuTitle ); %cmd = getField( %menu.item[%id], 2 ); %menu.setItemCommand( %id, %newCmd ); return %cmd; } function ShapeEditorPlugin::onWorldEditorStartup(%this) { // Add ourselves to the window menu. %accel = EditorGui.addToEditorsMenu("Shape Editor", "", ShapeEditorPlugin); // Add ourselves to the ToolsToolbar %tooltip = "Shape Editor (" @ %accel @ ")"; EditorGui.addToToolsToolbar( "ShapeEditorPlugin", "ShapeEditorPalette", expandFilename("tools/worldEditor/images/toolbar/shape-editor"), %tooltip ); // Add ourselves to the Editor Settings window exec( "./gui/ShapeEditorSettingsTab.gui" ); ESettingsWindow.addTabPage( EShapeEditorSettingsPage ); GuiWindowCtrl::attach(ShapeEdPropWindow, ShapeEdSelectWindow); ShapeEdAnimWindow.resize( -1, 526, 593, 53 ); // Initialise gui ShapeEdSeqNodeTabBook.selectPage(0); ShapeEdAdvancedWindow-->tabBook.selectPage(0); ShapeEdSelectWindow-->tabBook.selectPage(0); ShapeEdSelectWindow.navigate(""); SetToggleButtonValue( ShapeEditorToolbar-->orbitNodeBtn, 0 ); SetToggleButtonValue( ShapeEditorToolbar-->ghostMode, 0 ); // Initialise hints menu ShapeEdHintMenu.clear(); %count = ShapeHintGroup.getCount(); for (%i = 0; %i < %count; %i++) { %hint = ShapeHintGroup.getObject(%i); ShapeEdHintMenu.add(%hint.objectType, %hint); } } function ShapeEditorPlugin::openShapeAsset(%this, %assetId) { %this.selectedAssetId = %assetId; %this.selectedAssetDef = AssetDatabase.acquireAsset(%assetId); %this.open(%this.selectedAssetDef.fileName); } function ShapeEditorPlugin::open(%this, %filename) { if ( !%this.isActivated ) { // Activate the Shape Editor EditorGui.setEditor( %this, true ); // Get editor settings (note the sun angle is not configured in the settings // dialog, so apply the settings here instead of in readSettings) %this.readSettings(); ShapeEdShapeView.sunAngleX = EditorSettings.value("ShapeEditor/SunAngleX"); ShapeEdShapeView.sunAngleZ = EditorSettings.value("ShapeEditor/SunAngleZ"); EWorldEditor.forceLoadDAE = EditorSettings.value("forceLoadDAE"); $wasInWireFrameMode = $gfx::wireframe; ShapeEditorToolbar-->wireframeMode.setStateOn($gfx::wireframe); if ( GlobalGizmoProfile.getFieldValue(alignment) $= "Object" ) ShapeEdNodes-->objectTransform.setStateOn(1); else ShapeEdNodes-->worldTransform.setStateOn(1); // Initialise and show the shape editor ShapeEdShapeTreeView.open(getScene(0)); ShapeEdShapeTreeView.buildVisibleTree(true); ShapeEdPreviewGui.setVisible(true); ShapeEdSelectWindow.setVisible(true); ShapeEdPropWindow.setVisible(true); ShapeEdAnimWindow.setVisible(true); ShapeEdAdvancedWindow.setVisible(ShapeEditorToolbar-->showAdvanced.getValue()); ShapeEditorToolbar.setVisible(true); EditorGui.bringToFront(ShapeEdPreviewGui); ToolsPaletteArray->WorldEditorMove.performClick(); %this.map.push(); // Switch to the ShapeEditor UndoManager %this.oldUndoMgr = Editor.getUndoManager(); Editor.setUndoManager( ShapeEdUndoManager ); ShapeEdShapeView.setDisplayType( EditorGui.currentDisplayType ); %this.initStatusBar(); // Customise menu bar %this.oldCamFitCmd = %this.replaceMenuCmd( "Camera", 8, "ShapeEdShapeView.fitToShape();" ); %this.oldCamFitOrbitCmd = %this.replaceMenuCmd( "Camera", 9, "ShapeEdShapeView.fitToShape();" ); Parent::onActivated(%this); } // Select the new shape if (isObject(ShapeEditor.shape) && (ShapeEditor.shape.baseShape $= %filename)) { // Shape is already selected => re-highlight the selected material if necessary ShapeEdMaterials.updateSelectedMaterial(ShapeEdMaterials-->highlightMaterial.getValue()); } else if (%filename !$= "") { ShapeEditor.selectShape(%filename, ShapeEditor.isDirty()); // 'fitToShape' only works after the GUI has been rendered, so force a repaint first Canvas.repaint(); ShapeEdShapeView.fitToShape(); } } function ShapeEditorPlugin::onActivated(%this) { %this.open(""); // Try to start with the shape selected in the world editor %count = EWorldEditor.getSelectionSize(); for (%i = 0; %i < %count; %i++) { %obj = EWorldEditor.getSelectedObject(%i); %shapeFile = ShapeEditor.getObjectShapeFile(%obj); if (%shapeFile !$= "") { if (!isObject(ShapeEditor.shape) || (ShapeEditor.shape.baseShape !$= %shapeFile)) { // Call the 'onSelect' method directly if the object is not in the // MissionGroup tree (such as a Player or Projectile object). ShapeEdShapeTreeView.clearSelection(); if (!ShapeEdShapeTreeView.selectItem(%obj)) ShapeEdShapeTreeView.onSelect(%obj); // 'fitToShape' only works after the GUI has been rendered, so force a repaint first Canvas.repaint(); ShapeEdShapeView.fitToShape(); } break; } } } function ShapeEditorPlugin::initStatusBar(%this) { EditorGuiStatusBar.setInfo("Shape editor ( Shift Click ) to speed up camera."); EditorGuiStatusBar.setSelection( ShapeEditor.shape.baseShape ); } function ShapeEditorPlugin::onDeactivated(%this) { %this.writeSettings(); // Notify game objects if shape has been modified if ( ShapeEditor.isDirty() ) ShapeEditor.shape.notifyShapeChanged(); $gfx::wireframe = $wasInWireFrameMode; ShapeEdMaterials.updateSelectedMaterial(false); ShapeEditorToolbar.setVisible(false); ShapeEdPreviewGui.setVisible(false); ShapeEdSelectWindow.setVisible(false); ShapeEdPropWindow.setVisible(false); ShapeEdAnimWindow.setVisible(false); ShapeEdAdvancedWindow.setVisible(false); if( EditorGui-->MatEdPropertiesWindow.visible ) { ShapeEdMaterials.editSelectedMaterialEnd( true ); } %this.map.pop(); // Restore the original undo manager Editor.setUndoManager( %this.oldUndoMgr ); // Restore menu bar %this.replaceMenuCmd( "Camera", 8, %this.oldCamFitCmd ); %this.replaceMenuCmd( "Camera", 9, %this.oldCamFitOrbitCmd ); Parent::onDeactivated(%this); } function ShapeEditorPlugin::onExitMission( %this ) { // unselect the current shape ShapeEdShapeView.setModel( "" ); if (ShapeEditor.shape != -1) ShapeEditor.shape.delete(); ShapeEditor.shape = 0; ShapeEdUndoManager.clearAll(); ShapeEditor.setDirty( false ); ShapeEdSequenceList.clear(); ShapeEdNodeTreeView.removeItem( 0 ); ShapeEdPropWindow.update_onNodeSelectionChanged( -1 ); ShapeEdDetailTree.removeItem( 0 ); ShapeEdMaterialList.clear(); ShapeEdMountWindow-->mountList.clear(); ShapeEdThreadWindow-->seqList.clear(); ShapeEdThreadList.clear(); } function ShapeEditorPlugin::openShape( %this, %path, %discardChangesToCurrent ) { EditorGui.setEditor( ShapeEditorPlugin ); if( ShapeEditor.isDirty() && !%discardChangesToCurrent ) { MessageBoxYesNo( "Save Changes?", "Save changes to current shape?", "ShapeEditor.saveChanges(); ShapeEditorPlugin.openShape(\"" @ %path @ "\");", "ShapeEditorPlugin.openShape(\"" @ %path @ "\");" ); return; } ShapeEditor.selectShape( %path ); ShapeEdShapeView.fitToShape(); } function shapeEditorWireframeMode() { $gfx::wireframe = !$gfx::wireframe; ShapeEditorToolbar-->wireframeMode.setStateOn($gfx::wireframe); } //----------------------------------------------------------------------------- // Settings //----------------------------------------------------------------------------- function ShapeEditorPlugin::initSettings( %this ) { EditorSettings.beginGroup( "ShapeEditor", true ); // Display options EditorSettings.setDefaultValue( "BackgroundColor", "0 0 0 100" ); EditorSettings.setDefaultValue( "HighlightMaterial", 1 ); EditorSettings.setDefaultValue( "ShowNodes", 1 ); EditorSettings.setDefaultValue( "ShowBounds", 0 ); EditorSettings.setDefaultValue( "ShowObjBox", 1 ); EditorSettings.setDefaultValue( "RenderMounts", 1 ); EditorSettings.setDefaultValue( "RenderCollision", 0 ); // Grid EditorSettings.setDefaultValue( "ShowGrid", 1 ); EditorSettings.setDefaultValue( "GridSize", 0.1 ); EditorSettings.setDefaultValue( "GridDimension", "40 40" ); // Sun EditorSettings.setDefaultValue( "SunDiffuseColor", "255 255 255 255" ); EditorSettings.setDefaultValue( "SunAmbientColor", "180 180 180 255" ); EditorSettings.setDefaultValue( "SunAngleX", "45" ); EditorSettings.setDefaultValue( "SunAngleZ", "135" ); // Sub-windows EditorSettings.setDefaultValue( "AdvancedWndVisible", "1" ); EditorSettings.endGroup(); } function ShapeEditorPlugin::readSettings( %this ) { EditorSettings.beginGroup( "ShapeEditor", true ); // Display options ShapeEdPreviewGui-->previewBackground.color = ColorIntToFloat( EditorSettings.value("BackgroundColor") ); SetToggleButtonValue( ShapeEdMaterials-->highlightMaterial, EditorSettings.value( "HighlightMaterial" ) ); SetToggleButtonValue( ShapeEditorToolbar-->showNodes, EditorSettings.value( "ShowNodes" ) ); SetToggleButtonValue( ShapeEditorToolbar-->showBounds, EditorSettings.value( "ShowBounds" ) ); SetToggleButtonValue( ShapeEditorToolbar-->showObjBox, EditorSettings.value( "ShowObjBox" ) ); SetToggleButtonValue( ShapeEditorToolbar-->renderColMeshes, EditorSettings.value( "RenderCollision" ) ); SetToggleButtonValue( ShapeEdMountWindow-->renderMounts, EditorSettings.value( "RenderMounts" ) ); // Grid SetToggleButtonValue( ShapeEditorToolbar-->showGridBtn, EditorSettings.value( "ShowGrid" ) ); ShapeEdShapeView.gridSize = EditorSettings.value( "GridSize" ); ShapeEdShapeView.gridDimension = EditorSettings.value( "GridDimension" ); // Sun ShapeEdShapeView.sunDiffuse = EditorSettings.value("SunDiffuseColor"); ShapeEdShapeView.sunAmbient = EditorSettings.value("SunAmbientColor"); // Sub-windows SetToggleButtonValue( ShapeEditorToolbar-->showAdvanced, EditorSettings.value( "AdvancedWndVisible" ) ); EditorSettings.endGroup(); } function ShapeEditorPlugin::writeSettings( %this ) { EditorSettings.beginGroup( "ShapeEditor", true ); // Display options EditorSettings.setValue( "BackgroundColor", ColorFloatToInt( ShapeEdPreviewGui-->previewBackground.color ) ); EditorSettings.setValue( "HighlightMaterial", ShapeEdMaterials-->highlightMaterial.getValue() ); EditorSettings.setValue( "ShowNodes", ShapeEditorToolbar-->showNodes.getValue() ); EditorSettings.setValue( "ShowBounds", ShapeEditorToolbar-->showBounds.getValue() ); EditorSettings.setValue( "ShowObjBox", ShapeEditorToolbar-->showObjBox.getValue() ); EditorSettings.setValue( "RenderCollision", ShapeEditorToolbar-->renderColMeshes.getValue() ); EditorSettings.setValue( "RenderMounts", ShapeEdMountWindow-->renderMounts.getValue() ); // Grid EditorSettings.setValue( "ShowGrid", ShapeEditorToolbar-->showGridBtn.getValue() ); EditorSettings.setValue( "GridSize", ShapeEdShapeView.gridSize ); EditorSettings.setValue( "GridDimension", ShapeEdShapeView.gridDimension ); // Sun EditorSettings.setValue( "SunDiffuseColor", ShapeEdShapeView.sunDiffuse ); EditorSettings.setValue( "SunAmbientColor", ShapeEdShapeView.sunAmbient ); EditorSettings.setValue( "SunAngleX", ShapeEdShapeView.sunAngleX ); EditorSettings.setValue( "SunAngleZ", ShapeEdShapeView.sunAngleZ ); // Sub-windows EditorSettings.setValue( "AdvancedWndVisible", ShapeEditorToolbar-->showAdvanced.getValue() ); EditorSettings.endGroup(); }
// 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.Net; using System.Collections; using System.ComponentModel; using System.Runtime.InteropServices; namespace System.DirectoryServices.ActiveDirectory { public class AdamInstance : DirectoryServer { private readonly string[] _becomeRoleOwnerAttrs = null; private bool _disposed = false; // for public properties private string _cachedHostName = null; private int _cachedLdapPort = -1; private int _cachedSslPort = -1; private bool _defaultPartitionInitialized = false; private bool _defaultPartitionModified = false; private ConfigurationSet _currentConfigSet = null; private string _cachedDefaultPartition = null; private AdamRoleCollection _cachedRoles = null; private IntPtr _ADAMHandle = (IntPtr)0; private IntPtr _authIdentity = IntPtr.Zero; private SyncUpdateCallback _userDelegate = null; private readonly SyncReplicaFromAllServersCallback _syncAllFunctionPointer = null; #region constructors internal AdamInstance(DirectoryContext context, string adamInstanceName) : this(context, adamInstanceName, new DirectoryEntryManager(context), true) { } internal AdamInstance(DirectoryContext context, string adamInstanceName, DirectoryEntryManager directoryEntryMgr, bool nameIncludesPort) { this.context = context; this.replicaName = adamInstanceName; this.directoryEntryMgr = directoryEntryMgr; // initialize the transfer role owner attributes _becomeRoleOwnerAttrs = new String[2]; _becomeRoleOwnerAttrs[0] = PropertyManager.BecomeSchemaMaster; _becomeRoleOwnerAttrs[1] = PropertyManager.BecomeDomainMaster; // initialize the callback function _syncAllFunctionPointer = new SyncReplicaFromAllServersCallback(SyncAllCallbackRoutine); } internal AdamInstance(DirectoryContext context, string adamHostName, DirectoryEntryManager directoryEntryMgr) { this.context = context; // the replica name should be in the form dnshostname:port this.replicaName = adamHostName; string portNumber; Utils.SplitServerNameAndPortNumber(context.Name, out portNumber); if (portNumber != null) { this.replicaName = this.replicaName + ":" + portNumber; } // initialize the directory entry manager this.directoryEntryMgr = directoryEntryMgr; // initialize the transfer role owner attributes _becomeRoleOwnerAttrs = new String[2]; _becomeRoleOwnerAttrs[0] = PropertyManager.BecomeSchemaMaster; _becomeRoleOwnerAttrs[1] = PropertyManager.BecomeDomainMaster; // initialize the callback function _syncAllFunctionPointer = new SyncReplicaFromAllServersCallback(SyncAllCallbackRoutine); } #endregion constructors #region IDisposable ~AdamInstance() { // finalizer is called => Dispose has not been called yet. Dispose(false); } // private Dispose method protected override void Dispose(bool disposing) { if (!_disposed) { try { // if there are any managed or unmanaged // resources to be freed, those should be done here // if disposing = true, only unmanaged resources should // be freed, else both managed and unmanaged. FreeADAMHandle(); _disposed = true; } finally { base.Dispose(); } } } #endregion IDisposable #region public methods public static AdamInstance GetAdamInstance(DirectoryContext context) { DirectoryEntryManager directoryEntryMgr = null; string dnsHostName = null; // check that the context is not null if (context == null) { throw new ArgumentNullException("context"); } // contexttype should be DirectoryServer if (context.ContextType != DirectoryContextType.DirectoryServer) { throw new ArgumentException(SR.TargetShouldBeADAMServer, "context"); } // target must be a server if ((!context.isServer())) { throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.AINotFound , context.Name), typeof(AdamInstance), context.Name); } // work with copy of the context context = new DirectoryContext(context); // bind to the given adam instance try { directoryEntryMgr = new DirectoryEntryManager(context); DirectoryEntry rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE); // This will ensure that we are talking to ADAM instance only if (!Utils.CheckCapability(rootDSE, Capability.ActiveDirectoryApplicationMode)) { throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.AINotFound , context.Name), typeof(AdamInstance), context.Name); } dnsHostName = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.DnsHostName); } catch (COMException e) { int errorCode = e.ErrorCode; if (errorCode == unchecked((int)0x8007203a)) { throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.AINotFound , context.Name), typeof(AdamInstance), context.Name); } else { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } return new AdamInstance(context, dnsHostName, directoryEntryMgr); } public static AdamInstance FindOne(DirectoryContext context, string partitionName) { // validate parameters (partitionName validated by the call to ConfigSet) if (context == null) { throw new ArgumentNullException("context"); } // contexttype should be ConfigurationSet if (context.ContextType != DirectoryContextType.ConfigurationSet) { throw new ArgumentException(SR.TargetShouldBeConfigSet, "context"); } if (partitionName == null) { throw new ArgumentNullException("partitionName"); } if (partitionName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, "partitionName"); } // work with copy of the context context = new DirectoryContext(context); return ConfigurationSet.FindOneAdamInstance(context, partitionName, null); } public static AdamInstanceCollection FindAll(DirectoryContext context, string partitionName) { AdamInstanceCollection adamInstanceCollection = null; // validate parameters (partitionName validated by the call to ConfigSet) if (context == null) { throw new ArgumentNullException("context"); } // contexttype should be ConfigurationSet if (context.ContextType != DirectoryContextType.ConfigurationSet) { throw new ArgumentException(SR.TargetShouldBeConfigSet, "context"); } if (partitionName == null) { throw new ArgumentNullException("partitionName"); } if (partitionName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, "partitionName"); } // work with copy of the context context = new DirectoryContext(context); try { adamInstanceCollection = ConfigurationSet.FindAdamInstances(context, partitionName, null); } catch (ActiveDirectoryObjectNotFoundException) { // this is the case where we could not find an ADAM instance in that config set (return empty collection) adamInstanceCollection = new AdamInstanceCollection(new ArrayList()); } return adamInstanceCollection; } public void TransferRoleOwnership(AdamRole role) { CheckIfDisposed(); if (role < AdamRole.SchemaRole || role > AdamRole.NamingRole) { throw new InvalidEnumArgumentException("role", (int)role, typeof(AdamRole)); } // set the appropriate attribute on the root dse try { DirectoryEntry rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE); rootDSE.Properties[_becomeRoleOwnerAttrs[(int)role]].Value = 1; rootDSE.CommitChanges(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } // invalidate the role collection so that it gets loaded again next time _cachedRoles = null; } public void SeizeRoleOwnership(AdamRole role) { // set the "fsmoRoleOwner" attribute on the appropriate role object // to the NTDSAObjectName of this ADAM Instance string roleObjectDN = null; CheckIfDisposed(); switch (role) { case AdamRole.SchemaRole: { roleObjectDN = directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.SchemaNamingContext); break; } case AdamRole.NamingRole: { roleObjectDN = directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.PartitionsContainer); break; } default: { throw new InvalidEnumArgumentException("role", (int)role, typeof(AdamRole)); } } DirectoryEntry roleObjectEntry = null; try { roleObjectEntry = DirectoryEntryManager.GetDirectoryEntry(context, roleObjectDN); roleObjectEntry.Properties[PropertyManager.FsmoRoleOwner].Value = NtdsaObjectName; roleObjectEntry.CommitChanges(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { if (roleObjectEntry != null) { roleObjectEntry.Dispose(); } } // invalidate the role collection so that it gets loaded again next time _cachedRoles = null; } public override void CheckReplicationConsistency() { if (_disposed) throw new ObjectDisposedException(GetType().Name); // get the handle GetADAMHandle(); // call private helper function CheckConsistencyHelper(_ADAMHandle, DirectoryContext.ADAMHandle); } public override ReplicationCursorCollection GetReplicationCursors(string partition) { IntPtr info = (IntPtr)0; int context = 0; bool advanced = true; if (_disposed) throw new ObjectDisposedException(GetType().Name); if (partition == null) throw new ArgumentNullException("partition"); if (partition.Length == 0) throw new ArgumentException(SR.EmptyStringParameter, "partition"); // get the handle GetADAMHandle(); info = GetReplicationInfoHelper(_ADAMHandle, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_CURSORS_3_FOR_NC, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_CURSORS_FOR_NC, partition, ref advanced, context, DirectoryContext.ADAMHandle); return ConstructReplicationCursors(_ADAMHandle, advanced, info, partition, this, DirectoryContext.ADAMHandle); } public override ReplicationOperationInformation GetReplicationOperationInformation() { IntPtr info = (IntPtr)0; bool advanced = true; if (_disposed) throw new ObjectDisposedException(GetType().Name); // get the handle GetADAMHandle(); info = GetReplicationInfoHelper(_ADAMHandle, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_PENDING_OPS, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_PENDING_OPS, null, ref advanced, 0, DirectoryContext.ADAMHandle); return ConstructPendingOperations(info, this, DirectoryContext.ADAMHandle); } public override ReplicationNeighborCollection GetReplicationNeighbors(string partition) { IntPtr info = (IntPtr)0; bool advanced = true; if (_disposed) throw new ObjectDisposedException(GetType().Name); if (partition == null) throw new ArgumentNullException("partition"); if (partition.Length == 0) throw new ArgumentException(SR.EmptyStringParameter, "partition"); // get the handle GetADAMHandle(); info = GetReplicationInfoHelper(_ADAMHandle, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_NEIGHBORS, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_NEIGHBORS, partition, ref advanced, 0, DirectoryContext.ADAMHandle); return ConstructNeighbors(info, this, DirectoryContext.ADAMHandle); } public override ReplicationNeighborCollection GetAllReplicationNeighbors() { IntPtr info = (IntPtr)0; bool advanced = true; if (_disposed) throw new ObjectDisposedException(GetType().Name); // get the handle GetADAMHandle(); info = GetReplicationInfoHelper(_ADAMHandle, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_NEIGHBORS, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_NEIGHBORS, null, ref advanced, 0, DirectoryContext.ADAMHandle); return ConstructNeighbors(info, this, DirectoryContext.ADAMHandle); } public override ReplicationFailureCollection GetReplicationConnectionFailures() { return GetReplicationFailures(DS_REPL_INFO_TYPE.DS_REPL_INFO_KCC_DSA_CONNECT_FAILURES); } public override ActiveDirectoryReplicationMetadata GetReplicationMetadata(string objectPath) { IntPtr info = (IntPtr)0; bool advanced = true; if (_disposed) throw new ObjectDisposedException(GetType().Name); if (objectPath == null) throw new ArgumentNullException("objectPath"); if (objectPath.Length == 0) throw new ArgumentException(SR.EmptyStringParameter, "objectPath"); // get the handle GetADAMHandle(); info = GetReplicationInfoHelper(_ADAMHandle, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_METADATA_2_FOR_OBJ, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_METADATA_FOR_OBJ, objectPath, ref advanced, 0, DirectoryContext.ADAMHandle); return ConstructMetaData(advanced, info, this, DirectoryContext.ADAMHandle); } public override void SyncReplicaFromServer(string partition, string sourceServer) { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (partition == null) throw new ArgumentNullException("partition"); if (partition.Length == 0) throw new ArgumentException(SR.EmptyStringParameter, "partition"); if (sourceServer == null) throw new ArgumentNullException("sourceServer"); if (sourceServer.Length == 0) throw new ArgumentException(SR.EmptyStringParameter, "sourceServer"); // get the dsHandle GetADAMHandle(); SyncReplicaHelper(_ADAMHandle, true, partition, sourceServer, 0, DirectoryContext.ADAMHandle); } public override void TriggerSyncReplicaFromNeighbors(string partition) { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (partition == null) throw new ArgumentNullException("partition"); if (partition.Length == 0) throw new ArgumentException(SR.EmptyStringParameter, "partition"); // get the dsHandle GetADAMHandle(); SyncReplicaHelper(_ADAMHandle, true, partition, null, DS_REPSYNC_ASYNCHRONOUS_OPERATION | DS_REPSYNC_ALL_SOURCES, DirectoryContext.ADAMHandle); } public override void SyncReplicaFromAllServers(string partition, SyncFromAllServersOptions options) { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (partition == null) throw new ArgumentNullException("partition"); if (partition.Length == 0) throw new ArgumentException(SR.EmptyStringParameter, "partition"); // get the dsHandle GetADAMHandle(); SyncReplicaAllHelper(_ADAMHandle, _syncAllFunctionPointer, partition, options, SyncFromAllServersCallback, DirectoryContext.ADAMHandle); } public void Save() { CheckIfDisposed(); // only thing to be saved is the ntdsa entry (for default partition) if (_defaultPartitionModified) { DirectoryEntry ntdsaEntry = directoryEntryMgr.GetCachedDirectoryEntry(NtdsaObjectName); try { ntdsaEntry.CommitChanges(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } // reset the bools associated with this property _defaultPartitionInitialized = false; _defaultPartitionModified = false; } #endregion public methods #region public properties public ConfigurationSet ConfigurationSet { get { CheckIfDisposed(); if (_currentConfigSet == null) { DirectoryContext configSetContext = Utils.GetNewDirectoryContext(Name, DirectoryContextType.DirectoryServer, context); _currentConfigSet = ConfigurationSet.GetConfigurationSet(configSetContext); } return _currentConfigSet; } } public string HostName { get { CheckIfDisposed(); if (_cachedHostName == null) { DirectoryEntry serverEntry = directoryEntryMgr.GetCachedDirectoryEntry(ServerObjectName); _cachedHostName = (string)PropertyManager.GetPropertyValue(context, serverEntry, PropertyManager.DnsHostName); } return _cachedHostName; } } public int LdapPort { get { CheckIfDisposed(); if (_cachedLdapPort == -1) { DirectoryEntry ntdsaEntry = directoryEntryMgr.GetCachedDirectoryEntry(NtdsaObjectName); _cachedLdapPort = (int)PropertyManager.GetPropertyValue(context, ntdsaEntry, PropertyManager.MsDSPortLDAP); } return _cachedLdapPort; } } public int SslPort { get { CheckIfDisposed(); if (_cachedSslPort == -1) { DirectoryEntry ntdsaEntry = directoryEntryMgr.GetCachedDirectoryEntry(NtdsaObjectName); _cachedSslPort = (int)PropertyManager.GetPropertyValue(context, ntdsaEntry, PropertyManager.MsDSPortSSL); } return _cachedSslPort; } } // Abstract Properties public AdamRoleCollection Roles { get { CheckIfDisposed(); DirectoryEntry schemaEntry = null; DirectoryEntry partitionsEntry = null; try { if (_cachedRoles == null) { // check for the fsmoRoleOwner attribute on the Config and Schema objects ArrayList roleList = new ArrayList(); schemaEntry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.SchemaNamingContext)); if (NtdsaObjectName.Equals((string)PropertyManager.GetPropertyValue(context, schemaEntry, PropertyManager.FsmoRoleOwner))) { roleList.Add(AdamRole.SchemaRole); } partitionsEntry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.PartitionsContainer)); if (NtdsaObjectName.Equals((string)PropertyManager.GetPropertyValue(context, partitionsEntry, PropertyManager.FsmoRoleOwner))) { roleList.Add(AdamRole.NamingRole); } _cachedRoles = new AdamRoleCollection(roleList); } } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { if (schemaEntry != null) { schemaEntry.Dispose(); } if (partitionsEntry != null) { partitionsEntry.Dispose(); } } return _cachedRoles; } } public string DefaultPartition { get { CheckIfDisposed(); if (!_defaultPartitionInitialized || _defaultPartitionModified) { DirectoryEntry ntdsaEntry = directoryEntryMgr.GetCachedDirectoryEntry(NtdsaObjectName); try { ntdsaEntry.RefreshCache(); if (ntdsaEntry.Properties[PropertyManager.MsDSDefaultNamingContext].Value == null) { // property has not been set _cachedDefaultPartition = null; } else { _cachedDefaultPartition = (string)PropertyManager.GetPropertyValue(context, ntdsaEntry, PropertyManager.MsDSDefaultNamingContext); } } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } _defaultPartitionInitialized = true; } return _cachedDefaultPartition; } set { CheckIfDisposed(); DirectoryEntry ntdsaEntry = directoryEntryMgr.GetCachedDirectoryEntry(NtdsaObjectName); if (value == null) { if (ntdsaEntry.Properties.Contains(PropertyManager.MsDSDefaultNamingContext)) { ntdsaEntry.Properties[PropertyManager.MsDSDefaultNamingContext].Clear(); } } else { // // should be in DN format // if (!Utils.IsValidDNFormat(value)) { throw new ArgumentException(SR.InvalidDNFormat, "value"); } // this value should be one of partitions currently being hosted by // this adam instance if (!Partitions.Contains(value)) { throw new ArgumentException(SR.Format(SR.ServerNotAReplica , value), "value"); } ntdsaEntry.Properties[PropertyManager.MsDSDefaultNamingContext].Value = value; } _defaultPartitionModified = true; } } public override string IPAddress { get { CheckIfDisposed(); IPHostEntry hostEntry = Dns.GetHostEntry(HostName); if (hostEntry.AddressList.GetLength(0) > 0) { return (hostEntry.AddressList[0]).ToString(); } else { return null; } } } public override String SiteName { get { CheckIfDisposed(); if (cachedSiteName == null) { DirectoryEntry siteEntry = DirectoryEntryManager.GetDirectoryEntry(context, SiteObjectName); try { cachedSiteName = (string)PropertyManager.GetPropertyValue(context, siteEntry, PropertyManager.Cn); } finally { siteEntry.Dispose(); } } return cachedSiteName; } } internal String SiteObjectName { get { CheckIfDisposed(); if (cachedSiteObjectName == null) { // get the site object name from the server object name // CN=server1,CN=Servers,CN=Site1,CN=Sites // the site object name is the third component onwards string[] components = ServerObjectName.Split(new char[] { ',' }); if (components.GetLength(0) < 3) { // should not happen throw new ActiveDirectoryOperationException(SR.InvalidServerNameFormat); } cachedSiteObjectName = components[2]; for (int i = 3; i < components.GetLength(0); i++) { cachedSiteObjectName += "," + components[i]; } } return cachedSiteObjectName; } } internal String ServerObjectName { get { CheckIfDisposed(); if (cachedServerObjectName == null) { DirectoryEntry rootDSE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); try { cachedServerObjectName = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.ServerName); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { rootDSE.Dispose(); } } return cachedServerObjectName; } } internal String NtdsaObjectName { get { CheckIfDisposed(); if (cachedNtdsaObjectName == null) { DirectoryEntry rootDSE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); try { cachedNtdsaObjectName = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.DsServiceName); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { rootDSE.Dispose(); } } return cachedNtdsaObjectName; } } internal Guid NtdsaObjectGuid { get { CheckIfDisposed(); if (cachedNtdsaObjectGuid == Guid.Empty) { DirectoryEntry ntdsaEntry = directoryEntryMgr.GetCachedDirectoryEntry(NtdsaObjectName); byte[] guidByteArray = (byte[])PropertyManager.GetPropertyValue(context, ntdsaEntry, PropertyManager.ObjectGuid); cachedNtdsaObjectGuid = new Guid(guidByteArray); } return cachedNtdsaObjectGuid; } } public override SyncUpdateCallback SyncFromAllServersCallback { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); return _userDelegate; } set { if (_disposed) throw new ObjectDisposedException(GetType().Name); _userDelegate = value; } } public override ReplicationConnectionCollection InboundConnections => GetInboundConnectionsHelper(); public override ReplicationConnectionCollection OutboundConnections => GetOutboundConnectionsHelper(); #endregion public properties #region private methods private ReplicationFailureCollection GetReplicationFailures(DS_REPL_INFO_TYPE type) { IntPtr info = (IntPtr)0; bool advanced = true; if (_disposed) throw new ObjectDisposedException(GetType().Name); // get the handle GetADAMHandle(); info = GetReplicationInfoHelper(_ADAMHandle, (int)type, (int)type, null, ref advanced, 0, DirectoryContext.ADAMHandle); return ConstructFailures(info, this, DirectoryContext.ADAMHandle); } private void GetADAMHandle() { // this part of the code needs to be synchronized lock (this) { if (_ADAMHandle == IntPtr.Zero) { // get the credentials object if (_authIdentity == IntPtr.Zero) { _authIdentity = Utils.GetAuthIdentity(context, DirectoryContext.ADAMHandle); } // DSBind, but we need to have port as annotation specified string bindingString = HostName + ":" + LdapPort; _ADAMHandle = Utils.GetDSHandle(bindingString, null, _authIdentity, DirectoryContext.ADAMHandle); } } } private void FreeADAMHandle() { lock (this) { // DsUnbind Utils.FreeDSHandle(_ADAMHandle, DirectoryContext.ADAMHandle); // free the credentials object Utils.FreeAuthIdentity(_authIdentity, DirectoryContext.ADAMHandle); } } #endregion private methods } }
using System; using System.Collections; using System.Collections.Generic; using Algorithms; //using Theodis.Algorithm; using System.Drawing.Drawing2D; using System.Drawing; namespace Procedurality { public class RiverBuilder { public Channel chan; public Point Start; public Point End; public Dijkstra Pathfinder; public List<Point> AllPossibleNodes = new List<Point>(); private int[,] DistanceMap; public List<Point> RiverNodes = new List<Point>(); public RiverBuilder(Channel channel) { Directions = new int[,]{ {-1, 1},{ 0, 1},{ 1, 1}, {-1, 0}, { 1, 0}, {-1,-1},{ 0,-1},{ 1,-1} }; chan=channel; traversalCost=GetTraversalCost(); Console.WriteLine(" * River generator initialized with a {0}x{1} grid.",chan.Height,chan.Width); } int[,] traversalCost; protected int relevantPixelsCount { get { return chan.Width * chan.Height; } } private Rectangle GetRelevantRegion(Point start, Point finish) { const int minimumSpace = 5; const float expansion = 0.01F; Rectangle rect = Rectangle.FromLTRB( Math.Min(start.X, finish.X), Math.Min(start.Y, finish.Y), Math.Max(start.X, finish.X), Math.Max(start.Y, finish.Y) ); rect.Inflate(Math.Max((int)(rect.Width * expansion), minimumSpace), Math.Max((int)(rect.Height * expansion), minimumSpace)); // Make sure our relevant region stays within the bounds or calculating a gradient. rect.Intersect(Rectangle.FromLTRB(1, 1, chan.Width - 1, chan.Height - 1)); //Debug.Assert(rect.Contains(start), "Relevant region does not contain start point."); //Debug.Assert(rect.Contains(finish), "Relevant region does not contain finish point."); return rect; } private int GetArrayIndex(Point point) { if (!IsOnMap(point.X,point.Y)) { Console.WriteLine("*** {0} is outside region borders!",point); return -1; } Point offset = point; return offset.Y * chan.Width + offset.X; } private Point GetPointFromArrayIndex(int index) { Point point = new Point(index % chan.Width, index / chan.Width); return point; } private int[] GetPixelWeights() { int[] weights = new int[relevantPixelsCount]; for (int i = 0; i < weights.Length; i++) weights[i] = GetPixelWeight(GetPointFromArrayIndex(i)); return weights; } private int GetPixelWeight(Point p) { return (int)chan.getPixel(p.X,p.Y); } const int maximumNearbyPositions = 8; int[,] Directions; enum NearbyPosition : int { NorthWest, // (-1, 1) North, // (0, 1) NorthEast, // (1, 1) West, // (-1, 0) East, // (1, 0) SouthWest, South, SouthEast } private int GetNearbyPixel(int origin, NearbyPosition relative) { return GetArrayIndex(GetNearbyPixel(GetPointFromArrayIndex(origin), relative)); } Point LastPoint=new Point(-1,-1); int LastPointCount=0; private Point GetNearbyPixel(Point origin, NearbyPosition relative) { if(LastPoint==origin) { LastPointCount++; //Console.WriteLine("Stuck on {0} for {1} ticks!",origin,LastPointCount); if(LastPointCount>10) { Random r = new Random(); origin.Offset(r.Next(1),r.Next(1)); return origin; } } else { LastPointCount=0; LastPoint=origin; } Point offset = origin; int i = (int)relative; offset.Offset(Directions[i,0],Directions[i,1]); return Clamp(offset); } private int GetRelativePosition(int start, int finish) { Point startPoint = GetPointFromArrayIndex(start); Point finishPoint = GetPointFromArrayIndex(finish); foreach (NearbyPosition position in Enum.GetValues(typeof(NearbyPosition))) if (GetNearbyPixel(start, position) == finish) return (int)position; return -1; } private int[,] GetTraversalCost() { int[] weights = GetPixelWeights(); int[,] cost = new int[relevantPixelsCount, maximumNearbyPositions]; for (int i = 0; i < weights.Length; i++) { Point origin = GetPointFromArrayIndex(i); foreach (NearbyPosition relativePosition in Enum.GetValues(typeof(NearbyPosition))) { Point relative = GetNearbyPixel(origin, relativePosition); if (IsOnMap(relative.X,relative.Y)) { int j = GetArrayIndex(relative); cost[i, (int)relativePosition] = weights[j]; } } } return cost; } private IEnumerable<int> nearbyNodesHint(int startingNode) { List<int> nearbyNodes = new List<int>(maximumNearbyPositions); foreach (NearbyPosition position in Enum.GetValues(typeof(NearbyPosition))) nearbyNodes.Add(GetNearbyPixel(startingNode, position)); return nearbyNodes; } private int getInternodeTraversalCost(int start, int finish) { int relativePosition = GetRelativePosition(start, finish); if (relativePosition < 0) return int.MaxValue; return traversalCost[start, relativePosition]; } private bool IsOnMap(int x,int y) // Z doesn't matter. { return ( x < chan.Width && x >= 0 && y < chan.Height && y >= 0 ); } private Point DirectionFromAng(double angle,int dist) { return new Point((int)Math.Sin(angle)*dist,(int)Math.Cos(angle)*dist); } /// <summary> /// Update pathfinding progress... /// </summary> /// <param name="VP"> /// A <see cref="System.Int32"/> count of valid pathnodes. /// </param> /// <param name="IP"> /// A <see cref="System.Int32"/> count of invalid pathnodes. /// </param> private void UpdateProgress(int VP,int IP,Point lp) { Console.CursorLeft = 0; Console.Write(" * Building River: ["+VP.ToString()+" Good, "+IP.ToString()+" Bad, lp=("+lp.ToString()+" )] "); } public List<PathFinderNode> FindPath(Point s,Point e) { s=Clamp(s); e=Clamp(e); int si=GetArrayIndex(s); int ei=GetArrayIndex(e); Console.WriteLine("FindPath: Initializing Dijkstra with {0}*{1}={2}",chan.Width,chan.Height,chan.Width*chan.Height); Dijkstra p = new Dijkstra( chan.Width*chan.Height, this.getInternodeTraversalCost, this.nearbyNodesHint); Console.WriteLine("FindPath: Locating path from {0} to {1}.",s,e); int[] PointPath=p.GetMinimumPath(si,ei); List<PathFinderNode> Path=new List<PathFinderNode>(); foreach(int pi in PointPath) { Point pt = GetPointFromArrayIndex(pi); PathFinderNode pfn=new PathFinderNode(); pfn.X=pt.X; pfn.Y=pt.Y; Path.Add(pfn); } return Path; } /* public List<PathFinderNode> FindPath(Point s,Point e,int seed,float wl) { Channel mychan=chan.copy(); wl=wl/512f; Console.WriteLine(" * Building river, starting at ({0},{1})",s.X,s.Y); bool Done=false; double LastDir=Math.PI*3; // Angle float LastHeight=mychan.getPixel(s.X,s.Y); int Invalid=0; int Valid=0; int REPEATS=0; float h = int.MaxValue; Point candidate=new Point(0,0); Point Current=Start; Point oldPoint=new Point(-1,-1); Console.WriteLine(); Random r = new Random(seed); while(!Done) { candidate=new Point(-1,-1); for(int a=0;a<8;a++) { Point cp = new Point(direction[a,0],direction[a,1]); cp.X+=Current.X; cp.Y+=Current.Y; float nh=513f; // So it doesn't think the outside map = good place to go. if(IsOnMap(cp.X,cp.Y)) nh= mychan.getPixel(cp.X,cp.Y); if(nh<=h && cp!=oldPoint) { h=nh; //Current height candidate=cp; if(IsOnMap(cp.X,cp.Y)) mychan.putPixel(cp.X,cp.Y,2f); // Exclude already-used terrain. } } if(candidate==oldPoint) { Done=true; break; } if(candidate==(new Point(-1,-1))) { candidate=Current; candidate.X+=(Current.X-oldPoint.X); candidate.Y+=(Current.Y-oldPoint.Y); if(!IsOnMap(candidate.X,candidate.Y)) return path; h= mychan.getPixel(candidate.X,candidate.Y); mychan.putPixel(candidate.X,candidate.Y,2f); // Exclude already-used terrain. } UpdateProgress(Valid,Invalid,candidate); if(Valid>2000) return path; if(IsOnMap(candidate.X,candidate.Y)) { PathFinderNode np; np.X=candidate.X; np.Y=candidate.Y; path.Add(np); oldPoint=Current; Current=candidate; Valid++; if(!IsOnMap(candidate.X,candidate.Y)) { Console.WriteLine(); Console.WriteLine(" * <{0},{1},{2}> - River travelled outside of the map. Done.",candidate.X,candidate.Y,h); Done=true; } if(h<=wl) { Console.WriteLine(); Console.WriteLine(" * <{0},{1},{2}> - River hit water level (wl={3}). Done.",candidate.X,candidate.Y,h,wl); Done=true; } Current=candidate; continue; } if(path.Count>0) path.RemoveAt(path.Count-1); Invalid++; } return path; } */ private Point Clamp(Point p) { p.X=Math.Min(chan.Width-1 , p.X); p.X=Math.Max(0 , p.X); p.Y=Math.Min(chan.Height-1 , p.Y); p.Y=Math.Max(0 , p.Y); return p; } public RiverBuilder GenerateRiver(float waterlevel,int seed,out List<PathFinderNode> RiverPath) { float oldDelta = chan.getMaxDelta(); RiverPath=new List<PathFinderNode>(); //Start = FindStartPoint(DateTime.Now.Millisecond%4); //End = FindEndPoint((DateTime.Now.Millisecond+1)%4); Random r = new Random(seed); List<Point> StartPoints = new List<Point>(); float max=chan.findMax(); float min=chan.findMin(); float inv=1f/(max-min); waterlevel=Tools.interpolateLinear(0f,1f,(20f-0f)*(1f/(45f-0f))); float maxoffset=Tools.interpolateLinear(0f,1f,(5f-0f)*(1f/(45f-0f))); // Source can spawn >5m ASL, but must be >10m // from the highest altitude on the map. chan.normalize(); // stretch it the fsck out. Start=FindStartPoint(0); End=FindEndPoint(2); Console.WriteLine(" * Generating river, s={0}, e={1}.",Start,End); List<PathFinderNode> p=FindPath(Start,End);//,seed,20f); if(p==null) { Console.WriteLine(" ! Unable to retrieve path.."); return this; } CleanPath(p); CreateBank(p); //CleanupFloodplain(); Console.WriteLine(" * Maximum terrain delta: {0}",chan.getMaxDelta()); chan.setMaxDelta(oldDelta/2f); Console.WriteLine(" * Adjusted terrain delta: {0}",chan.getMaxDelta()); chan.smooth(1); // CleanupFloodplain is broken, dunno why. RiverPath=p; return this; } public RiverBuilder GenerateRiver(float waterlevel,int seed,Point start,Point end) { Console.WriteLine(" * Generating river, s={0}, e={1}.",Start,End); List<PathFinderNode> p=FindPath(Start,End);//,seed,20f); if(p==null) { Console.WriteLine(" ! Unable to retrieve path.."); return this; } CleanPath(p); CreateBank(p); //CleanupFloodplain(); Console.WriteLine(" * Maximum terrain delta: {0}",chan.getMaxDelta()); chan.setMaxDelta(chan.getMaxDelta()/5f); Console.WriteLine(" * Adjusted terrain delta: {0}",chan.getMaxDelta()); chan.smooth(1); // CleanupFloodplain is broken, dunno why. return this; } public void DebugPathFinder(int fromX, int fromY, int x, int y, PathFinderNodeType type, int totalCost, int cost) { Console.WriteLine("({0},{1}) -> ({2},{3}): Costs {4}",fromX,fromY,x,y,cost); } private void CleanPath(List<PathFinderNode> nodes) { Console.WriteLine("\n * Cleaning up path... ("+nodes.Count.ToString()+" nodes...)"); for ( int i = nodes.Count-1; i > 0 ; --i ) { //Console.Write(i.ToString()+","); int x,y; x=nodes[i].X; y=nodes[i].Y; float z=chan.getPixel(x,y); // Lower the vertices half way down z=z*0.5f; // Find previous river height float pz=1f; if(i<nodes.Count) chan.getPixel(nodes[i-1].X,nodes[i-1].Y); // If we actually went up (water doesn't go up) // then move us slightly lower than the previous vertex if (i < nodes.Count && z >= pz) z = pz-0.01f; // store the new height in the heightmap chan.putPixel(x,y,z); } Console.WriteLine("Done."); } private void CleanupFloodplain() { Console.WriteLine(" * Cleaning up floodplain..."); // Initialize the acceptable height changes in the terrain // this will affect the smoothness float fDeltaY = 0.1f; float fAdjY = 0.03f; // Initialize the repeat bool to run once bool bAltered = true; // loop while we are making changes float hD=0f; int pass=0; while ( bAltered ) { // assume we aren't going to make changes bAltered = false; pass++; int x,y; // for the entire terrain minus the last row and column Console.WriteLine(" > Pass {0} ...",pass); for ( x = 0; x < chan.Width-2; x++ ) { for ( y = 0; y < chan.Height-2; y++ ) { //Console.CursorLeft=0; //Console.Write(" - Processing point ({0},{1}) ...",x,y); // Check our right and our north neighbors float cD=chan.getPixel(x,y)-chan.getPixel(x,y+1); if(cD>hD) hD=cD; if (cD > fDeltaY ) { chan.putPixel(x,y,chan.getPixel(x,y)-fAdjY); bAltered = true; //Console.WriteLine("Corrected ({0},{1})...",x,y); } cD=chan.getPixel(x,y)-chan.getPixel(x+1,y); if ( cD > hD ) hD=cD; if ( cD > fDeltaY ) { chan.putPixel(x,y,chan.getPixel(x,y)-fAdjY); bAltered = true; //Console.WriteLine("Corrected ({0},{1})...",x,y); } } } // for the entire terrain minus the first row and column for ( x = chan.Width-1; x > 0; x-- ) { for ( y = chan.Height-1; y > 0; y-- ) { // check out our south and left neighbors float cD=chan.getPixel(x,y)-chan.getPixel(x,y-1); if(cD>hD)hD=cD; if ( cD > fDeltaY ) { chan.putPixel(x,y,chan.getPixel(x,y)-fAdjY); bAltered = true; //Console.WriteLine("Corrected ({0},{1})...",x,y); } cD=chan.getPixel(x,y)-chan.getPixel(x-1,y); if(cD>hD) hD=cD; if(cD > fDeltaY ) { chan.putPixel(x,y,chan.getPixel(x,y)-fAdjY); bAltered = true; //Console.WriteLine("Corrected ({0},{1})...",x,y); } } } } Console.WriteLine("Highest Delta = {0}",hD); } float HEIGHT_ADJ = 0.03f; int SLOPE_WIDTH = 64; float SLOPE_VAL = 0.1f; private void CreateBank(List<PathFinderNode> nodes) { Console.WriteLine("\n * Creating riverbank... ("+nodes.Count.ToString()+" nodes...)"); for ( int i = nodes.Count-1; i > 0 ; --i ) { int x=nodes[i].X; int y=nodes[i].Y; float z=chan.getPixel(x,y); // repeat variable bool bAltered = true; while ( bAltered ) { // Our default assumption is that we don't change anything // so we don't need to repeat the process bAltered = false; // Cycle through all valid terrain within the slope width // of the current position for ( int iX = Math.Max(0,x-SLOPE_WIDTH); iX < Math.Min(chan.Width,y+SLOPE_WIDTH); ++iX ) { for ( int iY = Math.Max(0,y-SLOPE_WIDTH); iY < Math.Min(chan.Height,y+SLOPE_WIDTH); ++iY ) { float fSlope; // find the slope from where we are to where we are checking fSlope = (chan.getPixel(iX,iY) - chan.getPixel(x,y)) /(float)Math.Sqrt((x-iX)*(x-iX)+(y-iY)*(y-iY)); if ( fSlope > SLOPE_VAL ) { // the slope is too big so adjust the height and keep in mind // that the terrain was altered and we should make another pass chan.putPixel(x,y,chan.getPixel(x,y)-HEIGHT_ADJ); bAltered = true; } } } } } Console.WriteLine("Done."); } public Point FindStartPoint(int direction) { int x,y; Point candidate=new Point(0,0); float h,nh; h=nh=0f; switch(direction) { case 0: // North y=chan.Height-1; for(x=0;x<chan.Width;x++) { nh = chan.getPixel(x,y); if(nh>h) { h=nh; candidate=new Point(x,y); } } break; case 1: // East x=chan.Width-1; for(y=0;y<chan.height;y++) { nh = chan.getPixel(x,y); if(nh>h) { h=nh; candidate=new Point(x,y); } } break; case 2: // South y=0; for(x=0;x<chan.Width;x++) { nh = chan.getPixel(x,y); if(nh>h) { h=nh; candidate=new Point(x,y); } } break; case 3: // West x=0; for(y=0;y<chan.height;y++) { nh = chan.getPixel(x,y); if(nh>h) { h=nh; candidate=new Point(x,y); } } break; } return Clamp(candidate); } public Point FindEndPoint(int direction) { int x,y; Point candidate=new Point(0,0); float h,nh; h=nh=1f; switch(direction) { case 0: // North y=chan.Height-1; for(x=0;x<chan.Width;x++) { nh = chan.getPixel(x,y); if(nh<h) { h=nh; candidate=new Point(x,y); } } break; case 1: // East x=chan.Width-1; for(y=0;y<chan.Height;y++) { nh = chan.getPixel(x,y); if(nh<h) { h=nh; candidate=new Point(x,y); } } break; case 2: // South y=0; for(x=0;x<chan.Width;x++) { nh = chan.getPixel(x,y); if(nh<h) { h=nh; candidate=new Point(x,y); } } break; case 3: // West x=0; for(y=0;y<chan.Height;y++) { nh = chan.getPixel(x,y); if(nh<h) { h=nh; candidate=new Point(x,y); } } break; } return Clamp(candidate); } public Channel toChannel() { return chan; } public Layer toLayer() { return new Layer(chan.copy(), chan.copy(), chan.copy()); } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace Codisa.InterwayDocs.Business { /// <summary> /// OutgoingInfo (read only object).<br/> /// This is a generated <see cref="OutgoingInfo"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="OutgoingBook"/> collection. /// </remarks> [Serializable] public partial class OutgoingInfo : ReadOnlyBase<OutgoingInfo> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="RegisterId"/> property. /// </summary> public static readonly PropertyInfo<int> RegisterIdProperty = RegisterProperty<int>(p => p.RegisterId, "Register Id"); /// <summary> /// Gets the Register Id. /// </summary> /// <value>The Register Id.</value> public int RegisterId { get { return GetProperty(RegisterIdProperty); } } /// <summary> /// Maintains metadata about <see cref="RegisterDate"/> property. /// </summary> public static readonly PropertyInfo<SmartDate> RegisterDateProperty = RegisterProperty<SmartDate>(p => p.RegisterDate, "Register Date"); /// <summary> /// Gets the Register Date. /// </summary> /// <value>The Register Date.</value> public string RegisterDate { get { return GetPropertyConvert<SmartDate, string>(RegisterDateProperty); } } /// <summary> /// Maintains metadata about <see cref="DocumentType"/> property. /// </summary> public static readonly PropertyInfo<string> DocumentTypeProperty = RegisterProperty<string>(p => p.DocumentType, "Document Type"); /// <summary> /// Gets the Document Type. /// </summary> /// <value>The Document Type.</value> public string DocumentType { get { return GetProperty(DocumentTypeProperty); } } /// <summary> /// Maintains metadata about <see cref="DocumentReference"/> property. /// </summary> public static readonly PropertyInfo<string> DocumentReferenceProperty = RegisterProperty<string>(p => p.DocumentReference, "Document Reference"); /// <summary> /// Gets the Document Reference. /// </summary> /// <value>The Document Reference.</value> public string DocumentReference { get { return GetProperty(DocumentReferenceProperty); } } /// <summary> /// Maintains metadata about <see cref="DocumentEntity"/> property. /// </summary> public static readonly PropertyInfo<string> DocumentEntityProperty = RegisterProperty<string>(p => p.DocumentEntity, "Document Entity"); /// <summary> /// Gets the Document Entity. /// </summary> /// <value>The Document Entity.</value> public string DocumentEntity { get { return GetProperty(DocumentEntityProperty); } } /// <summary> /// Maintains metadata about <see cref="DocumentDept"/> property. /// </summary> public static readonly PropertyInfo<string> DocumentDeptProperty = RegisterProperty<string>(p => p.DocumentDept, "Document Dept"); /// <summary> /// Gets the Document Dept. /// </summary> /// <value>The Document Dept.</value> public string DocumentDept { get { return GetProperty(DocumentDeptProperty); } } /// <summary> /// Maintains metadata about <see cref="DocumentClass"/> property. /// </summary> public static readonly PropertyInfo<string> DocumentClassProperty = RegisterProperty<string>(p => p.DocumentClass, "Document Class"); /// <summary> /// Gets the Document Class. /// </summary> /// <value>The Document Class.</value> public string DocumentClass { get { return GetProperty(DocumentClassProperty); } } /// <summary> /// Maintains metadata about <see cref="DocumentDate"/> property. /// </summary> public static readonly PropertyInfo<SmartDate> DocumentDateProperty = RegisterProperty<SmartDate>(p => p.DocumentDate, "Document Date"); /// <summary> /// Gets the Document Date. /// </summary> /// <value>The Document Date.</value> public string DocumentDate { get { return GetPropertyConvert<SmartDate, string>(DocumentDateProperty); } } /// <summary> /// Maintains metadata about <see cref="Subject"/> property. /// </summary> public static readonly PropertyInfo<string> SubjectProperty = RegisterProperty<string>(p => p.Subject, "Subject"); /// <summary> /// Gets the Subject. /// </summary> /// <value>The Subject.</value> public string Subject { get { return GetProperty(SubjectProperty); } } /// <summary> /// Maintains metadata about <see cref="SendDate"/> property. /// </summary> public static readonly PropertyInfo<SmartDate> SendDateProperty = RegisterProperty<SmartDate>(p => p.SendDate, "Send Date"); /// <summary> /// Gets the Send Date. /// </summary> /// <value>The Send Date.</value> public string SendDate { get { return GetPropertyConvert<SmartDate, string>(SendDateProperty); } } /// <summary> /// Maintains metadata about <see cref="RecipientName"/> property. /// </summary> public static readonly PropertyInfo<string> RecipientNameProperty = RegisterProperty<string>(p => p.RecipientName, "Recipient Name"); /// <summary> /// Gets the Recipient Name. /// </summary> /// <value>The Recipient Name.</value> public string RecipientName { get { return GetProperty(RecipientNameProperty); } } /// <summary> /// Maintains metadata about <see cref="RecipientTown"/> property. /// </summary> public static readonly PropertyInfo<string> RecipientTownProperty = RegisterProperty<string>(p => p.RecipientTown, "Recipient Town"); /// <summary> /// Gets the Recipient Town. /// </summary> /// <value>The Recipient Town.</value> public string RecipientTown { get { return GetProperty(RecipientTownProperty); } } /// <summary> /// Maintains metadata about <see cref="Notes"/> property. /// </summary> public static readonly PropertyInfo<string> NotesProperty = RegisterProperty<string>(p => p.Notes, "Notes"); /// <summary> /// Gets the Notes. /// </summary> /// <value>The Notes.</value> public string Notes { get { return GetProperty(NotesProperty); } } /// <summary> /// Maintains metadata about <see cref="ArchiveLocation"/> property. /// </summary> public static readonly PropertyInfo<string> ArchiveLocationProperty = RegisterProperty<string>(p => p.ArchiveLocation, "Archive Location"); /// <summary> /// Gets the Archive Location. /// </summary> /// <value>The Archive Location.</value> public string ArchiveLocation { get { return GetProperty(ArchiveLocationProperty); } } #endregion #region Factory Methods /// <summary> /// Factory method. Loads a <see cref="OutgoingInfo"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="OutgoingInfo"/> object.</returns> internal static OutgoingInfo GetOutgoingInfo(SafeDataReader dr) { OutgoingInfo obj = new OutgoingInfo(); obj.Fetch(dr); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="OutgoingInfo"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public OutgoingInfo() { // Use factory methods and do not use direct creation. } #endregion #region Data Access /// <summary> /// Loads a <see cref="OutgoingInfo"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(RegisterIdProperty, dr.GetInt32("RegisterId")); LoadProperty(RegisterDateProperty, dr.GetSmartDate("RegisterDate", true)); LoadProperty(DocumentTypeProperty, dr.GetString("DocumentType")); LoadProperty(DocumentReferenceProperty, dr.GetString("DocumentReference")); LoadProperty(DocumentEntityProperty, dr.GetString("DocumentEntity")); LoadProperty(DocumentDeptProperty, dr.GetString("DocumentDept")); LoadProperty(DocumentClassProperty, dr.GetString("DocumentClass")); LoadProperty(DocumentDateProperty, dr.GetSmartDate("DocumentDate", true)); LoadProperty(SubjectProperty, dr.GetString("Subject")); LoadProperty(SendDateProperty, dr.GetSmartDate("SendDate", true)); LoadProperty(RecipientNameProperty, dr.GetString("RecipientName")); LoadProperty(RecipientTownProperty, dr.GetString("RecipientTown")); LoadProperty(NotesProperty, dr.GetString("Notes")); LoadProperty(ArchiveLocationProperty, dr.GetString("ArchiveLocation")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } #endregion #region DataPortal Hooks /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); #endregion } }
/* * Copyright (C) 2005-2016 Christoph Rupp (chris@crupp.de). * All Rights Reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * See the file COPYING for License information. */ using System; using System.Collections.Generic; using System.Text; using Upscaledb; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Unittests { public class CursorTest { private int counter; private int Callback(byte[] b1, byte[] b2) { counter++; if (b1.GetLength(0) < b2.GetLength(0)) return (-1); if (b1.GetLength(0) > b2.GetLength(0)) return (+1); for (int i = b1.GetLength(0); --i >= 0; ) { if (b1[i] < b2[i]) return (-1); if (b1[i] > b2[i]) return (+1); } return 0; } private Upscaledb.Environment env; private Database db; private void SetUp() { env = new Upscaledb.Environment(); db = new Database(); env.Create("ntest.db"); db = env.CreateDatabase(1, UpsConst.UPS_ENABLE_DUPLICATE_KEYS); } private void TearDown() { env.Close(); } private void Create() { Cursor c = new Cursor(db); c.Close(); } private void Clone() { Cursor c1 = new Cursor(db); Cursor c2 = c1.Clone(); } private void Move() { Cursor c = new Cursor(db); byte[] k = new byte[5]; byte[] r = new byte[5]; k[0] = 0; db.Insert(k, r); k[0] = 1; db.Insert(k, r); k[0] = 2; db.Insert(k, r); k[0] = 3; db.Insert(k, r); k[0] = 4; db.Insert(k, r); c.Move(UpsConst.UPS_CURSOR_NEXT); c.Move(UpsConst.UPS_CURSOR_NEXT); c.Move(UpsConst.UPS_CURSOR_PREVIOUS); c.Move(UpsConst.UPS_CURSOR_LAST); c.Move(UpsConst.UPS_CURSOR_FIRST); } private void MoveNegative() { Cursor c = new Cursor(db); try { c.Move(UpsConst.UPS_CURSOR_NEXT); } catch (DatabaseException e) { Assert.AreEqual(UpsConst.UPS_KEY_NOT_FOUND, e.ErrorCode); } } private void MoveFirst() { Cursor c = new Cursor(db); byte[] k = new byte[5]; byte[] r = new byte[5]; db.Insert(k, r); c.MoveFirst(); } private void MoveLast() { Cursor c = new Cursor(db); byte[] k = new byte[5]; byte[] r = new byte[5]; db.Insert(k, r); c.MoveLast(); } private void MoveNext() { Cursor c = new Cursor(db); byte[] k = new byte[5]; byte[] r = new byte[5]; db.Insert(k, r); c.MoveNext(); } private void MovePrevious() { Cursor c = new Cursor(db); byte[] k = new byte[5]; byte[] r = new byte[5]; db.Insert(k, r); c.MovePrevious(); } void checkEqual(byte[] lhs, byte[] rhs) { Assert.AreEqual(lhs.Length, rhs.Length); for (int i = 0; i < lhs.Length; i++) Assert.AreEqual(lhs[i], rhs[i]); } private void TryMove() { Cursor c = new Cursor(db); byte[] k1 = BitConverter.GetBytes(1UL); byte[] r1 = BitConverter.GetBytes(2UL); db.Insert(k1, r1); byte[] k2 = null, r2 = null; Assert.IsTrue(c.TryMove(ref k2, ref r2, UpsConst.UPS_CURSOR_NEXT)); checkEqual(k1, k2); checkEqual(r1, r2); Assert.IsFalse(c.TryMove(ref k2, ref r2, UpsConst.UPS_CURSOR_NEXT)); Assert.IsNull(k2); Assert.IsNull(r2); } private void GetKey() { Cursor c = new Cursor(db); byte[] k = new byte[5]; byte[] r = new byte[5]; db.Insert(k, r); c.MovePrevious(); byte[] f = c.GetKey(); checkEqual(k, f); } private void GetRecord() { Cursor c = new Cursor(db); byte[] k = new byte[5]; byte[] r = new byte[5]; db.Insert(k, r); c.MovePrevious(); byte[] f = c.GetRecord(); checkEqual(r, f); } private void Overwrite() { Cursor c = new Cursor(db); byte[] k = new byte[5]; byte[] r1 = new byte[5]; r1[0] = 1; byte[] r2 = new byte[5]; r2[0] = 2; db.Insert(k, r1); c.MoveFirst(); byte[] f = c.GetRecord(); checkEqual(r1, f); c.Overwrite(r2); byte[] g = c.GetRecord(); checkEqual(r2, g); } private void Find() { Cursor c = new Cursor(db); byte[] k1 = new byte[5]; k1[0] = 5; byte[] k2 = new byte[5]; k2[0] = 6; byte[] r1 = new byte[5]; r1[0] = 1; byte[] r2 = new byte[5]; r2[0] = 2; db.Insert(k1, r1); db.Insert(k2, r2); c.Find(k1); byte[] f = c.GetRecord(); checkEqual(r1, f); c.Find(k2); byte[] g = c.GetRecord(); checkEqual(r2, g); } private void TryFind() { Cursor c = new Cursor(db); byte[] k1 = new byte[5]; k1[0] = 5; byte[] k2 = new byte[5]; k2[0] = 6; byte[] k3 = new byte[5]; k3[0] = 7; byte[] r1 = new byte[5]; r1[0] = 1; byte[] r2 = new byte[5]; r2[0] = 2; db.Insert(k1, r1); db.Insert(k2, r2); var f = c.TryFind(k1); checkEqual(r1, f); var g = c.TryFind(k2); checkEqual(r2, g); var h = c.TryFind(k3); Assert.IsNull(h); } private void Insert() { Cursor c = new Cursor(db); byte[] q; byte[] k1 = new byte[5]; k1[0] = 5; byte[] k2 = new byte[5]; k2[0] = 6; byte[] r1 = new byte[5]; r1[0] = 1; byte[] r2 = new byte[5]; r2[0] = 2; c.Insert(k1, r1); q = c.GetRecord(); checkEqual(r1, q); q = c.GetKey(); checkEqual(k1, q); c.Insert(k2, r2); q = c.GetRecord(); checkEqual(r2, q); q = c.GetKey(); checkEqual(k2, q); } private void InsertDuplicate() { Cursor c = new Cursor(db); byte[] q; byte[] k1 = new byte[5]; k1[0] = 5; byte[] r1 = new byte[5]; r1[0] = 1; byte[] r2 = new byte[5]; r2[0] = 2; c.Insert(k1, r1); q = c.GetRecord(); checkEqual(r1, q); q = c.GetKey(); checkEqual(k1, q); c.Insert(k1, r2, UpsConst.UPS_DUPLICATE); q = c.GetRecord(); checkEqual(r2, q); q = c.GetKey(); checkEqual(k1, q); } private void InsertNegative() { Cursor c = new Cursor(db); byte[] q; byte[] k1 = new byte[5]; k1[0] = 5; byte[] r1 = new byte[5]; r1[0] = 1; byte[] r2 = new byte[5]; r2[0] = 2; c.Insert(k1, r1); q = c.GetRecord(); checkEqual(r1, q); q = c.GetKey(); checkEqual(k1, q); try { c.Insert(k1, r2); } catch (DatabaseException e) { Assert.AreEqual(UpsConst.UPS_DUPLICATE_KEY, e.ErrorCode); } } private void Erase() { Cursor c = new Cursor(db); byte[] k1 = new byte[5]; k1[0] = 5; byte[] r1 = new byte[5]; r1[0] = 1; c.Insert(k1, r1); c.Erase(); } private void EraseNegative() { Cursor c = new Cursor(db); try { c.Erase(); } catch (DatabaseException e) { Assert.AreEqual(UpsConst.UPS_CURSOR_IS_NIL, e.ErrorCode); } } private void GetDuplicateCount() { Cursor c = new Cursor(db); byte[] k1 = new byte[5]; k1[0] = 5; byte[] r1 = new byte[5]; r1[0] = 1; byte[] r2 = new byte[5]; r2[0] = 2; byte[] r3 = new byte[5]; r2[0] = 2; c.Insert(k1, r1); Assert.AreEqual(1, c.GetDuplicateCount()); c.Insert(k1, r2, UpsConst.UPS_DUPLICATE); Assert.AreEqual(2, c.GetDuplicateCount()); c.Insert(k1, r3, UpsConst.UPS_DUPLICATE); Assert.AreEqual(3, c.GetDuplicateCount()); c.Erase(); c.MoveFirst(); Assert.AreEqual(2, c.GetDuplicateCount()); } private void ApproxMatching() { Upscaledb.Environment env = new Upscaledb.Environment(); Database db = new Database(); byte[] k1 = new byte[5]; byte[] r1 = new byte[5]; k1[0] = 1; r1[0] = 1; byte[] k2 = new byte[5]; byte[] r2 = new byte[5]; k2[0] = 2; r2[0] = 2; byte[] k3 = new byte[5]; byte[] r3 = new byte[5]; k3[0] = 3; r3[0] = 3; try { env.Create("ntest.db"); db = env.CreateDatabase(1); db.Insert(k1, r1); db.Insert(k2, r2); db.Insert(k3, r3); Cursor c = new Cursor(db); byte[] r = c.Find(k2, UpsConst.UPS_FIND_GT_MATCH); checkEqual(r, r3); checkEqual(k2, k3); k2[0] = 2; r = c.Find(k2, UpsConst.UPS_FIND_GT_MATCH); checkEqual(r, r1); checkEqual(k2, k1); db.Close(); env.Close(); } catch (DatabaseException e) { Assert.Fail("unexpected exception " + e); } } public void Run() { Console.WriteLine("CursorTest.Create"); SetUp(); Create(); TearDown(); Console.WriteLine("CursorTest.Clone"); SetUp(); Clone(); TearDown(); Console.WriteLine("CursorTest.Move"); SetUp(); Move(); TearDown(); Console.WriteLine("CursorTest.MoveNegative"); SetUp(); MoveNegative(); TearDown(); Console.WriteLine("CursorTest.MoveFirst"); SetUp(); MoveFirst(); TearDown(); Console.WriteLine("CursorTest.MoveLast"); SetUp(); MoveLast(); TearDown(); Console.WriteLine("CursorTest.MoveNext"); SetUp(); MoveNext(); TearDown(); Console.WriteLine("CursorTest.MovePrevious"); SetUp(); MovePrevious(); TearDown(); Console.WriteLine("CursorTest.TryMove"); SetUp(); TryMove(); TearDown(); Console.WriteLine("CursorTest.GetKey"); SetUp(); GetKey(); TearDown(); Console.WriteLine("CursorTest.GetRecord"); SetUp(); GetRecord(); TearDown(); Console.WriteLine("CursorTest.Find"); SetUp(); Find(); TearDown(); Console.WriteLine("CursorTest.TryFind"); SetUp(); TryFind(); TearDown(); Console.WriteLine("CursorTest.Insert"); SetUp(); Insert(); TearDown(); Console.WriteLine("CursorTest.InsertDuplicate"); SetUp(); InsertDuplicate(); TearDown(); Console.WriteLine("CursorTest.InsertNegative"); SetUp(); InsertNegative(); TearDown(); Console.WriteLine("CursorTest.Erase"); SetUp(); Erase(); TearDown(); Console.WriteLine("CursorTest.EraseNegative"); SetUp(); EraseNegative(); TearDown(); Console.WriteLine("CursorTest.GetDuplicateCount"); SetUp(); GetDuplicateCount(); TearDown(); } } }
// Copyright (c) 2021 Alachisoft // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License using Alachisoft.NCache.Common; using Alachisoft.NCache.Common.DataStructures.Clustered; using Alachisoft.NCache.Common.Enum; using Alachisoft.NCache.Common.Net; using Alachisoft.NCache.Common.Protobuf; using Alachisoft.NCache.Common.Sockets; using Alachisoft.NCache.Common.Threading; using Alachisoft.NCache.Common.Util; using Alachisoft.NCache.Management.Statistics; using Alachisoft.NCache.Runtime.Exceptions; using Alachisoft.NCache.Web.Communication; using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Security.Authentication; using System.Threading; using Exception = System.Exception; namespace Alachisoft.NCache.Client { internal sealed class Connection { #region --------Constants-------- internal const int CmdSizeHolderBytesCount = 10; internal const int ValSizeHolderBytesCount = 10; internal const int TotSizeHolderBytesCount = ValSizeHolderBytesCount + CmdSizeHolderBytesCount; //10 bytes for the message size... private const int MessageHeader = 10; //Threshold for maximum number of commands in a request. private const int MaxCmdsThreshold = 100; #endregion #region private members private OnCommandRecieved _commandRecieved = null; private OnServerLost _serverLost = null; private bool _isConnected = true; private Socket _primaryClient = null; private Socket _secondaryClient = null; private IPAddress _address; private string _ipAddress = string.Empty; private string _intendedRecipientIPAddress = string.Empty; private int _port = 0; private object _connectionMutex = new object(); private Latch _connectionStatusLatch = new Latch(ConnectionStatus.Disconnected); public static long s_receiveBufferSize = 2048000; private int _processID = AppUtil.CurrentProcess.Id; private string _cacheId; private Thread _primaryReceiveThread = null; private Thread _secondaryReceiveThread = null; private bool _notificationsRegistered = false; private bool _isReconnecting = false; private bool _forcedDisconnect = false; private bool _nagglingEnabled = false; private long _nagglingSize = 5 * 100 * 1024; //500k private NagglingManager _priNagglingMgr; private NagglingManager _secNagglingMgr; private Alachisoft.NCache.Common.DataStructures.Queue _msgQueue; private bool _supportDualSocket = false; private object _syncLock = new object(); private static IPEndPoint _bindIP; private Logs _logger; private ResponseIntegrator _responseIntegrator; private Address _serverAddress; private Broker _container; private StatisticsCounter _perfStatsColl = null; private object _socketSelectionMutex = new object(); private bool _usePrimary = true; private bool _requestLoggingEnabled; private bool _optimized = false; private int _hostPort; private bool _isIdle = false; #region SSL/TLS related attribute and properties private string _targetHost; private bool _provideCert; private SslProtocols _protocols; private EncryptionPolicy _policy; internal bool IsSecured { get; private set; } #endregion #endregion internal int inWriteQueue = 0; private int activeWriters = 0; private readonly CommandQueue _queue = new CommandQueue(); private NetworkStream _bufferedStream; internal Connection(Broker container, OnCommandRecieved commandRecieved, OnServerLost serverLost, Logs logs, StatisticsCounter perfStatsCollector, ResponseIntegrator rspIntegraotr, string bindIP, string cacheName) { _connectionStatusLatch = new Latch(ConnectionStatus.Disconnected); Initialize(container, commandRecieved, serverLost, logs, perfStatsCollector, rspIntegraotr, bindIP, cacheName); } #region Properties public bool Optimized { get { return _optimized; } set { _optimized = value; } } private bool DoNaggling { get { return (_nagglingEnabled && _priNagglingMgr != null); } } public bool SupportDualSocket { get { return _supportDualSocket; } } public Socket PrimaryClientSocket { get { return _primaryClient; } } public Socket SecondaryClientSocket { get { return _secondaryClient; } } internal Latch StatusLatch { get { return _connectionStatusLatch; } } /// <summary> /// Checks if request logging is enabled on this server or not. /// </summary> internal bool RequestInquiryEnabled { get { return _requestLoggingEnabled; } set { _requestLoggingEnabled = value; } } internal bool IsConnected { get { return _connectionStatusLatch.IsAnyBitsSet(ConnectionStatus.Connected); } } /// <summary> /// Get ip address of machine to which connection is made /// </summary> internal string IpAddress { get { return this._ipAddress; } } internal IPAddress Address { get { return this._address; } } internal Address ServerAddress { get { return this._serverAddress; } set { _serverAddress = value; } } internal string IntendedRecipientIPAddress { set { this._intendedRecipientIPAddress = value; } get { return this._intendedRecipientIPAddress; } } /// <summary> /// Get port on which connection is made /// </summary> internal int Port { get { return this._port; } private set { _port = value; } } internal bool NotifRegistered { get { return this._notificationsRegistered; } set { this._notificationsRegistered = value; } } internal bool IsReconnecting { get { return this._isReconnecting; } set { this._isReconnecting = value; } } /// <summary> /// Gets the prefered communication socket. /// </summary> private Socket CommunicationSocket { get { Socket selectedSocket = _primaryClient; if (SupportDualSocket) { selectedSocket = _primaryClient; lock (_socketSelectionMutex) { if (!_usePrimary) selectedSocket = _secondaryClient; _usePrimary = !_usePrimary; } } return selectedSocket; } } //Marking it where it needs to be... internal bool IsIdle { get { lock (_connectionMutex) return _isIdle; } set { lock (_connectionMutex) _isIdle = value; } } #endregion public string GetClientLocalIP() { string ip = string.Empty; if (PrimaryClientSocket != null) { if (this.IsConnected) { IPEndPoint add = (IPEndPoint)PrimaryClientSocket.LocalEndPoint; ip = add.Address.ToString(); } } return ip; } //function that sets string provided to bindIP internal void SetBindIP(string value) { if (value != null && value != string.Empty) { try { var ip = IPAddress.Parse(value.Trim()); if (!IPAddress.Loopback.Equals(ip)) _bindIP = new IPEndPoint(IPAddress.Parse(value.Trim()), 0); } catch (Exception ex) { } } } public override bool Equals(object obj) { Connection connection = obj as Connection; return (connection != null && this.IpAddress == connection.IpAddress); } public void Dispose() { if (_msgQueue != null && !_msgQueue.Closed) { _msgQueue.close(true); _msgQueue = null; } try { if (_priNagglingMgr != null && _priNagglingMgr.IsAlive) { #if !NETCORE _priNagglingMgr.Abort(); #elif NETCORE _priNagglingMgr.Interrupt(); #endif } if (_secNagglingMgr != null && _secNagglingMgr.IsAlive) { #if !NETCORE _secNagglingMgr.Abort(); #elif NETCORE _secNagglingMgr.Interrupt(); #endif } } catch (Exception) { } } internal bool Connect(IPAddress ipAddress, int port) { #if DEVELOPMENT bool connectingLocal = false; if(System.Net.IPAddress.IsLoopback(ipAddress)) { connectingLocal = true; } else { IPHostEntry entry = Dns.GetHostByName(Dns.GetHostName()); if (entry != null) { foreach (IPAddress add in entry.AddressList) { if (add.Equals(ipAddress)) connectingLocal = true; } } } if (!connectingLocal) throw new Alachisoft.NCache.Runtime.Exceptions.OperationNotSupportedException("Connection to a remote server is not allowed in this edition of NCache"); #endif int retry = 0; Optimized = false; _ipAddress = ipAddress.ToString(); _address = ipAddress; _port = port; _serverAddress = new Address(ipAddress, port); lock (_connectionMutex) { _primaryClient = PrepareToConnect(_primaryClient); IPEndPoint endPoint = new IPEndPoint(ipAddress, port); while (retry < 3) { try { _primaryClient.Connect(endPoint); _bufferedStream = new NetworkStream(_primaryClient, false); return true; } catch (Exception e) { if (_logger.IsErrorLogsEnabled) _logger.NCacheLog.Error("Connection.Connect", " can not connect to " + ipAddress + ":" + port + ". error: " + e.ToString()); if (e.Message.Contains("A connection attempt failed because the connected party did not properly respond after a period of time")) { retry++; } else { return false; } } } } return false; } internal bool Connect(string hostName, int port) { return Connect(((IPAddress[])Dns.GetHostByName(hostName).AddressList)[0], port); } public void Init() { #region Old mechanism... StartThread(); #endregion } private Socket PrepareToConnect(Socket client) { client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 1); if (_bindIP != null) { try { client.Bind(_bindIP); } catch (Exception) { throw new Exception("Invalid bind-ip-address specified in client configuration"); } } _forcedDisconnect = false; return client; } internal void ConnectSecondarySocket(IPAddress address, int port) { _secondaryClient = PrepareToConnect(_secondaryClient); IPEndPoint endPoint = new IPEndPoint(address, port); try { _secondaryClient.Connect(endPoint); } catch (Exception e) { if (_logger.IsErrorLogsEnabled) _logger.NCacheLog.Error("Connection.Connect", " can not connect to " + address + ":" + port + ". error: " + e.ToString()); } } /// <summary> /// it transfers the existing connection to a new connection without changing the object container /// </summary> /// <param name="container"></param> /// <param name="commandRecieved"></param> /// <param name="serverLost"></param> /// <param name="logs"></param> /// <param name="perfStatsCollector"></param> /// <param name="rspIntegraotr"></param> /// <param name="bindIP"></param> /// <param name="cacheName"></param> /// <param name="ipAddress"></param> /// <param name="cachePort"></param> /// <returns></returns> public bool SwitchTo(Broker container, OnCommandRecieved commandRecieved, OnServerLost serverLost, Logs logs, StatisticsCounter perfStatsCollector, ResponseIntegrator rspIntegraotr, string bindIP, string cacheName, IPAddress ipAddress, int cachePort) { int oldPort = Port; Initialize(container, commandRecieved, serverLost, logs, perfStatsCollector, rspIntegraotr, bindIP, cacheName); if (this.Connect(Address, cachePort)) { _hostPort = cachePort; this.Port = oldPort; this._serverAddress = new Address(ipAddress, oldPort); return true; } this.Port = oldPort; this._serverAddress = new Address(ipAddress, oldPort); return false; } internal void Disconnect() { Disconnect(true); } internal void Disconnect(bool changeStatus) { _forcedDisconnect = true; if (changeStatus) this._connectionStatusLatch.SetStatusBit(ConnectionStatus.Disconnected, ConnectionStatus.Connected); if (_primaryReceiveThread != null && _primaryReceiveThread.ThreadState != ThreadState.Aborted && _primaryReceiveThread.ThreadState != ThreadState.AbortRequested) { try { if (_logger.NCacheLog != null) _logger.NCacheLog.Flush(); #if !NETCORE _primaryReceiveThread.Abort(); #elif NETCORE _primaryReceiveThread.Interrupt(); #endif } catch (System.Threading.ThreadAbortException) { } catch (System.Threading.ThreadInterruptedException) { } _primaryReceiveThread = null; } if (_primaryClient != null && _primaryClient.Connected) { try { _primaryClient.Shutdown(SocketShutdown.Both); } catch (SocketException) { } catch (ObjectDisposedException) { } _primaryClient.Close(); } //dispose the secondary socket if (_secondaryReceiveThread != null && _secondaryReceiveThread.ThreadState != ThreadState.Aborted && _secondaryReceiveThread.ThreadState != ThreadState.AbortRequested) { try { if (_logger.NCacheLog != null) _logger.NCacheLog.Flush(); #if !NETCORE _secondaryReceiveThread.Abort(); #elif NETCORE _secondaryReceiveThread.Interrupt(); #endif } catch (System.Threading.ThreadAbortException) { } catch (System.Threading.ThreadInterruptedException) { } _secondaryReceiveThread = null; } if (_secondaryClient != null && _secondaryClient.Connected) { try { _secondaryClient.Shutdown(SocketShutdown.Both); } catch (SocketException) { } catch (ObjectDisposedException) { } _secondaryClient.Close(); _secondaryClient = null; } IsSecured = false; } public CommandResponse RecieveCommandResponse(bool _usingSecondary = false) { if (_usingSecondary) return RecieveCommandResponse(_secondaryClient); return RecieveCommandResponse(_primaryClient); } private CommandResponse RecieveCommandResponse(Socket client) { byte[] value = null; CommandResponse cmdRespose = null; try { value = AssureRecieve(client, Optimized); ///Deserialize the response Alachisoft.NCache.Common.Protobuf.Response response = null; using (MemoryStream stream = new MemoryStream(value)) { response = ProtoBuf.Serializer.Deserialize<Alachisoft.NCache.Common.Protobuf.Response>(stream); stream.Close(); } if (response != null && response.responseType == Alachisoft.NCache.Common.Protobuf.Response.Type.RESPONSE_FRAGMENT) { response = _responseIntegrator.AddResponseFragment(this._serverAddress, response.getResponseFragment); } if (response != null) { cmdRespose = new CommandResponse(false, new Address()); cmdRespose.CacheId = this._cacheId; cmdRespose.Result = response; } } catch (SocketException e) { throw new ConnectionException(e.Message, this._serverAddress.IpAddress, this._serverAddress.Port); } return cmdRespose; } internal void AssureSendDirect(byte[] buffer, Socket client, bool checkConnected) { int dataSent = 0, dataLeft = buffer.Length; lock (_connectionMutex) { if (checkConnected && _connectionStatusLatch.IsAnyBitsSet(ConnectionStatus.Disconnected | ConnectionStatus.Connecting)) { throw new ConnectionException(this._serverAddress.IpAddress, this._serverAddress.Port); } while (dataSent < buffer.Length) { try { dataLeft = buffer.Length - dataSent; dataSent += client.Send(buffer, dataSent, dataLeft, SocketFlags.None); } catch (SocketException se) { if (se.SocketErrorCode == SocketError.NoBufferSpaceAvailable) { } else { if (_logger.IsErrorLogsEnabled) _logger.NCacheLog.Error("Connection.AssureSend().SocketException ", se.ToString()); _connectionStatusLatch.SetStatusBit(ConnectionStatus.Disconnected, ConnectionStatus.Connected); throw new ConnectionException(this._serverAddress.IpAddress, this._serverAddress.Port); } } catch (ObjectDisposedException) { if (_logger.IsErrorLogsEnabled) _logger.NCacheLog.Error("Connection.AssureSend", "socket is already closed"); if (_connectionStatusLatch.IsAnyBitsSet(ConnectionStatus.Connected)) _connectionStatusLatch.SetStatusBit(ConnectionStatus.Disconnected, ConnectionStatus.Connected); throw new ConnectionException(this._serverAddress.IpAddress, this._serverAddress.Port); } } } } internal void AssureSend(byte[] buffer, Socket client, bool checkConnected) { int dataSent = 0, dataLeft = buffer.Length; if (checkConnected && _connectionStatusLatch.IsAnyBitsSet(ConnectionStatus.Disconnected | ConnectionStatus.Connecting)) { throw new ConnectionException(this._serverAddress.IpAddress, this._serverAddress.Port); } try { _bufferedStream.Write(buffer, dataSent, dataLeft); IsIdle = false; } catch (SocketException se) { if (se.SocketErrorCode == SocketError.NoBufferSpaceAvailable) { //Thread.Sleep(30); } else { if (_logger.IsErrorLogsEnabled) _logger.NCacheLog.Error("Connection.AssureSend().SocketException ", se.ToString()); _connectionStatusLatch.SetStatusBit(ConnectionStatus.Disconnected, ConnectionStatus.Connected); throw new ConnectionException(this._serverAddress.IpAddress, this._serverAddress.Port); } } catch (ObjectDisposedException) { if (_logger.IsErrorLogsEnabled) _logger.NCacheLog.Error("Connection.AssureSend", "socket is already closed"); if (_connectionStatusLatch.IsAnyBitsSet(ConnectionStatus.Connected)) _connectionStatusLatch.SetStatusBit(ConnectionStatus.Disconnected, ConnectionStatus.Connected); throw new ConnectionException(this._serverAddress.IpAddress, this._serverAddress.Port); } } /// <summary> /// This method is used by the naggling manager to send the naggled data. /// We pass a fixed sized buffer to this method that contains the naggled data. /// One extra argument 'bytesToSent' tells how many bytes we need to send from this buffer. /// </summary> /// <param name="client"></param> /// <param name="buffer"></param> /// <param name="bytesToSent"></param> /// <param name="checkConnected"></param> internal void AssureSend(Socket client, byte[] buffer, int bytesToSent, bool checkConnected) { int dataSent = 0, dataLeft = bytesToSent; lock (_connectionMutex) { if (checkConnected && _connectionStatusLatch.IsAnyBitsSet(ConnectionStatus.Disconnected | ConnectionStatus.Connecting)) { throw new ConnectionException(this._serverAddress.IpAddress, this._serverAddress.Port); } while (dataSent < bytesToSent) { try { dataLeft = bytesToSent - dataSent; dataSent += client.Send(buffer, dataSent, dataLeft, SocketFlags.None); } catch (SocketException se) { if (se.SocketErrorCode == SocketError.NoBufferSpaceAvailable) { } else { if (_logger.IsErrorLogsEnabled) _logger.NCacheLog.Error("Connection.AssureSend", se.ToString()); _connectionStatusLatch.SetStatusBit(ConnectionStatus.Disconnected, ConnectionStatus.Connected); throw new ConnectionException(this._serverAddress.IpAddress, this._serverAddress.Port); } } } IsIdle = false; } } private void Initialize(Broker container, OnCommandRecieved commandRecieved, OnServerLost serverLost, Logs logs, StatisticsCounter perfStatsCollector, ResponseIntegrator rspIntegraotr, string bindIP, string cacheName) { _commandRecieved = null; _isConnected = true; _primaryClient = null; _secondaryClient = null; _ipAddress = string.Empty; _intendedRecipientIPAddress = string.Empty; _port = 0; _connectionMutex = new object(); s_receiveBufferSize = 2048000; _processID = AppUtil.CurrentProcess.Id; _primaryReceiveThread = null; _secondaryReceiveThread = null; _notificationsRegistered = false; _isReconnecting = false; _forcedDisconnect = false; _nagglingEnabled = false; _nagglingSize = 5 * 100 * 1024; //500k _supportDualSocket = false; _syncLock = new object(); _perfStatsColl = null; _socketSelectionMutex = new object(); _usePrimary = true; _optimized = false; _isIdle = false; _container = container; _commandRecieved = commandRecieved; _serverLost = serverLost; _logger = logs; _responseIntegrator = rspIntegraotr; _cacheId = cacheName; _perfStatsColl = perfStatsCollector; SetBindIP(bindIP); if (System.Configuration.ConfigurationSettings.AppSettings["EnableNaggling"] != null) _nagglingEnabled = Convert.ToBoolean(System.Configuration.ConfigurationSettings.AppSettings["EnableNaggling"]); //read the naggling size from app.config and covert it to bytes. if (System.Configuration.ConfigurationSettings.AppSettings["NagglingSize"] != null) _nagglingSize = 1024 * Convert.ToInt64(System.Configuration.ConfigurationSettings.AppSettings["NagglingSize"]); if (System.Configuration.ConfigurationSettings.AppSettings["EnableDualSockets"] != null) _supportDualSocket = Convert.ToBoolean(System.Configuration.ConfigurationSettings.AppSettings["EnableDualSockets"]); } private byte[] AssureRecieve(Socket client, bool optimized) { byte[] buffer = new byte[CmdSizeHolderBytesCount + (optimized ? CmdSizeHolderBytesCount : 0)]; AssureRecieve(ref buffer, client); int commandSize; try { commandSize = HelperFxn.ToInt32(buffer, 0 + (optimized ? CmdSizeHolderBytesCount : 0), CmdSizeHolderBytesCount); } catch (InvalidCastException) { string str = System.Text.UTF8Encoding.UTF8.GetString(buffer); if (_logger.IsErrorLogsEnabled) _logger.NCacheLog.Error("AssureReceive", str); throw; } if (commandSize == 0) { return new byte[0]; } buffer = new byte[commandSize]; AssureRecieve(ref buffer, client); return buffer; } private void AssureRecieve(ref byte[] buffer, Socket client) { int totalBytesRecieved = 0; int bytesRecieved = 0; do { try { bytesRecieved = client.Receive(buffer, totalBytesRecieved, buffer.Length - totalBytesRecieved, SocketFlags.None); if (bytesRecieved == 0) throw new SocketException((int)SocketError.ConnectionReset); totalBytesRecieved += bytesRecieved; } catch (SocketException se) { if (se.SocketErrorCode != SocketError.NoBufferSpaceAvailable) throw; } } while (totalBytesRecieved < buffer.Length); IsIdle = false; } #region SSL/TLS secured connection related methods #endregion internal void SendCommand(byte[] commandBytes, bool checkConnected) { if (_perfStatsColl.IsEnabled) _perfStatsColl.IncrementClientRequestsPerSecStats(1); byte[] dataWithSize = new byte[commandBytes.Length + MessageHeader]; byte[] lengthBytes = HelperFxn.ToBytes(commandBytes.Length.ToString()); Buffer.BlockCopy(lengthBytes, 0, dataWithSize, 0, lengthBytes.Length); Buffer.BlockCopy(commandBytes, 0, dataWithSize, MessageHeader, commandBytes.Length); if (SupportDualSocket) { Socket selectedSocket = _primaryClient; lock (_socketSelectionMutex) { if (!_usePrimary) selectedSocket = _secondaryClient; _usePrimary = !_usePrimary; } AssureSend(dataWithSize, selectedSocket, checkConnected); } else { AssureSend(dataWithSize, _primaryClient, checkConnected); } } private void OnServerLost() { if (_forcedDisconnect) { if (_logger.IsErrorLogsEnabled) _logger.NCacheLog.Error("Connection.ReceivedThread", "Connection with server lost gracefully"); } else if (_logger.IsErrorLogsEnabled) _logger.NCacheLog.Error("Connection.ReceivedThread", "An established connection with the server " + _serverAddress + " is lost."); if (!_forcedDisconnect) _connectionStatusLatch.SetStatusBit(ConnectionStatus.Disconnected, ConnectionStatus.Connected); _serverLost(_serverAddress, _forcedDisconnect); } internal void StartThread() { _primaryReceiveThread = new Thread(new ParameterizedThreadStart(RecieveThread)); _primaryReceiveThread.Priority = ThreadPriority.AboveNormal; _primaryReceiveThread.IsBackground = true; _primaryReceiveThread.Start((object)_primaryClient); if (SupportDualSocket) { _secondaryReceiveThread = new Thread(new ParameterizedThreadStart(RecieveThread)); _secondaryReceiveThread.Priority = ThreadPriority.AboveNormal; _secondaryReceiveThread.IsBackground = true; _secondaryReceiveThread.Start((object)_secondaryClient); } } private void RecieveThread(object client) { Socket clientSocket = client as Socket; int count; while (true) { try { count = 0; byte[] cmdBytes = null; if (clientSocket != null) cmdBytes = AssureRecieve(clientSocket, false); using (Stream tempStream = new ClusteredMemoryStream(cmdBytes)) { tempStream.Position = 0; while (tempStream.Position < tempStream.Length) { ProcessResponse(tempStream); count++; } } // Broker.AverageCounterRecieve.IncrementBy(count); } catch (SocketException se) { OnConnectionBroken(se, ExType.Socket); break; } catch (IOException ie) { //System.IOException is going to thrown in the case SslStream when the connection gets forcibly closed. //Thus we are going to handle it as a SocketException.... OnConnectionBroken(ie, ExType.Socket); break; } catch (ConnectionException ce) { OnConnectionBroken(ce, ExType.Connection); break; } catch (ThreadAbortException te) { OnConnectionBroken(te, ExType.Abort); break; } catch (ThreadInterruptedException tae) { OnConnectionBroken(tae, ExType.Interrupt); break; } catch (Exception e) { OnConnectionBroken(e, ExType.General); break; } } } private void OnConnectionBroken(Exception e, ExType exType) { try { if (_logger != null ) switch (exType) { case ExType.Socket: case ExType.Connection: if (_forcedDisconnect) { if (_logger.IsErrorLogsEnabled) _logger.NCacheLog.Error("Connection.ReceivedThread", "Connection with server lost gracefully"); } else if (_logger.IsErrorLogsEnabled) _logger.NCacheLog.Error("Connection.ReceivedThread", "An established connection with the server " + _serverAddress + " is lost. Error:" + e.ToString()); if (!_forcedDisconnect) _connectionStatusLatch.SetStatusBit(ConnectionStatus.Disconnected, ConnectionStatus.Connected); _primaryReceiveThread = null; _serverLost(_serverAddress, _forcedDisconnect); break; case ExType.Interrupt: case ExType.Abort: if (AppDomain.CurrentDomain.IsFinalizingForUnload()) return; if (_forcedDisconnect) { if (_logger.IsErrorLogsEnabled) { _logger.NCacheLog.Error("Connection.ReceivedThread", "Connection with server lost gracefully"); _logger.NCacheLog.Flush(); } } if (!_forcedDisconnect) _connectionStatusLatch.SetStatusBit(ConnectionStatus.Disconnected, ConnectionStatus.Connected); _serverLost(_serverAddress, _forcedDisconnect); break; case ExType.General: if (_logger.IsErrorLogsEnabled) { _logger.NCacheLog.Error("Connection.ReceivedThread", e.ToString()); _logger.NCacheLog.Flush(); } if (!_forcedDisconnect) _connectionStatusLatch.SetStatusBit(ConnectionStatus.Disconnected, ConnectionStatus.Connected); _serverLost(_serverAddress, _forcedDisconnect); break; } IsSecured = false; } catch (Exception ex) { AppUtil.LogEvent($"OnConnectionBroken : {ex.ToString()} inner exception: {e.ToString()}", System.Diagnostics.EventLogEntryType.Warning); } } public static bool WriteRequestIdInResponse = true; /// <summary> /// Reads a single single response from the stream and processes it. /// </summary> /// <param name="stream"></param> private void ProcessResponse(Stream stream) { Response response; long requestId = 0; if (WriteRequestIdInResponse) { byte[] requestIdBytes = new byte[sizeof(long)]; stream.Read(requestIdBytes, 0, requestIdBytes.Length); requestId = BitConverter.ToInt64(requestIdBytes, 0); } byte[] responseTypeBytes = new byte[2]; stream.Read(responseTypeBytes, 0, responseTypeBytes.Length); Response.Type responseType = (Response.Type)BitConverter.ToInt16(responseTypeBytes, 0); //Reading a response's header... byte[] cmdSzBytes = new byte[CmdSizeHolderBytesCount]; stream.Read(cmdSzBytes, 0, CmdSizeHolderBytesCount); int commandSize = HelperFxn.ToInt32(cmdSzBytes, 0, CmdSizeHolderBytesCount); byte[] cmdBytes = new byte[commandSize]; stream.Read(cmdBytes, 0, commandSize); CommandResponse cmdRespose = new CommandResponse(false, new Address()); cmdRespose.CacheId = _cacheId; cmdRespose.Src = this.ServerAddress; if (WriteRequestIdInResponse) { cmdRespose.NeedsDeserialization = true; cmdRespose.RequestId = requestId; cmdRespose.SerializedResponse = cmdBytes; cmdRespose.Type = responseType; } else { using (Stream tempStream = new ClusteredMemoryStream(cmdBytes)) response = ResponseHelper.DeserializeResponse(responseType, tempStream); cmdRespose.NeedsDeserialization = false; if (response != null) cmdRespose.Result = response; } if (_perfStatsColl.IsEnabled) { _perfStatsColl.IncrementClientResponsesPerSecStats(1); } if (cmdRespose != null) { _container.ProcessResponse(cmdRespose, _serverAddress); } } #region Physcial Bridge private bool WriteMessageDirect(CommandBase command) { //SendCommand(command.Serialized, true); SendCommand(command.ToByte(command.AcknowledgmentId, RequestInquiryEnabled), true); return true; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using Xunit; namespace System.Net.Tests { public class ServicePointManagerTest : RemoteExecutorTestBase { [Fact] public static void RequireEncryption_ExpectedDefault() { RemoteInvoke(() => Assert.Equal(EncryptionPolicy.RequireEncryption, ServicePointManager.EncryptionPolicy)); } [Fact] public static void CheckCertificateRevocationList_Roundtrips() { RemoteInvoke(() => { Assert.False(ServicePointManager.CheckCertificateRevocationList); ServicePointManager.CheckCertificateRevocationList = true; Assert.True(ServicePointManager.CheckCertificateRevocationList); ServicePointManager.CheckCertificateRevocationList = false; Assert.False(ServicePointManager.CheckCertificateRevocationList); }); } [Fact] public static void DefaultConnectionLimit_Roundtrips() { RemoteInvoke(() => { Assert.Equal(2, ServicePointManager.DefaultConnectionLimit); ServicePointManager.DefaultConnectionLimit = 20; Assert.Equal(20, ServicePointManager.DefaultConnectionLimit); ServicePointManager.DefaultConnectionLimit = 2; Assert.Equal(2, ServicePointManager.DefaultConnectionLimit); }); } [Fact] public static void DnsRefreshTimeout_Roundtrips() { RemoteInvoke(() => { Assert.Equal(120000, ServicePointManager.DnsRefreshTimeout); ServicePointManager.DnsRefreshTimeout = 42; Assert.Equal(42, ServicePointManager.DnsRefreshTimeout); ServicePointManager.DnsRefreshTimeout = 120000; Assert.Equal(120000, ServicePointManager.DnsRefreshTimeout); }); } [Fact] public static void EnableDnsRoundRobin_Roundtrips() { RemoteInvoke(() => { Assert.False(ServicePointManager.EnableDnsRoundRobin); ServicePointManager.EnableDnsRoundRobin = true; Assert.True(ServicePointManager.EnableDnsRoundRobin); ServicePointManager.EnableDnsRoundRobin = false; Assert.False(ServicePointManager.EnableDnsRoundRobin); }); } [Fact] public static void Expect100Continue_Roundtrips() { RemoteInvoke(() => { Assert.True(ServicePointManager.Expect100Continue); ServicePointManager.Expect100Continue = false; Assert.False(ServicePointManager.Expect100Continue); ServicePointManager.Expect100Continue = true; Assert.True(ServicePointManager.Expect100Continue); }); } [Fact] public static void MaxServicePointIdleTime_Roundtrips() { RemoteInvoke(() => { Assert.Equal(100000, ServicePointManager.MaxServicePointIdleTime); ServicePointManager.MaxServicePointIdleTime = 42; Assert.Equal(42, ServicePointManager.MaxServicePointIdleTime); ServicePointManager.MaxServicePointIdleTime = 100000; Assert.Equal(100000, ServicePointManager.MaxServicePointIdleTime); }); } [Fact] public static void MaxServicePoints_Roundtrips() { RemoteInvoke(() => { Assert.Equal(0, ServicePointManager.MaxServicePoints); ServicePointManager.MaxServicePoints = 42; Assert.Equal(42, ServicePointManager.MaxServicePoints); ServicePointManager.MaxServicePoints = 0; Assert.Equal(0, ServicePointManager.MaxServicePoints); }); } [Fact] public static void ReusePort_Roundtrips() { RemoteInvoke(() => { Assert.False(ServicePointManager.ReusePort); ServicePointManager.ReusePort = true; Assert.True(ServicePointManager.ReusePort); ServicePointManager.ReusePort = false; Assert.False(ServicePointManager.ReusePort); }); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Desktop default SecurityProtocol to Ssl3; explicitly changed to SystemDefault for core.")] public static void SecurityProtocol_Roundtrips() { RemoteInvoke(() => { var orig = (SecurityProtocolType)0; // SystemDefault. Assert.Equal(orig, ServicePointManager.SecurityProtocol); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11; Assert.Equal(SecurityProtocolType.Tls11, ServicePointManager.SecurityProtocol); ServicePointManager.SecurityProtocol = orig; Assert.Equal(orig, ServicePointManager.SecurityProtocol); }); } [Fact] public static void ServerCertificateValidationCallback_Roundtrips() { RemoteInvoke(() => { Assert.Null(ServicePointManager.ServerCertificateValidationCallback); RemoteCertificateValidationCallback callback = delegate { return true; }; ServicePointManager.ServerCertificateValidationCallback = callback; Assert.Same(callback, ServicePointManager.ServerCertificateValidationCallback); ServicePointManager.ServerCertificateValidationCallback = null; Assert.Null(ServicePointManager.ServerCertificateValidationCallback); }); } [Fact] public static void UseNagleAlgorithm_Roundtrips() { RemoteInvoke(() => { Assert.True(ServicePointManager.UseNagleAlgorithm); ServicePointManager.UseNagleAlgorithm = false; Assert.False(ServicePointManager.UseNagleAlgorithm); ServicePointManager.UseNagleAlgorithm = true; Assert.True(ServicePointManager.UseNagleAlgorithm); }); } [Fact] public static void InvalidArguments_Throw() { RemoteInvoke(() => { const int ssl2Client = 0x00000008; const int ssl2Server = 0x00000004; const SecurityProtocolType ssl2 = (SecurityProtocolType)(ssl2Client | ssl2Server); Assert.Throws<NotSupportedException>(() => ServicePointManager.SecurityProtocol = ssl2); AssertExtensions.Throws<ArgumentNullException>("uriString", () => ServicePointManager.FindServicePoint((string)null, null)); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => ServicePointManager.MaxServicePoints = -1); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => ServicePointManager.DefaultConnectionLimit = 0); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => ServicePointManager.MaxServicePointIdleTime = -2); AssertExtensions.Throws<ArgumentOutOfRangeException>("keepAliveTime", () => ServicePointManager.SetTcpKeepAlive(true, -1, 1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("keepAliveInterval", () => ServicePointManager.SetTcpKeepAlive(true, 1, -1)); AssertExtensions.Throws<ArgumentNullException>("address", () => ServicePointManager.FindServicePoint(null)); AssertExtensions.Throws<ArgumentNullException>("uriString", () => ServicePointManager.FindServicePoint((string)null, null)); AssertExtensions.Throws<ArgumentNullException>("address", () => ServicePointManager.FindServicePoint((Uri)null, null)); Assert.Throws<NotSupportedException>(() => ServicePointManager.FindServicePoint("http://anything", new FixedWebProxy("https://anything"))); ServicePoint sp = ServicePointManager.FindServicePoint("http://" + Guid.NewGuid().ToString("N"), null); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => sp.ConnectionLeaseTimeout = -2); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => sp.ConnectionLimit = 0); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => sp.MaxIdleTime = -2); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => sp.ReceiveBufferSize = -2); AssertExtensions.Throws<ArgumentOutOfRangeException>("keepAliveTime", () => sp.SetTcpKeepAlive(true, -1, 1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("keepAliveInterval", () => sp.SetTcpKeepAlive(true, 1, -1)); }); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Ssl3 is supported by desktop but explicitly not by core")] [Fact] public static void SecurityProtocol_Ssl3_NotSupported() { RemoteInvoke(() => { const int ssl2Client = 0x00000008; const int ssl2Server = 0x00000004; const SecurityProtocolType ssl2 = (SecurityProtocolType)(ssl2Client | ssl2Server); #pragma warning disable 0618 // Ssl2, Ssl3 are deprecated. Assert.Throws<NotSupportedException>(() => ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3); Assert.Throws<NotSupportedException>(() => ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | ssl2); #pragma warning restore }); } [Fact] public static void FindServicePoint_ReturnsCachedServicePoint() { RemoteInvoke(() => { const string Localhost = "http://localhost"; string address1 = "http://" + Guid.NewGuid().ToString("N"); string address2 = "http://" + Guid.NewGuid().ToString("N"); Assert.NotNull(ServicePointManager.FindServicePoint(new Uri(address1))); Assert.Same( ServicePointManager.FindServicePoint(address1, null), ServicePointManager.FindServicePoint(address1, null)); Assert.Same( ServicePointManager.FindServicePoint(address1, new FixedWebProxy(address1)), ServicePointManager.FindServicePoint(address1, new FixedWebProxy(address1))); Assert.Same( ServicePointManager.FindServicePoint(address1, new FixedWebProxy(address1)), ServicePointManager.FindServicePoint(address2, new FixedWebProxy(address1))); Assert.Same( ServicePointManager.FindServicePoint(Localhost, new FixedWebProxy(address1)), ServicePointManager.FindServicePoint(Localhost, new FixedWebProxy(address2))); Assert.NotSame( ServicePointManager.FindServicePoint(address1, null), ServicePointManager.FindServicePoint(address2, null)); Assert.NotSame( ServicePointManager.FindServicePoint(address1, null), ServicePointManager.FindServicePoint(address1, new FixedWebProxy(address1))); Assert.NotSame( ServicePointManager.FindServicePoint(address1, new FixedWebProxy(address1)), ServicePointManager.FindServicePoint(address1, new FixedWebProxy(address2))); }); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Desktop ServicePoint lifetime is slightly longer due to implementation details of real implementation")] public static void FindServicePoint_Collectible() { RemoteInvoke(() => { string address = "http://" + Guid.NewGuid().ToString("N"); bool initial = GetExpect100Continue(address); SetExpect100Continue(address, !initial); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); Assert.Equal(initial, GetExpect100Continue(address)); }); } [Fact] public static void FindServicePoint_ReturnedServicePointMatchesExpectedValues() { RemoteInvoke(() => { string address = "http://" + Guid.NewGuid().ToString("N"); DateTime start = DateTime.Now; ServicePoint sp = ServicePointManager.FindServicePoint(address, null); Assert.InRange(sp.IdleSince, start, DateTime.MaxValue); Assert.Equal(new Uri(address), sp.Address); Assert.Null(sp.BindIPEndPointDelegate); Assert.Null(sp.Certificate); Assert.Null(sp.ClientCertificate); Assert.Equal(-1, sp.ConnectionLeaseTimeout); Assert.Equal("http", sp.ConnectionName); Assert.Equal(0, sp.CurrentConnections); Assert.Equal(true, sp.Expect100Continue); Assert.Equal(100000, sp.MaxIdleTime); Assert.Equal(new Version(1, 1), sp.ProtocolVersion); Assert.Equal(-1, sp.ReceiveBufferSize); Assert.True(sp.SupportsPipelining, "SupportsPipelining"); Assert.True(sp.UseNagleAlgorithm, "UseNagleAlgorithm"); }); } [Fact] public static void FindServicePoint_PropertiesRoundtrip() { RemoteInvoke(() => { string address = "http://" + Guid.NewGuid().ToString("N"); BindIPEndPoint expectedBindIPEndPointDelegate = delegate { return null; }; int expectedConnectionLeaseTimeout = 42; int expectedConnectionLimit = 84; bool expected100Continue = false; int expectedMaxIdleTime = 200000; int expectedReceiveBufferSize = 123; bool expectedUseNagleAlgorithm = false; ServicePoint sp1 = ServicePointManager.FindServicePoint(address, null); sp1.BindIPEndPointDelegate = expectedBindIPEndPointDelegate; sp1.ConnectionLeaseTimeout = expectedConnectionLeaseTimeout; sp1.ConnectionLimit = expectedConnectionLimit; sp1.Expect100Continue = expected100Continue; sp1.MaxIdleTime = expectedMaxIdleTime; sp1.ReceiveBufferSize = expectedReceiveBufferSize; sp1.UseNagleAlgorithm = expectedUseNagleAlgorithm; ServicePoint sp2 = ServicePointManager.FindServicePoint(address, null); Assert.Same(expectedBindIPEndPointDelegate, sp2.BindIPEndPointDelegate); Assert.Equal(expectedConnectionLeaseTimeout, sp2.ConnectionLeaseTimeout); Assert.Equal(expectedConnectionLimit, sp2.ConnectionLimit); Assert.Equal(expected100Continue, sp2.Expect100Continue); Assert.Equal(expectedMaxIdleTime, sp2.MaxIdleTime); Assert.Equal(expectedReceiveBufferSize, sp2.ReceiveBufferSize); Assert.Equal(expectedUseNagleAlgorithm, sp2.UseNagleAlgorithm); }); } [Fact] public static void FindServicePoint_NewServicePointsInheritCurrentValues() { RemoteInvoke(() => { string address1 = "http://" + Guid.NewGuid().ToString("N"); string address2 = "http://" + Guid.NewGuid().ToString("N"); bool orig100Continue = ServicePointManager.Expect100Continue; bool origNagle = ServicePointManager.UseNagleAlgorithm; ServicePointManager.Expect100Continue = false; ServicePointManager.UseNagleAlgorithm = false; ServicePoint sp1 = ServicePointManager.FindServicePoint(address1, null); Assert.False(sp1.Expect100Continue); Assert.False(sp1.UseNagleAlgorithm); ServicePointManager.Expect100Continue = true; ServicePointManager.UseNagleAlgorithm = true; ServicePoint sp2 = ServicePointManager.FindServicePoint(address2, null); Assert.True(sp2.Expect100Continue); Assert.True(sp2.UseNagleAlgorithm); Assert.False(sp1.Expect100Continue); Assert.False(sp1.UseNagleAlgorithm); ServicePointManager.Expect100Continue = orig100Continue; ServicePointManager.UseNagleAlgorithm = origNagle; }); } // Separated out to avoid the JIT in debug builds interfering with object lifetimes private static bool GetExpect100Continue(string address) => ServicePointManager.FindServicePoint(address, null).Expect100Continue; private static void SetExpect100Continue(string address, bool value) => ServicePointManager.FindServicePoint(address, null).Expect100Continue = value; private sealed class FixedWebProxy : IWebProxy { private readonly Uri _proxyAddress; public FixedWebProxy(string proxyAddress) { _proxyAddress = new Uri(proxyAddress); } public Uri GetProxy(Uri destination) => _proxyAddress; public bool IsBypassed(Uri host) => false; public ICredentials Credentials { get; set; } } } }
using System; using System.IO; using System.Threading; using System.Collections; namespace Chat { public delegate void PacketReadHandler(Packet packet); public delegate void LinkBrokenHandler(ChatLink chatLink); /// <summary> /// ChatLink constitutes the link layer communication protocol and enables secure transmission /// of packets. Each packet sent through the ChatLink has a strict structure, and once sent, /// the ChatLink will block until an acknowledgement on the packet has been received. /// </summary> public class ChatLink { /// <summary> /// A DataStream instance that allows us to read primitives from the stream. /// </summary> private DataStream dataStream = null; /// <summary> /// We'll synchronize with this event when awaiting an acknowledgement /// </summary> private ManualResetEvent ackEvent = new ManualResetEvent(false); /// <summary> /// The latest ack that was received /// </summary> private Packet ack = null; /// <summary> /// The number of packets written. Used to compute a sequence number for outgoing packages. /// </summary> private byte packetsWritten = 0; /// <summary> /// A queue for outgoing packages. We'll let a thread consume packets available on this queue. /// This is necessary since we don't want to block the main thread. /// </summary> private ArrayList writeQueue = new ArrayList(); /// <summary> /// The TX thread will synchronize against this event. /// </summary> private ManualResetEvent writeEvent = new ManualResetEvent(false); /// <summary> /// Whether or not the link is opened /// </summary> private bool opened = true; /// <summary> /// Event that is raised whenever a packet is read /// </summary> public event PacketReadHandler OnPacketRead; /// <summary> /// Event that is raised whenever the link is broken. /// </summary> public event LinkBrokenHandler LinkBroken; /// <summary> /// Creates a new chat link that operates on the provided stream. /// </summary> /// <param name="stream">The stream from which to read data from and write data to.</param> public ChatLink(Stream stream) { dataStream = new DataStream(stream); new Thread(new ThreadStart(ReadFromStream)).Start(); new Thread(new ThreadStart(WriteToStream)).Start(); } /// <summary> /// Write a packet to the stream. This method will write the packet and await an acknowledgement. /// </summary> /// <param name="packet">The packet to write.</param> public void Write(Packet packet) { writeQueue.Add(packet); writeEvent.Set(); } /// <summary> /// Closes the link. /// </summary> public void Close() { opened = false; // Release any threads that might be blocked // writeEvent.Set(); ackEvent.Set(); dataStream.Close(); if(LinkBroken != null) { LinkBroken(this); } } #region Private methods private void WriteToStream() { while(opened) { while(writeQueue.Count > 0) { Packet packet = (Packet)writeQueue[0]; writeQueue.RemoveAt(0); try { if(!Write0(packet)) { Close(); break; } } catch (Exception) { Close(); break; } } writeEvent.WaitOne(); writeEvent.Reset(); } } private bool Write0(Packet packet) { bool acknowledged = false; for(int i = 0; i < 5 && opened && !acknowledged; i++) { ackEvent.Reset(); // Assign a sequence number // packet.SequenceNumber = packetsWritten++; lock(this) { // Write the start bytes // dataStream.WriteShort(0x1003); // Start computing checksum // dataStream.ComputeOutputChecksum = true; // Write the contents of the packet // dataStream.WriteByte((byte)packet.PacketType); dataStream.WriteByte(packet.SequenceNumber); dataStream.WriteShort((short)packet.Data.Length); dataStream.Write(packet.Data, 0, packet.Data.Length); // Write the checksum // dataStream.WriteInt(dataStream.OutputChecksum); // Write the end-of-packet bytes // dataStream.WriteByte(0x03); } dataStream.Flush(); // Check if we're sending an ack // if(packet.PacketType == PacketType.Ack || packet.PacketType == PacketType.Nak) { break; } // Await an ack // ackEvent.WaitOne(); ackEvent.Reset(); acknowledged = (ack.PacketType == PacketType.Ack); } return acknowledged; } private void SendAck(int sequenceNumber, bool positive) { Packet packet = new Packet(); packet.PacketType = (positive ? PacketType.Ack : PacketType.Nak); packet.Data = new byte[] { (byte)(( sequenceNumber >> 24 ) & 0xFF), (byte)(( sequenceNumber >> 16 ) & 0xFF), (byte)(( sequenceNumber >> 8 ) & 0xFF), (byte)(( sequenceNumber >> 0 ) & 0xFF) }; Write0(packet); } private void ReadFromStream() { while(opened) { Packet packet = null; try { packet = Read0(); } catch (Exception) { Close(); break; } if(packet == null) { break; } else { if(packet.PacketType == PacketType.Ack || packet.PacketType == PacketType.Nak) { ack = packet; ackEvent.Set(); } else { if(OnPacketRead != null) { OnPacketRead(packet); } } } } } private Packet Read0() { while(opened && dataStream.Await(new byte[] { 0x10, 0x03 })) { Packet packet = new Packet(); int length = 0; // Start computing checksum on the incoming data // dataStream.ComputeInputChecksum = true; // Read the contents of the packet // packet.PacketType = (PacketType)dataStream.ReadByte(); packet.SequenceNumber = (byte)dataStream.ReadByte(); length = dataStream.ReadShort(); // Check that the length is less than the MTU // if(length <= 4096) { // Allocate a new buffer for the data // packet.Data = new byte[length]; // Read the contents of the packet // dataStream.Read(packet.Data, 0, length); // Fetch the computed input checksum // int checksum = dataStream.InputChecksum; // Read the provided input checksum // packet.Checksum = dataStream.ReadInt(); // Verify that the next byte is an EOP identifier // if(dataStream.ReadByte() == 0x03) { if(packet.Checksum == checksum) { if(packet.PacketType != PacketType.Ack && packet.PacketType != PacketType.Nak) { SendAck(packet.SequenceNumber, true); } return packet; } } } if(packet.PacketType != PacketType.Ack && packet.PacketType != PacketType.Nak) { SendAck(packet.SequenceNumber, false); } } return null; } } #endregion }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #if !SILVERLIGHT using System; using System.IO; using System.Runtime; using System.Runtime.Serialization; using System.Security.Principal; using System.Diagnostics.Contracts; namespace System.Net { // Summary: // Makes a request to a Uniform Resource Identifier (URI). This is an abstract // class. public abstract class WebRequest //: MarshalByRefObject, ISerializable { // Summary: // Initializes a new instance of the System.Net.WebRequest class. protected WebRequest() { } // // Summary: // Initializes a new instance of the System.Net.WebRequest class from the specified // instances of the System.Runtime.Serialization.SerializationInfo and System.Runtime.Serialization.StreamingContext // classes. // // Parameters: // serializationInfo: // A System.Runtime.Serialization.SerializationInfo that contains the information // required to serialize the new System.Net.WebRequest instance. // // streamingContext: // A System.Runtime.Serialization.StreamingContext that indicates the source // of the serialized stream associated with the new System.Net.WebRequest instance. // // Exceptions: // System.NotImplementedException: // Any attempt is made to access the constructor, when the constructor is not // overridden in a descendant class. //[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] //protected WebRequest(SerializationInfo serializationInfo, StreamingContext streamingContext) { } // Summary: // Gets or sets values indicating the level of authentication and impersonation // used for this request. // // Returns: // A bitwise combination of the System.Net.Security.AuthenticationLevel values. // The default value is System.Net.Security.AuthenticationLevel.MutualAuthRequested.In // mutual authentication, both the client and server present credentials to // establish their identity. The System.Net.Security.AuthenticationLevel.MutualAuthRequired // and System.Net.Security.AuthenticationLevel.MutualAuthRequested values are // relevant for Kerberos authentication. Kerberos authentication can be supported // directly, or can be used if the Negotiate security protocol is used to select // the actual security protocol. For more information about authentication protocols, // see Internet Authentication.To determine whether mutual authentication occurred, // check the System.Net.WebResponse.IsMutuallyAuthenticated property. If you // specify the System.Net.Security.AuthenticationLevel.MutualAuthRequired authentication // flag value and mutual authentication does not occur, your application will // receive an System.IO.IOException with a System.Net.ProtocolViolationException // inner exception indicating that mutual authentication failed. //public AuthenticationLevel AuthenticationLevel { get; set; } // // Summary: // Gets or sets the cache policy for this request. // // Returns: // A System.Net.Cache.RequestCachePolicy object that defines a cache policy. //public virtual RequestCachePolicy CachePolicy { get; set; } // // Summary: // When overridden in a descendant class, gets or sets the name of the connection // group for the request. // // Returns: // The name of the connection group for the request. // // Exceptions: // System.NotImplementedException: // Any attempt is made to get or set the property, when the property is not // overridden in a descendant class. //public virtual string ConnectionGroupName { get; set; } // // Summary: // When overridden in a descendant class, gets or sets the content length of // the request data being sent. // // Returns: // The number of bytes of request data being sent. // // Exceptions: // System.NotImplementedException: // Any attempt is made to get or set the property, when the property is not // overridden in a descendant class. //public virtual long ContentLength { get; set; } // // Summary: // When overridden in a descendant class, gets or sets the content type of the // request data being sent. // // Returns: // The content type of the request data. // // Exceptions: // System.NotImplementedException: // Any attempt is made to get or set the property, when the property is not // overridden in a descendant class. //public virtual string ContentType { get; set; } // // Summary: // When overridden in a descendant class, gets or sets the network credentials // used for authenticating the request with the Internet resource. // // Returns: // An System.Net.ICredentials containing the authentication credentials associated // with the request. The default is null. // // Exceptions: // System.NotImplementedException: // Any attempt is made to get or set the property, when the property is not // overridden in a descendant class. //public virtual ICredentials Credentials { get; set; } // // Summary: // Gets or sets the default cache policy for this request. // // Returns: // A System.Net.Cache.HttpRequestCachePolicy that specifies the cache policy // in effect for this request when no other policy is applicable. //public static RequestCachePolicy DefaultCachePolicy { get; set; } // // Summary: // Gets or sets the global HTTP proxy. // // Returns: // An System.Net.IWebProxy used by every call to instances of System.Net.WebRequest. public static IWebProxy DefaultWebProxy { get { return default(IWebProxy); } set { } } // // Summary: // When overridden in a descendant class, gets or sets the collection of header // name/value pairs associated with the request. // // Returns: // A System.Net.WebHeaderCollection containing the header name/value pairs associated // with this request. // // Exceptions: // System.NotImplementedException: // Any attempt is made to get or set the property, when the property is not // overridden in a descendant class. public virtual WebHeaderCollection Headers { get { Contract.Ensures(Contract.Result<WebHeaderCollection>() != null); return null; } set { } } // // Summary: // Gets or sets the impersonation level for the current request. // // Returns: // A System.Security.Principal.TokenImpersonationLevel value. //extern public TokenImpersonationLevel ImpersonationLevel { get; set; } // // Summary: // When overridden in a descendant class, gets or sets the protocol method to // use in this request. // // Returns: // The protocol method to use in this request. // // Exceptions: // System.NotImplementedException: // If the property is not overridden in a descendant class, any attempt is made // to get or set the property. public virtual string Method { get { Contract.Ensures(!String.IsNullOrEmpty(Contract.Result<string>())); return null; } set { Contract.Requires(!String.IsNullOrEmpty(value)); } } // // Summary: // When overridden in a descendant class, indicates whether to pre-authenticate // the request. // // Returns: // true to pre-authenticate; otherwise, false. // // Exceptions: // System.NotImplementedException: // Any attempt is made to get or set the property, when the property is not // overridden in a descendant class. extern public virtual bool PreAuthenticate { get; set; } // // Summary: // When overridden in a descendant class, gets or sets the network proxy to // use to access this Internet resource. // // Returns: // The System.Net.IWebProxy to use to access the Internet resource. // // Exceptions: // System.NotImplementedException: // Any attempt is made to get or set the property, when the property is not // overridden in a descendant class. public virtual IWebProxy Proxy { get { // default is not null, but it's possible to set proxy to null. return default(IWebProxy); } set { } } // // Summary: // When overridden in a descendant class, gets the URI of the Internet resource // associated with the request. // // Returns: // A System.Uri representing the resource associated with the request // // Exceptions: // System.NotImplementedException: // Any attempt is made to get or set the property, when the property is not // overridden in a descendant class. //public virtual Uri RequestUri { get; } // // Summary: // Gets or sets the length of time, in milliseconds, before the request times // out. // // Returns: // The length of time, in milliseconds, until the request times out, or the // value System.Threading.Timeout.Infinite to indicate that the request does // not time out. The default value is defined by the descendant class. // // Exceptions: // System.NotImplementedException: // Any attempt is made to get or set the property, when the property is not // overridden in a descendant class. //public virtual int Timeout { get; set; } // // Summary: // When overridden in a descendant class, gets or sets a System.Boolean value // that controls whether System.Net.CredentialCache.DefaultCredentials are sent // with requests. // // Returns: // true if the default credentials are used; otherwise false. The default value // is false. // // Exceptions: // System.InvalidOperationException: // You attempted to set this property after the request was sent. //public virtual bool UseDefaultCredentials { get; set; } // Summary: // Aborts the Request // // Exceptions: // System.NotImplementedException: // Any attempt is made to access the method, when the method is not overridden // in a descendant class. //public virtual void Abort(); // // Summary: // When overridden in a descendant class, provides an asynchronous version of // the System.Net.WebRequest.GetRequestStream() method. // // Parameters: // callback: // The System.AsyncCallback delegate. // // state: // An object containing state information for this asynchronous request. // // Returns: // An System.IAsyncResult that references the asynchronous request. // // Exceptions: // System.NotImplementedException: // Any attempt is made to access the method, when the method is not overridden // in a descendant class. public virtual IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state) { Contract.Ensures(Contract.Result<IAsyncResult>() != null); return null; } // // Summary: // When overridden in a descendant class, begins an asynchronous request for // an Internet resource. // // Parameters: // callback: // The System.AsyncCallback delegate. // // state: // An object containing state information for this asynchronous request. // // Returns: // An System.IAsyncResult that references the asynchronous request. // // Exceptions: // System.NotImplementedException: // Any attempt is made to access the method, when the method is not overridden // in a descendant class. public virtual IAsyncResult BeginGetResponse(AsyncCallback callback, object state) { Contract.Ensures(Contract.Result<IAsyncResult>() != null); return null; } // // Summary: // Initializes a new System.Net.WebRequest instance for the specified URI scheme. // // Parameters: // requestUriString: // The URI that identifies the Internet resource. // // Returns: // A System.Net.WebRequest descendant for the specific URI scheme. // // Exceptions: // System.NotSupportedException: // The request scheme specified in requestUriString has not been registered. // // System.ArgumentNullException: // requestUriString is null. // // System.Security.SecurityException: // The caller does not have permission to connect to the requested URI or a // URI that the request is redirected to. // // System.UriFormatException: // The URI specified in requestUriString is not a valid URI. public static WebRequest Create(string requestUriString) { Contract.Requires(requestUriString != null); Contract.Ensures(Contract.Result<WebRequest>() != null); return default(WebRequest); } // // Summary: // Initializes a new System.Net.WebRequest instance for the specified URI scheme. // // Parameters: // requestUri: // A System.Uri containing the URI of the requested resource. // // Returns: // A System.Net.WebRequest descendant for the specified URI scheme. // // Exceptions: // System.NotSupportedException: // The request scheme specified in requestUri is not registered. // // System.ArgumentNullException: // requestUri is null. // // System.Security.SecurityException: // The caller does not have permission to connect to the requested URI or a // URI that the request is redirected to. public static WebRequest Create(Uri requestUri) { Contract.Requires(requestUri != null); Contract.Ensures(Contract.Result<WebRequest>() != null); return default(WebRequest); } // // Summary: // Initializes a new System.Net.WebRequest instance for the specified URI scheme. // // Parameters: // requestUri: // A System.Uri containing the URI of the requested resource. // // Returns: // A System.Net.WebRequest descendant for the specified URI scheme. // // Exceptions: // System.NotSupportedException: // The request scheme specified in requestUri is not registered. // // System.ArgumentNullException: // requestUri is null. // // System.Security.SecurityException: // The caller does not have permission to connect to the requested URI or a // URI that the request is redirected to. public static WebRequest CreateDefault(Uri requestUri) { Contract.Requires(requestUri != null); Contract.Ensures(Contract.Result<WebRequest>() != null); return default(WebRequest); } // // Summary: // When overridden in a descendant class, returns a System.IO.Stream for writing // data to the Internet resource. // // Parameters: // asyncResult: // An System.IAsyncResult that references a pending request for a stream. // // Returns: // A System.IO.Stream to write data to. // // Exceptions: // System.NotImplementedException: // Any attempt is made to access the method, when the method is not overridden // in a descendant class. public virtual Stream EndGetRequestStream(IAsyncResult asyncResult) { Contract.Requires(asyncResult != null); Contract.Ensures(Contract.Result<Stream>() != null); return null; } // // Summary: // When overridden in a descendant class, returns a System.Net.WebResponse. // // Parameters: // asyncResult: // An System.IAsyncResult that references a pending request for a response. // // Returns: // A System.Net.WebResponse that contains a response to the Internet request. // // Exceptions: // System.NotImplementedException: // Any attempt is made to access the method, when the method is not overridden // in a descendant class. public virtual WebResponse EndGetResponse(IAsyncResult asyncResult) { Contract.Requires(asyncResult != null); Contract.Ensures(Contract.Result<WebResponse>() != null); return null; } // // Summary: // Populates a System.Runtime.Serialization.SerializationInfo with the data // needed to serialize the target object. // // Parameters: // serializationInfo: // The System.Runtime.Serialization.SerializationInfo to populate with data. // // streamingContext: // A System.Runtime.Serialization.StreamingContext that specifies the destination // for this serialization. //protected virtual void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext); // // Summary: // When overridden in a descendant class, returns a System.IO.Stream for writing // data to the Internet resource. // // Returns: // A System.IO.Stream for writing data to the Internet resource. // // Exceptions: // System.NotImplementedException: // Any attempt is made to access the method, when the method is not overridden // in a descendant class. public virtual Stream GetRequestStream() { Contract.Ensures(Contract.Result<Stream>() != null); return null; } // // Summary: // When overridden in a descendant class, returns a response to an Internet // request. // // Returns: // A System.Net.WebResponse containing the response to the Internet request. // // Exceptions: // System.NotImplementedException: // Any attempt is made to access the method, when the method is not overridden // in a descendant class. public virtual WebResponse GetResponse() { Contract.Ensures(Contract.Result<WebResponse>() != null); return null; } // // Summary: // Returns a proxy configured with the Internet Explorer settings of the currently // impersonated user. // // Returns: // An System.Net.IWebProxy used by every call to instances of System.Net.WebRequest. public static IWebProxy GetSystemWebProxy() { Contract.Ensures(Contract.Result<IWebProxy>() != null); return default(IWebProxy); } // // Summary: // Registers a System.Net.WebRequest descendant for the specified URI. // // Parameters: // prefix: // The complete URI or URI prefix that the System.Net.WebRequest descendant // services. // // creator: // The create method that the System.Net.WebRequest calls to create the System.Net.WebRequest // descendant. // // Returns: // true if registration is successful; otherwise, false. // // Exceptions: // System.ArgumentNullException: // prefix is null-or- creator is null. //public static bool RegisterPrefix(string prefix, IWebRequestCreate creator); } } #endif
/******************************************************************** 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. *********************************************************************/ namespace Multiverse.Tools.MosaicCreator { partial class MosaicCreator { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MosaicCreator)); this.sourceLabel = new System.Windows.Forms.Label(); this.tileSizeLabel = new System.Windows.Forms.Label(); this.tileSizeComboBox = new System.Windows.Forms.ComboBox(); this.mpsLabel = new System.Windows.Forms.Label(); this.mpsComboBox = new System.Windows.Forms.ComboBox(); this.sourceGroupBox = new System.Windows.Forms.GroupBox(); this.sourceImageInfoLabel = new System.Windows.Forms.Label(); this.heightMapCheckbox = new System.Windows.Forms.CheckBox(); this.minAltLabel = new System.Windows.Forms.Label(); this.minAltTextBox = new System.Windows.Forms.TextBox(); this.altPanel = new System.Windows.Forms.Panel(); this.maxAltTextBox = new System.Windows.Forms.TextBox(); this.maxAltLabel = new System.Windows.Forms.Label(); this.sourceImageFilenameLabel = new System.Windows.Forms.Label(); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.loadImageToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveMosaicToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.launchOnlineHelpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.launchReleaseNotesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.submitFeedbackOrABugToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.aboutMosaicCreatorToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.sourceGroupBox.SuspendLayout(); this.altPanel.SuspendLayout(); this.menuStrip1.SuspendLayout(); this.SuspendLayout(); // // sourceLabel // this.sourceLabel.AutoSize = true; this.sourceLabel.Location = new System.Drawing.Point(36, 53); this.sourceLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.sourceLabel.Name = "sourceLabel"; this.sourceLabel.Size = new System.Drawing.Size(99, 17); this.sourceLabel.TabIndex = 0; this.sourceLabel.Text = "Source Image:"; // // tileSizeLabel // this.tileSizeLabel.AutoSize = true; this.tileSizeLabel.Location = new System.Drawing.Point(36, 100); this.tileSizeLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.tileSizeLabel.Name = "tileSizeLabel"; this.tileSizeLabel.Size = new System.Drawing.Size(66, 17); this.tileSizeLabel.TabIndex = 2; this.tileSizeLabel.Text = "Tile Size:"; // // tileSizeComboBox // this.tileSizeComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.tileSizeComboBox.FormattingEnabled = true; this.tileSizeComboBox.Items.AddRange(new object[] { "128", "256", "512", "1024", "2048"}); this.tileSizeComboBox.Location = new System.Drawing.Point(192, 96); this.tileSizeComboBox.Margin = new System.Windows.Forms.Padding(4); this.tileSizeComboBox.Name = "tileSizeComboBox"; this.tileSizeComboBox.Size = new System.Drawing.Size(160, 24); this.tileSizeComboBox.TabIndex = 3; // // mpsLabel // this.mpsLabel.AutoSize = true; this.mpsLabel.Location = new System.Drawing.Point(36, 148); this.mpsLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.mpsLabel.Name = "mpsLabel"; this.mpsLabel.Size = new System.Drawing.Size(114, 17); this.mpsLabel.TabIndex = 6; this.mpsLabel.Text = "Meters Per Pixel:"; // // mpsComboBox // this.mpsComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.mpsComboBox.FormattingEnabled = true; this.mpsComboBox.Items.AddRange(new object[] { "1", "2", "4", "8", "16", "32", "64", "128", "256"}); this.mpsComboBox.Location = new System.Drawing.Point(192, 144); this.mpsComboBox.Margin = new System.Windows.Forms.Padding(4); this.mpsComboBox.Name = "mpsComboBox"; this.mpsComboBox.Size = new System.Drawing.Size(160, 24); this.mpsComboBox.TabIndex = 7; // // sourceGroupBox // this.sourceGroupBox.Controls.Add(this.sourceImageInfoLabel); this.sourceGroupBox.Location = new System.Drawing.Point(411, 84); this.sourceGroupBox.Margin = new System.Windows.Forms.Padding(4); this.sourceGroupBox.Name = "sourceGroupBox"; this.sourceGroupBox.Padding = new System.Windows.Forms.Padding(4); this.sourceGroupBox.Size = new System.Drawing.Size(323, 108); this.sourceGroupBox.TabIndex = 4; this.sourceGroupBox.TabStop = false; this.sourceGroupBox.Text = "Source Image Info"; // // sourceImageInfoLabel // this.sourceImageInfoLabel.AutoSize = true; this.sourceImageInfoLabel.Location = new System.Drawing.Point(24, 34); this.sourceImageInfoLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.sourceImageInfoLabel.Name = "sourceImageInfoLabel"; this.sourceImageInfoLabel.Size = new System.Drawing.Size(0, 17); this.sourceImageInfoLabel.TabIndex = 5; // // heightMapCheckbox // this.heightMapCheckbox.AutoSize = true; this.heightMapCheckbox.Location = new System.Drawing.Point(40, 252); this.heightMapCheckbox.Margin = new System.Windows.Forms.Padding(4); this.heightMapCheckbox.Name = "heightMapCheckbox"; this.heightMapCheckbox.Size = new System.Drawing.Size(102, 21); this.heightMapCheckbox.TabIndex = 8; this.heightMapCheckbox.Text = "Height Map"; this.heightMapCheckbox.UseVisualStyleBackColor = true; this.heightMapCheckbox.CheckedChanged += new System.EventHandler(this.heightMapCheckbox_CheckedChanged); // // minAltLabel // this.minAltLabel.AutoSize = true; this.minAltLabel.Location = new System.Drawing.Point(9, 20); this.minAltLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.minAltLabel.Name = "minAltLabel"; this.minAltLabel.Size = new System.Drawing.Size(118, 17); this.minAltLabel.TabIndex = 10; this.minAltLabel.Text = "Minimum Altitude:"; // // minAltTextBox // this.minAltTextBox.Location = new System.Drawing.Point(136, 16); this.minAltTextBox.Margin = new System.Windows.Forms.Padding(4); this.minAltTextBox.Name = "minAltTextBox"; this.minAltTextBox.Size = new System.Drawing.Size(132, 22); this.minAltTextBox.TabIndex = 11; this.minAltTextBox.Text = "0"; // // altPanel // this.altPanel.Controls.Add(this.maxAltTextBox); this.altPanel.Controls.Add(this.maxAltLabel); this.altPanel.Controls.Add(this.minAltLabel); this.altPanel.Controls.Add(this.minAltTextBox); this.altPanel.Enabled = false; this.altPanel.Location = new System.Drawing.Point(179, 234); this.altPanel.Margin = new System.Windows.Forms.Padding(4); this.altPanel.Name = "altPanel"; this.altPanel.Size = new System.Drawing.Size(612, 62); this.altPanel.TabIndex = 9; // // maxAltTextBox // this.maxAltTextBox.Location = new System.Drawing.Point(449, 16); this.maxAltTextBox.Margin = new System.Windows.Forms.Padding(4); this.maxAltTextBox.Name = "maxAltTextBox"; this.maxAltTextBox.Size = new System.Drawing.Size(132, 22); this.maxAltTextBox.TabIndex = 13; this.maxAltTextBox.Text = "1000"; // // maxAltLabel // this.maxAltLabel.AutoSize = true; this.maxAltLabel.Location = new System.Drawing.Point(319, 20); this.maxAltLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.maxAltLabel.Name = "maxAltLabel"; this.maxAltLabel.Size = new System.Drawing.Size(121, 17); this.maxAltLabel.TabIndex = 12; this.maxAltLabel.Text = "Maximum Altitude:"; // // sourceImageFilenameLabel // this.sourceImageFilenameLabel.AutoSize = true; this.sourceImageFilenameLabel.Location = new System.Drawing.Point(175, 53); this.sourceImageFilenameLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.sourceImageFilenameLabel.Name = "sourceImageFilenameLabel"; this.sourceImageFilenameLabel.Size = new System.Drawing.Size(0, 17); this.sourceImageFilenameLabel.TabIndex = 1; // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem, this.helpToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Padding = new System.Windows.Forms.Padding(8, 2, 0, 2); this.menuStrip1.Size = new System.Drawing.Size(804, 28); this.menuStrip1.TabIndex = 18; this.menuStrip1.Text = "menuStrip1"; // // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.loadImageToolStripMenuItem, this.saveMosaicToolStripMenuItem, this.exitToolStripMenuItem}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size(44, 24); this.fileToolStripMenuItem.Text = "File"; // // loadImageToolStripMenuItem // this.loadImageToolStripMenuItem.Name = "loadImageToolStripMenuItem"; this.loadImageToolStripMenuItem.Size = new System.Drawing.Size(169, 24); this.loadImageToolStripMenuItem.Text = "Load Image..."; this.loadImageToolStripMenuItem.Click += new System.EventHandler(this.loadImageToolStripMenuItem_Click); // // saveMosaicToolStripMenuItem // this.saveMosaicToolStripMenuItem.Name = "saveMosaicToolStripMenuItem"; this.saveMosaicToolStripMenuItem.Size = new System.Drawing.Size(169, 24); this.saveMosaicToolStripMenuItem.Text = "Save Mosaic..."; this.saveMosaicToolStripMenuItem.Click += new System.EventHandler(this.saveMosaicToolStripMenuItem_Click); // // exitToolStripMenuItem // this.exitToolStripMenuItem.Name = "exitToolStripMenuItem"; this.exitToolStripMenuItem.Size = new System.Drawing.Size(169, 24); this.exitToolStripMenuItem.Text = "Exit"; this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click); // // helpToolStripMenuItem // this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.launchOnlineHelpToolStripMenuItem, this.launchReleaseNotesToolStripMenuItem, this.submitFeedbackOrABugToolStripMenuItem, this.aboutMosaicCreatorToolStripMenuItem}); this.helpToolStripMenuItem.Name = "helpToolStripMenuItem"; this.helpToolStripMenuItem.Size = new System.Drawing.Size(53, 24); this.helpToolStripMenuItem.Text = "Help"; // // launchOnlineHelpToolStripMenuItem // this.launchOnlineHelpToolStripMenuItem.Name = "launchOnlineHelpToolStripMenuItem"; this.launchOnlineHelpToolStripMenuItem.Size = new System.Drawing.Size(252, 24); this.launchOnlineHelpToolStripMenuItem.Text = "Launch Online Help"; this.launchOnlineHelpToolStripMenuItem.Click += new System.EventHandler(this.launchOnlineHelpToolStripMenuItem_Click); // // launchReleaseNotesToolStripMenuItem // this.launchReleaseNotesToolStripMenuItem.Name = "launchReleaseNotesToolStripMenuItem"; this.launchReleaseNotesToolStripMenuItem.Size = new System.Drawing.Size(252, 24); this.launchReleaseNotesToolStripMenuItem.Text = "Launch Release Notes"; this.launchReleaseNotesToolStripMenuItem.Click += new System.EventHandler(this.launchReleaseNotesToolStripMenuItem_Click); // // submitFeedbackOrABugToolStripMenuItem // this.submitFeedbackOrABugToolStripMenuItem.Name = "submitFeedbackOrABugToolStripMenuItem"; this.submitFeedbackOrABugToolStripMenuItem.Size = new System.Drawing.Size(252, 24); this.submitFeedbackOrABugToolStripMenuItem.Text = "Submit Feedback or a Bug"; this.submitFeedbackOrABugToolStripMenuItem.Click += new System.EventHandler(this.submitFeedbackOrABugToolStripMenuItem_Click); // // aboutMosaicCreatorToolStripMenuItem // this.aboutMosaicCreatorToolStripMenuItem.Name = "aboutMosaicCreatorToolStripMenuItem"; this.aboutMosaicCreatorToolStripMenuItem.Size = new System.Drawing.Size(252, 24); this.aboutMosaicCreatorToolStripMenuItem.Text = "About Mosaic Creator"; this.aboutMosaicCreatorToolStripMenuItem.Click += new System.EventHandler(this.aboutMosaicCreatorToolStripMenuItem_Click); // // MosaicCreator // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(804, 309); this.Controls.Add(this.sourceImageFilenameLabel); this.Controls.Add(this.altPanel); this.Controls.Add(this.heightMapCheckbox); this.Controls.Add(this.sourceGroupBox); this.Controls.Add(this.mpsComboBox); this.Controls.Add(this.mpsLabel); this.Controls.Add(this.tileSizeComboBox); this.Controls.Add(this.tileSizeLabel); this.Controls.Add(this.sourceLabel); this.Controls.Add(this.menuStrip1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MainMenuStrip = this.menuStrip1; this.Margin = new System.Windows.Forms.Padding(4); this.Name = "MosaicCreator"; this.Text = "Mosaic Creator"; this.sourceGroupBox.ResumeLayout(false); this.sourceGroupBox.PerformLayout(); this.altPanel.ResumeLayout(false); this.altPanel.PerformLayout(); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label sourceLabel; private System.Windows.Forms.Label tileSizeLabel; private System.Windows.Forms.ComboBox tileSizeComboBox; private System.Windows.Forms.Label mpsLabel; private System.Windows.Forms.ComboBox mpsComboBox; private System.Windows.Forms.GroupBox sourceGroupBox; private System.Windows.Forms.Label sourceImageInfoLabel; private System.Windows.Forms.CheckBox heightMapCheckbox; private System.Windows.Forms.Label minAltLabel; private System.Windows.Forms.TextBox minAltTextBox; private System.Windows.Forms.Panel altPanel; private System.Windows.Forms.TextBox maxAltTextBox; private System.Windows.Forms.Label maxAltLabel; private System.Windows.Forms.Label sourceImageFilenameLabel; private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem loadImageToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem saveMosaicToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem launchOnlineHelpToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem launchReleaseNotesToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem submitFeedbackOrABugToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem aboutMosaicCreatorToolStripMenuItem; } }
// // 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.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Hyak.Common.Internals; using Microsoft.Azure; 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 test jobs. (see /// http://aka.ms/azureautomationsdk/testjoboperations for more /// information) /// </summary> internal partial class TestJobOperations : IServiceOperations<AutomationManagementClient>, ITestJobOperations { /// <summary> /// Initializes a new instance of the TestJobOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal TestJobOperations(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> /// Create a test job of the runbook. (see /// http://aka.ms/azureautomationsdk/testjoboperations 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='parameters'> /// Required. The parameters supplied to the create test job operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the create test job operation. /// </returns> public async Task<TestJobCreateResponse> CreateAsync(string resourceGroupName, string automationAccount, TestJobCreateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.RunbookName == null) { throw new ArgumentNullException("parameters.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("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateAsync", 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(parameters.RunbookName); url = url + "/draft/testJob"; 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.Put; 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); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject testJobCreateParametersValue = new JObject(); requestDoc = testJobCreateParametersValue; if (parameters.Parameters != null) { if (parameters.Parameters is ILazyCollection == false || ((ILazyCollection)parameters.Parameters).IsInitialized) { JObject parametersDictionary = new JObject(); foreach (KeyValuePair<string, string> pair in parameters.Parameters) { string parametersKey = pair.Key; string parametersValue = pair.Value; parametersDictionary[parametersKey] = parametersValue; } testJobCreateParametersValue["parameters"] = parametersDictionary; } } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // 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.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result TestJobCreateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new TestJobCreateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { TestJob testJobInstance = new TestJob(); result.TestJob = testJobInstance; JToken creationTimeValue = responseDoc["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); testJobInstance.CreationTime = creationTimeInstance; } JToken statusValue = responseDoc["status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { string statusInstance = ((string)statusValue); testJobInstance.Status = statusInstance; } JToken statusDetailsValue = responseDoc["statusDetails"]; if (statusDetailsValue != null && statusDetailsValue.Type != JTokenType.Null) { string statusDetailsInstance = ((string)statusDetailsValue); testJobInstance.StatusDetails = statusDetailsInstance; } JToken startTimeValue = responseDoc["startTime"]; if (startTimeValue != null && startTimeValue.Type != JTokenType.Null) { DateTimeOffset startTimeInstance = ((DateTimeOffset)startTimeValue); testJobInstance.StartTime = startTimeInstance; } JToken endTimeValue = responseDoc["endTime"]; if (endTimeValue != null && endTimeValue.Type != JTokenType.Null) { DateTimeOffset endTimeInstance = ((DateTimeOffset)endTimeValue); testJobInstance.EndTime = endTimeInstance; } JToken exceptionValue = responseDoc["exception"]; if (exceptionValue != null && exceptionValue.Type != JTokenType.Null) { string exceptionInstance = ((string)exceptionValue); testJobInstance.Exception = exceptionInstance; } JToken lastModifiedTimeValue = responseDoc["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); testJobInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken lastStatusModifiedTimeValue = responseDoc["lastStatusModifiedTime"]; if (lastStatusModifiedTimeValue != null && lastStatusModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastStatusModifiedTimeInstance = ((DateTimeOffset)lastStatusModifiedTimeValue); testJobInstance.LastStatusModifiedTime = lastStatusModifiedTimeInstance; } JToken parametersSequenceElement = ((JToken)responseDoc["parameters"]); if (parametersSequenceElement != null && parametersSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in parametersSequenceElement) { string parametersKey2 = ((string)property.Name); string parametersValue2 = ((string)property.Value); testJobInstance.Parameters.Add(parametersKey2, parametersValue2); } } } } 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 the test job for the specified runbook. (see /// http://aka.ms/azureautomationsdk/testjoboperations 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='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the get test job operation. /// </returns> public async Task<TestJobGetResponse> GetAsync(string resourceGroupName, string automationAccount, string runbookName, 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); 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 + "/Runbooks/"; url = url + Uri.EscapeDataString(runbookName); url = url + "/draft/testJob"; 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 TestJobGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new TestJobGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { TestJob testJobInstance = new TestJob(); result.TestJob = testJobInstance; JToken creationTimeValue = responseDoc["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); testJobInstance.CreationTime = creationTimeInstance; } JToken statusValue = responseDoc["status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { string statusInstance = ((string)statusValue); testJobInstance.Status = statusInstance; } JToken statusDetailsValue = responseDoc["statusDetails"]; if (statusDetailsValue != null && statusDetailsValue.Type != JTokenType.Null) { string statusDetailsInstance = ((string)statusDetailsValue); testJobInstance.StatusDetails = statusDetailsInstance; } JToken startTimeValue = responseDoc["startTime"]; if (startTimeValue != null && startTimeValue.Type != JTokenType.Null) { DateTimeOffset startTimeInstance = ((DateTimeOffset)startTimeValue); testJobInstance.StartTime = startTimeInstance; } JToken endTimeValue = responseDoc["endTime"]; if (endTimeValue != null && endTimeValue.Type != JTokenType.Null) { DateTimeOffset endTimeInstance = ((DateTimeOffset)endTimeValue); testJobInstance.EndTime = endTimeInstance; } JToken exceptionValue = responseDoc["exception"]; if (exceptionValue != null && exceptionValue.Type != JTokenType.Null) { string exceptionInstance = ((string)exceptionValue); testJobInstance.Exception = exceptionInstance; } JToken lastModifiedTimeValue = responseDoc["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); testJobInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken lastStatusModifiedTimeValue = responseDoc["lastStatusModifiedTime"]; if (lastStatusModifiedTimeValue != null && lastStatusModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastStatusModifiedTimeInstance = ((DateTimeOffset)lastStatusModifiedTimeValue); testJobInstance.LastStatusModifiedTime = lastStatusModifiedTimeInstance; } JToken parametersSequenceElement = ((JToken)responseDoc["parameters"]); if (parametersSequenceElement != null && parametersSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in parametersSequenceElement) { string parametersKey = ((string)property.Name); string parametersValue = ((string)property.Value); testJobInstance.Parameters.Add(parametersKey, parametersValue); } } } } 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> /// Resume the test job. (see /// http://aka.ms/azureautomationsdk/testjoboperations 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='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> ResumeAsync(string resourceGroupName, string automationAccount, string runbookName, 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); TracingAdapter.Enter(invocationId, this, "ResumeAsync", 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/resume"; 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.Post; 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 AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); 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> /// Stop the test job. (see /// http://aka.ms/azureautomationsdk/testjoboperations 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='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> StopAsync(string resourceGroupName, string automationAccount, string runbookName, 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); TracingAdapter.Enter(invocationId, this, "StopAsync", 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/stop"; 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.Post; 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 AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); 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> /// Suspend the test job. (see /// http://aka.ms/azureautomationsdk/testjoboperations 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='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> SuspendAsync(string resourceGroupName, string automationAccount, string runbookName, 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); TracingAdapter.Enter(invocationId, this, "SuspendAsync", 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/suspend"; 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.Post; 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 AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); 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.Collections; using System.Security.Authentication.ExtendedProtection; using System.Text; using System.Threading.Tasks; namespace System.Net { public sealed unsafe partial class HttpListener : IDisposable { public delegate ExtendedProtectionPolicy ExtendedProtectionSelector(HttpListenerRequest request); private readonly object _internalLock; private volatile State _state; // _state is set only within lock blocks, but often read outside locks. private readonly HttpListenerPrefixCollection _prefixes; internal Hashtable _uriPrefixes = new Hashtable(); private bool _ignoreWriteExceptions; private ServiceNameStore _defaultServiceNames; private HttpListenerTimeoutManager _timeoutManager; private ExtendedProtectionPolicy _extendedProtectionPolicy; private AuthenticationSchemeSelector _authenticationDelegate; private AuthenticationSchemes _authenticationScheme = AuthenticationSchemes.Anonymous; private ExtendedProtectionSelector _extendedProtectionSelectorDelegate; private string _realm; internal ICollection PrefixCollection => _uriPrefixes.Keys; public HttpListener() { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); _state = State.Stopped; _internalLock = new object(); _defaultServiceNames = new ServiceNameStore(); _timeoutManager = new HttpListenerTimeoutManager(this); _prefixes = new HttpListenerPrefixCollection(this); // default: no CBT checks on any platform (appcompat reasons); applies also to PolicyEnforcement // config element _extendedProtectionPolicy = new ExtendedProtectionPolicy(PolicyEnforcement.Never); if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } public AuthenticationSchemeSelector AuthenticationSchemeSelectorDelegate { get => _authenticationDelegate; set { CheckDisposed(); _authenticationDelegate = value; } } public ExtendedProtectionSelector ExtendedProtectionSelectorDelegate { get => _extendedProtectionSelectorDelegate; set { CheckDisposed(); if (value == null) { throw new ArgumentNullException(nameof(value)); } _extendedProtectionSelectorDelegate = value; } } public AuthenticationSchemes AuthenticationSchemes { get => _authenticationScheme; set { CheckDisposed(); _authenticationScheme = value; } } public ExtendedProtectionPolicy ExtendedProtectionPolicy { get => _extendedProtectionPolicy; set { CheckDisposed(); if (value == null) { throw new ArgumentNullException(nameof(value)); } if (value.CustomChannelBinding != null) { throw new ArgumentException(SR.net_listener_cannot_set_custom_cbt, nameof(value)); } _extendedProtectionPolicy = value; } } public ServiceNameCollection DefaultServiceNames => _defaultServiceNames.ServiceNames; public HttpListenerPrefixCollection Prefixes { get { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); CheckDisposed(); if (NetEventSource.IsEnabled) NetEventSource.Enter(this); return _prefixes; } } internal void AddPrefix(string uriPrefix) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this, $"uriPrefix:{uriPrefix}"); string registeredPrefix = null; try { if (uriPrefix == null) { throw new ArgumentNullException(nameof(uriPrefix)); } CheckDisposed(); int i; if (string.Compare(uriPrefix, 0, "http://", 0, 7, StringComparison.OrdinalIgnoreCase) == 0) { i = 7; } else if (string.Compare(uriPrefix, 0, "https://", 0, 8, StringComparison.OrdinalIgnoreCase) == 0) { i = 8; } else { throw new ArgumentException(SR.net_listener_scheme, nameof(uriPrefix)); } bool inSquareBrakets = false; int j = i; while (j < uriPrefix.Length && uriPrefix[j] != '/' && (uriPrefix[j] != ':' || inSquareBrakets)) { if (uriPrefix[j] == '[') { if (inSquareBrakets) { j = i; break; } inSquareBrakets = true; } if (inSquareBrakets && uriPrefix[j] == ']') { inSquareBrakets = false; } j++; } if (i == j) { throw new ArgumentException(SR.net_listener_host, nameof(uriPrefix)); } if (uriPrefix[uriPrefix.Length - 1] != '/') { throw new ArgumentException(SR.net_listener_slash, nameof(uriPrefix)); } StringBuilder registeredPrefixBuilder = new StringBuilder(); if (uriPrefix[j] == ':') { registeredPrefixBuilder.Append(uriPrefix); } else { registeredPrefixBuilder.Append(uriPrefix, 0, j); registeredPrefixBuilder.Append(i == 7 ? ":80" : ":443"); registeredPrefixBuilder.Append(uriPrefix, j, uriPrefix.Length - j); } for (i = 0; registeredPrefixBuilder[i] != ':'; i++) { registeredPrefixBuilder[i] = (char)CaseInsensitiveAscii.AsciiToLower[(byte)registeredPrefixBuilder[i]]; } registeredPrefix = registeredPrefixBuilder.ToString(); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"mapped uriPrefix: {uriPrefix} to registeredPrefix: {registeredPrefix}"); if (_state == State.Started) { AddPrefixCore(registeredPrefix); } _uriPrefixes[uriPrefix] = registeredPrefix; _defaultServiceNames.Add(uriPrefix); } catch (Exception exception) { if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception); throw; } finally { if (NetEventSource.IsEnabled) NetEventSource.Exit(this, $"prefix: {registeredPrefix}"); } } internal bool ContainsPrefix(string uriPrefix) => _uriPrefixes.Contains(uriPrefix); internal bool RemovePrefix(string uriPrefix) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this, $"uriPrefix: {uriPrefix}"); try { CheckDisposed(); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"uriPrefix: {uriPrefix}"); if (uriPrefix == null) { throw new ArgumentNullException(nameof(uriPrefix)); } if (!_uriPrefixes.Contains(uriPrefix)) { return false; } if (_state == State.Started) { RemovePrefixCore((string)_uriPrefixes[uriPrefix]); } _uriPrefixes.Remove(uriPrefix); _defaultServiceNames.Remove(uriPrefix); } catch (Exception exception) { if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception); throw; } finally { if (NetEventSource.IsEnabled) NetEventSource.Exit(this, $"uriPrefix: {uriPrefix}"); } return true; } internal void RemoveAll(bool clear) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); try { CheckDisposed(); // go through the uri list and unregister for each one of them if (_uriPrefixes.Count > 0) { if (_state == State.Started) { foreach (string registeredPrefix in _uriPrefixes.Values) { RemovePrefixCore(registeredPrefix); } } if (clear) { _uriPrefixes.Clear(); _defaultServiceNames.Clear(); } } } finally { if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } } public string Realm { get => _realm; set { CheckDisposed(); _realm = value; } } public bool IsListening => _state == State.Started; public bool IgnoreWriteExceptions { get => _ignoreWriteExceptions; set { CheckDisposed(); _ignoreWriteExceptions = value; } } public Task<HttpListenerContext> GetContextAsync() { return Task.Factory.FromAsync( (callback, state) => ((HttpListener)state).BeginGetContext(callback, state), iar => ((HttpListener)iar.AsyncState).EndGetContext(iar), this); } public void Close() { if (NetEventSource.IsEnabled) NetEventSource.Enter(this, nameof(Close)); try { if (NetEventSource.IsEnabled) NetEventSource.Info("HttpListenerRequest::Close()"); ((IDisposable)this).Dispose(); } catch (Exception exception) { if (NetEventSource.IsEnabled) NetEventSource.Error(this, $"Close {exception}"); throw; } finally { if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } } internal void CheckDisposed() { if (_state == State.Closed) { throw new ObjectDisposedException(GetType().FullName); } } private enum State { Stopped, Started, Closed, } void IDisposable.Dispose() => Dispose(); } }
/** * Copyright 2015 d-fens GmbH * * 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 Newtonsoft.Json.Linq; using System; using System.Collections; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; namespace biz.dfch.CS.Activiti.Client { public class RestClient { #region Constants and Properties // DFTODO - define properties such as Username, Password, Server, ... //private const String URIBASE = "activiti-rest"; private const int TIMEOUTSEC = 90; private const String CONTENTTYPE = "application/json"; private const String AUTHORIZATIONHEADERFORMAT = "Basic {0}"; private const String USERAGENT = "d-fens biz.dfch.CS.Activiti.Client.RestClient"; public string Username { get; set; } private string _password; public string Password { set { _password = value; } private get { return _password; } } private NetworkCredential _Credential; private String _CredentialBase64; public NetworkCredential Credential { get { return _Credential; } set { _Credential = value ?? (new NetworkCredential(String.Empty, String.Empty)); var abCredential = System.Text.UTF8Encoding.UTF8.GetBytes(String.Format("{0}:{1}", _Credential.UserName, _Credential.Password)); _CredentialBase64 = Convert.ToBase64String(abCredential); } } public void SetCredential(String username, String password) { this.Credential = new NetworkCredential(username, password); } private String _ContentType = CONTENTTYPE; public String ContentType { get { return _ContentType; } set { _ContentType = value; } } private Uri _UriServer; public Uri UriServer { get { return _UriServer; } set { _UriServer = value; } } private int _TimeoutSec = TIMEOUTSEC; public int TimeoutSec { get { return _TimeoutSec; } set { _TimeoutSec = value; } } #endregion #region Constructor And Initialisation public RestClient() { // N/A } public RestClient(Uri server) { Contract.Requires(null != server); this.UriServer = server; } public RestClient(Uri server, string username, string password) { Contract.Requires(null != server); Contract.Requires(!string.IsNullOrWhiteSpace(username)); Contract.Requires(!string.IsNullOrWhiteSpace(password)); this.UriServer = server; this.Username = username; this.Password = password; this.Initialise(UriServer, Username, Password); } private void Initialise(Uri server, string username, string password) { this.UriServer = server; this.Username = username; this.Password = password; SetCredential(Username, Password); } #endregion #region Invoke public String Invoke( String method , String uri , Hashtable queryParameters , Hashtable headers , String body ) { // Parameter validation if (String.IsNullOrWhiteSpace(method)) throw new ArgumentException(String.Format("Method: Parameter validation FAILED. Parameter cannot be null or empty."), "Method"); if (String.IsNullOrWhiteSpace(uri)) throw new ArgumentException(String.Format("Uri: Parameter validation FAILED. Parameter cannot be null or empty."), "Uri"); headers = headers ?? (new Hashtable()); queryParameters = queryParameters ?? (new Hashtable()); Debug.WriteLine(String.Format("Invoke: UriServer '{0}'. TimeoutSec '{1}'. Method '{2}'. Uri '{3}'.", _UriServer.AbsoluteUri, _TimeoutSec, method, uri)); if (null == Credential) { Debug.WriteLine(String.Format("No Credential specified.")); } else { if (String.IsNullOrWhiteSpace(Credential.Password)) { Debug.WriteLine(String.Format("Username '{0}', Password '{1}'.", Credential.UserName, "*")); } else { Debug.WriteLine(String.Format("Username '{0}', Password '{1}'.", Credential.UserName, "********")); } } using (var cl = new HttpClient()) { char[] achTrim = { '/' }; var s = String.Format("{0}/", _UriServer.AbsoluteUri.TrimEnd(achTrim)); cl.BaseAddress = new Uri(s); cl.Timeout = new TimeSpan(0, 0, _TimeoutSec); cl.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(_ContentType)); //cl.DefaultRequestHeaders.Add("Authorization", String.Format(RestClient.AUTHORIZATIONHEADERFORMAT, _CredentialBase64)); cl.DefaultRequestHeaders.Add("User-Agent", RestClient.USERAGENT); foreach (DictionaryEntry item in headers) { cl.DefaultRequestHeaders.Add(item.Key.ToString(), item.Value.ToString()); } var queryParametersString = "?"; foreach (DictionaryEntry item in queryParameters) { queryParametersString += String.Format("{0}={1}&", item.Key, item.Value); } char[] achTrimAmp = { '&' }; queryParametersString = queryParametersString.TrimEnd(achTrimAmp); // Invoke request HttpResponseMessage response; var _method = new HttpMethod(method); uri += queryParametersString; char[] achTrimQuestion = { '?' }; uri = uri.TrimEnd(achTrimQuestion); switch (_method.ToString().ToUpper()) { case "GET": case "HEAD": response = cl.GetAsync(uri).Result; break; case "POST": { var _body = new StringContent(body); _body.Headers.ContentType = new MediaTypeHeaderValue(_ContentType); response = cl.PostAsync(uri, _body).Result; } break; case "PUT": { var _body = new StringContent(body); _body.Headers.ContentType = new MediaTypeHeaderValue(_ContentType); response = cl.PutAsync(uri, _body).Result; } break; case "DELETE": response = cl.DeleteAsync(uri).Result; break; default: throw new NotImplementedException(String.Format("{0}: Method not implemented. Currently only the following methods are implemented: 'GET', 'HEAD', 'POST', 'PUT', 'DELETE'.", _method.ToString().ToUpper())); } if (response.StatusCode.Equals(HttpStatusCode.Unauthorized)) { throw new UnauthorizedAccessException(String.Format("Invoking '{0}' with username '{1}' FAILED.", uri, _Credential.UserName)); } if (response.StatusCode.Equals(HttpStatusCode.BadRequest)) { var message = String.Empty; var contentError = response.Content.ReadAsStringAsync().Result; try { JToken jv = JObject.Parse(contentError); var messageError = jv.SelectToken("Error", true).ToString(); var messageCode = jv.SelectToken("code", true).ToString(); var messageText = jv.SelectToken("text", true).ToString(); message = String.Format("{0}\r\nCode: {1}\r\nText: {2}", messageError, messageCode, messageText); } catch { message = contentError; } throw new ArgumentException(message); } response.EnsureSuccessStatusCode(); Debug.WriteLine(String.Format("response '{0}'", response.ToString())); var content = response.Content.ReadAsStringAsync().Result; Debug.WriteLine(String.Format("content '{0}'", content.ToString())); return content; } } public String Invoke( String uri , Hashtable queryParameters ) { return this.Invoke(HttpMethod.Get.ToString(), uri, queryParameters, null, null); } public String Invoke( String uri ) { return this.Invoke(HttpMethod.Get.ToString(), uri, null, null, null); } #endregion } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V8.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V8.Services { /// <summary>Settings for <see cref="AdGroupLabelServiceClient"/> instances.</summary> public sealed partial class AdGroupLabelServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="AdGroupLabelServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="AdGroupLabelServiceSettings"/>.</returns> public static AdGroupLabelServiceSettings GetDefault() => new AdGroupLabelServiceSettings(); /// <summary>Constructs a new <see cref="AdGroupLabelServiceSettings"/> object with default settings.</summary> public AdGroupLabelServiceSettings() { } private AdGroupLabelServiceSettings(AdGroupLabelServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetAdGroupLabelSettings = existing.GetAdGroupLabelSettings; MutateAdGroupLabelsSettings = existing.MutateAdGroupLabelsSettings; OnCopy(existing); } partial void OnCopy(AdGroupLabelServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>AdGroupLabelServiceClient.GetAdGroupLabel</c> and <c>AdGroupLabelServiceClient.GetAdGroupLabelAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetAdGroupLabelSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>AdGroupLabelServiceClient.MutateAdGroupLabels</c> and /// <c>AdGroupLabelServiceClient.MutateAdGroupLabelsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings MutateAdGroupLabelsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="AdGroupLabelServiceSettings"/> object.</returns> public AdGroupLabelServiceSettings Clone() => new AdGroupLabelServiceSettings(this); } /// <summary> /// Builder class for <see cref="AdGroupLabelServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class AdGroupLabelServiceClientBuilder : gaxgrpc::ClientBuilderBase<AdGroupLabelServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public AdGroupLabelServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public AdGroupLabelServiceClientBuilder() { UseJwtAccessWithScopes = AdGroupLabelServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref AdGroupLabelServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AdGroupLabelServiceClient> task); /// <summary>Builds the resulting client.</summary> public override AdGroupLabelServiceClient Build() { AdGroupLabelServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<AdGroupLabelServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<AdGroupLabelServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private AdGroupLabelServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return AdGroupLabelServiceClient.Create(callInvoker, Settings); } private async stt::Task<AdGroupLabelServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return AdGroupLabelServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => AdGroupLabelServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => AdGroupLabelServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => AdGroupLabelServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>AdGroupLabelService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage labels on ad groups. /// </remarks> public abstract partial class AdGroupLabelServiceClient { /// <summary> /// The default endpoint for the AdGroupLabelService service, which is a host of "googleads.googleapis.com" and /// a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default AdGroupLabelService scopes.</summary> /// <remarks> /// The default AdGroupLabelService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="AdGroupLabelServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use /// <see cref="AdGroupLabelServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="AdGroupLabelServiceClient"/>.</returns> public static stt::Task<AdGroupLabelServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new AdGroupLabelServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="AdGroupLabelServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use /// <see cref="AdGroupLabelServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="AdGroupLabelServiceClient"/>.</returns> public static AdGroupLabelServiceClient Create() => new AdGroupLabelServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="AdGroupLabelServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="AdGroupLabelServiceSettings"/>.</param> /// <returns>The created <see cref="AdGroupLabelServiceClient"/>.</returns> internal static AdGroupLabelServiceClient Create(grpccore::CallInvoker callInvoker, AdGroupLabelServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } AdGroupLabelService.AdGroupLabelServiceClient grpcClient = new AdGroupLabelService.AdGroupLabelServiceClient(callInvoker); return new AdGroupLabelServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC AdGroupLabelService client</summary> public virtual AdGroupLabelService.AdGroupLabelServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested ad group label in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::AdGroupLabel GetAdGroupLabel(GetAdGroupLabelRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested ad group label in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupLabel> GetAdGroupLabelAsync(GetAdGroupLabelRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested ad group label in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupLabel> GetAdGroupLabelAsync(GetAdGroupLabelRequest request, st::CancellationToken cancellationToken) => GetAdGroupLabelAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested ad group label in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group label to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::AdGroupLabel GetAdGroupLabel(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetAdGroupLabel(new GetAdGroupLabelRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested ad group label in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group label to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupLabel> GetAdGroupLabelAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetAdGroupLabelAsync(new GetAdGroupLabelRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested ad group label in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group label to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupLabel> GetAdGroupLabelAsync(string resourceName, st::CancellationToken cancellationToken) => GetAdGroupLabelAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested ad group label in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group label to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::AdGroupLabel GetAdGroupLabel(gagvr::AdGroupLabelName resourceName, gaxgrpc::CallSettings callSettings = null) => GetAdGroupLabel(new GetAdGroupLabelRequest { ResourceNameAsAdGroupLabelName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested ad group label in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group label to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupLabel> GetAdGroupLabelAsync(gagvr::AdGroupLabelName resourceName, gaxgrpc::CallSettings callSettings = null) => GetAdGroupLabelAsync(new GetAdGroupLabelRequest { ResourceNameAsAdGroupLabelName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested ad group label in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group label to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupLabel> GetAdGroupLabelAsync(gagvr::AdGroupLabelName resourceName, st::CancellationToken cancellationToken) => GetAdGroupLabelAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates and removes ad group labels. /// Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [LabelError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateAdGroupLabelsResponse MutateAdGroupLabels(MutateAdGroupLabelsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates and removes ad group labels. /// Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [LabelError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateAdGroupLabelsResponse> MutateAdGroupLabelsAsync(MutateAdGroupLabelsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates and removes ad group labels. /// Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [LabelError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateAdGroupLabelsResponse> MutateAdGroupLabelsAsync(MutateAdGroupLabelsRequest request, st::CancellationToken cancellationToken) => MutateAdGroupLabelsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates and removes ad group labels. /// Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [LabelError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. ID of the customer whose ad group labels are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on ad group labels. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateAdGroupLabelsResponse MutateAdGroupLabels(string customerId, scg::IEnumerable<AdGroupLabelOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateAdGroupLabels(new MutateAdGroupLabelsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates and removes ad group labels. /// Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [LabelError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. ID of the customer whose ad group labels are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on ad group labels. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateAdGroupLabelsResponse> MutateAdGroupLabelsAsync(string customerId, scg::IEnumerable<AdGroupLabelOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateAdGroupLabelsAsync(new MutateAdGroupLabelsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates and removes ad group labels. /// Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [LabelError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. ID of the customer whose ad group labels are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on ad group labels. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateAdGroupLabelsResponse> MutateAdGroupLabelsAsync(string customerId, scg::IEnumerable<AdGroupLabelOperation> operations, st::CancellationToken cancellationToken) => MutateAdGroupLabelsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>AdGroupLabelService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage labels on ad groups. /// </remarks> public sealed partial class AdGroupLabelServiceClientImpl : AdGroupLabelServiceClient { private readonly gaxgrpc::ApiCall<GetAdGroupLabelRequest, gagvr::AdGroupLabel> _callGetAdGroupLabel; private readonly gaxgrpc::ApiCall<MutateAdGroupLabelsRequest, MutateAdGroupLabelsResponse> _callMutateAdGroupLabels; /// <summary> /// Constructs a client wrapper for the AdGroupLabelService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="AdGroupLabelServiceSettings"/> used within this client.</param> public AdGroupLabelServiceClientImpl(AdGroupLabelService.AdGroupLabelServiceClient grpcClient, AdGroupLabelServiceSettings settings) { GrpcClient = grpcClient; AdGroupLabelServiceSettings effectiveSettings = settings ?? AdGroupLabelServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetAdGroupLabel = clientHelper.BuildApiCall<GetAdGroupLabelRequest, gagvr::AdGroupLabel>(grpcClient.GetAdGroupLabelAsync, grpcClient.GetAdGroupLabel, effectiveSettings.GetAdGroupLabelSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetAdGroupLabel); Modify_GetAdGroupLabelApiCall(ref _callGetAdGroupLabel); _callMutateAdGroupLabels = clientHelper.BuildApiCall<MutateAdGroupLabelsRequest, MutateAdGroupLabelsResponse>(grpcClient.MutateAdGroupLabelsAsync, grpcClient.MutateAdGroupLabels, effectiveSettings.MutateAdGroupLabelsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateAdGroupLabels); Modify_MutateAdGroupLabelsApiCall(ref _callMutateAdGroupLabels); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_GetAdGroupLabelApiCall(ref gaxgrpc::ApiCall<GetAdGroupLabelRequest, gagvr::AdGroupLabel> call); partial void Modify_MutateAdGroupLabelsApiCall(ref gaxgrpc::ApiCall<MutateAdGroupLabelsRequest, MutateAdGroupLabelsResponse> call); partial void OnConstruction(AdGroupLabelService.AdGroupLabelServiceClient grpcClient, AdGroupLabelServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC AdGroupLabelService client</summary> public override AdGroupLabelService.AdGroupLabelServiceClient GrpcClient { get; } partial void Modify_GetAdGroupLabelRequest(ref GetAdGroupLabelRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_MutateAdGroupLabelsRequest(ref MutateAdGroupLabelsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested ad group label in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::AdGroupLabel GetAdGroupLabel(GetAdGroupLabelRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetAdGroupLabelRequest(ref request, ref callSettings); return _callGetAdGroupLabel.Sync(request, callSettings); } /// <summary> /// Returns the requested ad group label in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::AdGroupLabel> GetAdGroupLabelAsync(GetAdGroupLabelRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetAdGroupLabelRequest(ref request, ref callSettings); return _callGetAdGroupLabel.Async(request, callSettings); } /// <summary> /// Creates and removes ad group labels. /// Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [LabelError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override MutateAdGroupLabelsResponse MutateAdGroupLabels(MutateAdGroupLabelsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateAdGroupLabelsRequest(ref request, ref callSettings); return _callMutateAdGroupLabels.Sync(request, callSettings); } /// <summary> /// Creates and removes ad group labels. /// Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [LabelError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<MutateAdGroupLabelsResponse> MutateAdGroupLabelsAsync(MutateAdGroupLabelsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateAdGroupLabelsRequest(ref request, ref callSettings); return _callMutateAdGroupLabels.Async(request, callSettings); } } }
/* * Copyright (c) 2006-2014, openmetaverse.org * 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. * - Neither the name of the openmetaverse.org nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ //#define DEBUG_VOICE using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Threading; using OpenMetaverse; using OpenMetaverse.StructuredData; namespace OpenMetaverse.Voice { public partial class VoiceGateway : IDisposable { // These states should be in increasing order of 'completeness' // so that the (int) values can drive a progress bar. public enum ConnectionState { None = 0, Provisioned, DaemonStarted, DaemonConnected, ConnectorConnected, AccountLogin, RegionCapAvailable, SessionRunning } internal string sipServer = ""; private string acctServer = "https://www.bhr.vivox.com/api2/"; private string connectionHandle; private string accountHandle; private string sessionHandle; // Parameters to Vivox daemon private string slvoicePath = ""; private string slvoiceArgs = "-ll 5"; private string daemonNode = "127.0.0.1"; private int daemonPort = 37331; private string voiceUser; private string voicePassword; private string spatialUri; private string spatialCredentials; // Session management private Dictionary<string, VoiceSession> sessions; private VoiceSession spatialSession; private Uri currentParcelCap; private Uri nextParcelCap; private string regionName; // Position update thread private Thread posThread; private ManualResetEvent posRestart; public GridClient Client; private VoicePosition position; private Vector3d oldPosition; private Vector3d oldAt; // Audio interfaces private List<string> inputDevices; /// <summary> /// List of audio input devices /// </summary> public List<string> CaptureDevices { get { return inputDevices; } } private List<string> outputDevices; /// <summary> /// List of audio output devices /// </summary> public List<string> PlaybackDevices { get { return outputDevices; } } private string currentCaptureDevice; private string currentPlaybackDevice; private bool testing = false; public event EventHandler OnSessionCreate; public event EventHandler OnSessionRemove; public delegate void VoiceConnectionChangeCallback(ConnectionState state); public event VoiceConnectionChangeCallback OnVoiceConnectionChange; public delegate void VoiceMicTestCallback(float level); public event VoiceMicTestCallback OnVoiceMicTest; public VoiceGateway(GridClient c) { Random rand = new Random(); daemonPort = rand.Next(34000, 44000); Client = c; sessions = new Dictionary<string, VoiceSession>(); position = new VoicePosition(); position.UpOrientation = new Vector3d(0.0, 1.0, 0.0); position.Velocity = new Vector3d(0.0, 0.0, 0.0); oldPosition = new Vector3d(0, 0, 0); oldAt = new Vector3d(1, 0, 0); slvoiceArgs = " -ll -1"; // Min logging slvoiceArgs += " -i 127.0.0.1:" + daemonPort.ToString(); // slvoiceArgs += " -lf " + control.instance.ClientDir; } /// <summary> /// Start up the Voice service. /// </summary> public void Start() { // Start the background thread if (posThread != null && posThread.IsAlive) posThread.Abort(); posThread = new Thread(new ThreadStart(PositionThreadBody)); posThread.Name = "VoicePositionUpdate"; posThread.IsBackground = true; posRestart = new ManualResetEvent(false); posThread.Start(); Client.Network.EventQueueRunning += new EventHandler<EventQueueRunningEventArgs>(Network_EventQueueRunning); // Connection events OnDaemonRunning += new VoiceGateway.DaemonRunningCallback(connector_OnDaemonRunning); OnDaemonCouldntRun += new VoiceGateway.DaemonCouldntRunCallback(connector_OnDaemonCouldntRun); OnConnectorCreateResponse += new EventHandler<VoiceGateway.VoiceConnectorEventArgs>(connector_OnConnectorCreateResponse); OnDaemonConnected += new DaemonConnectedCallback(connector_OnDaemonConnected); OnDaemonCouldntConnect += new DaemonCouldntConnectCallback(connector_OnDaemonCouldntConnect); OnAuxAudioPropertiesEvent += new EventHandler<AudioPropertiesEventArgs>(connector_OnAuxAudioPropertiesEvent); // Session events OnSessionStateChangeEvent += new EventHandler<SessionStateChangeEventArgs>(connector_OnSessionStateChangeEvent); OnSessionAddedEvent += new EventHandler<SessionAddedEventArgs>(connector_OnSessionAddedEvent); // Session Participants events OnSessionParticipantUpdatedEvent += new EventHandler<ParticipantUpdatedEventArgs>(connector_OnSessionParticipantUpdatedEvent); OnSessionParticipantAddedEvent += new EventHandler<ParticipantAddedEventArgs>(connector_OnSessionParticipantAddedEvent); // Device events OnAuxGetCaptureDevicesResponse += new EventHandler<VoiceDevicesEventArgs>(connector_OnAuxGetCaptureDevicesResponse); OnAuxGetRenderDevicesResponse += new EventHandler<VoiceDevicesEventArgs>(connector_OnAuxGetRenderDevicesResponse); // Generic status response OnVoiceResponse += new EventHandler<VoiceResponseEventArgs>(connector_OnVoiceResponse); // Account events OnAccountLoginResponse += new EventHandler<VoiceAccountEventArgs>(connector_OnAccountLoginResponse); Logger.Log("Voice initialized", Helpers.LogLevel.Info); // If voice provisioning capability is already available, // proceed with voice startup. Otherwise the EventQueueRunning // event will do it. System.Uri vCap = Client.Network.CurrentSim.Caps.CapabilityURI("ProvisionVoiceAccountRequest"); if (vCap != null) RequestVoiceProvision(vCap); } /// <summary> /// Handle miscellaneous request status /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// ///<remarks>If something goes wrong, we log it.</remarks> void connector_OnVoiceResponse(object sender, VoiceGateway.VoiceResponseEventArgs e) { if (e.StatusCode == 0) return; Logger.Log(e.Message + " on " + sender as string, Helpers.LogLevel.Error); } public void Stop() { Client.Network.EventQueueRunning -= new EventHandler<EventQueueRunningEventArgs>(Network_EventQueueRunning); // Connection events OnDaemonRunning -= new VoiceGateway.DaemonRunningCallback(connector_OnDaemonRunning); OnDaemonCouldntRun -= new VoiceGateway.DaemonCouldntRunCallback(connector_OnDaemonCouldntRun); OnConnectorCreateResponse -= new EventHandler<VoiceGateway.VoiceConnectorEventArgs>(connector_OnConnectorCreateResponse); OnDaemonConnected -= new VoiceGateway.DaemonConnectedCallback(connector_OnDaemonConnected); OnDaemonCouldntConnect -= new VoiceGateway.DaemonCouldntConnectCallback(connector_OnDaemonCouldntConnect); OnAuxAudioPropertiesEvent -= new EventHandler<AudioPropertiesEventArgs>(connector_OnAuxAudioPropertiesEvent); // Session events OnSessionStateChangeEvent -= new EventHandler<SessionStateChangeEventArgs>(connector_OnSessionStateChangeEvent); OnSessionAddedEvent -= new EventHandler<SessionAddedEventArgs>(connector_OnSessionAddedEvent); // Session Participants events OnSessionParticipantUpdatedEvent -= new EventHandler<ParticipantUpdatedEventArgs>(connector_OnSessionParticipantUpdatedEvent); OnSessionParticipantAddedEvent -= new EventHandler<ParticipantAddedEventArgs>(connector_OnSessionParticipantAddedEvent); OnSessionParticipantRemovedEvent -= new EventHandler<ParticipantRemovedEventArgs>(connector_OnSessionParticipantRemovedEvent); // Tuning events OnAuxGetCaptureDevicesResponse -= new EventHandler<VoiceGateway.VoiceDevicesEventArgs>(connector_OnAuxGetCaptureDevicesResponse); OnAuxGetRenderDevicesResponse -= new EventHandler<VoiceGateway.VoiceDevicesEventArgs>(connector_OnAuxGetRenderDevicesResponse); // Account events OnAccountLoginResponse -= new EventHandler<VoiceGateway.VoiceAccountEventArgs>(connector_OnAccountLoginResponse); // Stop the background thread if (posThread != null) { PosUpdating(false); if (posThread.IsAlive) posThread.Abort(); posThread = null; } // Close all sessions foreach (VoiceSession s in sessions.Values) { if (OnSessionRemove != null) OnSessionRemove(s, EventArgs.Empty); s.Close(); } // Clear out lots of state so in case of restart we begin at the beginning. currentParcelCap = null; sessions.Clear(); accountHandle = null; voiceUser = null; voicePassword = null; SessionTerminate(sessionHandle); sessionHandle = null; AccountLogout(accountHandle); accountHandle = null; ConnectorInitiateShutdown(connectionHandle); connectionHandle = null; StopDaemon(); } /// <summary> /// Cleanup oject resources /// </summary> public void Dispose() { Stop(); } internal string GetVoiceDaemonPath() { string myDir = Path.GetDirectoryName( (System.Reflection.Assembly.GetEntryAssembly() ?? typeof (VoiceGateway).Assembly).Location); if (Environment.OSVersion.Platform != PlatformID.MacOSX && Environment.OSVersion.Platform != PlatformID.Unix) { string localDaemon = Path.Combine(myDir, Path.Combine("voice", "SLVoice.exe")); if (File.Exists(localDaemon)) return localDaemon; string progFiles; if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ProgramFiles(x86)"))) { progFiles = Environment.GetEnvironmentVariable("ProgramFiles(x86)"); } else { progFiles = Environment.GetEnvironmentVariable("ProgramFiles"); } if (System.IO.File.Exists(Path.Combine(progFiles, @"SecondLife" + Path.DirectorySeparatorChar + @"SLVoice.exe"))) { return Path.Combine(progFiles, @"SecondLife" + Path.DirectorySeparatorChar + @"SLVoice.exe"); } return Path.Combine(myDir, @"SLVoice.exe"); } else { string localDaemon = Path.Combine(myDir, Path.Combine("voice", "SLVoice")); if (File.Exists(localDaemon)) return localDaemon; return Path.Combine(myDir,"SLVoice"); } } void RequestVoiceProvision(System.Uri cap) { OpenMetaverse.Http.CapsClient capClient = new OpenMetaverse.Http.CapsClient(cap); capClient.OnComplete += new OpenMetaverse.Http.CapsClient.CompleteCallback(cClient_OnComplete); OSD postData = new OSD(); // STEP 0 Logger.Log("Requesting voice capability", Helpers.LogLevel.Info); capClient.BeginGetResponse(postData, OSDFormat.Xml, 10000); } /// <summary> /// Request voice cap when changing regions /// </summary> void Network_EventQueueRunning(object sender, EventQueueRunningEventArgs e) { // We only care about the sim we are in. if (e.Simulator != Client.Network.CurrentSim) return; // Did we provision voice login info? if (string.IsNullOrEmpty(voiceUser)) { // The startup steps are // 0. Get voice account info // 1. Start Daemon // 2. Create TCP connection // 3. Create Connector // 4. Account login // 5. Create session // Get the voice provisioning data System.Uri vCap = Client.Network.CurrentSim.Caps.CapabilityURI("ProvisionVoiceAccountRequest"); // Do we have voice capability? if (vCap == null) { Logger.Log("Null voice capability after event queue running", Helpers.LogLevel.Warning); } else { RequestVoiceProvision(vCap); } return; } else { // Change voice session for this region. ParcelChanged(); } } #region Participants void connector_OnSessionParticipantUpdatedEvent(object sender, ParticipantUpdatedEventArgs e) { VoiceSession s = FindSession(e.SessionHandle, false); if (s == null) return; s.ParticipantUpdate(e.URI, e.IsMuted, e.IsSpeaking, e.Volume, e.Energy); } public string SIPFromUUID(UUID id) { return "sip:" + nameFromID(id) + "@" + sipServer; } private static string nameFromID(UUID id) { string result = null; if (id == UUID.Zero) return result; // Prepending this apparently prevents conflicts with reserved names inside the vivox and diamondware code. result = "x"; // Base64 encode and replace the pieces of base64 that are less compatible // with e-mail local-parts. // See RFC-4648 "Base 64 Encoding with URL and Filename Safe Alphabet" byte[] encbuff = id.GetBytes(); result += Convert.ToBase64String(encbuff); result = result.Replace('+', '-'); result = result.Replace('/', '_'); return result; } void connector_OnSessionParticipantAddedEvent(object sender, ParticipantAddedEventArgs e) { VoiceSession s = FindSession(e.SessionHandle, false); if (s == null) { Logger.Log("Orphan participant", Helpers.LogLevel.Error); return; } s.AddParticipant(e.URI); } void connector_OnSessionParticipantRemovedEvent(object sender, ParticipantRemovedEventArgs e) { VoiceSession s = FindSession(e.SessionHandle, false); if (s == null) return; s.RemoveParticipant(e.URI); } #endregion #region Sessions void connector_OnSessionAddedEvent(object sender, SessionAddedEventArgs e) { sessionHandle = e.SessionHandle; // Create our session context. VoiceSession s = FindSession(sessionHandle, true); s.RegionName = regionName; spatialSession = s; // Tell any user-facing code. if (OnSessionCreate != null) OnSessionCreate(s, null); Logger.Log("Added voice session in " + regionName, Helpers.LogLevel.Info); } /// <summary> /// Handle a change in session state /// </summary> void connector_OnSessionStateChangeEvent(object sender, SessionStateChangeEventArgs e) { VoiceSession s; switch (e.State) { case VoiceGateway.SessionState.Connected: s = FindSession(e.SessionHandle, true); sessionHandle = e.SessionHandle; s.RegionName = regionName; spatialSession = s; Logger.Log("Voice connected in " + regionName, Helpers.LogLevel.Info); // Tell any user-facing code. if (OnSessionCreate != null) OnSessionCreate(s, null); break; case VoiceGateway.SessionState.Disconnected: s = FindSession(sessionHandle, false); sessions.Remove(sessionHandle); if (s != null) { Logger.Log("Voice disconnected in " + s.RegionName, Helpers.LogLevel.Info); // Inform interested parties if (OnSessionRemove != null) OnSessionRemove(s, null); if (s == spatialSession) spatialSession = null; } // The previous session is now ended. Check for a new one and // start it going. if (nextParcelCap != null) { currentParcelCap = nextParcelCap; nextParcelCap = null; RequestParcelInfo(currentParcelCap); } break; } } /// <summary> /// Close a voice session /// </summary> /// <param name="sessionHandle"></param> internal void CloseSession(string sessionHandle) { if (!sessions.ContainsKey(sessionHandle)) return; PosUpdating(false); ReportConnectionState(ConnectionState.AccountLogin); // Clean up spatial pointers. VoiceSession s = sessions[sessionHandle]; if (s.IsSpatial) { spatialSession = null; currentParcelCap = null; } // Remove this session from the master session list sessions.Remove(sessionHandle); // Let any user-facing code clean up. if (OnSessionRemove != null) OnSessionRemove(s, null); // Tell SLVoice to clean it up as well. SessionTerminate(sessionHandle); } /// <summary> /// Locate a Session context from its handle /// </summary> /// <remarks>Creates the session context if it does not exist.</remarks> VoiceSession FindSession(string sessionHandle, bool make) { if (sessions.ContainsKey(sessionHandle)) return sessions[sessionHandle]; if (!make) return null; // Create a new session and add it to the sessions list. VoiceSession s = new VoiceSession(this, sessionHandle); // Turn on position updating for spatial sessions // (For now, only spatial sessions are supported) if (s.IsSpatial) PosUpdating(true); // Register the session by its handle sessions.Add(sessionHandle, s); return s; } #endregion #region MinorResponses void connector_OnAuxAudioPropertiesEvent(object sender, AudioPropertiesEventArgs e) { if (OnVoiceMicTest != null) OnVoiceMicTest(e.MicEnergy); } #endregion private void ReportConnectionState(ConnectionState s) { if (OnVoiceConnectionChange == null) return; OnVoiceConnectionChange(s); } /// <summary> /// Handle completion of main voice cap request. /// </summary> /// <param name="client"></param> /// <param name="result"></param> /// <param name="error"></param> void cClient_OnComplete(OpenMetaverse.Http.CapsClient client, OpenMetaverse.StructuredData.OSD result, Exception error) { if (error != null) { Logger.Log("Voice cap error " + error.Message, Helpers.LogLevel.Error); return; } Logger.Log("Voice provisioned", Helpers.LogLevel.Info); ReportConnectionState(ConnectionState.Provisioned); OpenMetaverse.StructuredData.OSDMap pMap = result as OpenMetaverse.StructuredData.OSDMap; // We can get back 4 interesting values: // voice_sip_uri_hostname // voice_account_server_name (actually a full URI) // username // password if (pMap.ContainsKey("voice_sip_uri_hostname")) sipServer = pMap["voice_sip_uri_hostname"].AsString(); if (pMap.ContainsKey("voice_account_server_name")) acctServer = pMap["voice_account_server_name"].AsString(); voiceUser = pMap["username"].AsString(); voicePassword = pMap["password"].AsString(); // Start the SLVoice daemon slvoicePath = GetVoiceDaemonPath(); // Test if the executable exists if (!System.IO.File.Exists(slvoicePath)) { Logger.Log("SLVoice is missing", Helpers.LogLevel.Error); return; } // STEP 1 StartDaemon(slvoicePath, slvoiceArgs); } #region Daemon void connector_OnDaemonCouldntConnect() { Logger.Log("No voice daemon connect", Helpers.LogLevel.Error); } void connector_OnDaemonCouldntRun() { Logger.Log("Daemon not started", Helpers.LogLevel.Error); } /// <summary> /// Daemon has started so connect to it. /// </summary> void connector_OnDaemonRunning() { OnDaemonRunning -= new VoiceGateway.DaemonRunningCallback(connector_OnDaemonRunning); Logger.Log("Daemon started", Helpers.LogLevel.Info); ReportConnectionState(ConnectionState.DaemonStarted); // STEP 2 ConnectToDaemon(daemonNode, daemonPort); } /// <summary> /// The daemon TCP connection is open. /// </summary> void connector_OnDaemonConnected() { Logger.Log("Daemon connected", Helpers.LogLevel.Info); ReportConnectionState(ConnectionState.DaemonConnected); // The connector is what does the logging. VoiceGateway.VoiceLoggingSettings vLog = new VoiceGateway.VoiceLoggingSettings(); #if DEBUG_VOICE vLog.Enabled = true; vLog.FileNamePrefix = "OpenmetaverseVoice"; vLog.FileNameSuffix = ".log"; vLog.LogLevel = 4; #endif // STEP 3 int reqId = ConnectorCreate( "V2 SDK", // Magic value keeps SLVoice happy acctServer, // Account manager server 30000, 30099, // port range vLog); if (reqId < 0) { Logger.Log("No voice connector request", Helpers.LogLevel.Error); } } /// <summary> /// Handle creation of the Connector. /// </summary> void connector_OnConnectorCreateResponse( object sender, VoiceGateway.VoiceConnectorEventArgs e) { Logger.Log("Voice daemon protocol started " + e.Message, Helpers.LogLevel.Info); connectionHandle = e.Handle; if (e.StatusCode != 0) return; // STEP 4 AccountLogin( connectionHandle, voiceUser, voicePassword, "VerifyAnswer", // This can also be "AutoAnswer" "", // Default account management server URI 10, // Throttle state changes true); // Enable buddies and presence } #endregion void connector_OnAccountLoginResponse( object sender, VoiceGateway.VoiceAccountEventArgs e) { Logger.Log("Account Login " + e.Message, Helpers.LogLevel.Info); accountHandle = e.AccountHandle; ReportConnectionState(ConnectionState.AccountLogin); ParcelChanged(); } #region Audio devices /// <summary> /// Handle response to audio output device query /// </summary> void connector_OnAuxGetRenderDevicesResponse( object sender, VoiceGateway.VoiceDevicesEventArgs e) { outputDevices = e.Devices; currentPlaybackDevice = e.CurrentDevice; } /// <summary> /// Handle response to audio input device query /// </summary> void connector_OnAuxGetCaptureDevicesResponse( object sender, VoiceGateway.VoiceDevicesEventArgs e) { inputDevices = e.Devices; currentCaptureDevice = e.CurrentDevice; } public string CurrentCaptureDevice { get { return currentCaptureDevice; } set { currentCaptureDevice = value; AuxSetCaptureDevice(value); } } public string PlaybackDevice { get { return currentPlaybackDevice; } set { currentPlaybackDevice = value; AuxSetRenderDevice(value); } } public int MicLevel { set { ConnectorSetLocalMicVolume(connectionHandle, value); } } public int SpkrLevel { set { ConnectorSetLocalSpeakerVolume(connectionHandle, value); } } public bool MicMute { set { ConnectorMuteLocalMic(connectionHandle, value); } } public bool SpkrMute { set { ConnectorMuteLocalSpeaker(connectionHandle, value); } } /// <summary> /// Set audio test mode /// </summary> public bool TestMode { get { return testing; } set { testing = value; if (testing) { if (spatialSession != null) { spatialSession.Close(); spatialSession = null; } AuxCaptureAudioStart(0); } else { AuxCaptureAudioStop(); ParcelChanged(); } } } #endregion /// <summary> /// Set voice channel for new parcel /// </summary> /// internal void ParcelChanged() { // Get the capability for this parcel. Caps c = Client.Network.CurrentSim.Caps; System.Uri pCap = c.CapabilityURI("ParcelVoiceInfoRequest"); if (pCap == null) { Logger.Log("Null voice capability", Helpers.LogLevel.Error); return; } // Parcel has changed. If we were already in a spatial session, we have to close it first. if (spatialSession != null) { nextParcelCap = pCap; CloseSession(spatialSession.Handle); } // Not already in a session, so can start the new one. RequestParcelInfo(pCap); } private OpenMetaverse.Http.CapsClient parcelCap; /// <summary> /// Request info from a parcel capability Uri. /// </summary> /// <param name="cap"></param> void RequestParcelInfo(Uri cap) { Logger.Log("Requesting region voice info", Helpers.LogLevel.Info); parcelCap = new OpenMetaverse.Http.CapsClient(cap); parcelCap.OnComplete += new OpenMetaverse.Http.CapsClient.CompleteCallback(pCap_OnComplete); OSD postData = new OSD(); currentParcelCap = cap; parcelCap.BeginGetResponse(postData, OSDFormat.Xml, 10000); } /// <summary> /// Receive parcel voice cap /// </summary> /// <param name="client"></param> /// <param name="result"></param> /// <param name="error"></param> void pCap_OnComplete(OpenMetaverse.Http.CapsClient client, OpenMetaverse.StructuredData.OSD result, Exception error) { parcelCap.OnComplete -= new OpenMetaverse.Http.CapsClient.CompleteCallback(pCap_OnComplete); parcelCap = null; if (error != null) { Logger.Log("Region voice cap " + error.Message, Helpers.LogLevel.Error); return; } OpenMetaverse.StructuredData.OSDMap pMap = result as OpenMetaverse.StructuredData.OSDMap; regionName = pMap["region_name"].AsString(); ReportConnectionState(ConnectionState.RegionCapAvailable); if (pMap.ContainsKey("voice_credentials")) { OpenMetaverse.StructuredData.OSDMap cred = pMap["voice_credentials"] as OpenMetaverse.StructuredData.OSDMap; if (cred.ContainsKey("channel_uri")) spatialUri = cred["channel_uri"].AsString(); if (cred.ContainsKey("channel_credentials")) spatialCredentials = cred["channel_credentials"].AsString(); } if (spatialUri == null || spatialUri == "") { // "No voice chat allowed here"); return; } Logger.Log("Voice connecting for region " + regionName, Helpers.LogLevel.Info); // STEP 5 int reqId = SessionCreate( accountHandle, spatialUri, // uri "", // Channel name seems to be always null spatialCredentials, // spatialCredentials, // session password true, // Join Audio false, // Join Text ""); if (reqId < 0) { Logger.Log("Voice Session ReqID " + reqId.ToString(), Helpers.LogLevel.Error); } } #region Location Update /// <summary> /// Tell Vivox where we are standing /// </summary> /// <remarks>This has to be called when we move or turn.</remarks> internal void UpdatePosition(AgentManager self) { // Get position in Global coordinates Vector3d OMVpos = new Vector3d(self.GlobalPosition); // Do not send trivial updates. if (OMVpos.ApproxEquals(oldPosition, 1.0)) return; oldPosition = OMVpos; // Convert to the coordinate space that Vivox uses // OMV X is East, Y is North, Z is up // VVX X is East, Y is up, Z is South position.Position = new Vector3d(OMVpos.X, OMVpos.Z, -OMVpos.Y); // TODO Rotate these two vectors // Get azimuth from the facing Quaternion. // By definition, facing.W = Cos( angle/2 ) double angle = 2.0 * Math.Acos(self.Movement.BodyRotation.W); position.LeftOrientation = new Vector3d(-1.0, 0.0, 0.0); position.AtOrientation = new Vector3d((float)Math.Acos(angle), 0.0, -(float)Math.Asin(angle)); SessionSet3DPosition( sessionHandle, position, position); } /// <summary> /// Start and stop updating out position. /// </summary> /// <param name="go"></param> internal void PosUpdating(bool go) { if (go) posRestart.Set(); else posRestart.Reset(); } private void PositionThreadBody() { while (true) { posRestart.WaitOne(); Thread.Sleep(1500); UpdatePosition(Client.Self); } } #endregion } }
// // Mono.Data.Tds.Protocol.Tds70.cs // // Author: // Tim Coleman (tim@timcoleman.com) // Diego Caravana (diego@toth.it) // Sebastien Pouliot (sebastien@ximian.com) // Daniel Morgan (danielmorgan@verizon.net) // // Copyright (C) 2002 Tim Coleman // Portions (C) 2003 Motus Technologies Inc. (http://www.motus.com) // Portions (C) 2003 Daniel Morgan // // // 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.Security.Protocol.Ntlm; using System; using System.Text; namespace Mono.Data.Tds.Protocol { public class Tds70 : Tds { #region Fields public readonly static TdsVersion Version = TdsVersion.tds70; #endregion // Fields #region Constructors public Tds70 (string server, int port) : this (server, port, 512, 15) { } public Tds70 (string server, int port, int packetSize, int timeout) : base (server, port, packetSize, timeout, Version) { } #endregion // Constructors #region Methods private string BuildExec (string sql) { string esql = sql.Replace ("'", "''"); // escape single quote if (Parameters != null && Parameters.Count > 0) return BuildProcedureCall (String.Format ("sp_executesql N'{0}', N'{1}', ", esql, BuildPreparedParameters ())); else return BuildProcedureCall (String.Format ("sp_executesql N'{0}'", esql)); } private string BuildParameters () { if (Parameters == null || Parameters.Count == 0) return String.Empty; StringBuilder result = new StringBuilder (); foreach (TdsMetaParameter p in Parameters) { if (p.Direction != TdsParameterDirection.ReturnValue) { if (result.Length > 0) result.Append (", "); if (p.Direction == TdsParameterDirection.InputOutput) result.Append (String.Format("{0}={0} output", p.ParameterName)); else result.Append (FormatParameter (p)); } } return result.ToString (); } private string BuildPreparedParameters () { StringBuilder parms = new StringBuilder (); foreach (TdsMetaParameter p in Parameters) { if (parms.Length > 0) parms.Append (", "); parms.Append (p.Prepare ()); if (p.Direction == TdsParameterDirection.Output) parms.Append (" output"); } return parms.ToString (); } private string BuildPreparedQuery (string id) { return BuildProcedureCall (String.Format ("sp_execute {0},", id)); } private string BuildProcedureCall (string procedure) { string exec = String.Empty; StringBuilder declare = new StringBuilder (); StringBuilder select = new StringBuilder (); StringBuilder set = new StringBuilder (); int count = 0; if (Parameters != null) { foreach (TdsMetaParameter p in Parameters) { if (p.Direction != TdsParameterDirection.Input) { if (count == 0) select.Append ("select "); else select.Append (", "); select.Append (p.ParameterName); declare.Append (String.Format ("declare {0}\n", p.Prepare ())); if (p.Direction != TdsParameterDirection.ReturnValue) { if( p.Direction == TdsParameterDirection.InputOutput ) set.Append (String.Format ("set {0}\n", FormatParameter(p))); else set.Append (String.Format ("set {0}=NULL\n", p.ParameterName)); } count += 1; } if (p.Direction == TdsParameterDirection.ReturnValue) { exec = p.ParameterName + "="; } } } exec = "exec " + exec; string sql = String.Format ("{0}{1}{2}{3} {4}\n{5}", declare.ToString (), set.ToString (), exec, procedure, BuildParameters (), select.ToString ()); return sql; } public override bool Connect (TdsConnectionParameters connectionParameters) { if (IsConnected) throw new InvalidOperationException ("The connection is already open."); connectionParms = connectionParameters; SetLanguage (connectionParameters.Language); SetCharset ("utf-8"); byte[] empty = new byte[0]; short authLen = 0; byte pad = (byte) 0; byte[] domainMagic = { 6, 0x7d, 0x0f, 0xfd, 0xff, 0x0, 0x0, 0x0, 0x0, 0xe0, 0x83, 0x0, 0x0, 0x68, 0x01, 0x00, 0x00, 0x09, 0x04, 0x00, 0x00 }; byte[] sqlserverMagic = { 6, 0x83, 0xf2, 0xf8, 0xff, 0x0, 0x0, 0x0, 0x0, 0xe0, 0x03, 0x0, 0x0, 0x88, 0xff, 0xff, 0xff, 0x36, 0x04, 0x00, 0x00 }; byte[] magic = null; if (connectionParameters.DomainLogin == true) magic = domainMagic; else magic = sqlserverMagic; string username = connectionParameters.User; string domain = Environment.UserDomainName; domain = connectionParameters.DefaultDomain = Environment.UserDomainName; int idx = 0; if ((idx = username.IndexOf ("\\")) > -1) { domain = username.Substring (0, idx); username = username.Substring (idx + 1); connectionParameters.DefaultDomain = domain; connectionParameters.User = username; } short partialPacketSize = (short) (86 + ( connectionParameters.Hostname.Length + connectionParameters.ApplicationName.Length + DataSource.Length + connectionParameters.LibraryName.Length + Language.Length + connectionParameters.Database.Length) * 2); if(connectionParameters.DomainLogin == true) { authLen = ((short) (32 + (connectionParameters.Hostname.Length + domain.Length))); partialPacketSize += authLen; } else partialPacketSize += ((short) ((username.Length + connectionParameters.Password.Length) * 2)); short totalPacketSize = (short) partialPacketSize; Comm.StartPacket (TdsPacketType.Logon70); Comm.Append (totalPacketSize); Comm.Append (empty, 5, pad); Comm.Append ((byte) 0x70); // TDS Version 7 Comm.Append (empty, 3, pad); Comm.Append (empty, 4, pad); Comm.Append (magic); short curPos = 86; // Hostname Comm.Append (curPos); Comm.Append ((short) connectionParameters.Hostname.Length); curPos += (short) (connectionParameters.Hostname.Length * 2); if(connectionParameters.DomainLogin.Equals(true)) { Comm.Append((short)0); Comm.Append((short)0); Comm.Append((short)0); Comm.Append((short)0); } else { // Username Comm.Append (curPos); Comm.Append ((short) username.Length); curPos += ((short) (username.Length * 2)); // Password Comm.Append (curPos); Comm.Append ((short) connectionParameters.Password.Length); curPos += (short) (connectionParameters.Password.Length * 2); } // AppName Comm.Append (curPos); Comm.Append ((short) connectionParameters.ApplicationName.Length); curPos += (short) (connectionParameters.ApplicationName.Length * 2); // Server Name Comm.Append (curPos); Comm.Append ((short) DataSource.Length); curPos += (short) (DataSource.Length * 2); // Unknown Comm.Append ((short) 0); Comm.Append ((short) 0); // Library Name Comm.Append (curPos); Comm.Append ((short) connectionParameters.LibraryName.Length); curPos += (short) (connectionParameters.LibraryName.Length * 2); // Language Comm.Append (curPos); Comm.Append ((short) Language.Length); curPos += (short) (Language.Length * 2); // Database Comm.Append (curPos); Comm.Append ((short) connectionParameters.Database.Length); curPos += (short) (connectionParameters.Database.Length * 2); // MAC Address Comm.Append((byte) 0); Comm.Append((byte) 0); Comm.Append((byte) 0); Comm.Append((byte) 0); Comm.Append((byte) 0); Comm.Append((byte) 0); // Authentication Stuff Comm.Append ((short) curPos); if (connectionParameters.DomainLogin == true) { Comm.Append ((short) authLen); curPos += (short) authLen; } else Comm.Append ((short) 0); // Unknown Comm.Append (curPos); Comm.Append ((short) 0); // Connection Parameters Comm.Append (connectionParameters.Hostname); if (connectionParameters.DomainLogin == false) { // SQL Server Authentication Comm.Append (connectionParameters.User); string scrambledPwd = EncryptPassword (connectionParameters.Password); Comm.Append (scrambledPwd); } Comm.Append (connectionParameters.ApplicationName); Comm.Append (DataSource); Comm.Append (connectionParameters.LibraryName); Comm.Append (Language); Comm.Append (connectionParameters.Database); if (connectionParameters.DomainLogin) { // the rest of the packet is NTLMSSP authentication Type1Message msg = new Type1Message (); msg.Domain = domain; msg.Host = connectionParameters.Hostname; msg.Flags = NtlmFlags.NegotiateUnicode | NtlmFlags.NegotiateNtlm | NtlmFlags.NegotiateDomainSupplied | NtlmFlags.NegotiateWorkstationSupplied | NtlmFlags.NegotiateAlwaysSign; // 0xb201 Comm.Append (msg.GetBytes ()); } Comm.SendPacket (); MoreResults = true; SkipToEnd (); return IsConnected; } private static string EncryptPassword (string pass) { int xormask = 0x5a5a; int len = pass.Length; char[] chars = new char[len]; for (int i = 0; i < len; ++i) { int c = ((int) (pass[i])) ^ xormask; int m1 = (c >> 4) & 0x0f0f; int m2 = (c << 4) & 0xf0f0; chars[i] = (char) (m1 | m2); } return new String (chars); } public override bool Reset () { try { ExecProc ("exec sp_reset_connection"); } catch (Exception e) { System.Reflection.PropertyInfo pinfo = e.GetType ().GetProperty ("Class"); if (pinfo != null && pinfo.PropertyType == typeof (byte)) { byte klass = (byte) pinfo.GetValue (e, null); // 11 to 16 indicates error that can be fixed by the user such as 'Invalid object name' if (klass < 11 || klass > 16) return false; } } return true; } public override void ExecPrepared (string commandText, TdsMetaParameterCollection parameters, int timeout, bool wantResults) { Parameters = parameters; ExecuteQuery (BuildPreparedQuery (commandText), timeout, wantResults); } public override void ExecProc (string commandText, TdsMetaParameterCollection parameters, int timeout, bool wantResults) { Parameters = parameters; ExecuteQuery (BuildProcedureCall (commandText), timeout, wantResults); } public override void Execute (string commandText, TdsMetaParameterCollection parameters, int timeout, bool wantResults) { Parameters = parameters; string sql = commandText; if (wantResults || (Parameters != null && Parameters.Count > 0)) sql = BuildExec (commandText); ExecuteQuery (sql, timeout, wantResults); } private bool IsBlobType (TdsColumnType columnType) { return (columnType == TdsColumnType.Text || columnType == TdsColumnType.Image || columnType == TdsColumnType.NText); } private bool IsLargeType (TdsColumnType columnType) { return (columnType == TdsColumnType.NChar || (byte) columnType > 128); } private string FormatParameter (TdsMetaParameter parameter) { if (parameter.Direction == TdsParameterDirection.Output) return String.Format ("{0}={0} output", parameter.ParameterName); if (parameter.Value == null || parameter.Value == DBNull.Value) return parameter.ParameterName + "=NULL"; string value = null; switch (parameter.TypeName) { case "smalldatetime": case "datetime": DateTime d = (DateTime)parameter.Value; value = String.Format(System.Globalization.CultureInfo.InvariantCulture, "'{0:MMM dd yyyy hh:mm:ss tt}'", d ); break; case "bigint": case "decimal": case "float": case "int": case "money": case "real": case "smallint": case "smallmoney": case "tinyint": object paramValue = parameter.Value; Type paramType = paramValue.GetType (); if (paramType.IsEnum) paramValue = Convert.ChangeType (paramValue, Type.GetTypeCode (paramType)); value = paramValue.ToString (); break; case "nvarchar": case "nchar": value = String.Format ("N'{0}'", parameter.Value.ToString ().Replace ("'", "''")); break; case "uniqueidentifier": value = String.Format ("0x{0}", ((Guid) parameter.Value).ToString ("N")); break; case "bit": if (parameter.Value.GetType () == typeof (bool)) value = (((bool) parameter.Value) ? "0x1" : "0x0"); else value = parameter.Value.ToString (); break; case "image": case "binary": case "varbinary": value = String.Format ("0x{0}", BitConverter.ToString ((byte[]) parameter.Value).Replace ("-", "").ToLower ()); break; default: value = String.Format ("'{0}'", parameter.Value.ToString ().Replace ("'", "''")); break; } return parameter.ParameterName + "=" + value; } public override string Prepare (string commandText, TdsMetaParameterCollection parameters) { Parameters = parameters; TdsMetaParameterCollection parms = new TdsMetaParameterCollection (); TdsMetaParameter parm = new TdsMetaParameter ("@P1", "int", null); parm.Direction = TdsParameterDirection.Output; parms.Add (parm); parms.Add (new TdsMetaParameter ("@P2", "nvarchar", BuildPreparedParameters ())); parms.Add (new TdsMetaParameter ("@P3", "nvarchar", commandText)); ExecProc ("sp_prepare", parms, 0, true); SkipToEnd (); if (ColumnValues [0] == null || ColumnValues [0] == DBNull.Value) throw new TdsInternalException (); return ColumnValues [0].ToString (); } protected override TdsDataColumnCollection ProcessColumnInfo () { TdsDataColumnCollection result = new TdsDataColumnCollection (); int numColumns = Comm.GetTdsShort (); for (int i = 0; i < numColumns; i += 1) { byte[] flagData = new byte[4]; for (int j = 0; j < 4; j += 1) flagData[j] = Comm.GetByte (); bool nullable = (flagData[2] & 0x01) > 0; bool caseSensitive = (flagData[2] & 0x02) > 0; bool writable = (flagData[2] & 0x0c) > 0; bool autoIncrement = (flagData[2] & 0x10) > 0; bool isIdentity = (flagData[2] & 0x10) > 0; TdsColumnType columnType = (TdsColumnType) (Comm.GetByte () & 0xff); if ((byte) columnType == 0xef) columnType = TdsColumnType.NChar; byte xColumnType = 0; if (IsLargeType (columnType)) { xColumnType = (byte) columnType; if (columnType != TdsColumnType.NChar) columnType -= 128; } int columnSize; string tableName = null; if (IsBlobType (columnType)) { columnSize = Comm.GetTdsInt (); tableName = Comm.GetString (Comm.GetTdsShort ()); } else if (IsFixedSizeColumn (columnType)) columnSize = LookupBufferSize (columnType); else if (IsLargeType ((TdsColumnType) xColumnType)) columnSize = Comm.GetTdsShort (); else columnSize = Comm.GetByte () & 0xff; byte precision = 0; byte scale = 0; switch (columnType) { case TdsColumnType.NText: case TdsColumnType.NChar: case TdsColumnType.NVarChar: columnSize /= 2; break; case TdsColumnType.Decimal: case TdsColumnType.Numeric: precision = Comm.GetByte (); scale = Comm.GetByte (); break; } string columnName = Comm.GetString (Comm.GetByte ()); int index = result.Add (new TdsDataColumn ()); result[index]["AllowDBNull"] = nullable; result[index]["ColumnName"] = columnName; result[index]["ColumnSize"] = columnSize; result[index]["ColumnType"] = columnType; result[index]["IsIdentity"] = isIdentity; result[index]["IsReadOnly"] = !writable; result[index]["NumericPrecision"] = precision; result[index]["NumericScale"] = scale; result[index]["BaseTableName"] = tableName; } return result; } public override void Unprepare (string statementId) { TdsMetaParameterCollection parms = new TdsMetaParameterCollection (); parms.Add (new TdsMetaParameter ("@P1", "int", Int32.Parse (statementId))); ExecProc ("sp_unprepare", parms, 0, false); } #endregion // Methods #if NET_2_0 #region Asynchronous Methods public override IAsyncResult BeginExecuteNonQuery (string cmdText, TdsMetaParameterCollection parameters, AsyncCallback callback, object state) { Parameters = parameters; string sql = cmdText; if (Parameters != null && Parameters.Count > 0) sql = BuildExec (cmdText); IAsyncResult ar = BeginExecuteQueryInternal (sql, false, callback, state); return ar; } public override void EndExecuteNonQuery (IAsyncResult ar) { EndExecuteQueryInternal (ar); } public override IAsyncResult BeginExecuteQuery (string cmdText, TdsMetaParameterCollection parameters, AsyncCallback callback, object state) { Parameters = parameters; string sql = cmdText; if (Parameters != null && Parameters.Count > 0) sql = BuildExec (cmdText); IAsyncResult ar = BeginExecuteQueryInternal (sql, true, callback, state); return ar; } public override void EndExecuteQuery (IAsyncResult ar) { EndExecuteQueryInternal (ar); } public override IAsyncResult BeginExecuteProcedure (string prolog, string epilog, string cmdText, bool IsNonQuery, TdsMetaParameterCollection parameters, AsyncCallback callback, object state) { Parameters = parameters; string pcall = BuildProcedureCall (cmdText); string sql = String.Format ("{0};{1};{2};", prolog, pcall, epilog); IAsyncResult ar = BeginExecuteQueryInternal (sql, !IsNonQuery, callback, state); return ar; } public override void EndExecuteProcedure (IAsyncResult ar) { EndExecuteQueryInternal (ar); } #endregion // Asynchronous Methods #endif // NET_2_0 } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Net.Mail { public partial class AlternateView : System.Net.Mail.AttachmentBase { public AlternateView(System.IO.Stream contentStream) : base (default(System.IO.Stream)) { } public AlternateView(System.IO.Stream contentStream, System.Net.Mime.ContentType contentType) : base (default(System.IO.Stream)) { } public AlternateView(System.IO.Stream contentStream, string mediaType) : base (default(System.IO.Stream)) { } public AlternateView(string fileName) : base (default(System.IO.Stream)) { } public AlternateView(string fileName, System.Net.Mime.ContentType contentType) : base (default(System.IO.Stream)) { } public AlternateView(string fileName, string mediaType) : base (default(System.IO.Stream)) { } public System.Uri BaseUri { get { throw null; } set { } } public System.Net.Mail.LinkedResourceCollection LinkedResources { get { throw null; } } public static System.Net.Mail.AlternateView CreateAlternateViewFromString(string content) { throw null; } public static System.Net.Mail.AlternateView CreateAlternateViewFromString(string content, System.Net.Mime.ContentType contentType) { throw null; } public static System.Net.Mail.AlternateView CreateAlternateViewFromString(string content, System.Text.Encoding contentEncoding, string mediaType) { throw null; } protected override void Dispose(bool disposing) { } } public sealed partial class AlternateViewCollection : System.Collections.ObjectModel.Collection<System.Net.Mail.AlternateView>, System.IDisposable { internal AlternateViewCollection() { } protected override void ClearItems() { } public void Dispose() { } protected override void InsertItem(int index, System.Net.Mail.AlternateView item) { } protected override void RemoveItem(int index) { } protected override void SetItem(int index, System.Net.Mail.AlternateView item) { } } public partial class Attachment : System.Net.Mail.AttachmentBase { public Attachment(System.IO.Stream contentStream, System.Net.Mime.ContentType contentType) : base (default(System.IO.Stream)) { } public Attachment(System.IO.Stream contentStream, string name) : base (default(System.IO.Stream)) { } public Attachment(System.IO.Stream contentStream, string name, string mediaType) : base (default(System.IO.Stream)) { } public Attachment(string fileName) : base (default(System.IO.Stream)) { } public Attachment(string fileName, System.Net.Mime.ContentType contentType) : base (default(System.IO.Stream)) { } public Attachment(string fileName, string mediaType) : base (default(System.IO.Stream)) { } public System.Net.Mime.ContentDisposition ContentDisposition { get { throw null; } } public string Name { get { throw null; } set { } } public System.Text.Encoding NameEncoding { get { throw null; } set { } } public static System.Net.Mail.Attachment CreateAttachmentFromString(string content, System.Net.Mime.ContentType contentType) { throw null; } public static System.Net.Mail.Attachment CreateAttachmentFromString(string content, string name) { throw null; } public static System.Net.Mail.Attachment CreateAttachmentFromString(string content, string name, System.Text.Encoding contentEncoding, string mediaType) { throw null; } } public abstract partial class AttachmentBase : System.IDisposable { protected AttachmentBase(System.IO.Stream contentStream) { } protected AttachmentBase(System.IO.Stream contentStream, System.Net.Mime.ContentType contentType) { } protected AttachmentBase(System.IO.Stream contentStream, string mediaType) { } protected AttachmentBase(string fileName) { } protected AttachmentBase(string fileName, System.Net.Mime.ContentType contentType) { } protected AttachmentBase(string fileName, string mediaType) { } public string ContentId { get { throw null; } set { } } public System.IO.Stream ContentStream { get { throw null; } } public System.Net.Mime.ContentType ContentType { get { throw null; } set { } } public System.Net.Mime.TransferEncoding TransferEncoding { get { throw null; } set { } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } } public sealed partial class AttachmentCollection : System.Collections.ObjectModel.Collection<System.Net.Mail.Attachment>, System.IDisposable { internal AttachmentCollection() { } protected override void ClearItems() { } public void Dispose() { } protected override void InsertItem(int index, System.Net.Mail.Attachment item) { } protected override void RemoveItem(int index) { } protected override void SetItem(int index, System.Net.Mail.Attachment item) { } } [System.FlagsAttribute] public enum DeliveryNotificationOptions { Delay = 4, Never = 134217728, None = 0, OnFailure = 2, OnSuccess = 1, } public partial class LinkedResource : System.Net.Mail.AttachmentBase { public LinkedResource(System.IO.Stream contentStream) : base (default(System.IO.Stream)) { } public LinkedResource(System.IO.Stream contentStream, System.Net.Mime.ContentType contentType) : base (default(System.IO.Stream)) { } public LinkedResource(System.IO.Stream contentStream, string mediaType) : base (default(System.IO.Stream)) { } public LinkedResource(string fileName) : base (default(System.IO.Stream)) { } public LinkedResource(string fileName, System.Net.Mime.ContentType contentType) : base (default(System.IO.Stream)) { } public LinkedResource(string fileName, string mediaType) : base (default(System.IO.Stream)) { } public System.Uri ContentLink { get { throw null; } set { } } public static System.Net.Mail.LinkedResource CreateLinkedResourceFromString(string content) { throw null; } public static System.Net.Mail.LinkedResource CreateLinkedResourceFromString(string content, System.Net.Mime.ContentType contentType) { throw null; } public static System.Net.Mail.LinkedResource CreateLinkedResourceFromString(string content, System.Text.Encoding contentEncoding, string mediaType) { throw null; } } public sealed partial class LinkedResourceCollection : System.Collections.ObjectModel.Collection<System.Net.Mail.LinkedResource>, System.IDisposable { internal LinkedResourceCollection() { } protected override void ClearItems() { } public void Dispose() { } protected override void InsertItem(int index, System.Net.Mail.LinkedResource item) { } protected override void RemoveItem(int index) { } protected override void SetItem(int index, System.Net.Mail.LinkedResource item) { } } public partial class MailAddress { public MailAddress(string address) { } public MailAddress(string address, string displayName) { } public MailAddress(string address, string displayName, System.Text.Encoding displayNameEncoding) { } public string Address { get { throw null; } } public string DisplayName { get { throw null; } } public string Host { get { throw null; } } public string User { get { throw null; } } public override bool Equals(object value) { throw null; } public override int GetHashCode() { throw null; } public override string ToString() { throw null; } } public partial class MailAddressCollection : System.Collections.ObjectModel.Collection<System.Net.Mail.MailAddress> { public MailAddressCollection() { } public void Add(string addresses) { } protected override void InsertItem(int index, System.Net.Mail.MailAddress item) { } protected override void SetItem(int index, System.Net.Mail.MailAddress item) { } public override string ToString() { throw null; } } public partial class MailMessage : System.IDisposable { public MailMessage() { } public MailMessage(System.Net.Mail.MailAddress from, System.Net.Mail.MailAddress to) { } public MailMessage(string from, string to) { } public MailMessage(string from, string to, string subject, string body) { } public System.Net.Mail.AlternateViewCollection AlternateViews { get { throw null; } } public System.Net.Mail.AttachmentCollection Attachments { get { throw null; } } public System.Net.Mail.MailAddressCollection Bcc { get { throw null; } } public string Body { get { throw null; } set { } } public System.Text.Encoding BodyEncoding { get { throw null; } set { } } public System.Net.Mime.TransferEncoding BodyTransferEncoding { get { throw null; } set { } } public System.Net.Mail.MailAddressCollection CC { get { throw null; } } public System.Net.Mail.DeliveryNotificationOptions DeliveryNotificationOptions { get { throw null; } set { } } public System.Net.Mail.MailAddress From { get { throw null; } set { } } public System.Collections.Specialized.NameValueCollection Headers { get { throw null; } } public System.Text.Encoding HeadersEncoding { get { throw null; } set { } } public bool IsBodyHtml { get { throw null; } set { } } public System.Net.Mail.MailPriority Priority { get { throw null; } set { } } [System.ObsoleteAttribute("ReplyTo is obsoleted for this type. Please use ReplyToList instead which can accept multiple addresses. https://go.microsoft.com/fwlink/?linkid=14202")] public System.Net.Mail.MailAddress ReplyTo { get { throw null; } set { } } public System.Net.Mail.MailAddressCollection ReplyToList { get { throw null; } } public System.Net.Mail.MailAddress Sender { get { throw null; } set { } } public string Subject { get { throw null; } set { } } public System.Text.Encoding SubjectEncoding { get { throw null; } set { } } public System.Net.Mail.MailAddressCollection To { get { throw null; } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } } public enum MailPriority { High = 2, Low = 1, Normal = 0, } public delegate void SendCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e); public partial class SmtpClient : System.IDisposable { public SmtpClient() { } public SmtpClient(string host) { } public SmtpClient(string host, int port) { } public System.Security.Cryptography.X509Certificates.X509CertificateCollection ClientCertificates { get { throw null; } } public System.Net.ICredentialsByHost Credentials { get { throw null; } set { } } public System.Net.Mail.SmtpDeliveryFormat DeliveryFormat { get { throw null; } set { } } public System.Net.Mail.SmtpDeliveryMethod DeliveryMethod { get { throw null; } set { } } public bool EnableSsl { get { throw null; } set { } } public string Host { get { throw null; } set { } } public string PickupDirectoryLocation { get { throw null; } set { } } public int Port { get { throw null; } set { } } public System.Net.ServicePoint ServicePoint { get { throw null; } } public string TargetName { get { throw null; } set { } } public int Timeout { get { throw null; } set { } } public bool UseDefaultCredentials { get { throw null; } set { } } public event System.Net.Mail.SendCompletedEventHandler SendCompleted { add { } remove { } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } protected void OnSendCompleted(System.ComponentModel.AsyncCompletedEventArgs e) { } public void Send(System.Net.Mail.MailMessage message) { } public void Send(string from, string recipients, string subject, string body) { } public void SendAsync(System.Net.Mail.MailMessage message, object userToken) { } public void SendAsync(string from, string recipients, string subject, string body, object userToken) { } public void SendAsyncCancel() { } public System.Threading.Tasks.Task SendMailAsync(System.Net.Mail.MailMessage message) { throw null; } public System.Threading.Tasks.Task SendMailAsync(string from, string recipients, string subject, string body) { throw null; } } public enum SmtpDeliveryFormat { International = 1, SevenBit = 0, } public enum SmtpDeliveryMethod { Network = 0, PickupDirectoryFromIis = 2, SpecifiedPickupDirectory = 1, } public partial class SmtpException : System.Exception, System.Runtime.Serialization.ISerializable { public SmtpException() { } public SmtpException(System.Net.Mail.SmtpStatusCode statusCode) { } public SmtpException(System.Net.Mail.SmtpStatusCode statusCode, string message) { } protected SmtpException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } public SmtpException(string message) { } public SmtpException(string message, System.Exception innerException) { } public System.Net.Mail.SmtpStatusCode StatusCode { get { throw null; } set { } } public override void GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } } public partial class SmtpFailedRecipientException : System.Net.Mail.SmtpException, System.Runtime.Serialization.ISerializable { public SmtpFailedRecipientException() { } public SmtpFailedRecipientException(System.Net.Mail.SmtpStatusCode statusCode, string failedRecipient) { } public SmtpFailedRecipientException(System.Net.Mail.SmtpStatusCode statusCode, string failedRecipient, string serverResponse) { } protected SmtpFailedRecipientException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public SmtpFailedRecipientException(string message) { } public SmtpFailedRecipientException(string message, System.Exception innerException) { } public SmtpFailedRecipientException(string message, string failedRecipient, System.Exception innerException) { } public string FailedRecipient { get { throw null; } } public override void GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } } public partial class SmtpFailedRecipientsException : System.Net.Mail.SmtpFailedRecipientException, System.Runtime.Serialization.ISerializable { public SmtpFailedRecipientsException() { } protected SmtpFailedRecipientsException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public SmtpFailedRecipientsException(string message) { } public SmtpFailedRecipientsException(string message, System.Exception innerException) { } public SmtpFailedRecipientsException(string message, System.Net.Mail.SmtpFailedRecipientException[] innerExceptions) { } public System.Net.Mail.SmtpFailedRecipientException[] InnerExceptions { get { throw null; } } public override void GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } } public enum SmtpStatusCode { BadCommandSequence = 503, CannotVerifyUserWillAttemptDelivery = 252, ClientNotPermitted = 454, CommandNotImplemented = 502, CommandParameterNotImplemented = 504, CommandUnrecognized = 500, ExceededStorageAllocation = 552, GeneralFailure = -1, HelpMessage = 214, InsufficientStorage = 452, LocalErrorInProcessing = 451, MailboxBusy = 450, MailboxNameNotAllowed = 553, MailboxUnavailable = 550, MustIssueStartTlsFirst = 530, Ok = 250, ServiceClosingTransmissionChannel = 221, ServiceNotAvailable = 421, ServiceReady = 220, StartMailInput = 354, SyntaxError = 501, SystemStatus = 211, TransactionFailed = 554, UserNotLocalTryAlternatePath = 551, UserNotLocalWillForward = 251, } }
using UnityEngine; using System.Collections; using UMA; public class UMACustomization : MonoBehaviour { public Transform sliderPrefab; public UMAData umaData; public UMADynamicAvatar umaDynamicAvatar; public CameraTrack cameraTrack; private UMADnaHumanoid umaDna; private UMADnaTutorial umaTutorialDna; public SliderControl[] sliderControlList = new SliderControl[0]; public SlotLibrary mySlotLibrary; public OverlayLibrary myOverlayLibrary; public bool editing = false; protected virtual void Start() { sliderControlList = new SliderControl[47]; //Changed slider order sliderControlList[0] = InstantiateSlider("height",0,0); sliderControlList[1] = InstantiateSlider("headSize",1,0); sliderControlList[43] = InstantiateSlider("headWidth",2,0); sliderControlList[32] = InstantiateSlider("forehead size",3,0); sliderControlList[33] = InstantiateSlider("forehead position",4,0); sliderControlList[12] = InstantiateSlider("ears size",0,1); sliderControlList[13] = InstantiateSlider("ears position",1,1); sliderControlList[14] = InstantiateSlider("ears rotation",2,1); sliderControlList[28] = InstantiateSlider("cheek size",0,2); sliderControlList[29] = InstantiateSlider("cheek position",1,2); sliderControlList[30] = InstantiateSlider("lowCheek pronounced",2,2); sliderControlList[31] = InstantiateSlider("lowCheek position",3,2); sliderControlList[15] = InstantiateSlider("nose size",0,3); sliderControlList[16] = InstantiateSlider("nose curve",1,3); sliderControlList[17] = InstantiateSlider("nose width",2,3); sliderControlList[18] = InstantiateSlider("nose inclination",0,4); sliderControlList[19] = InstantiateSlider("nose position",1,4); sliderControlList[20] = InstantiateSlider("nose pronounced",2,4); sliderControlList[21] = InstantiateSlider("nose flatten",3,4); sliderControlList[44] = InstantiateSlider("eye Size",0,5); sliderControlList[45] = InstantiateSlider("eye Rotation",1,5); sliderControlList[34] = InstantiateSlider("lips size",2,5); sliderControlList[35] = InstantiateSlider("mouth size",3,5); sliderControlList[25] = InstantiateSlider("mandible size",4,5); sliderControlList[26] = InstantiateSlider("jaw Size",0,6); sliderControlList[27] = InstantiateSlider("jaw Position",1,6); sliderControlList[2] = InstantiateSlider("neck",2,6); sliderControlList[22] = InstantiateSlider("chinSize",0,7); sliderControlList[23] = InstantiateSlider("chinPronounced",1,7); sliderControlList[24] = InstantiateSlider("chinPosition",2,7); sliderControlList[7] = InstantiateSlider("upper muscle",0,8); sliderControlList[8] = InstantiateSlider("lower muscle",1,8); sliderControlList[9] = InstantiateSlider("upper weight",2,8); sliderControlList[10] = InstantiateSlider("lower weight",3,8); sliderControlList[3] = InstantiateSlider("arm Length",0,9); sliderControlList[38] = InstantiateSlider("arm Width",1,9); sliderControlList[39] = InstantiateSlider("forearm Length",2,9); sliderControlList[40] = InstantiateSlider("forearm Width",3,9); sliderControlList[4] = InstantiateSlider("hands Size",4,9); sliderControlList[5] = InstantiateSlider("feet Size",0,10); sliderControlList[6] = InstantiateSlider("leg Separation",1,10); sliderControlList[11] = InstantiateSlider("legsSize",2,10); sliderControlList[37] = InstantiateSlider("Gluteus Size",3,10); sliderControlList[36] = InstantiateSlider("breatsSize",0,11); sliderControlList[41] = InstantiateSlider("belly",1,11); sliderControlList[42] = InstantiateSlider("waist",2,11); sliderControlList[46] = InstantiateSlider("Eye Spacing",3,6); } void Update () { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if(Input.GetMouseButtonDown(1)){ if (Physics.Raycast(ray, out hit, 100)){ Transform tempTransform = hit.collider.transform; //Dont want to use an extra layer or specific tag on UMAs, and since UMAData has moved, Ill keep this for now if(tempTransform.parent){ if(tempTransform.parent.parent){ umaData = tempTransform.parent.parent.GetComponent<UMAData>(); } } if(umaData){ AvatarSetup(); } } } if(umaData){ TransferValues(); editing = false; for(int i = 0; i < sliderControlList.Length; i++){ if(sliderControlList[i].pressed == true){ editing = true; UpdateUMAShape(); } } } } public void AvatarSetup(){ umaDynamicAvatar = umaData.gameObject.GetComponent<UMADynamicAvatar>(); if(cameraTrack){ cameraTrack.target = umaData.umaRoot.transform; } umaDna = umaData.GetDna<UMADnaHumanoid>(); umaTutorialDna = umaData.GetDna<UMADnaTutorial>(); ReceiveValues(); } public SliderControl InstantiateSlider(string name, int X, int Y){ Transform TempSlider; TempSlider = Instantiate(sliderPrefab,Vector3.zero, Quaternion.identity) as Transform; TempSlider.parent = transform; TempSlider.gameObject.name = name; SliderControl tempSlider = TempSlider.GetComponent("SliderControl") as SliderControl; tempSlider.actualValue = 0.5f; tempSlider.descriptionText.text = name; tempSlider.sliderOffset.x = 20 + X*100; tempSlider.sliderOffset.y = -20 - Y*60; return tempSlider; } public SliderControl InstantiateStepSlider(string name, int X, int Y){ SliderControl tempSlider = InstantiateSlider(name,X,Y); tempSlider.stepSlider = true; return tempSlider; } public void UpdateUMAAtlas(){ umaData.isTextureDirty = true; umaData.Dirty(); } public void UpdateUMAShape(){ umaData.isShapeDirty = true; umaData.Dirty(); } public virtual void ReceiveValues() { if(umaDna != null){ sliderControlList[0].actualValue = umaDna.height; sliderControlList[1].actualValue = umaDna.headSize ; sliderControlList[43].actualValue = umaDna.headWidth ; sliderControlList[2].actualValue = umaDna.neckThickness; sliderControlList[3].actualValue = umaDna.armLength; sliderControlList[4].actualValue = umaDna.handsSize; sliderControlList[5].actualValue = umaDna.feetSize; sliderControlList[6].actualValue = umaDna.legSeparation; sliderControlList[7].actualValue = umaDna.upperMuscle; sliderControlList[8].actualValue = umaDna.lowerMuscle; sliderControlList[9].actualValue = umaDna.upperWeight; sliderControlList[10].actualValue = umaDna.lowerWeight; sliderControlList[11].actualValue = umaDna.legsSize; sliderControlList[12].actualValue = umaDna.earsSize; sliderControlList[13].actualValue = umaDna.earsPosition; sliderControlList[14].actualValue = umaDna.earsRotation; sliderControlList[15].actualValue = umaDna.noseSize; sliderControlList[16].actualValue = umaDna.noseCurve; sliderControlList[17].actualValue = umaDna.noseWidth; sliderControlList[18].actualValue = umaDna.noseInclination; sliderControlList[19].actualValue = umaDna.nosePosition; sliderControlList[20].actualValue = umaDna.nosePronounced; sliderControlList[21].actualValue = umaDna.noseFlatten; sliderControlList[22].actualValue = umaDna.chinSize; sliderControlList[23].actualValue = umaDna.chinPronounced; sliderControlList[24].actualValue = umaDna.chinPosition; sliderControlList[25].actualValue = umaDna.mandibleSize; sliderControlList[26].actualValue = umaDna.jawsSize; sliderControlList[27].actualValue = umaDna.jawsPosition; sliderControlList[28].actualValue = umaDna.cheekSize; sliderControlList[29].actualValue = umaDna.cheekPosition; sliderControlList[30].actualValue = umaDna.lowCheekPronounced; sliderControlList[31].actualValue = umaDna.lowCheekPosition; sliderControlList[32].actualValue = umaDna.foreheadSize; sliderControlList[33].actualValue = umaDna.foreheadPosition; sliderControlList[44].actualValue = umaDna.eyeSize; sliderControlList[45].actualValue = umaDna.eyeRotation; sliderControlList[34].actualValue = umaDna.lipsSize; sliderControlList[35].actualValue = umaDna.mouthSize; sliderControlList[36].actualValue = umaDna.breastSize; sliderControlList[37].actualValue = umaDna.gluteusSize; sliderControlList[38].actualValue = umaDna.armWidth; sliderControlList[39].actualValue = umaDna.forearmLength; sliderControlList[40].actualValue = umaDna.forearmWidth; sliderControlList[41].actualValue = umaDna.belly; sliderControlList[42].actualValue = umaDna.waist; // for(int i = 0; i < sliderControlList.Length; i++){ // sliderControlList[i].ForceUpdate(); // } } if (umaTutorialDna != null) { sliderControlList[46].enabled = true; sliderControlList[46].actualValue = umaTutorialDna.eyeSpacing; } else { sliderControlList[46].enabled = false; } } public virtual void TransferValues(){ if(umaDna != null){ umaDna.height = sliderControlList[0].actualValue; umaDna.headSize = sliderControlList[1].actualValue; umaDna.headWidth = sliderControlList[43].actualValue; umaDna.neckThickness = sliderControlList[2].actualValue; umaDna.armLength = sliderControlList[3].actualValue; umaDna.handsSize = sliderControlList[4].actualValue; umaDna.feetSize = sliderControlList[5].actualValue; umaDna.legSeparation = sliderControlList[6].actualValue; umaDna.upperMuscle = sliderControlList[7].actualValue; umaDna.lowerMuscle = sliderControlList[8].actualValue; umaDna.upperWeight = sliderControlList[9].actualValue; umaDna.lowerWeight = sliderControlList[10].actualValue; umaDna.legsSize = sliderControlList[11].actualValue; umaDna.earsSize = sliderControlList[12].actualValue; umaDna.earsPosition = sliderControlList[13].actualValue; umaDna.earsRotation = sliderControlList[14].actualValue; umaDna.noseSize = sliderControlList[15].actualValue; umaDna.noseCurve = sliderControlList[16].actualValue; umaDna.noseWidth = sliderControlList[17].actualValue; umaDna.noseInclination = sliderControlList[18].actualValue; umaDna.nosePosition = sliderControlList[19].actualValue; umaDna.nosePronounced = sliderControlList[20].actualValue; umaDna.noseFlatten = sliderControlList[21].actualValue; umaDna.chinSize = sliderControlList[22].actualValue; umaDna.chinPronounced = sliderControlList[23].actualValue; umaDna.chinPosition = sliderControlList[24].actualValue; umaDna.mandibleSize = sliderControlList[25].actualValue; umaDna.jawsSize = sliderControlList[26].actualValue; umaDna.jawsPosition = sliderControlList[27].actualValue; umaDna.cheekSize = sliderControlList[28].actualValue; umaDna.cheekPosition = sliderControlList[29].actualValue; umaDna.lowCheekPronounced = sliderControlList[30].actualValue; umaDna.lowCheekPosition = sliderControlList[31].actualValue; umaDna.foreheadSize = sliderControlList[32].actualValue; umaDna.foreheadPosition = sliderControlList[33].actualValue; umaDna.eyeSize = sliderControlList[44].actualValue; umaDna.eyeRotation = sliderControlList[45].actualValue; umaDna.lipsSize = sliderControlList[34].actualValue; umaDna.mouthSize = sliderControlList[35].actualValue; umaDna.breastSize = sliderControlList[36].actualValue; umaDna.gluteusSize = sliderControlList[37].actualValue; umaDna.armWidth = sliderControlList[38].actualValue; umaDna.forearmLength = sliderControlList[39].actualValue; umaDna.forearmWidth = sliderControlList[40].actualValue; umaDna.belly = sliderControlList[41].actualValue; umaDna.waist = sliderControlList[42].actualValue; } if (umaTutorialDna != null) { umaTutorialDna.eyeSpacing = sliderControlList[46].actualValue; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; using System.Xml; namespace System.Xml.XPath { /// <summary> /// Reader that traverses the subtree rooted at the current position of the specified navigator. /// </summary> internal class XPathNavigatorReader : XmlReader, IXmlNamespaceResolver { enum State { Initial, Content, EndElement, Attribute, AttrVal, InReadBinary, EOF, Closed, Error, } private XPathNavigator nav; private XPathNavigator navToRead; private int depth; private State state; private XmlNodeType nodeType; private int attrCount; private bool readEntireDocument; private ReadContentAsBinaryHelper readBinaryHelper; private State savedState; internal const string space = "space"; internal static XmlNodeType[] convertFromXPathNodeType = { XmlNodeType.Document, // XPathNodeType.Root XmlNodeType.Element, // XPathNodeType.Element XmlNodeType.Attribute, // XPathNodeType.Attribute XmlNodeType.Attribute, // XPathNodeType.Namespace XmlNodeType.Text, // XPathNodeType.Text XmlNodeType.SignificantWhitespace, // XPathNodeType.SignificantWhitespace XmlNodeType.Whitespace, // XPathNodeType.Whitespace XmlNodeType.ProcessingInstruction, // XPathNodeType.ProcessingInstruction XmlNodeType.Comment, // XPathNodeType.Comment XmlNodeType.None // XPathNodeType.All }; /// <summary> /// Translates an XPathNodeType value into the corresponding XmlNodeType value. /// XPathNodeType.Whitespace and XPathNodeType.SignificantWhitespace are mapped into XmlNodeType.Text. /// </summary> internal static XmlNodeType ToXmlNodeType(XPathNodeType typ) { return XPathNavigatorReader.convertFromXPathNodeType[(int)typ]; } static public XPathNavigatorReader Create(XPathNavigator navToRead) { XPathNavigator nav = navToRead.Clone(); return new XPathNavigatorReader(nav); } protected XPathNavigatorReader(XPathNavigator navToRead) { // Need clone that can be moved independently of original navigator this.navToRead = navToRead; this.nav = XmlEmptyNavigator.Singleton; this.state = State.Initial; this.depth = 0; this.nodeType = XPathNavigatorReader.ToXmlNodeType(this.nav.NodeType); } //----------------------------------------------- // IXmlNamespaceResolver -- pass through to Navigator //----------------------------------------------- public override XmlNameTable NameTable { get { return this.navToRead.NameTable; } } IDictionary<string, string> IXmlNamespaceResolver.GetNamespacesInScope(XmlNamespaceScope scope) { return this.nav.GetNamespacesInScope(scope); } string IXmlNamespaceResolver.LookupNamespace(string prefix) { return this.nav.LookupNamespace(prefix); } string IXmlNamespaceResolver.LookupPrefix(string namespaceName) { return this.nav.LookupPrefix(namespaceName); } //----------------------------------------------- // XmlReader -- pass through to Navigator //----------------------------------------------- public override XmlReaderSettings Settings { get { XmlReaderSettings rs = new XmlReaderSettings(); rs.NameTable = this.NameTable; rs.ConformanceLevel = ConformanceLevel.Fragment; rs.CheckCharacters = false; return rs; } } public override System.Type ValueType { get { return this.nav.ValueType; } } public override XmlNodeType NodeType { get { return this.nodeType; } } public override string NamespaceURI { get { //NamespaceUri for namespace nodes is different in case of XPathNavigator and Reader if (this.nav.NodeType == XPathNodeType.Namespace) return this.NameTable.Add(XmlConst.ReservedNsXmlNs); //Special case attribute text node if (this.NodeType == XmlNodeType.Text) return string.Empty; return this.nav.NamespaceURI; } } public override string LocalName { get { //Default namespace in case of reader has a local name value of 'xmlns' if (this.nav.NodeType == XPathNodeType.Namespace && this.nav.LocalName.Length == 0) return this.NameTable.Add("xmlns"); //Special case attribute text node if (this.NodeType == XmlNodeType.Text) return string.Empty; return this.nav.LocalName; } } public override string Prefix { get { //Prefix for namespace nodes is different in case of XPathNavigator and Reader if (this.nav.NodeType == XPathNodeType.Namespace && this.nav.LocalName.Length != 0) return this.NameTable.Add("xmlns"); //Special case attribute text node if (this.NodeType == XmlNodeType.Text) return string.Empty; return this.nav.Prefix; } } public override string BaseURI { get { //reader returns BaseUri even before read method is called. if (this.state == State.Initial) return this.navToRead.BaseURI; return this.nav.BaseURI; } } public override bool IsEmptyElement { get { return this.nav.IsEmptyElement; } } public override XmlSpace XmlSpace { get { XPathNavigator tempNav = this.nav.Clone(); do { if (tempNav.MoveToAttribute(XPathNavigatorReader.space, XmlConst.ReservedNsXml)) { switch (XmlConvertEx.TrimString(tempNav.Value)) { case "default": return XmlSpace.Default; case "preserve": return XmlSpace.Preserve; default: break; } tempNav.MoveToParent(); } } while (tempNav.MoveToParent()); return XmlSpace.None; } } public override string XmlLang { get { return this.nav.XmlLang; } } public override bool HasValue { get { if ((this.nodeType != XmlNodeType.Element) && (this.nodeType != XmlNodeType.Document) && (this.nodeType != XmlNodeType.EndElement) && (this.nodeType != XmlNodeType.None)) return true; return false; } } public override string Value { get { if ((this.nodeType != XmlNodeType.Element) && (this.nodeType != XmlNodeType.Document) && (this.nodeType != XmlNodeType.EndElement) && (this.nodeType != XmlNodeType.None)) return this.nav.Value; return string.Empty; } } private XPathNavigator GetElemNav() { XPathNavigator tempNav; switch (this.state) { case State.Content: return this.nav.Clone(); case State.Attribute: case State.AttrVal: tempNav = this.nav.Clone(); if (tempNav.MoveToParent()) return tempNav; break; case State.InReadBinary: state = savedState; XPathNavigator nav = GetElemNav(); state = State.InReadBinary; return nav; } return null; } private XPathNavigator GetElemNav(out int depth) { XPathNavigator nav = null; switch (this.state) { case State.Content: if (this.nodeType == XmlNodeType.Element) nav = this.nav.Clone(); depth = this.depth; break; case State.Attribute: nav = this.nav.Clone(); nav.MoveToParent(); depth = this.depth - 1; break; case State.AttrVal: nav = this.nav.Clone(); nav.MoveToParent(); depth = this.depth - 2; break; case State.InReadBinary: state = savedState; nav = GetElemNav(out depth); state = State.InReadBinary; break; default: depth = this.depth; break; } return nav; } private void MoveToAttr(XPathNavigator nav, int depth) { this.nav.MoveTo(nav); this.depth = depth; this.nodeType = XmlNodeType.Attribute; this.state = State.Attribute; } public override int AttributeCount { get { if (this.attrCount < 0) { // attribute count works for element, regardless of where you are in start tag XPathNavigator tempNav = GetElemNav(); int count = 0; if (null != tempNav) { if (tempNav.MoveToFirstNamespace(XPathNamespaceScope.Local)) { do { count++; } while (tempNav.MoveToNextNamespace((XPathNamespaceScope.Local))); tempNav.MoveToParent(); } if (tempNav.MoveToFirstAttribute()) { do { count++; } while (tempNav.MoveToNextAttribute()); } } this.attrCount = count; } return this.attrCount; } } public override string GetAttribute(string name) { // reader allows calling GetAttribute, even when positioned inside attributes XPathNavigator nav = this.nav; switch (nav.NodeType) { case XPathNodeType.Element: break; case XPathNodeType.Attribute: nav = nav.Clone(); if (!nav.MoveToParent()) return null; break; default: return null; } string prefix, localname; ValidateNames.SplitQName(name, out prefix, out localname); if (0 == prefix.Length) { if (localname == "xmlns") return nav.GetNamespace(string.Empty); if ((object)nav == (object)this.nav) nav = nav.Clone(); if (nav.MoveToAttribute(localname, string.Empty)) return nav.Value; } else { if (prefix == "xmlns") return nav.GetNamespace(localname); if ((object)nav == (object)this.nav) nav = nav.Clone(); if (nav.MoveToFirstAttribute()) { do { if (nav.LocalName == localname && nav.Prefix == prefix) return nav.Value; } while (nav.MoveToNextAttribute()); } } return null; } public override string GetAttribute(string localName, string namespaceURI) { if (null == localName) throw new ArgumentNullException("localName"); // reader allows calling GetAttribute, even when positioned inside attributes XPathNavigator nav = this.nav; switch (nav.NodeType) { case XPathNodeType.Element: break; case XPathNodeType.Attribute: nav = nav.Clone(); if (!nav.MoveToParent()) return null; break; default: return null; } // are they really looking for a namespace-decl? if (namespaceURI == XmlConst.ReservedNsXmlNs) { if (localName == "xmlns") localName = string.Empty; return nav.GetNamespace(localName); } if (null == namespaceURI) namespaceURI = string.Empty; // We need to clone the navigator and move the clone to the attribute to see whether the attribute exists, // because XPathNavigator.GetAttribute return string.Empty for both when the the attribute is not there or when // it has an empty value. XmlReader.GetAttribute must return null if the attribute does not exist. if ((object)nav == (object)this.nav) nav = nav.Clone(); if (nav.MoveToAttribute(localName, namespaceURI)) { return nav.Value; } else { return null; } } private static string GetNamespaceByIndex(XPathNavigator nav, int index, out int count) { string thisValue = nav.Value; string value = null; if (nav.MoveToNextNamespace(XPathNamespaceScope.Local)) { value = GetNamespaceByIndex(nav, index, out count); } else { count = 0; } if (count == index) { Debug.Assert(value == null); value = thisValue; } count++; return value; } public override string GetAttribute(int index) { if (index < 0) goto Error; XPathNavigator nav = GetElemNav(); if (null == nav) goto Error; if (nav.MoveToFirstNamespace(XPathNamespaceScope.Local)) { // namespaces are returned in reverse order, // but we want to return them in the correct order, // so first count the namespaces int nsCount; string value = GetNamespaceByIndex(nav, index, out nsCount); if (null != value) { return value; } index -= nsCount; nav.MoveToParent(); } if (nav.MoveToFirstAttribute()) { do { if (index == 0) return nav.Value; index--; } while (nav.MoveToNextAttribute()); } // can't find it... error Error: throw new ArgumentOutOfRangeException("index"); } public override bool MoveToAttribute(string localName, string namespaceName) { if (null == localName) throw new ArgumentNullException("localName"); int depth = this.depth; XPathNavigator nav = GetElemNav(out depth); if (null != nav) { if (namespaceName == XmlConst.ReservedNsXmlNs) { if (localName == "xmlns") localName = string.Empty; if (nav.MoveToFirstNamespace(XPathNamespaceScope.Local)) { do { if (nav.LocalName == localName) goto FoundMatch; } while (nav.MoveToNextNamespace(XPathNamespaceScope.Local)); } } else { if (null == namespaceName) namespaceName = string.Empty; if (nav.MoveToAttribute(localName, namespaceName)) goto FoundMatch; } } return false; FoundMatch: if (state == State.InReadBinary) { readBinaryHelper.Finish(); state = savedState; } MoveToAttr(nav, depth + 1); return true; } public override bool MoveToFirstAttribute() { int depth; XPathNavigator nav = GetElemNav(out depth); if (null != nav) { if (nav.MoveToFirstNamespace(XPathNamespaceScope.Local)) { // attributes are in reverse order while (nav.MoveToNextNamespace(XPathNamespaceScope.Local)) ; goto FoundMatch; } if (nav.MoveToFirstAttribute()) { goto FoundMatch; } } return false; FoundMatch: if (state == State.InReadBinary) { readBinaryHelper.Finish(); state = savedState; } MoveToAttr(nav, depth + 1); return true; } public override bool MoveToNextAttribute() { switch (this.state) { case State.Content: return MoveToFirstAttribute(); case State.Attribute: { if (XPathNodeType.Attribute == this.nav.NodeType) return this.nav.MoveToNextAttribute(); // otherwise it is on a namespace... namespace are in reverse order Debug.Assert(XPathNodeType.Namespace == this.nav.NodeType); XPathNavigator nav = this.nav.Clone(); if (!nav.MoveToParent()) return false; // shouldn't happen if (!nav.MoveToFirstNamespace(XPathNamespaceScope.Local)) return false; // shouldn't happen if (nav.IsSamePosition(this.nav)) { // this was the last one... start walking attributes nav.MoveToParent(); if (!nav.MoveToFirstAttribute()) return false; // otherwise we are there this.nav.MoveTo(nav); return true; } else { XPathNavigator prev = nav.Clone(); for (;;) { if (!nav.MoveToNextNamespace(XPathNamespaceScope.Local)) { Debug.Assert(false, "Couldn't find Namespace Node! Should not happen!"); return false; } if (nav.IsSamePosition(this.nav)) { this.nav.MoveTo(prev); return true; } prev.MoveTo(nav); } // found previous namespace position } } case State.AttrVal: depth--; this.state = State.Attribute; if (!MoveToNextAttribute()) { depth++; this.state = State.AttrVal; return false; } this.nodeType = XmlNodeType.Attribute; return true; case State.InReadBinary: state = savedState; if (!MoveToNextAttribute()) { state = State.InReadBinary; return false; } readBinaryHelper.Finish(); return true; default: return false; } } public override bool MoveToAttribute(string name) { int depth; XPathNavigator nav = GetElemNav(out depth); if (null == nav) return false; string prefix, localname; ValidateNames.SplitQName(name, out prefix, out localname); // watch for a namespace name bool IsXmlnsNoPrefix = false; if ((IsXmlnsNoPrefix = (0 == prefix.Length && localname == "xmlns")) || (prefix == "xmlns")) { if (IsXmlnsNoPrefix) localname = string.Empty; if (nav.MoveToFirstNamespace(XPathNamespaceScope.Local)) { do { if (nav.LocalName == localname) goto FoundMatch; } while (nav.MoveToNextNamespace(XPathNamespaceScope.Local)); } } else if (0 == prefix.Length) { // the empty prefix always means empty namespaceUri for attributes if (nav.MoveToAttribute(localname, string.Empty)) goto FoundMatch; } else { if (nav.MoveToFirstAttribute()) { do { if (nav.LocalName == localname && nav.Prefix == prefix) goto FoundMatch; } while (nav.MoveToNextAttribute()); } } return false; FoundMatch: if (state == State.InReadBinary) { readBinaryHelper.Finish(); state = savedState; } MoveToAttr(nav, depth + 1); return true; } public override bool MoveToElement() { switch (this.state) { case State.Attribute: case State.AttrVal: if (!nav.MoveToParent()) return false; this.depth--; if (this.state == State.AttrVal) this.depth--; this.state = State.Content; this.nodeType = XmlNodeType.Element; return true; case State.InReadBinary: state = savedState; if (!MoveToElement()) { state = State.InReadBinary; return false; } readBinaryHelper.Finish(); break; } return false; } public override bool EOF { get { return this.state == State.EOF; } } public override ReadState ReadState { get { switch (this.state) { case State.Initial: return ReadState.Initial; case State.Content: case State.EndElement: case State.Attribute: case State.AttrVal: case State.InReadBinary: return ReadState.Interactive; case State.EOF: return ReadState.EndOfFile; case State.Closed: return ReadState.Closed; default: return ReadState.Error; } } } public override void ResolveEntity() { throw new InvalidOperationException(SR.Xml_InvalidOperation); } public override bool ReadAttributeValue() { if (state == State.InReadBinary) { readBinaryHelper.Finish(); state = savedState; } if (this.state == State.Attribute) { this.state = State.AttrVal; this.nodeType = XmlNodeType.Text; this.depth++; return true; } return false; } public override bool CanReadBinaryContent { get { return true; } } public override int ReadContentAsBase64(byte[] buffer, int index, int count) { if (ReadState != ReadState.Interactive) { return 0; } // init ReadContentAsBinaryHelper when called first time if (state != State.InReadBinary) { readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(readBinaryHelper, this); savedState = state; } // turn off InReadBinary state in order to have a normal Read() behavior when called from readBinaryHelper state = savedState; // call to the helper int readCount = readBinaryHelper.ReadContentAsBase64(buffer, index, count); // turn on InReadBinary state again and return savedState = state; state = State.InReadBinary; return readCount; } public override int ReadContentAsBinHex(byte[] buffer, int index, int count) { if (ReadState != ReadState.Interactive) { return 0; } // init ReadContentAsBinaryHelper when called first time if (state != State.InReadBinary) { readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(readBinaryHelper, this); savedState = state; } // turn off InReadBinary state in order to have a normal Read() behavior when called from readBinaryHelper state = savedState; // call to the helper int readCount = readBinaryHelper.ReadContentAsBinHex(buffer, index, count); // turn on InReadBinary state again and return savedState = state; state = State.InReadBinary; return readCount; } public override int ReadElementContentAsBase64(byte[] buffer, int index, int count) { if (ReadState != ReadState.Interactive) { return 0; } // init ReadContentAsBinaryHelper when called first time if (state != State.InReadBinary) { readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(readBinaryHelper, this); savedState = state; } // turn off InReadBinary state in order to have a normal Read() behavior when called from readBinaryHelper state = savedState; // call to the helper int readCount = readBinaryHelper.ReadElementContentAsBase64(buffer, index, count); // turn on InReadBinary state again and return savedState = state; state = State.InReadBinary; return readCount; } public override int ReadElementContentAsBinHex(byte[] buffer, int index, int count) { if (ReadState != ReadState.Interactive) { return 0; } // init ReadContentAsBinaryHelper when called first time if (state != State.InReadBinary) { readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(readBinaryHelper, this); savedState = state; } // turn off InReadBinary state in order to have a normal Read() behavior when called from readBinaryHelper state = savedState; // call to the helper int readCount = readBinaryHelper.ReadElementContentAsBinHex(buffer, index, count); // turn on InReadBinary state again and return savedState = state; state = State.InReadBinary; return readCount; } public override string LookupNamespace(string prefix) { return this.nav.LookupNamespace(prefix); } /// <summary> /// Current depth in subtree. /// </summary> public override int Depth { get { return this.depth; } } /// <summary> /// Move to the next reader state. Return false if that is ReaderState.Closed. /// </summary> public override bool Read() { this.attrCount = -1; switch (this.state) { case State.Error: case State.Closed: case State.EOF: return false; case State.Initial: // Starting state depends on the navigator's item type this.nav = this.navToRead; this.state = State.Content; if (XPathNodeType.Root == this.nav.NodeType) { if (!nav.MoveToFirstChild()) { SetEOF(); return false; } this.readEntireDocument = true; } else if (XPathNodeType.Attribute == this.nav.NodeType) { this.state = State.Attribute; } this.nodeType = ToXmlNodeType(this.nav.NodeType); break; case State.Content: if (this.nav.MoveToFirstChild()) { this.nodeType = ToXmlNodeType(this.nav.NodeType); this.depth++; this.state = State.Content; } else if (this.nodeType == XmlNodeType.Element && !this.nav.IsEmptyElement) { this.nodeType = XmlNodeType.EndElement; this.state = State.EndElement; } else goto case State.EndElement; break; case State.EndElement: if (0 == depth && !this.readEntireDocument) { SetEOF(); return false; } else if (this.nav.MoveToNext()) { this.nodeType = ToXmlNodeType(this.nav.NodeType); this.state = State.Content; } else if (depth > 0 && this.nav.MoveToParent()) { Debug.Assert(this.nav.NodeType == XPathNodeType.Element, this.nav.NodeType.ToString() + " == XPathNodeType.Element"); this.nodeType = XmlNodeType.EndElement; this.state = State.EndElement; depth--; } else { SetEOF(); return false; } break; case State.Attribute: case State.AttrVal: if (!this.nav.MoveToParent()) { SetEOF(); return false; } this.nodeType = ToXmlNodeType(this.nav.NodeType); this.depth--; if (state == State.AttrVal) this.depth--; goto case State.Content; case State.InReadBinary: state = savedState; readBinaryHelper.Finish(); return Read(); } return true; } /// <summary> /// set reader to EOF state /// </summary> private void SetEOF() { this.nav = XmlEmptyNavigator.Singleton; this.nodeType = XmlNodeType.None; this.state = State.EOF; this.depth = 0; } } /// <summary> /// The XmlEmptyNavigator exposes a document node with no children. /// Only one XmlEmptyNavigator exists per AppDomain (Singleton). That's why the constructor is private. /// Use the Singleton property to get the EmptyNavigator. /// </summary> internal class XmlEmptyNavigator : XPathNavigator { private static volatile XmlEmptyNavigator singleton; private XmlEmptyNavigator() { } public static XmlEmptyNavigator Singleton { get { if (XmlEmptyNavigator.singleton == null) XmlEmptyNavigator.singleton = new XmlEmptyNavigator(); return XmlEmptyNavigator.singleton; } } //----------------------------------------------- // XmlReader //----------------------------------------------- public override XPathNodeType NodeType { get { return XPathNodeType.All; } } public override string NamespaceURI { get { return string.Empty; } } public override string LocalName { get { return string.Empty; } } public override string Name { get { return string.Empty; } } public override string Prefix { get { return string.Empty; } } public override string BaseURI { get { return string.Empty; } } public override string Value { get { return string.Empty; } } public override bool IsEmptyElement { get { return false; } } public override string XmlLang { get { return string.Empty; } } public override bool HasAttributes { get { return false; } } public override bool HasChildren { get { return false; } } //----------------------------------------------- // IXmlNamespaceResolver //----------------------------------------------- public override XmlNameTable NameTable { get { return new NameTable(); } } public override bool MoveToFirstChild() { return false; } public override void MoveToRoot() { //always on root return; } public override bool MoveToNext() { return false; } public override bool MoveToPrevious() { return false; } public override bool MoveToFirst() { return false; } public override bool MoveToFirstAttribute() { return false; } public override bool MoveToNextAttribute() { return false; } public override bool MoveToId(string id) { return false; } public override string GetAttribute(string localName, string namespaceName) { return null; } public override bool MoveToAttribute(string localName, string namespaceName) { return false; } public override string GetNamespace(string name) { return null; } public override bool MoveToNamespace(string prefix) { return false; } public override bool MoveToFirstNamespace(XPathNamespaceScope scope) { return false; } public override bool MoveToNextNamespace(XPathNamespaceScope scope) { return false; } public override bool MoveToParent() { return false; } public override bool MoveTo(XPathNavigator other) { // Only one instance of XmlEmptyNavigator exists on the system return (object)this == (object)other; } public override XmlNodeOrder ComparePosition(XPathNavigator other) { // Only one instance of XmlEmptyNavigator exists on the system return ((object)this == (object)other) ? XmlNodeOrder.Same : XmlNodeOrder.Unknown; } public override bool IsSamePosition(XPathNavigator other) { // Only one instance of XmlEmptyNavigator exists on the system return (object)this == (object)other; } //----------------------------------------------- // XPathNavigator2 //----------------------------------------------- public override XPathNavigator Clone() { // Singleton, so clone just returns this return this; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; namespace Lucene.Net.Search { /* * 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 BytesRef = Lucene.Net.Util.BytesRef; using StringHelper = Lucene.Net.Util.StringHelper; /// <summary> /// Stores information about how to sort documents by terms in an individual /// field. Fields must be indexed in order to sort by them. /// /// <para/>Created: Feb 11, 2004 1:25:29 PM /// <para/> /// @since lucene 1.4 </summary> /// <seealso cref="Sort"/> public class SortField { // LUCENENET NOTE: de-nested the Type enum and renamed to SortFieldType to avoid potential naming collisions with System.Type /// <summary> /// Represents sorting by document score (relevance). </summary> public static readonly SortField FIELD_SCORE = new SortField(null, SortFieldType.SCORE); /// <summary> /// Represents sorting by document number (index order). </summary> public static readonly SortField FIELD_DOC = new SortField(null, SortFieldType.DOC); private string field; private SortFieldType type; // defaults to determining type dynamically internal bool reverse = false; // defaults to natural order private FieldCache.IParser parser; // Used for CUSTOM sort private FieldComparerSource comparerSource; // Used for 'sortMissingFirst/Last' public virtual object MissingValue { get { return m_missingValue; } set { if (type == SortFieldType.STRING) { if (value != STRING_FIRST && value != STRING_LAST) { throw new ArgumentException("For STRING type, missing value must be either STRING_FIRST or STRING_LAST"); } } #pragma warning disable 612, 618 else if (type != SortFieldType.BYTE && type != SortFieldType.INT16 #pragma warning restore 612, 618 && type != SortFieldType.INT32 && type != SortFieldType.SINGLE && type != SortFieldType.INT64 && type != SortFieldType.DOUBLE) { throw new ArgumentException("Missing value only works for numeric or STRING types"); } this.m_missingValue = value; } } protected object m_missingValue = null; // LUCENENET NOTE: added protected backing field /// <summary> /// Creates a sort by terms in the given field with the type of term /// values explicitly given. </summary> /// <param name="field"> Name of field to sort by. Can be <c>null</c> if /// <paramref name="type"/> is <see cref="SortFieldType.SCORE"/> or <see cref="SortFieldType.DOC"/>. </param> /// <param name="type"> Type of values in the terms. </param> public SortField(string field, SortFieldType type) { InitFieldType(field, type); } /// <summary> /// Creates a sort, possibly in reverse, by terms in the given field with the /// type of term values explicitly given. </summary> /// <param name="field"> Name of field to sort by. Can be <c>null</c> if /// <paramref name="type"/> is <see cref="SortFieldType.SCORE"/> or <see cref="SortFieldType.DOC"/>. </param> /// <param name="type"> Type of values in the terms. </param> /// <param name="reverse"> <c>True</c> if natural order should be reversed. </param> public SortField(string field, SortFieldType type, bool reverse) { InitFieldType(field, type); this.reverse = reverse; } /// <summary> /// Creates a sort by terms in the given field, parsed /// to numeric values using a custom <see cref="FieldCache.IParser"/>. </summary> /// <param name="field"> Name of field to sort by. Must not be <c>null</c>. </param> /// <param name="parser"> Instance of a <see cref="FieldCache.IParser"/>, /// which must subclass one of the existing numeric /// parsers from <see cref="IFieldCache"/>. Sort type is inferred /// by testing which numeric parser the parser subclasses. </param> /// <exception cref="ArgumentException"> if the parser fails to /// subclass an existing numeric parser, or field is <c>null</c> </exception> public SortField(string field, FieldCache.IParser parser) : this(field, parser, false) { } /// <summary> /// Creates a sort, possibly in reverse, by terms in the given field, parsed /// to numeric values using a custom <see cref="FieldCache.IParser"/>. </summary> /// <param name="field"> Name of field to sort by. Must not be <c>null</c>. </param> /// <param name="parser"> Instance of a <see cref="FieldCache.IParser"/>, /// which must subclass one of the existing numeric /// parsers from <see cref="IFieldCache"/>. Sort type is inferred /// by testing which numeric parser the parser subclasses. </param> /// <param name="reverse"> <c>True</c> if natural order should be reversed. </param> /// <exception cref="ArgumentException"> if the parser fails to /// subclass an existing numeric parser, or field is <c>null</c> </exception> public SortField(string field, FieldCache.IParser parser, bool reverse) { if (parser is FieldCache.IInt32Parser) { InitFieldType(field, SortFieldType.INT32); } else if (parser is FieldCache.ISingleParser) { InitFieldType(field, SortFieldType.SINGLE); } #pragma warning disable 612, 618 else if (parser is FieldCache.IInt16Parser) { InitFieldType(field, SortFieldType.INT16); } else if (parser is FieldCache.IByteParser) { InitFieldType(field, SortFieldType.BYTE); #pragma warning restore 612, 618 } else if (parser is FieldCache.IInt64Parser) { InitFieldType(field, SortFieldType.INT64); } else if (parser is FieldCache.IDoubleParser) { InitFieldType(field, SortFieldType.DOUBLE); } else { throw new ArgumentException("Parser instance does not subclass existing numeric parser from FieldCache (got " + parser + ")"); } this.reverse = reverse; this.parser = parser; } /// <summary> /// Pass this to <see cref="MissingValue"/> to have missing /// string values sort first. /// </summary> public static readonly object STRING_FIRST = new ObjectAnonymousInnerClassHelper(); private class ObjectAnonymousInnerClassHelper : object { public ObjectAnonymousInnerClassHelper() { } public override string ToString() { return "SortField.STRING_FIRST"; } } /// <summary> /// Pass this to <see cref="MissingValue"/> to have missing /// string values sort last. /// </summary> public static readonly object STRING_LAST = new ObjectAnonymousInnerClassHelper2(); private class ObjectAnonymousInnerClassHelper2 : object { public ObjectAnonymousInnerClassHelper2() { } public override string ToString() { return "SortField.STRING_LAST"; } } // LUCENENET NOTE: Made this into a property setter above //public virtual void SetMissingValue(object value) //{ // if (type == SortFieldType.STRING) // { // if (value != STRING_FIRST && value != STRING_LAST) // { // throw new ArgumentException("For STRING type, missing value must be either STRING_FIRST or STRING_LAST"); // } // } // else if (type != SortFieldType.BYTE && type != SortFieldType.SHORT && type != SortFieldType.INT && type != SortFieldType.FLOAT && type != SortFieldType.LONG && type != SortFieldType.DOUBLE) // { // throw new ArgumentException("Missing value only works for numeric or STRING types"); // } // this.missingValue = value; //} /// <summary> /// Creates a sort with a custom comparison function. </summary> /// <param name="field"> Name of field to sort by; cannot be <c>null</c>. </param> /// <param name="comparer"> Returns a comparer for sorting hits. </param> public SortField(string field, FieldComparerSource comparer) { InitFieldType(field, SortFieldType.CUSTOM); this.comparerSource = comparer; } /// <summary> /// Creates a sort, possibly in reverse, with a custom comparison function. </summary> /// <param name="field"> Name of field to sort by; cannot be <c>null</c>. </param> /// <param name="comparer"> Returns a comparer for sorting hits. </param> /// <param name="reverse"> <c>True</c> if natural order should be reversed. </param> public SortField(string field, FieldComparerSource comparer, bool reverse) { InitFieldType(field, SortFieldType.CUSTOM); this.reverse = reverse; this.comparerSource = comparer; } // Sets field & type, and ensures field is not NULL unless // type is SCORE or DOC private void InitFieldType(string field, SortFieldType type) { this.type = type; if (field == null) { if (type != SortFieldType.SCORE && type != SortFieldType.DOC) { throw new ArgumentException("field can only be null when type is SCORE or DOC"); } } else { this.field = field; } } /// <summary> /// Returns the name of the field. Could return <c>null</c> /// if the sort is by <see cref="SortFieldType.SCORE"/> or <see cref="SortFieldType.DOC"/>. </summary> /// <returns> Name of field, possibly <c>null</c>. </returns> public virtual string Field => field; /// <summary> /// Returns the type of contents in the field. </summary> /// <returns> One of <see cref="SortFieldType.SCORE"/>, <see cref="SortFieldType.DOC"/>, /// <see cref="SortFieldType.STRING"/>, <see cref="SortFieldType.INT32"/> or <see cref="SortFieldType.SINGLE"/>. </returns> public virtual SortFieldType Type => type; /// <summary> /// Returns the instance of a <see cref="IFieldCache"/> parser that fits to the given sort type. /// May return <c>null</c> if no parser was specified. Sorting is using the default parser then. </summary> /// <returns> An instance of a <see cref="IFieldCache"/> parser, or <c>null</c>. </returns> public virtual FieldCache.IParser Parser => parser; /// <summary> /// Returns whether the sort should be reversed. </summary> /// <returns> <c>True</c> if natural order should be reversed. </returns> public virtual bool IsReverse => reverse; /// <summary> /// Returns the <see cref="FieldComparerSource"/> used for /// custom sorting. /// </summary> public virtual FieldComparerSource ComparerSource => comparerSource; public override string ToString() { StringBuilder buffer = new StringBuilder(); switch (type) { case SortFieldType.SCORE: buffer.Append("<score>"); break; case SortFieldType.DOC: buffer.Append("<doc>"); break; case SortFieldType.STRING: buffer.Append("<string" + ": \"").Append(field).Append("\">"); break; case SortFieldType.STRING_VAL: buffer.Append("<string_val" + ": \"").Append(field).Append("\">"); break; #pragma warning disable 612, 618 case SortFieldType.BYTE: buffer.Append("<byte: \"").Append(field).Append("\">"); break; case SortFieldType.INT16: #pragma warning restore 612, 618 buffer.Append("<short: \"").Append(field).Append("\">"); break; case SortFieldType.INT32: buffer.Append("<int" + ": \"").Append(field).Append("\">"); break; case SortFieldType.INT64: buffer.Append("<long: \"").Append(field).Append("\">"); break; case SortFieldType.SINGLE: buffer.Append("<float" + ": \"").Append(field).Append("\">"); break; case SortFieldType.DOUBLE: buffer.Append("<double" + ": \"").Append(field).Append("\">"); break; case SortFieldType.CUSTOM: buffer.Append("<custom:\"").Append(field).Append("\": ").Append(comparerSource).Append('>'); break; case SortFieldType.REWRITEABLE: buffer.Append("<rewriteable: \"").Append(field).Append("\">"); break; default: buffer.Append("<???: \"").Append(field).Append("\">"); break; } if (reverse) { buffer.Append('!'); } if (m_missingValue != null) { buffer.Append(" missingValue="); buffer.Append(m_missingValue); } return buffer.ToString(); } /// <summary> /// Returns <c>true</c> if <paramref name="o"/> is equal to this. If a /// <see cref="FieldComparerSource"/> or /// <see cref="FieldCache.IParser"/> was provided, it must properly /// implement equals (unless a singleton is always used). /// </summary> public override bool Equals(object o) { if (this == o) { return true; } if (!(o is SortField)) { return false; } SortField other = (SortField)o; return (StringHelper.Equals(other.field, this.field) && other.type == this.type && other.reverse == this.reverse && (other.comparerSource == null ? this.comparerSource == null : other.comparerSource.Equals(this.comparerSource))); } /// <summary> /// Returns a hash code value for this object. If a /// <see cref="FieldComparerSource"/> or /// <see cref="FieldCache.IParser"/> was provided, it must properly /// implement GetHashCode() (unless a singleton is always /// used). /// </summary> public override int GetHashCode() { int hash = (int)(type.GetHashCode() ^ 0x346565dd + reverse.GetHashCode() ^ 0xaf5998bb); if (field != null) { hash += (int)(field.GetHashCode() ^ 0xff5685dd); } if (comparerSource != null) { hash += comparerSource.GetHashCode(); } return hash; } private IComparer<BytesRef> bytesComparer = BytesRef.UTF8SortedAsUnicodeComparer; public virtual IComparer<BytesRef> BytesComparer { get => bytesComparer; set => bytesComparer = value; } /// <summary> /// Returns the <see cref="FieldComparer"/> to use for /// sorting. /// <para/> /// @lucene.experimental /// </summary> /// <param name="numHits"> Number of top hits the queue will store </param> /// <param name="sortPos"> Position of this <see cref="SortField"/> within /// <see cref="Sort"/>. The comparer is primary if sortPos==0, /// secondary if sortPos==1, etc. Some comparers can /// optimize themselves when they are the primary sort. </param> /// <returns> <see cref="FieldComparer"/> to use when sorting </returns> public virtual FieldComparer GetComparer(int numHits, int sortPos) { switch (type) { case SortFieldType.SCORE: return new FieldComparer.RelevanceComparer(numHits); case SortFieldType.DOC: return new FieldComparer.DocComparer(numHits); case SortFieldType.INT32: return new FieldComparer.Int32Comparer(numHits, field, parser, (int?)m_missingValue); case SortFieldType.SINGLE: return new FieldComparer.SingleComparer(numHits, field, parser, (float?)m_missingValue); case SortFieldType.INT64: return new FieldComparer.Int64Comparer(numHits, field, parser, (long?)m_missingValue); case SortFieldType.DOUBLE: return new FieldComparer.DoubleComparer(numHits, field, parser, (double?)m_missingValue); #pragma warning disable 612, 618 case SortFieldType.BYTE: return new FieldComparer.ByteComparer(numHits, field, parser, (sbyte?)m_missingValue); case SortFieldType.INT16: return new FieldComparer.Int16Comparer(numHits, field, parser, (short?)m_missingValue); #pragma warning restore 612, 618 case SortFieldType.CUSTOM: Debug.Assert(comparerSource != null); return comparerSource.NewComparer(field, numHits, sortPos, reverse); case SortFieldType.STRING: return new FieldComparer.TermOrdValComparer(numHits, field, m_missingValue == STRING_LAST); case SortFieldType.STRING_VAL: // TODO: should we remove this? who really uses it? return new FieldComparer.TermValComparer(numHits, field); case SortFieldType.REWRITEABLE: throw new InvalidOperationException("SortField needs to be rewritten through Sort.rewrite(..) and SortField.rewrite(..)"); default: throw new InvalidOperationException("Illegal sort type: " + type); } } /// <summary> /// Rewrites this <see cref="SortField"/>, returning a new <see cref="SortField"/> if a change is made. /// Subclasses should override this define their rewriting behavior when this /// SortField is of type <see cref="SortFieldType.REWRITEABLE"/>. /// <para/> /// @lucene.experimental /// </summary> /// <param name="searcher"> <see cref="IndexSearcher"/> to use during rewriting </param> /// <returns> New rewritten <see cref="SortField"/>, or <c>this</c> if nothing has changed. </returns> /// <exception cref="IOException"> Can be thrown by the rewriting </exception> public virtual SortField Rewrite(IndexSearcher searcher) { return this; } /// <summary> /// Whether the relevance score is needed to sort documents. </summary> public virtual bool NeedsScores => type == SortFieldType.SCORE; } /// <summary> /// Specifies the type of the terms to be sorted, or special types such as CUSTOM /// </summary> public enum SortFieldType // LUCENENET NOTE: de-nested and renamed from Type to avoid naming collision with Type property and with System.Type { /// <summary> /// Sort by document score (relevance). Sort values are <see cref="float"/> and higher /// values are at the front. /// </summary> SCORE, /// <summary> /// Sort by document number (index order). Sort values are <see cref="int"/> and lower /// values are at the front. /// </summary> DOC, /// <summary> /// Sort using term values as <see cref="string"/>s. Sort values are <see cref="string"/>s and lower /// values are at the front. /// </summary> STRING, /// <summary> /// Sort using term values as encoded <see cref="int"/>s. Sort values are <see cref="int"/> and /// lower values are at the front. /// <para/> /// NOTE: This was INT in Lucene /// </summary> INT32, /// <summary> /// Sort using term values as encoded <see cref="float"/>s. Sort values are <see cref="float"/> and /// lower values are at the front. /// <para/> /// NOTE: This was FLOAT in Lucene /// </summary> SINGLE, /// <summary> /// Sort using term values as encoded <see cref="long"/>s. Sort values are <see cref="long"/> and /// lower values are at the front. /// <para/> /// NOTE: This was LONG in Lucene /// </summary> INT64, /// <summary> /// Sort using term values as encoded <see cref="double"/>s. Sort values are <see cref="double"/> and /// lower values are at the front. /// </summary> DOUBLE, /// <summary> /// Sort using term values as encoded <see cref="short"/>s. Sort values are <see cref="short"/> and /// lower values are at the front. /// <para/> /// NOTE: This was SHORT in Lucene /// </summary> [System.Obsolete] INT16, /// <summary> /// Sort using a custom <see cref="IComparer{T}"/>. Sort values are any <see cref="IComparable{T}"/> and /// sorting is done according to natural order. /// </summary> CUSTOM, /// <summary> /// Sort using term values as encoded <see cref="byte"/>s. Sort values are <see cref="byte"/> and /// lower values are at the front. /// </summary> [System.Obsolete] BYTE, /// <summary> /// Sort using term values as <see cref="string"/>s, but comparing by /// value (using <see cref="BytesRef.CompareTo(BytesRef)"/>) for all comparisons. /// this is typically slower than <see cref="STRING"/>, which /// uses ordinals to do the sorting. /// </summary> STRING_VAL, /// <summary> /// Sort use <see cref="T:byte[]"/> index values. </summary> BYTES, /// <summary> /// Force rewriting of <see cref="SortField"/> using <see cref="SortField.Rewrite(IndexSearcher)"/> /// before it can be used for sorting /// </summary> REWRITEABLE } }
// Copyright (c) Umbraco. // See LICENSE for more details. using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using Umbraco.Cms.Core; using Umbraco.Cms.Core.Composing; using Umbraco.Cms.Core.Strings; namespace Umbraco.Extensions { public static class TypeExtensions { public static object GetDefaultValue(this Type t) { return t.IsValueType ? Activator.CreateInstance(t) : null; } internal static MethodInfo GetGenericMethod(this Type type, string name, params Type[] parameterTypes) { var methods = type.GetMethods().Where(method => method.Name == name); foreach (var method in methods) { if (method.HasParameters(parameterTypes)) return method; } return null; } /// <summary> /// Checks if the type is an anonymous type /// </summary> /// <param name="type"></param> /// <returns></returns> /// <remarks> /// reference: http://jclaes.blogspot.com/2011/05/checking-for-anonymous-types.html /// </remarks> public static bool IsAnonymousType(this Type type) { if (type == null) throw new ArgumentNullException("type"); return Attribute.IsDefined(type, typeof(CompilerGeneratedAttribute), false) && type.IsGenericType && type.Name.Contains("AnonymousType") && (type.Name.StartsWith("<>") || type.Name.StartsWith("VB$")) && (type.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic; } /// <summary> /// Determines whether the specified type is enumerable. /// </summary> /// <param name="method">The type.</param> /// <param name="parameterTypes"></param> internal static bool HasParameters(this MethodInfo method, params Type[] parameterTypes) { var methodParameters = method.GetParameters().Select(parameter => parameter.ParameterType).ToArray(); if (methodParameters.Length != parameterTypes.Length) return false; for (int i = 0; i < methodParameters.Length; i++) if (methodParameters[i].ToString() != parameterTypes[i].ToString()) return false; return true; } public static IEnumerable<Type> GetBaseTypes(this Type type, bool andSelf) { if (andSelf) yield return type; while ((type = type.BaseType) != null) yield return type; } public static IEnumerable<MethodInfo> AllMethods(this Type target) { //var allTypes = target.AllInterfaces().ToList(); var allTypes = target.GetInterfaces().ToList(); // GetInterfaces is ok here allTypes.Add(target); return allTypes.SelectMany(t => t.GetMethods()); } /// <returns> /// <c>true</c> if the specified type is enumerable; otherwise, <c>false</c>. /// </returns> public static bool IsEnumerable(this Type type) { if (type.IsGenericType) { if (type.GetGenericTypeDefinition().GetInterfaces().Contains(typeof(IEnumerable))) return true; } else { if (type.GetInterfaces().Contains(typeof(IEnumerable))) return true; } return false; } /// <summary> /// Determines whether [is of generic type] [the specified type]. /// </summary> /// <param name="type">The type.</param> /// <param name="genericType">Type of the generic.</param> /// <returns> /// <c>true</c> if [is of generic type] [the specified type]; otherwise, <c>false</c>. /// </returns> public static bool IsOfGenericType(this Type type, Type genericType) { Type[] args; return type.TryGetGenericArguments(genericType, out args); } /// <summary> /// Will find the generic type of the 'type' parameter passed in that is equal to the 'genericType' parameter passed in /// </summary> /// <param name="type"></param> /// <param name="genericType"></param> /// <param name="genericArgType"></param> /// <returns></returns> public static bool TryGetGenericArguments(this Type type, Type genericType, out Type[] genericArgType) { if (type == null) { throw new ArgumentNullException("type"); } if (genericType == null) { throw new ArgumentNullException("genericType"); } if (genericType.IsGenericType == false) { throw new ArgumentException("genericType must be a generic type"); } Func<Type, Type, Type[]> checkGenericType = (@int, t) => { if (@int.IsGenericType) { var def = @int.GetGenericTypeDefinition(); if (def == t) { return @int.GetGenericArguments(); } } return null; }; //first, check if the type passed in is already the generic type genericArgType = checkGenericType(type, genericType); if (genericArgType != null) return true; //if we're looking for interfaces, enumerate them: if (genericType.IsInterface) { foreach (Type @interface in type.GetInterfaces()) { genericArgType = checkGenericType(@interface, genericType); if (genericArgType != null) return true; } } else { //loop back into the base types as long as they are generic while (type.BaseType != null && type.BaseType != typeof(object)) { genericArgType = checkGenericType(type.BaseType, genericType); if (genericArgType != null) return true; type = type.BaseType; } } return false; } /// <summary> /// Gets all properties in a flat hierarchy /// </summary> /// <remarks>Includes both Public and Non-Public properties</remarks> /// <param name="type"></param> /// <returns></returns> public static PropertyInfo[] GetAllProperties(this Type type) { if (type.IsInterface) { var propertyInfos = new List<PropertyInfo>(); var considered = new List<Type>(); var queue = new Queue<Type>(); considered.Add(type); queue.Enqueue(type); while (queue.Count > 0) { var subType = queue.Dequeue(); foreach (var subInterface in subType.GetInterfaces()) { if (considered.Contains(subInterface)) continue; considered.Add(subInterface); queue.Enqueue(subInterface); } var typeProperties = subType.GetProperties( BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); var newPropertyInfos = typeProperties .Where(x => !propertyInfos.Contains(x)); propertyInfos.InsertRange(0, newPropertyInfos); } return propertyInfos.ToArray(); } return type.GetProperties(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); } /// <summary> /// Returns all public properties including inherited properties even for interfaces /// </summary> /// <param name="type"></param> /// <returns></returns> /// <remarks> /// taken from http://stackoverflow.com/questions/358835/getproperties-to-return-all-properties-for-an-interface-inheritance-hierarchy /// </remarks> public static PropertyInfo[] GetPublicProperties(this Type type) { if (type.IsInterface) { var propertyInfos = new List<PropertyInfo>(); var considered = new List<Type>(); var queue = new Queue<Type>(); considered.Add(type); queue.Enqueue(type); while (queue.Count > 0) { var subType = queue.Dequeue(); foreach (var subInterface in subType.GetInterfaces()) { if (considered.Contains(subInterface)) continue; considered.Add(subInterface); queue.Enqueue(subInterface); } var typeProperties = subType.GetProperties( BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance); var newPropertyInfos = typeProperties .Where(x => !propertyInfos.Contains(x)); propertyInfos.InsertRange(0, newPropertyInfos); } return propertyInfos.ToArray(); } return type.GetProperties(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance); } /// <summary> /// Determines whether the specified actual type is type. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="actualType">The actual type.</param> /// <returns> /// <c>true</c> if the specified actual type is type; otherwise, <c>false</c>. /// </returns> public static bool IsType<T>(this Type actualType) { return TypeHelper.IsTypeAssignableFrom<T>(actualType); } public static bool Inherits<TBase>(this Type type) { return typeof(TBase).IsAssignableFrom(type); } public static bool Inherits(this Type type, Type tbase) { return tbase.IsAssignableFrom(type); } public static bool Implements<TInterface>(this Type type) { return typeof(TInterface).IsAssignableFrom(type); } public static TAttribute FirstAttribute<TAttribute>(this Type type) { return type.FirstAttribute<TAttribute>(true); } public static TAttribute FirstAttribute<TAttribute>(this Type type, bool inherit) { var attrs = type.GetCustomAttributes(typeof(TAttribute), inherit); return (TAttribute)(attrs.Length > 0 ? attrs[0] : null); } public static TAttribute FirstAttribute<TAttribute>(this PropertyInfo propertyInfo) { return propertyInfo.FirstAttribute<TAttribute>(true); } public static TAttribute FirstAttribute<TAttribute>(this PropertyInfo propertyInfo, bool inherit) { var attrs = propertyInfo.GetCustomAttributes(typeof(TAttribute), inherit); return (TAttribute)(attrs.Length > 0 ? attrs[0] : null); } public static IEnumerable<TAttribute> MultipleAttribute<TAttribute>(this PropertyInfo propertyInfo) { return propertyInfo.MultipleAttribute<TAttribute>(true); } public static IEnumerable<TAttribute> MultipleAttribute<TAttribute>(this PropertyInfo propertyInfo, bool inherit) { var attrs = propertyInfo.GetCustomAttributes(typeof(TAttribute), inherit); return (attrs.Length > 0 ? attrs.ToList().ConvertAll(input => (TAttribute)input) : null); } /// <summary> /// Returns the full type name with the assembly but without all of the assembly specific version information. /// </summary> /// <param name="type"></param> /// <returns></returns> /// <remarks> /// This method is like an 'in between' of Type.FullName and Type.AssemblyQualifiedName which returns the type and the assembly separated /// by a comma. /// </remarks> /// <example> /// The output of this class would be: /// /// Umbraco.Core.TypeExtensions, Umbraco.Core /// </example> public static string GetFullNameWithAssembly(this Type type) { var assemblyName = type.Assembly.GetName(); return string.Concat(type.FullName, ", ", assemblyName.FullName.StartsWith("App_Code.") ? "App_Code" : assemblyName.Name); } /// <summary> /// Determines whether an instance of a specified type can be assigned to the current type instance. /// </summary> /// <param name="type">The current type.</param> /// <param name="c">The type to compare with the current type.</param> /// <returns>A value indicating whether an instance of the specified type can be assigned to the current type instance.</returns> /// <remarks>This extended version supports the current type being a generic type definition, and will /// consider that eg <c>List{int}</c> is "assignable to" <c>IList{}</c>.</remarks> public static bool IsAssignableFromGtd(this Type type, Type c) { // type *can* be a generic type definition // c is a real type, cannot be a generic type definition if (type.IsGenericTypeDefinition == false) return type.IsAssignableFrom(c); if (c.IsInterface == false) { var t = c; while (t != typeof(object)) { if (t.IsGenericType && t.GetGenericTypeDefinition() == type) return true; t = t.BaseType; } } return c.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == type); } /// <summary> /// If the given <paramref name="type"/> is an array or some other collection /// comprised of 0 or more instances of a "subtype", get that type /// </summary> /// <param name="type">the source type</param> /// <returns></returns> public static Type GetEnumeratedType(this Type type) { if (typeof(IEnumerable).IsAssignableFrom(type) == false) return null; // provided by Array var elType = type.GetElementType(); if (null != elType) return elType; // otherwise provided by collection var elTypes = type.GetGenericArguments(); if (elTypes.Length > 0) return elTypes[0]; // otherwise is not an 'enumerated' type return null; } public static T GetCustomAttribute<T>(this Type type, bool inherit) where T : Attribute { return type.GetCustomAttributes<T>(inherit).SingleOrDefault(); } public static IEnumerable<T> GetCustomAttributes<T>(this Type type, bool inherited) where T : Attribute { if (type == null) return Enumerable.Empty<T>(); return type.GetCustomAttributes(typeof (T), inherited).OfType<T>(); } /// <summary> /// Tries to return a value based on a property name for an object but ignores case sensitivity /// </summary> /// <param name="type"></param> /// <param name="shortStringHelper"></param> /// <param name="target"></param> /// <param name="memberName"></param> /// <returns></returns> /// <remarks> /// Currently this will only work for ProperCase and camelCase properties, see the TODO below to enable complete case insensitivity /// </remarks> internal static Attempt<object> GetMemberIgnoreCase(this Type type, IShortStringHelper shortStringHelper, object target, string memberName) { Func<string, Attempt<object>> getMember = memberAlias => { try { return Attempt<object>.Succeed( type.InvokeMember(memberAlias, System.Reflection.BindingFlags.GetProperty | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public, null, target, null)); } catch (MissingMethodException ex) { return Attempt<object>.Fail(ex); } }; //try with the current casing var attempt = getMember(memberName); if (attempt.Success == false) { //if we cannot get with the current alias, try changing it's case attempt = memberName[0].IsUpperCase() ? getMember(memberName.ToCleanString(shortStringHelper, CleanStringType.Ascii | CleanStringType.ConvertCase | CleanStringType.CamelCase)) : getMember(memberName.ToCleanString(shortStringHelper, CleanStringType.Ascii | CleanStringType.ConvertCase | CleanStringType.PascalCase)); // TODO: If this still fails then we should get a list of properties from the object and then compare - doing the above without listing // all properties will surely be faster than using reflection to get ALL properties first and then query against them. } return attempt; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Collections; using System.Globalization; using System.Diagnostics; using System.IO; using System.Net; using System.Text; using System.Xml; using OpenLiveWriter.CoreServices.Diagnostics; namespace OpenLiveWriter.CoreServices { public class XmlRpcClient { /// <summary> /// Create an XmlRpcClient for the specified host name /// </summary> /// <param name="hostname"></param> public XmlRpcClient(string hostname, string userAgent) { _hostname = hostname; _userAgent = userAgent; } /// <summary> /// Create an XmlRpcClient for the specified host name /// </summary> /// <param name="hostname"></param> public XmlRpcClient(string hostname, string userAgent, HttpRequestFilter filter, string transportEncoding) { _hostname = hostname; _userAgent = userAgent; _requestFilter = filter; _transportEncoding = transportEncoding; } /// <summary> /// Call an XmlRpc method /// </summary> /// <param name="methodName">method name</param> /// <param name="parameters">variabile length list of parameters</param> /// <returns>response from the remote host</returns> /// <exception cref="Exception">allows all exceptions to propogate out of the method</exception> public XmlRpcMethodResponse CallMethod(string methodName, params XmlRpcValue[] parameters) { //select the encoding Encoding encodingToUse = StringHelper.GetEncoding(_transportEncoding, new UTF8Encoding(false, false)); // build the XmlRpc packet byte[] requestBytes = GetRequestBytes(encodingToUse, methodName, parameters, false); if (ApplicationDiagnostics.VerboseLogging) { LogXmlRpcRequest(encodingToUse, methodName, parameters); } // send the request HttpWebResponse response; try { response = HttpRequestHelper.SendRequest(_hostname, delegate (HttpWebRequest request) { request.Method = "POST"; request.AllowAutoRedirect = false; request.ContentType = String.Format(CultureInfo.InvariantCulture, "{0};charset={1}", MimeHelper.TEXT_XML, encodingToUse.WebName); if (_requestFilter != null) _requestFilter(request); using (Stream requestStream = request.GetRequestStream()) StreamHelper.Transfer(new MemoryStream(requestBytes), requestStream); }); } catch { if (!ApplicationDiagnostics.VerboseLogging) // if test mode, request has already been logged { LogXmlRpcRequest(encodingToUse, methodName, parameters); } throw; } // WinLive 616: The response encoding may not necessarily be the same as our request encoding. Attempt to // use the encoding specified in the HTTP header. string characterSet; if (TryGetCharacterSet(response, out characterSet)) { encodingToUse = StringHelper.GetEncoding(characterSet, encodingToUse); } // return the response using (StreamReader reader = new StreamReader(response.GetResponseStream(), encodingToUse)) { string xmlRpcString = reader.ReadToEnd(); if (ApplicationDiagnostics.VerboseLogging) { LogXmlRpcResponse(xmlRpcString); } try { XmlRpcMethodResponse xmlRpcResponse = new XmlRpcMethodResponse(xmlRpcString); if (xmlRpcResponse.FaultOccurred) { if (!ApplicationDiagnostics.VerboseLogging) // if test mode, response has already been logged { LogXmlRpcRequest(encodingToUse, methodName, parameters); LogXmlRpcResponse(xmlRpcString); } } return xmlRpcResponse; } catch (Exception ex) { Trace.WriteLine("Exception parsing XML-RPC response:\r\n\r\n" + ex.ToString() + "\r\n\r\n" + xmlRpcString); throw; } } } /// <summary> /// Gets the character set associated with the WebResponse. /// </summary> /// <param name="response">The WebResponse to inspect for a character set.</param> /// <param name="characterSet">When this method returns, contains the character set associated with the /// WebResponse if the character set is explicitly specified; otherwise, null. This parameter is passed /// uninitialized.</param> /// <returns>true if the WebResponse explicitly specifies a character set; otherwise, false.</returns> private bool TryGetCharacterSet(HttpWebResponse response, out string characterSet) { // A very applicable comment from MSDN on why not to use the HttpWebResponse.CharacterSet property: // http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.characterset(v=VS.80).aspx // // "As stated in a previous comment, many web servers are poorly configured and don't include the charset // in their content type header, e. g. they just return "text/html". In theory, user agents should treat // it as ISO-8859-1, as recommended by W3C. This is what the CharacterSet property actually does: It // always returns ISO-8859-1 if the charset it not specified, although often the content has a different // encoding (which of course HttpWebResponse cannot know). // In real life however, in case of a missing charset definition in the HTTP header user agents look into // the markup, and usully a meta tag can be found that contains the correct encoding, like "utf-8". To // implement this pragmatic approach, it would IMHO be much more convenient if the CharacterSet would // default to an empty string, then you know, that the encoding is not specified and you need a workaround // to determine the correct encoding to use. // The only workaround that I could find for me was to parse ContentType myself to extract the character // set, and ignore ContentEncoding and CharacterSet because they are useless." string contentType = response.ContentType; if (!String.IsNullOrEmpty(contentType)) { IDictionary values = MimeHelper.ParseContentType(contentType, true); const string charset = "charset"; if (values.Contains(charset)) { characterSet = values[charset] as string; if (!String.IsNullOrEmpty(characterSet)) { Debug.Assert(characterSet.Equals(response.CharacterSet, StringComparison.OrdinalIgnoreCase), "CharacterSet was parsed incorrectly!"); return true; } } } characterSet = null; return false; } private void LogXmlRpcRequest(Encoding encodingToUse, string methodName, XmlRpcValue[] parameters) { Trace.WriteLine("XML-RPC request:\r\n" + _hostname + "\r\n" + encodingToUse.GetString(GetRequestBytes(encodingToUse, methodName, parameters, true))); } private void LogXmlRpcResponse(string xmlRpcString) { Trace.WriteLine("XML-RPC response:\r\n" + _hostname + "\r\n" + xmlRpcString); } private static byte[] GetRequestBytes(Encoding encoding, string methodName, XmlRpcValue[] parameters, bool logging) { MemoryStream request = new MemoryStream(); XmlTextWriter writer = new XmlTextWriter(request, encoding); // Amazingly, some configs of WordPress complain // about malformed XML when uploading large posts/images (greater than // 100,000 bytes) if we don't indent. More precisely, there needs to be // fewer than 100,000 bytes before the first line break. Let's just // indent and be done with it. writer.Formatting = Formatting.Indented; writer.Indentation = 1; writer.IndentChar = ' '; writer.WriteStartDocument(); using (new WriteXmlElement(writer, "methodCall")) { using (new WriteXmlElement(writer, "methodName")) writer.WriteString(methodName); using (new WriteXmlElement(writer, "params")) { foreach (XmlRpcValue param in parameters) { using (new WriteXmlElement(writer, "param")) param.Write(writer, logging); } } } writer.WriteEndDocument(); writer.Flush(); return request.ToArray(); } //private Encoding _utf8EncodingNoBOM = new UTF8Encoding(false) ; private string _hostname; private string _userAgent; private HttpRequestFilter _requestFilter; private string _transportEncoding; } public abstract class XmlRpcValue { protected XmlRpcValue(object value) : this(value, false) { } protected XmlRpcValue(object value, bool suppressLog) { _value = value; _suppressLog = suppressLog; } public void Write(XmlWriter writer) { Write(writer, false); } public void Write(XmlWriter writer, bool logging) { using (new WriteXmlElement(writer, "value")) { WriteValue(writer, _value, logging); } } protected virtual void WriteValue(XmlWriter writer, object value, bool logging) { if (!_suppressLog || !logging) WriteValue(writer, value); else writer.WriteString("[removed]"); } protected abstract void WriteValue(XmlWriter writer, object value); private object _value; private readonly bool _suppressLog; } public class XmlRpcString : XmlRpcValue { public XmlRpcString(string value, bool suppressLog) : base(value, suppressLog) { } public XmlRpcString(string value) : base(value) { } protected override void WriteValue(XmlWriter writer, object value) { using (new WriteXmlElement(writer, "string")) writer.WriteString(value as string); } } public class XmlRpcBase64 : XmlRpcValue { public XmlRpcBase64(byte[] bytes) : base(bytes) { } protected override void WriteValue(XmlWriter writer, object value, bool logging) { byte[] bytes = (byte[])value; using (new WriteXmlElement(writer, "base64")) { if (!logging) writer.WriteBase64(bytes, 0, bytes.Length); else writer.WriteString(string.Format(CultureInfo.InvariantCulture, "[{0} bytes]", bytes.Length)); } } protected override void WriteValue(XmlWriter writer, object value) { Trace.Fail("This should never be called"); } } public class XmlRpcInt : XmlRpcValue { public XmlRpcInt(int value) : base(value) { } protected override void WriteValue(XmlWriter writer, object value) { using (new WriteXmlElement(writer, "int")) writer.WriteString(((int)value).ToString(CultureInfo.InvariantCulture)); } } public class XmlRpcBoolean : XmlRpcValue { public XmlRpcBoolean(bool value) : base(value) { } protected override void WriteValue(XmlWriter writer, object value) { using (new WriteXmlElement(writer, "boolean")) writer.WriteString((bool)value ? "1" : "0"); } } public class BloggerXmlRpcFormatTime : XmlRpcValue { private string formatString; public BloggerXmlRpcFormatTime(DateTime value, string format) : base(value) { if (String.Empty == format) { formatString = "yyyy-MM-dd'T'HH':'mm':'ss"; } else { formatString = format; } } protected override void WriteValue(XmlWriter writer, object value) { using (new WriteXmlElement(writer, "dateTime.iso8601")) writer.WriteString(((DateTime)value).ToString(formatString, CultureInfo.InvariantCulture)); } } public class XmlRpcFormatTime : XmlRpcValue { private string formatString; public XmlRpcFormatTime(DateTime value, string format) : base(value) { if (String.Empty == format) { formatString = "yyyyMMdd'T'HH':'mm':'ss"; } else { formatString = format; } } protected override void WriteValue(XmlWriter writer, object value) { using (new WriteXmlElement(writer, "dateTime.iso8601")) writer.WriteString(((DateTime)value).ToString(formatString, CultureInfo.InvariantCulture)); } } public class XmlRpcArray : XmlRpcValue { public XmlRpcArray(XmlRpcValue[] values) : base(values) { } protected override void WriteValue(XmlWriter writer, object value, bool logging) { using (new WriteXmlElement(writer, "array")) using (new WriteXmlElement(writer, "data")) foreach (XmlRpcValue val in (value as XmlRpcValue[])) { val.Write(writer, logging); } } protected override void WriteValue(XmlWriter writer, object value) { Trace.Fail("This should never be called"); } } public class XmlRpcStruct : XmlRpcValue { /// <summary> /// A structure is a dictionary of names and values /// </summary> /// <param name="values"></param> public XmlRpcStruct(XmlRpcMember[] members) : base(members) { } protected override void WriteValue(XmlWriter writer, object value, bool logging) { using (new WriteXmlElement(writer, "struct")) { foreach (XmlRpcMember member in (value as XmlRpcMember[])) { using (new WriteXmlElement(writer, "member")) { using (new WriteXmlElement(writer, "name")) writer.WriteString(member.Name); member.Value.Write(writer, logging); } } } } protected override void WriteValue(XmlWriter writer, object value) { Trace.Fail("This should never be called"); } } public class XmlRpcMember { public XmlRpcMember(string name, string value) : this(name, new XmlRpcString(value)) { } public XmlRpcMember(string name, string value, bool suppressLog) : this(name, new XmlRpcString(value, suppressLog)) { } public XmlRpcMember(string name, bool value) : this(name, new XmlRpcBoolean(value)) { } public XmlRpcMember(string name, int value) : this(name, new XmlRpcInt(value)) { } public XmlRpcMember(string name, XmlRpcMember[] members) : this(name, new XmlRpcStruct(members)) { } public XmlRpcMember(string name, XmlRpcValue value) { Name = name; _value = value; } public readonly string Name; public XmlRpcValue Value { get { return _value; } } private readonly XmlRpcValue _value; } public class XmlRpcMethodResponse { internal XmlRpcMethodResponse(string responseText) { try { // analyze the response text to determine the content of the response XmlDocument document = new XmlDocument(); if (responseText != null) responseText = responseText.TrimStart(' ', '\t', '\r', '\n'); document.LoadXml(responseText); XmlNode responseValue = document.SelectSingleNode("/methodResponse/params/param/value"); if (responseValue != null) { _response = responseValue; } else { // fault occurred _faultOccurred = true; XmlNode errorCode = document.SelectSingleNode("/methodResponse/fault/value/struct/member[name='faultCode']/value"); _faultCode = errorCode.InnerText; XmlNode errorString = document.SelectSingleNode("/methodResponse/fault/value/struct/member[name='faultString']/value"); _faultString = errorString.InnerText; } } catch (Exception ex) { throw new XmlRpcClientInvalidResponseException(responseText, ex); } } public XmlNode Response { get { return _response; } } private XmlNode _response = null; public bool FaultOccurred { get { return _faultOccurred; } } private bool _faultOccurred = false; public string FaultCode { get { return _faultCode; } } private string _faultCode = String.Empty; public string FaultString { get { return _faultString; } } private string _faultString = String.Empty; } public class XmlRpcClientInvalidResponseException : ApplicationException { public XmlRpcClientInvalidResponseException(string response, Exception innerException) : base("Invalid response document returned from XmlRpc server", innerException) { Response = response; } public readonly string Response; } /// <summary> /// Utility class used to write elements /// </summary> internal class WriteXmlElement : IDisposable { public WriteXmlElement(XmlWriter writer, string elName) { _writer = writer; _writer.WriteStartElement(elName); } public void Dispose() { _writer.WriteEndElement(); } private XmlWriter _writer; } }
// 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.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; namespace System.Collections.Immutable { /// <summary> /// An immutable unordered dictionary implementation. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TValue">The type of the value.</typeparam> [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(ImmutableDictionaryDebuggerProxy<,>))] public sealed partial class ImmutableDictionary<TKey, TValue> : IImmutableDictionary<TKey, TValue>, IImmutableDictionaryInternal<TKey, TValue>, IHashKeyCollection<TKey>, IDictionary<TKey, TValue>, IDictionary { /// <summary> /// An empty immutable dictionary with default equality comparers. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly ImmutableDictionary<TKey, TValue> Empty = new ImmutableDictionary<TKey, TValue>(); /// <summary> /// The singleton delegate that freezes the contents of hash buckets when the root of the data structure is frozen. /// </summary> private static readonly Action<KeyValuePair<int, HashBucket>> s_FreezeBucketAction = (kv) => kv.Value.Freeze(); /// <summary> /// The number of elements in the collection. /// </summary> private readonly int _count; /// <summary> /// The root node of the tree that stores this map. /// </summary> private readonly SortedInt32KeyNode<HashBucket> _root; /// <summary> /// The comparer used when comparing hash buckets. /// </summary> private readonly Comparers _comparers; /// <summary> /// Initializes a new instance of the <see cref="ImmutableDictionary{TKey, TValue}"/> class. /// </summary> /// <param name="root">The root.</param> /// <param name="comparers">The comparers.</param> /// <param name="count">The number of elements in the map.</param> private ImmutableDictionary(SortedInt32KeyNode<HashBucket> root, Comparers comparers, int count) : this(Requires.NotNullPassthrough(comparers, nameof(comparers))) { Requires.NotNull(root, nameof(root)); root.Freeze(s_FreezeBucketAction); _root = root; _count = count; } /// <summary> /// Initializes a new instance of the <see cref="ImmutableDictionary{TKey, TValue}"/> class. /// </summary> /// <param name="comparers">The comparers.</param> private ImmutableDictionary(Comparers comparers = null) { _comparers = comparers ?? Comparers.Get(EqualityComparer<TKey>.Default, EqualityComparer<TValue>.Default); _root = SortedInt32KeyNode<HashBucket>.EmptyNode; } /// <summary> /// How to respond when a key collision is discovered. /// </summary> internal enum KeyCollisionBehavior { /// <summary> /// Sets the value for the given key, even if that overwrites an existing value. /// </summary> SetValue, /// <summary> /// Skips the mutating operation if a key conflict is detected. /// </summary> Skip, /// <summary> /// Throw an exception if the key already exists with a different key. /// </summary> ThrowIfValueDifferent, /// <summary> /// Throw an exception if the key already exists regardless of its value. /// </summary> ThrowAlways, } /// <summary> /// The result of a mutation operation. /// </summary> internal enum OperationResult { /// <summary> /// The change was applied and did not require a change to the number of elements in the collection. /// </summary> AppliedWithoutSizeChange, /// <summary> /// The change required element(s) to be added or removed from the collection. /// </summary> SizeChanged, /// <summary> /// No change was required (the operation ended in a no-op). /// </summary> NoChangeRequired, } #region Public Properties /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface. /// </summary> public ImmutableDictionary<TKey, TValue> Clear() { return this.IsEmpty ? this : EmptyWithComparers(_comparers); } /// <summary> /// Gets the number of elements in this collection. /// </summary> public int Count { get { return _count; } } /// <summary> /// Gets a value indicating whether this instance is empty. /// </summary> /// <value> /// <c>true</c> if this instance is empty; otherwise, <c>false</c>. /// </value> public bool IsEmpty { get { return this.Count == 0; } } /// <summary> /// Gets the key comparer. /// </summary> public IEqualityComparer<TKey> KeyComparer { get { return _comparers.KeyComparer; } } /// <summary> /// Gets the value comparer used to determine whether values are equal. /// </summary> public IEqualityComparer<TValue> ValueComparer { get { return _comparers.ValueComparer; } } /// <summary> /// Gets the keys in the map. /// </summary> public IEnumerable<TKey> Keys { get { foreach (var bucket in _root) { foreach (var item in bucket.Value) { yield return item.Key; } } } } /// <summary> /// Gets the values in the map. /// </summary> public IEnumerable<TValue> Values { get { foreach (var bucket in _root) { foreach (var item in bucket.Value) { yield return item.Value; } } } } #endregion #region IImmutableDictionary<TKey,TValue> Properties /// <summary> /// Gets the empty instance. /// </summary> [ExcludeFromCodeCoverage] IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Clear() { return this.Clear(); } #endregion #region IDictionary<TKey, TValue> Properties /// <summary> /// Gets the keys. /// </summary> ICollection<TKey> IDictionary<TKey, TValue>.Keys { get { return new KeysCollectionAccessor<TKey, TValue>(this); } } /// <summary> /// Gets the values. /// </summary> ICollection<TValue> IDictionary<TKey, TValue>.Values { get { return new ValuesCollectionAccessor<TKey, TValue>(this); } } #endregion /// <summary> /// Gets a data structure that captures the current state of this map, as an input into a query or mutating function. /// </summary> private MutationInput Origin { get { return new MutationInput(this); } } /// <summary> /// Gets the <typeparamref name="TValue"/> with the specified key. /// </summary> public TValue this[TKey key] { get { Requires.NotNullAllowStructs(key, nameof(key)); TValue value; if (this.TryGetValue(key, out value)) { return value; } throw new KeyNotFoundException(); } } /// <summary> /// Gets or sets the <typeparamref name="TValue"/> with the specified key. /// </summary> TValue IDictionary<TKey, TValue>.this[TKey key] { get { return this[key]; } set { throw new NotSupportedException(); } } #region ICollection<KeyValuePair<TKey, TValue>> Properties bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly { get { return true; } } #endregion #region Public methods /// <summary> /// Creates a collection with the same contents as this collection that /// can be efficiently mutated across multiple operations using standard /// mutable interfaces. /// </summary> /// <remarks> /// This is an O(1) operation and results in only a single (small) memory allocation. /// The mutable collection that is returned is *not* thread-safe. /// </remarks> [Pure] public Builder ToBuilder() { // We must not cache the instance created here and return it to various callers. // Those who request a mutable collection must get references to the collection // that version independently of each other. return new Builder(this); } /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface. /// </summary> [Pure] public ImmutableDictionary<TKey, TValue> Add(TKey key, TValue value) { Requires.NotNullAllowStructs(key, nameof(key)); Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null); var result = Add(key, value, KeyCollisionBehavior.ThrowIfValueDifferent, this.Origin); return result.Finalize(this); } /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface. /// </summary> [Pure] [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public ImmutableDictionary<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs) { Requires.NotNull(pairs, nameof(pairs)); Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null); return this.AddRange(pairs, false); } /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface. /// </summary> [Pure] public ImmutableDictionary<TKey, TValue> SetItem(TKey key, TValue value) { Requires.NotNullAllowStructs(key, nameof(key)); Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null); Contract.Ensures(!Contract.Result<ImmutableDictionary<TKey, TValue>>().IsEmpty); var result = Add(key, value, KeyCollisionBehavior.SetValue, this.Origin); return result.Finalize(this); } /// <summary> /// Applies a given set of key=value pairs to an immutable dictionary, replacing any conflicting keys in the resulting dictionary. /// </summary> /// <param name="items">The key=value pairs to set on the map. Any keys that conflict with existing keys will overwrite the previous values.</param> /// <returns>An immutable dictionary.</returns> [Pure] [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public ImmutableDictionary<TKey, TValue> SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items) { Requires.NotNull(items, nameof(items)); Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null); var result = AddRange(items, this.Origin, KeyCollisionBehavior.SetValue); return result.Finalize(this); } /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface. /// </summary> [Pure] public ImmutableDictionary<TKey, TValue> Remove(TKey key) { Requires.NotNullAllowStructs(key, nameof(key)); Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null); var result = Remove(key, this.Origin); return result.Finalize(this); } /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface. /// </summary> [Pure] public ImmutableDictionary<TKey, TValue> RemoveRange(IEnumerable<TKey> keys) { Requires.NotNull(keys, nameof(keys)); Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null); int count = _count; var root = _root; foreach (var key in keys) { int hashCode = this.KeyComparer.GetHashCode(key); HashBucket bucket; if (root.TryGetValue(hashCode, out bucket)) { OperationResult result; var newBucket = bucket.Remove(key, _comparers.KeyOnlyComparer, out result); root = UpdateRoot(root, hashCode, newBucket, _comparers.HashBucketEqualityComparer); if (result == OperationResult.SizeChanged) { count--; } } } return this.Wrap(root, count); } /// <summary> /// Determines whether the specified key contains key. /// </summary> /// <param name="key">The key.</param> /// <returns> /// <c>true</c> if the specified key contains key; otherwise, <c>false</c>. /// </returns> public bool ContainsKey(TKey key) { Requires.NotNullAllowStructs(key, nameof(key)); return ContainsKey(key, this.Origin); } /// <summary> /// Determines whether [contains] [the specified key value pair]. /// </summary> /// <param name="pair">The key value pair.</param> /// <returns> /// <c>true</c> if [contains] [the specified key value pair]; otherwise, <c>false</c>. /// </returns> public bool Contains(KeyValuePair<TKey, TValue> pair) { return Contains(pair, this.Origin); } /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface. /// </summary> public bool TryGetValue(TKey key, out TValue value) { Requires.NotNullAllowStructs(key, nameof(key)); return TryGetValue(key, this.Origin, out value); } /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface. /// </summary> public bool TryGetKey(TKey equalKey, out TKey actualKey) { Requires.NotNullAllowStructs(equalKey, nameof(equalKey)); return TryGetKey(equalKey, this.Origin, out actualKey); } /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface. /// </summary> [Pure] public ImmutableDictionary<TKey, TValue> WithComparers(IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer) { if (keyComparer == null) { keyComparer = EqualityComparer<TKey>.Default; } if (valueComparer == null) { valueComparer = EqualityComparer<TValue>.Default; } if (this.KeyComparer == keyComparer) { if (this.ValueComparer == valueComparer) { return this; } else { // When the key comparer is the same but the value comparer is different, we don't need a whole new tree // because the structure of the tree does not depend on the value comparer. // We just need a new root node to store the new value comparer. var comparers = _comparers.WithValueComparer(valueComparer); return new ImmutableDictionary<TKey, TValue>(_root, comparers, _count); } } else { var comparers = Comparers.Get(keyComparer, valueComparer); var set = new ImmutableDictionary<TKey, TValue>(comparers); set = set.AddRange(this, avoidToHashMap: true); return set; } } /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface. /// </summary> [Pure] public ImmutableDictionary<TKey, TValue> WithComparers(IEqualityComparer<TKey> keyComparer) { return this.WithComparers(keyComparer, _comparers.ValueComparer); } /// <summary> /// Determines whether the <see cref="ImmutableDictionary{TKey, TValue}"/> /// contains an element with the specified value. /// </summary> /// <param name="value"> /// The value to locate in the <see cref="ImmutableDictionary{TKey, TValue}"/>. /// The value can be null for reference types. /// </param> /// <returns> /// true if the <see cref="ImmutableDictionary{TKey, TValue}"/> contains /// an element with the specified value; otherwise, false. /// </returns> [Pure] public bool ContainsValue(TValue value) { foreach (KeyValuePair<TKey, TValue> item in this) { if (this.ValueComparer.Equals(value, item.Value)) { return true; } } return false; } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> public Enumerator GetEnumerator() { return new Enumerator(_root); } #endregion #region IImmutableDictionary<TKey,TValue> Methods /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface /// </summary> [ExcludeFromCodeCoverage] IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Add(TKey key, TValue value) { return this.Add(key, value); } /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface /// </summary> [ExcludeFromCodeCoverage] IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.SetItem(TKey key, TValue value) { return this.SetItem(key, value); } /// <summary> /// Applies a given set of key=value pairs to an immutable dictionary, replacing any conflicting keys in the resulting dictionary. /// </summary> /// <param name="items">The key=value pairs to set on the map. Any keys that conflict with existing keys will overwrite the previous values.</param> /// <returns>An immutable dictionary.</returns> IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items) { return this.SetItems(items); } /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface /// </summary> [ExcludeFromCodeCoverage] IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs) { return this.AddRange(pairs); } /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface /// </summary> [ExcludeFromCodeCoverage] IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.RemoveRange(IEnumerable<TKey> keys) { return this.RemoveRange(keys); } /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface /// </summary> [ExcludeFromCodeCoverage] IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Remove(TKey key) { return this.Remove(key); } #endregion #region IDictionary<TKey, TValue> Methods /// <summary> /// Adds an element with the provided key and value to the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <param name="key">The object to use as the key of the element to add.</param> /// <param name="value">The object to use as the value of the element to add.</param> /// <exception cref="ArgumentNullException"><paramref name="key"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// An element with the same key already exists in the <see cref="IDictionary{TKey, TValue}"/>. /// </exception> /// <exception cref="NotSupportedException"> /// The <see cref="IDictionary{TKey, TValue}"/> is read-only. /// </exception> void IDictionary<TKey, TValue>.Add(TKey key, TValue value) { throw new NotSupportedException(); } /// <summary> /// Removes the element with the specified key from the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <param name="key">The key of the element to remove.</param> /// <returns> /// true if the element is successfully removed; otherwise, false. This method also returns false if <paramref name="key"/> was not found in the original <see cref="IDictionary{TKey, TValue}"/>. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="key"/> is null. /// </exception> /// <exception cref="NotSupportedException"> /// The <see cref="IDictionary{TKey, TValue}"/> is read-only. /// </exception> bool IDictionary<TKey, TValue>.Remove(TKey key) { throw new NotSupportedException(); } #endregion #region ICollection<KeyValuePair<TKey, TValue>> Methods void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item) { throw new NotSupportedException(); } void ICollection<KeyValuePair<TKey, TValue>>.Clear() { throw new NotSupportedException(); } bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) { throw new NotSupportedException(); } void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { Requires.NotNull(array, nameof(array)); Requires.Range(arrayIndex >= 0, nameof(arrayIndex)); Requires.Range(array.Length >= arrayIndex + this.Count, nameof(arrayIndex)); foreach (var item in this) { array[arrayIndex++] = item; } } #endregion #region IDictionary Properties /// <summary> /// Gets a value indicating whether the <see cref="IDictionary"/> object has a fixed size. /// </summary> /// <returns>true if the <see cref="IDictionary"/> object has a fixed size; otherwise, false.</returns> bool IDictionary.IsFixedSize { get { return true; } } /// <summary> /// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only. /// </summary> /// <returns>true if the <see cref="ICollection{T}"/> is read-only; otherwise, false. /// </returns> bool IDictionary.IsReadOnly { get { return true; } } /// <summary> /// Gets an <see cref="ICollection{T}"/> containing the keys of the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <returns> /// An <see cref="ICollection{T}"/> containing the keys of the object that implements <see cref="IDictionary{TKey, TValue}"/>. /// </returns> ICollection IDictionary.Keys { get { return new KeysCollectionAccessor<TKey, TValue>(this); } } /// <summary> /// Gets an <see cref="ICollection{T}"/> containing the values in the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <returns> /// An <see cref="ICollection{T}"/> containing the values in the object that implements <see cref="IDictionary{TKey, TValue}"/>. /// </returns> ICollection IDictionary.Values { get { return new ValuesCollectionAccessor<TKey, TValue>(this); } } #endregion /// <summary> /// Gets the root node (for testing purposes). /// </summary> internal SortedInt32KeyNode<HashBucket> Root { get { return _root; } } #region IDictionary Methods /// <summary> /// Adds an element with the provided key and value to the <see cref="IDictionary"/> object. /// </summary> /// <param name="key">The <see cref="object"/> to use as the key of the element to add.</param> /// <param name="value">The <see cref="object"/> to use as the value of the element to add.</param> void IDictionary.Add(object key, object value) { throw new NotSupportedException(); } /// <summary> /// Determines whether the <see cref="IDictionary"/> object contains an element with the specified key. /// </summary> /// <param name="key">The key to locate in the <see cref="IDictionary"/> object.</param> /// <returns> /// true if the <see cref="IDictionary"/> contains an element with the key; otherwise, false. /// </returns> bool IDictionary.Contains(object key) { return this.ContainsKey((TKey)key); } /// <summary> /// Returns an <see cref="IDictionaryEnumerator"/> object for the <see cref="IDictionary"/> object. /// </summary> /// <returns> /// An <see cref="IDictionaryEnumerator"/> object for the <see cref="IDictionary"/> object. /// </returns> IDictionaryEnumerator IDictionary.GetEnumerator() { return new DictionaryEnumerator<TKey, TValue>(this.GetEnumerator()); } /// <summary> /// Removes the element with the specified key from the <see cref="IDictionary"/> object. /// </summary> /// <param name="key">The key of the element to remove.</param> void IDictionary.Remove(object key) { throw new NotSupportedException(); } /// <summary> /// Gets or sets the element with the specified key. /// </summary> /// <param name="key">The key.</param> /// <returns></returns> object IDictionary.this[object key] { get { return this[(TKey)key]; } set { throw new NotSupportedException(); } } /// <summary> /// Clears this instance. /// </summary> /// <exception cref="System.NotSupportedException"></exception> void IDictionary.Clear() { throw new NotSupportedException(); } #endregion #region ICollection Methods /// <summary> /// Copies the elements of the <see cref="ICollection"/> to an <see cref="Array"/>, starting at a particular <see cref="Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ICollection"/>. The <see cref="Array"/> must have zero-based indexing.</param> /// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param> void ICollection.CopyTo(Array array, int arrayIndex) { Requires.NotNull(array, nameof(array)); Requires.Range(arrayIndex >= 0, nameof(arrayIndex)); Requires.Range(array.Length >= arrayIndex + this.Count, nameof(arrayIndex)); foreach (var item in this) { array.SetValue(new DictionaryEntry(item.Key, item.Value), arrayIndex++); } } #endregion #region ICollection Properties /// <summary> /// Gets an object that can be used to synchronize access to the <see cref="ICollection"/>. /// </summary> /// <returns>An object that can be used to synchronize access to the <see cref="ICollection"/>.</returns> [DebuggerBrowsable(DebuggerBrowsableState.Never)] object ICollection.SyncRoot { get { return this; } } /// <summary> /// Gets a value indicating whether access to the <see cref="ICollection"/> is synchronized (thread safe). /// </summary> /// <returns>true if access to the <see cref="ICollection"/> is synchronized (thread safe); otherwise, false.</returns> [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool ICollection.IsSynchronized { get { // This is immutable, so it is always thread-safe. return true; } } #endregion #region IEnumerable<KeyValuePair<TKey, TValue>> Members /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { return this.GetEnumerator(); } #endregion #region IEnumerable Members /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="IEnumerator"/> object that can be used to iterate through the collection. /// </returns> [ExcludeFromCodeCoverage] IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion /// <summary> /// Gets an empty collection with the specified comparers. /// </summary> /// <param name="comparers">The comparers.</param> /// <returns>The empty dictionary.</returns> [Pure] private static ImmutableDictionary<TKey, TValue> EmptyWithComparers(Comparers comparers) { Requires.NotNull(comparers, nameof(comparers)); return Empty._comparers == comparers ? Empty : new ImmutableDictionary<TKey, TValue>(comparers); } /// <summary> /// Attempts to discover an <see cref="ImmutableDictionary{TKey, TValue}"/> instance beneath some enumerable sequence /// if one exists. /// </summary> /// <param name="sequence">The sequence that may have come from an immutable map.</param> /// <param name="other">Receives the concrete <see cref="ImmutableDictionary{TKey, TValue}"/> typed value if one can be found.</param> /// <returns><c>true</c> if the cast was successful; <c>false</c> otherwise.</returns> private static bool TryCastToImmutableMap(IEnumerable<KeyValuePair<TKey, TValue>> sequence, out ImmutableDictionary<TKey, TValue> other) { other = sequence as ImmutableDictionary<TKey, TValue>; if (other != null) { return true; } var builder = sequence as Builder; if (builder != null) { other = builder.ToImmutable(); return true; } return false; } #region Static query and manipulator methods /// <summary> /// Performs the operation on a given data structure. /// </summary> private static bool ContainsKey(TKey key, MutationInput origin) { int hashCode = origin.KeyComparer.GetHashCode(key); HashBucket bucket; if (origin.Root.TryGetValue(hashCode, out bucket)) { TValue value; return bucket.TryGetValue(key, origin.KeyOnlyComparer, out value); } return false; } /// <summary> /// Performs the operation on a given data structure. /// </summary> private static bool Contains(KeyValuePair<TKey, TValue> keyValuePair, MutationInput origin) { int hashCode = origin.KeyComparer.GetHashCode(keyValuePair.Key); HashBucket bucket; if (origin.Root.TryGetValue(hashCode, out bucket)) { TValue value; return bucket.TryGetValue(keyValuePair.Key, origin.KeyOnlyComparer, out value) && origin.ValueComparer.Equals(value, keyValuePair.Value); } return false; } /// <summary> /// Performs the operation on a given data structure. /// </summary> private static bool TryGetValue(TKey key, MutationInput origin, out TValue value) { int hashCode = origin.KeyComparer.GetHashCode(key); HashBucket bucket; if (origin.Root.TryGetValue(hashCode, out bucket)) { return bucket.TryGetValue(key, origin.KeyOnlyComparer, out value); } value = default(TValue); return false; } /// <summary> /// Performs the operation on a given data structure. /// </summary> private static bool TryGetKey(TKey equalKey, MutationInput origin, out TKey actualKey) { int hashCode = origin.KeyComparer.GetHashCode(equalKey); HashBucket bucket; if (origin.Root.TryGetValue(hashCode, out bucket)) { return bucket.TryGetKey(equalKey, origin.KeyOnlyComparer, out actualKey); } actualKey = equalKey; return false; } /// <summary> /// Performs the operation on a given data structure. /// </summary> private static MutationResult Add(TKey key, TValue value, KeyCollisionBehavior behavior, MutationInput origin) { Requires.NotNullAllowStructs(key, nameof(key)); OperationResult result; int hashCode = origin.KeyComparer.GetHashCode(key); HashBucket bucket = origin.Root.GetValueOrDefault(hashCode); var newBucket = bucket.Add(key, value, origin.KeyOnlyComparer, origin.ValueComparer, behavior, out result); if (result == OperationResult.NoChangeRequired) { return new MutationResult(origin); } var newRoot = UpdateRoot(origin.Root, hashCode, newBucket, origin.HashBucketComparer); return new MutationResult(newRoot, result == OperationResult.SizeChanged ? +1 : 0); } /// <summary> /// Performs the operation on a given data structure. /// </summary> private static MutationResult AddRange(IEnumerable<KeyValuePair<TKey, TValue>> items, MutationInput origin, KeyCollisionBehavior collisionBehavior = KeyCollisionBehavior.ThrowIfValueDifferent) { Requires.NotNull(items, nameof(items)); int countAdjustment = 0; var newRoot = origin.Root; foreach (var pair in items) { int hashCode = origin.KeyComparer.GetHashCode(pair.Key); HashBucket bucket = newRoot.GetValueOrDefault(hashCode); OperationResult result; var newBucket = bucket.Add(pair.Key, pair.Value, origin.KeyOnlyComparer, origin.ValueComparer, collisionBehavior, out result); newRoot = UpdateRoot(newRoot, hashCode, newBucket, origin.HashBucketComparer); if (result == OperationResult.SizeChanged) { countAdjustment++; } } return new MutationResult(newRoot, countAdjustment); } /// <summary> /// Performs the operation on a given data structure. /// </summary> private static MutationResult Remove(TKey key, MutationInput origin) { int hashCode = origin.KeyComparer.GetHashCode(key); HashBucket bucket; if (origin.Root.TryGetValue(hashCode, out bucket)) { OperationResult result; var newRoot = UpdateRoot(origin.Root, hashCode, bucket.Remove(key, origin.KeyOnlyComparer, out result), origin.HashBucketComparer); return new MutationResult(newRoot, result == OperationResult.SizeChanged ? -1 : 0); } return new MutationResult(origin); } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static SortedInt32KeyNode<HashBucket> UpdateRoot(SortedInt32KeyNode<HashBucket> root, int hashCode, HashBucket newBucket, IEqualityComparer<HashBucket> hashBucketComparer) { bool mutated; if (newBucket.IsEmpty) { return root.Remove(hashCode, out mutated); } else { bool replacedExistingValue; return root.SetItem(hashCode, newBucket, hashBucketComparer, out replacedExistingValue, out mutated); } } #endregion /// <summary> /// Wraps the specified data structure with an immutable collection wrapper. /// </summary> /// <param name="root">The root of the data structure.</param> /// <param name="comparers">The comparers.</param> /// <param name="count">The number of elements in the data structure.</param> /// <returns> /// The immutable collection. /// </returns> private static ImmutableDictionary<TKey, TValue> Wrap(SortedInt32KeyNode<HashBucket> root, Comparers comparers, int count) { Requires.NotNull(root, nameof(root)); Requires.NotNull(comparers, nameof(comparers)); Requires.Range(count >= 0, nameof(count)); return new ImmutableDictionary<TKey, TValue>(root, comparers, count); } /// <summary> /// Wraps the specified data structure with an immutable collection wrapper. /// </summary> /// <param name="root">The root of the data structure.</param> /// <param name="adjustedCountIfDifferentRoot">The adjusted count if the root has changed.</param> /// <returns>The immutable collection.</returns> private ImmutableDictionary<TKey, TValue> Wrap(SortedInt32KeyNode<HashBucket> root, int adjustedCountIfDifferentRoot) { if (root == null) { return this.Clear(); } if (_root != root) { return root.IsEmpty ? this.Clear() : new ImmutableDictionary<TKey, TValue>(root, _comparers, adjustedCountIfDifferentRoot); } return this; } /// <summary> /// Bulk adds entries to the map. /// </summary> /// <param name="pairs">The entries to add.</param> /// <param name="avoidToHashMap"><c>true</c> when being called from <see cref="WithComparers(IEqualityComparer{TKey}, IEqualityComparer{TValue})"/> to avoid <see cref="T:System.StackOverflowException"/>.</param> [Pure] private ImmutableDictionary<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs, bool avoidToHashMap) { Requires.NotNull(pairs, nameof(pairs)); Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null); // Some optimizations may apply if we're an empty list. if (this.IsEmpty && !avoidToHashMap) { // If the items being added actually come from an ImmutableDictionary<TKey, TValue> // then there is no value in reconstructing it. ImmutableDictionary<TKey, TValue> other; if (TryCastToImmutableMap(pairs, out other)) { return other.WithComparers(this.KeyComparer, this.ValueComparer); } } var result = AddRange(pairs, this.Origin); return result.Finalize(this); } } }
// <copyright> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> namespace Microsoft.Activities.Presentation.Xaml { using System; using System.Activities; using System.Activities.Debugger.Symbol; using System.Collections.Generic; using System.Globalization; using System.IO; using System.ServiceModel.Activities; using System.Xaml; using System.Xml; class DesignTimeXamlWriter : XamlXmlWriter { //namespaces to ignore (don't load assembilies for) at root node HashSet<string> namespacesToIgnore; //namespaces we've seen at root level, we use this to figure out appropriate alias for MC namespace HashSet<string> rootLevelNamespaces; // for duplicate namespace filtering (happens if we're using the local assembly to compile itself) HashSet<string> emittedNamespacesInLocalAssembly; //For namespace defined in local assembly with assembly info in namespace declaration, we'll strip out the assembly info //and hold the namespace temporarily. Before writing the start object, we'll check whether the short version gets written //as a separate declaration, if not, we write it out. List<NamespaceDeclaration> localNamespacesWithAssemblyInfo; WorkflowDesignerXamlSchemaContext schemaContext; int currentDepth; int debugSymbolDepth; bool writeDebugSymbol; bool debugSymbolNamespaceAdded; bool isWritingElementStyleString; internal static readonly string EmptyWorkflowSymbol = (new WorkflowSymbol() { FileName = @"C:\Empty.xaml" }).Encode(); private bool shouldWriteDebugSymbol; public DesignTimeXamlWriter(TextWriter textWriter, WorkflowDesignerXamlSchemaContext context, bool shouldWriteDebugSymbol) : this(new NamespaceIndentingXmlWriter(textWriter), context, shouldWriteDebugSymbol) { } DesignTimeXamlWriter(NamespaceIndentingXmlWriter underlyingWriter, WorkflowDesignerXamlSchemaContext context, bool shouldWriteDebugSymbol) : base(underlyingWriter, context, // Setting AssumeValidInput to true allows to save a document even if it has duplicate members new XamlXmlWriterSettings { AssumeValidInput = true }) { underlyingWriter.Parent = this; this.namespacesToIgnore = new HashSet<string>(); this.rootLevelNamespaces = new HashSet<string>(); this.schemaContext = context; this.currentDepth = 0; this.shouldWriteDebugSymbol = shouldWriteDebugSymbol; } public override void WriteNamespace(NamespaceDeclaration namespaceDeclaration) { if (this.currentDepth == 0) { //we need to track every namespace alias appeared in root element to figure out right alias for MC namespace this.rootLevelNamespaces.Add(namespaceDeclaration.Prefix); //Remember namespaces needed to be ignored at top level so we will add ignore attribute for them when we write start object if (NameSpaces.ShouldIgnore(namespaceDeclaration.Namespace)) { this.namespacesToIgnore.Add(namespaceDeclaration.Prefix); } if (namespaceDeclaration.Namespace == NameSpaces.DebugSymbol) { debugSymbolNamespaceAdded = true; } } EmitNamespace(namespaceDeclaration); } void EmitNamespace(NamespaceDeclaration namespaceDeclaration) { // Write the namespace, filtering for duplicates in the local assembly because VS might be using it to compile itself. if (schemaContext.IsClrNamespaceWithNoAssembly(namespaceDeclaration.Namespace)) { // Might still need to trim a semicolon, even though it shouldn't strictly be there. string nonassemblyQualifedNamespace = namespaceDeclaration.Namespace; if (nonassemblyQualifedNamespace[nonassemblyQualifedNamespace.Length - 1] == ';') { nonassemblyQualifedNamespace = nonassemblyQualifedNamespace.Substring(0, nonassemblyQualifedNamespace.Length - 1); namespaceDeclaration = new NamespaceDeclaration(nonassemblyQualifedNamespace, namespaceDeclaration.Prefix); } EmitLocalNamespace(namespaceDeclaration); } else if (schemaContext.IsClrNamespaceInLocalAssembly(namespaceDeclaration.Namespace)) { string nonassemblyQualifedNamespace = schemaContext.TrimLocalAssembly(namespaceDeclaration.Namespace); namespaceDeclaration = new NamespaceDeclaration(nonassemblyQualifedNamespace, namespaceDeclaration.Prefix); if (this.localNamespacesWithAssemblyInfo == null) { this.localNamespacesWithAssemblyInfo = new List<NamespaceDeclaration>(); } this.localNamespacesWithAssemblyInfo.Add(namespaceDeclaration); } else { base.WriteNamespace(namespaceDeclaration); } } void EmitLocalNamespace(NamespaceDeclaration namespaceDeclaration) { if (this.emittedNamespacesInLocalAssembly == null) // lazy initialization { this.emittedNamespacesInLocalAssembly = new HashSet<string>(); } // Write the namespace only once. Add() returns false if it was already there. if (this.emittedNamespacesInLocalAssembly.Add(namespaceDeclaration.Namespace)) { base.WriteNamespace(namespaceDeclaration); } } public override void WriteStartObject(XamlType type) { if (type.UnderlyingType == typeof(string)) { isWritingElementStyleString = true; } // this is the top-level object if (this.currentDepth == 0) { if (!this.debugSymbolNamespaceAdded) { string sadsNamespaceAlias = GenerateNamespaceAlias(NameSpaces.DebugSymbolPrefix); this.WriteNamespace(new NamespaceDeclaration(NameSpaces.DebugSymbol, sadsNamespaceAlias)); this.debugSymbolNamespaceAdded = true; } // we need to write MC namespace if any namespaces need to be ignored if (this.namespacesToIgnore.Count > 0) { string mcNamespaceAlias = GenerateNamespaceAlias(NameSpaces.McPrefix); this.WriteNamespace(new NamespaceDeclaration(NameSpaces.Mc, mcNamespaceAlias)); } if (this.localNamespacesWithAssemblyInfo != null) { foreach (NamespaceDeclaration xamlNamespace in this.localNamespacesWithAssemblyInfo) { if ((this.emittedNamespacesInLocalAssembly == null) || (!this.emittedNamespacesInLocalAssembly.Contains(xamlNamespace.Namespace))) { base.WriteNamespace(xamlNamespace); } } } if ((type.UnderlyingType == typeof(Activity)) || (type.IsGeneric && type.UnderlyingType != null && type.UnderlyingType.GetGenericTypeDefinition() == typeof(Activity<>)) || (type.UnderlyingType == typeof(WorkflowService))) { // Exist ActivityBuilder, DebugSymbolObject will be inserted at the depth == 1. debugSymbolDepth = 1; } else { debugSymbolDepth = 0; } } if (this.currentDepth == debugSymbolDepth) { if (type.UnderlyingType != null && type.UnderlyingType.IsSubclassOf(typeof(Activity)) && this.shouldWriteDebugSymbol) { this.writeDebugSymbol = true; } } base.WriteStartObject(type); if (this.currentDepth == 0) { // we need to add Ignore attribute for all namespaces which we don't want to load assemblies for // this has to be done after WriteStartObject if (this.namespacesToIgnore.Count > 0) { string nsString = null; foreach (string ns in this.namespacesToIgnore) { if (nsString == null) { nsString = ns; } else { nsString += " " + ns; } } XamlDirective ignorable = new XamlDirective(NameSpaces.Mc, "Ignorable"); base.WriteStartMember(ignorable); base.WriteValue(nsString); base.WriteEndMember(); this.namespacesToIgnore.Clear(); } } ++this.currentDepth; } public override void WriteGetObject() { ++this.currentDepth; base.WriteGetObject(); } public override void WriteEndObject() { --this.currentDepth; SharedFx.Assert(this.currentDepth >= 0, "Unmatched WriteEndObject"); if (this.currentDepth == this.debugSymbolDepth && this.writeDebugSymbol) { base.WriteStartMember(new XamlMember(DebugSymbol.SymbolName.MemberName, this.SchemaContext.GetXamlType(typeof(DebugSymbol)), true)); base.WriteValue(EmptyWorkflowSymbol); base.WriteEndMember(); this.writeDebugSymbol = false; } base.WriteEndObject(); isWritingElementStyleString = false; } string GenerateNamespaceAlias(string prefix) { string aliasPostfix = string.Empty; //try "mc"~"mc1000" first for (int i = 1; i <= 1000; i++) { string mcAlias = prefix + aliasPostfix; if (!this.rootLevelNamespaces.Contains(mcAlias)) { return mcAlias; } aliasPostfix = i.ToString(CultureInfo.InvariantCulture); } //roll the dice return prefix + Guid.NewGuid().ToString(); } class NamespaceIndentingXmlWriter : XmlTextWriter { int currentDepth; TextWriter textWriter; public NamespaceIndentingXmlWriter(TextWriter textWriter) : base(textWriter) { this.textWriter = textWriter; this.Formatting = Formatting.Indented; } public DesignTimeXamlWriter Parent { get; set; } public override void WriteStartElement(string prefix, string localName, string ns) { base.WriteStartElement(prefix, localName, ns); this.currentDepth++; } public override void WriteStartAttribute(string prefix, string localName, string ns) { if (prefix == "xmlns" && (this.currentDepth == 1)) { this.textWriter.Write(new char[] { '\r', '\n' }); } base.WriteStartAttribute(prefix, localName, ns); } public override void WriteEndElement() { if (this.Parent.isWritingElementStyleString) { base.WriteRaw(string.Empty); } base.WriteEndElement(); this.currentDepth--; } public override void WriteStartDocument() { // No-op to avoid XmlDeclaration from being written. // Overriding this is equivalent of XmlWriterSettings.OmitXmlDeclaration = true. } public override void WriteStartDocument(bool standalone) { // No-op to avoid XmlDeclaration from being written. // Overriding this is equivalent of XmlWriterSettings.OmitXmlDeclaration = true. } public override void WriteEndDocument() { // No-op to avoid end of XmlDeclaration from being written. // Overriding this is equivalent of XmlWriterSettings.OmitXmlDeclaration = true. } } } }
/** * 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. * * Contains some contributions under the Thrift Software License. * Please see doc/old-thrift-license.txt in the Thrift distribution for * details. */ using System; using System.Text; using Thrift.Transport; namespace Thrift.Protocol { public class TBinaryProtocol : TProtocol { protected const uint VERSION_MASK = 0xffff0000; protected const uint VERSION_1 = 0x80010000; protected bool strictRead_ = false; protected bool strictWrite_ = true; protected int readLength_; protected bool checkReadLength_ = false; #region BinaryProtocol Factory /** * Factory */ public class Factory : TProtocolFactory { protected bool strictRead_ = false; protected bool strictWrite_ = true; public Factory() :this(false, true) { } public Factory(bool strictRead, bool strictWrite) { strictRead_ = strictRead; strictWrite_ = strictWrite; } public TProtocol GetProtocol(TTransport trans) { return new TBinaryProtocol(trans, strictRead_, strictWrite_); } } #endregion public TBinaryProtocol(TTransport trans) : this(trans, false, true) { } public TBinaryProtocol(TTransport trans, bool strictRead, bool strictWrite) :base(trans) { strictRead_ = strictRead; strictWrite_ = strictWrite; } #region Write Methods public override void WriteMessageBegin(TMessage message) { if (strictWrite_) { uint version = VERSION_1 | (uint)(message.Type); WriteI32((int)version); WriteString(message.Name); WriteI32(message.SeqID); } else { WriteString(message.Name); WriteByte((byte)message.Type); WriteI32(message.SeqID); } } public override void WriteMessageEnd() { } public override void WriteStructBegin(TStruct struc) { } public override void WriteStructEnd() { } public override void WriteFieldBegin(TField field) { WriteByte((byte)field.Type); WriteI16(field.ID); } public override void WriteFieldEnd() { } public override void WriteFieldStop() { WriteByte((byte)TType.Stop); } public override void WriteMapBegin(TMap map) { WriteByte((byte)map.KeyType); WriteByte((byte)map.ValueType); WriteI32(map.Count); } public override void WriteMapEnd() { } public override void WriteListBegin(TList list) { WriteByte((byte)list.ElementType); WriteI32(list.Count); } public override void WriteListEnd() { } public override void WriteSetBegin(TSet set) { WriteByte((byte)set.ElementType); WriteI32(set.Count); } public override void WriteSetEnd() { } public override void WriteBool(bool b) { WriteByte(b ? (byte)1 : (byte)0); } private byte[] bout = new byte[1]; public override void WriteByte(byte b) { bout[0] = b; trans.Write(bout, 0, 1); } private byte[] i16out = new byte[2]; public override void WriteI16(short s) { i16out[0] = (byte)(0xff & (s >> 8)); i16out[1] = (byte)(0xff & s); trans.Write(i16out, 0, 2); } private byte[] i32out = new byte[4]; public override void WriteI32(int i32) { i32out[0] = (byte)(0xff & (i32 >> 24)); i32out[1] = (byte)(0xff & (i32 >> 16)); i32out[2] = (byte)(0xff & (i32 >> 8)); i32out[3] = (byte)(0xff & i32); trans.Write(i32out, 0, 4); } private byte[] i64out = new byte[8]; public override void WriteI64(long i64) { i64out[0] = (byte)(0xff & (i64 >> 56)); i64out[1] = (byte)(0xff & (i64 >> 48)); i64out[2] = (byte)(0xff & (i64 >> 40)); i64out[3] = (byte)(0xff & (i64 >> 32)); i64out[4] = (byte)(0xff & (i64 >> 24)); i64out[5] = (byte)(0xff & (i64 >> 16)); i64out[6] = (byte)(0xff & (i64 >> 8)); i64out[7] = (byte)(0xff & i64); trans.Write(i64out, 0, 8); } public override void WriteDouble(double d) { #if !SILVERLIGHT WriteI64(BitConverter.DoubleToInt64Bits(d)); #else var bytes = BitConverter.GetBytes(d); WriteI64(BitConverter.ToInt64(bytes, 0)); #endif } public override void WriteBinary(byte[] b) { WriteI32(b.Length); trans.Write(b, 0, b.Length); } #endregion #region ReadMethods public override TMessage ReadMessageBegin() { TMessage message = new TMessage(); int size = ReadI32(); if (size < 0) { uint version = (uint)size & VERSION_MASK; if (version != VERSION_1) { throw new TProtocolException(TProtocolException.BAD_VERSION, "Bad version in ReadMessageBegin: " + version); } message.Type = (TMessageType)(size & 0x000000ff); message.Name = ReadString(); message.SeqID = ReadI32(); } else { if (strictRead_) { throw new TProtocolException(TProtocolException.BAD_VERSION, "Missing version in readMessageBegin, old client?"); } message.Name = ReadStringBody(size); message.Type = (TMessageType)ReadByte(); message.SeqID = ReadI32(); } return message; } public override void ReadMessageEnd() { } public override TStruct ReadStructBegin() { return new TStruct(); } public override void ReadStructEnd() { } public override TField ReadFieldBegin() { TField field = new TField(); field.Type = (TType)ReadByte(); if (field.Type != TType.Stop) { field.ID = ReadI16(); } return field; } public override void ReadFieldEnd() { } public override TMap ReadMapBegin() { TMap map = new TMap(); map.KeyType = (TType)ReadByte(); map.ValueType = (TType)ReadByte(); map.Count = ReadI32(); return map; } public override void ReadMapEnd() { } public override TList ReadListBegin() { TList list = new TList(); list.ElementType = (TType)ReadByte(); list.Count = ReadI32(); return list; } public override void ReadListEnd() { } public override TSet ReadSetBegin() { TSet set = new TSet(); set.ElementType = (TType)ReadByte(); set.Count = ReadI32(); return set; } public override void ReadSetEnd() { } public override bool ReadBool() { return ReadByte() == 1; } private byte[] bin = new byte[1]; public override byte ReadByte() { ReadAll(bin, 0, 1); return bin[0]; } private byte[] i16in = new byte[2]; public override short ReadI16() { ReadAll(i16in, 0, 2); return (short)(((i16in[0] & 0xff) << 8) | ((i16in[1] & 0xff))); } private byte[] i32in = new byte[4]; public override int ReadI32() { ReadAll(i32in, 0, 4); return (int)(((i32in[0] & 0xff) << 24) | ((i32in[1] & 0xff) << 16) | ((i32in[2] & 0xff) << 8) | ((i32in[3] & 0xff))); } private byte[] i64in = new byte[8]; public override long ReadI64() { ReadAll(i64in, 0, 8); return (long)( (ulong)((ulong)(i64in[0] & 0xff) << 56) | (ulong)((ulong)(i64in[1] & 0xff) << 48) | (ulong)((ulong)(i64in[2] & 0xff) << 40) | (ulong)((ulong)(i64in[3] & 0xff) << 32) | (ulong)((ulong)(i64in[4] & 0xff) << 24) | (ulong)((ulong)(i64in[5] & 0xff) << 16) | (ulong)((ulong)(i64in[6] & 0xff) << 8) | (ulong)((ulong)(i64in[7] & 0xff))); } public override double ReadDouble() { #if !SILVERLIGHT return BitConverter.Int64BitsToDouble(ReadI64()); #else var value = ReadI64(); var bytes = BitConverter.GetBytes(value); return BitConverter.ToDouble(bytes, 0); #endif } public void SetReadLength(int readLength) { readLength_ = readLength; checkReadLength_ = true; } protected void CheckReadLength(int length) { if (checkReadLength_) { readLength_ -= length; if (readLength_ < 0) { throw new Exception("Message length exceeded: " + length); } } } public override byte[] ReadBinary() { int size = ReadI32(); CheckReadLength(size); byte[] buf = new byte[size]; trans.ReadAll(buf, 0, size); return buf; } private string ReadStringBody(int size) { CheckReadLength(size); byte[] buf = new byte[size]; trans.ReadAll(buf, 0, size); return Encoding.UTF8.GetString(buf, 0, buf.Length); } private int ReadAll(byte[] buf, int off, int len) { CheckReadLength(len); return trans.ReadAll(buf, off, len); } #endregion } }
using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Pdelvo.Minecraft.Network; using Pdelvo.Minecraft.Protocol.Helper; using Pdelvo.Minecraft.Protocol.Packets; using ThreadState = System.Threading.ThreadState; namespace Pdelvo.Minecraft.Protocol { /// <summary> /// </summary> /// <remarks> /// </remarks> public abstract class RemoteInterface : IMinecraftRemoteInterface, IDisposable { private readonly LockFreeQueue<Dieable<Packet>> _fastQueue = new LockFreeQueue<Dieable<Packet>> (); private readonly LockFreeQueue<Dieable<Packet>> _slowQueue = new LockFreeQueue<Dieable<Packet>> (); /// <summary> /// </summary> private bool _aborting; private AutoResetEvent _writeEvent = new AutoResetEvent(false); /// <summary> /// Initializes a new instance of the <see cref="RemoteInterface" /> class. /// </summary> /// <param name="endPoint"> The end point. </param> /// <remarks> /// </remarks> protected RemoteInterface(PacketEndPoint endPoint) { EndPoint = endPoint; } /// <summary> /// </summary> protected Thread Thread { get; set; } #region IDisposable Members public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion #region IMinecraftRemoteInterface Members /// <summary> /// Runs this instance. /// </summary> /// <remarks> /// </remarks> public async Task Run() { InitializeThread (); try { while (true) { byte packetId = await EndPoint.Stream.ReadByteAsync (); Packet p = await EndPoint.ReadPacketAsync(packetId); if (EndPoint.Stream.BufferEnabled) p.Data = EndPoint.Stream.GetBuffer (); if (PacketReceived != null) PacketReceived(this, new PacketEventArgs(p)); } } catch (ThreadAbortException) { if (Aborted != null) Aborted(this, new RemoteInterfaceAbortedEventArgs ()); } catch (Exception ex) { if (Aborted != null) Aborted(this, new RemoteInterfaceAbortedEventArgs(ex)); } if (Thread.ThreadState == ThreadState.Running) throw new InvalidOperationException("Thread already running"); //BeginReceivePacket(); } /// <summary> /// Registers the packet. /// </summary> /// <typeparam name="T"> </typeparam> /// <param name="id"> The id. </param> /// <remarks> /// </remarks> public void RegisterPacket<T>(byte id) where T : Packet, new () { EndPoint.RegisterPacket<T>(id); } /// <summary> /// Gets the end point. /// </summary> /// <remarks> /// </remarks> public PacketEndPoint EndPoint { get; private set; } /// <summary> /// Occurs when [packet received]. /// </summary> /// <remarks> /// </remarks> public event EventHandler<PacketEventArgs> PacketReceived; /// <summary> /// Occurs when [aborted]. /// </summary> /// <remarks> /// </remarks> public event EventHandler<RemoteInterfaceAbortedEventArgs> Aborted; /// <summary> /// Shutdowns this instance. /// </summary> /// <remarks> /// </remarks> public void Shutdown() { try { if (!_aborting) { _aborting = true; _writeEvent.Set (); if (Aborted != null) Aborted(this, new RemoteInterfaceAbortedEventArgs ()); } EndPoint.Shutdown (); } catch (ObjectDisposedException) { } } ///// <summary> ///// Runs the loop. ///// </summary> ///// <remarks></remarks> //private void RunLoop() //{ // try // { // while (true) // { // if (_aborting) return; // ReadPacket(); // } // } // catch (ThreadAbortException) // { // if (Aborted != null) // Aborted(this, new RemoteInterfaceAbortedEventArgs()); // } // catch (Exception ex) // { // if (Aborted != null) // Aborted(this, new RemoteInterfaceAbortedEventArgs(ex)); // } //} public void SendPacketQueued(Packet packet) { InitializeThread (); if (packet == null) _slowQueue.Enqueue(packet); if (!packet.CanBeDelayed) { _fastQueue.Enqueue(packet); _writeEvent.Set (); } else { var pc = packet as PreChunk; var mc = packet as MapChunk; if (mc != null) { _slowQueue.EnumerateItems ().Where(t => t.Item is MapChunk).Each(a => a.Die(r => { var mapChunk = r as MapChunk; return mapChunk. PositionX == mc.PositionX && mapChunk. PositionZ == mc.PositionZ; })); //_slowQueue.EnumerateItems().Where(t => t.Item is PreChunk).Each(a => a.Die(r => (r as PreChunk).X == mc.X && (r as PreChunk).Z == mc.Z)); } else if (pc != null) { _slowQueue.EnumerateItems ().Where(t => t.Item is MapChunk).Each(a => a.Die(r => { var mapChunk = r as MapChunk; return mapChunk. PositionX == pc.PositionX && mapChunk. PositionZ == pc.PositionZ; })); } _slowQueue.Enqueue(packet); _writeEvent.Set (); } } #endregion /// <summary> /// Sends the packet. /// </summary> /// <param name="packet"> The packet. </param> /// <remarks> /// </remarks> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The general exception is passed to a event")] [Obsolete] private void SendPacket(Packet packet) { try { EndPoint.SendPacket(packet); } catch (ThreadAbortException) { if (Aborted != null) Aborted(this, new RemoteInterfaceAbortedEventArgs ()); } catch (Exception ex) { if (Aborted != null) Aborted(this, new RemoteInterfaceAbortedEventArgs(ex)); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The general exception is passed to a event")] public async Task SendPacketAsync(Packet packet) { try { await EndPoint.SendPacketAsync(packet); } catch (ThreadAbortException) { if (Aborted != null) Aborted(this, new RemoteInterfaceAbortedEventArgs ()); } catch (Exception ex) { if (Aborted != null) Aborted(this, new RemoteInterfaceAbortedEventArgs(ex)); } } private void InitializeThread() { if (Thread == null) { Thread = new Thread(WriteLoop); Thread.Start (); } } private async void WriteLoop() { while (true) { _writeEvent.WaitOne (); if (_aborting) return; Dieable<Packet> packet; if (_fastQueue.TryDequeue(out packet)) { //write data _writeEvent.Set (); if (!packet.IsDead) await SendPacketAsync(packet); } if (packet == null) { if (_slowQueue.TryDequeue(out packet)) { //write data _writeEvent.Set (); if (packet == null) { Shutdown (); } if (!packet.IsDead) await SendPacketAsync(packet); //else Debug.WriteLine("Packet dropped"); } } } } //public void SendPacketQueued(Packet packet) //{ // if (packet == null) // throw new ArgumentNullException("packet"); // SendPacketQueued(packet, !packet.CanBeDelayed); //} //private void BeginReceivePacket() //{ // var buff = new byte[1]; // EndPoint.Stream.BeginRead(buff, 0, 1, ReadCompleted, buff); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification="Exception is redirected to a event")] //private void ReadCompleted(IAsyncResult a) //{ // if (a.IsCompleted) // { // try // { // EndPoint.Stream.EndRead(a); // Packet p = EndPoint.ReadPacket(((byte[]) a.AsyncState)[0]); // if (EndPoint.Stream.BufferEnabled) // p.Data = EndPoint.Stream.GetBuffer(); // if (PacketReceived != null) // PacketReceived(this, new PacketEventArgs(p)); // BeginReceivePacket(); // } // catch (ThreadAbortException) // { // if (Aborted != null) // Aborted(this, new RemoteInterfaceAbortedEventArgs()); // } // catch (Exception ex) // { // if (Aborted != null) // Aborted(this, new RemoteInterfaceAbortedEventArgs(ex)); // } // } //} /// <summary> /// Begins the receive packet. /// </summary> /// <remarks> /// </remarks> /// <summary> /// Reads the completed. /// </summary> /// <param name="a"> A. </param> /// <remarks> /// </remarks> /// <summary> /// Reads the packet. /// </summary> /// <returns> </returns> /// <remarks> /// </remarks> [DebuggerStepThrough] public Packet ReadPacket() { Packet p = EndPoint.ReadPacket (); if (EndPoint.Stream.BufferEnabled) p.Data = EndPoint.Stream.GetBuffer (); if (PacketReceived != null) PacketReceived(this, new PacketEventArgs(p)); return p; } [DebuggerStepThrough] public async Task<Packet> ReadPacketAsync() { Packet p = await EndPoint.ReadPacketAsync (); if (EndPoint.Stream.BufferEnabled) p.Data = EndPoint.Stream.GetBuffer (); if (PacketReceived != null) PacketReceived(this, new PacketEventArgs(p)); return p; } public void SwitchToAesMode(byte[] key) { var stream = EndPoint.Stream.Net as FullyReadStream; if (stream.BaseStream is AesStream) { //var hc4 = stream.BaseStream as AesStream; //hc4.Key = key; } else { stream.BaseStream = new AesStream(stream.BaseStream, key); } } ~RemoteInterface() { Dispose(false); } protected virtual void Dispose(bool disposing) { if (disposing) { _writeEvent.Dispose (); _writeEvent = null; } if (Thread != null) { Thread.Abort (); Thread = 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. namespace Microsoft.CodeDom.Compiler { using System.Text; using System.Diagnostics; using System; using Microsoft.Win32; using Microsoft.Win32.SafeHandles; using System.IO; using System.Collections; using System.Security; using System.Reflection; using Microsoft.CodeDom; using System.Globalization; using System.Runtime.Versioning; /// <devdoc> /// <para>Provides a /// base /// class for code compilers.</para> /// </devdoc> public abstract class CodeCompiler : CodeGenerator, ICodeCompiler { /// <internalonly/> CompilerResults ICodeCompiler.CompileAssemblyFromDom(CompilerParameters options, CodeCompileUnit e) { if (options == null) { throw new ArgumentNullException("options"); } try { return FromDom(options, e); } finally { options.TempFiles.SafeDelete(); } } /// <internalonly/> CompilerResults ICodeCompiler.CompileAssemblyFromFile(CompilerParameters options, string fileName) { if (options == null) { throw new ArgumentNullException("options"); } try { return FromFile(options, fileName); } finally { options.TempFiles.SafeDelete(); } } /// <internalonly/> CompilerResults ICodeCompiler.CompileAssemblyFromSource(CompilerParameters options, string source) { if (options == null) { throw new ArgumentNullException("options"); } try { return FromSource(options, source); } finally { options.TempFiles.SafeDelete(); } } /// <internalonly/> CompilerResults ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters options, string[] sources) { if (options == null) { throw new ArgumentNullException("options"); } try { return FromSourceBatch(options, sources); } finally { options.TempFiles.SafeDelete(); } } /// <internalonly/> CompilerResults ICodeCompiler.CompileAssemblyFromFileBatch(CompilerParameters options, string[] fileNames) { if (options == null) { throw new ArgumentNullException("options"); } if (fileNames == null) throw new ArgumentNullException("fileNames"); try { // Try opening the files to make sure they exists. This will throw an exception // if it doesn't foreach (string fileName in fileNames) { using (Stream str = File.OpenRead(fileName)) { } } return FromFileBatch(options, fileNames); } finally { options.TempFiles.SafeDelete(); } } /// <internalonly/> CompilerResults ICodeCompiler.CompileAssemblyFromDomBatch(CompilerParameters options, CodeCompileUnit[] ea) { if (options == null) { throw new ArgumentNullException("options"); } try { return FromDomBatch(options, ea); } finally { options.TempFiles.SafeDelete(); } } /// <devdoc> /// <para> /// Gets /// or sets the file extension to use for source files. /// </para> /// </devdoc> protected abstract string FileExtension { get; } /// <devdoc> /// <para>Gets or /// sets the name of the compiler executable.</para> /// </devdoc> protected abstract string CompilerName { get; } internal void Compile(CompilerParameters options, string compilerDirectory, string compilerExe, string arguments, ref string outputFile, ref int nativeReturnValue, string trueArgs) { throw new NotImplementedException(); } /// <devdoc> /// <para> /// Compiles the specified compile unit and options, and returns the results /// from the compilation. /// </para> /// </devdoc> protected virtual CompilerResults FromDom(CompilerParameters options, CodeCompileUnit e) { if (options == null) { throw new ArgumentNullException("options"); } CodeCompileUnit[] units = new CodeCompileUnit[1]; units[0] = e; return FromDomBatch(options, units); } /// <devdoc> /// <para> /// Compiles the specified file using the specified options, and returns the /// results from the compilation. /// </para> /// </devdoc> protected virtual CompilerResults FromFile(CompilerParameters options, string fileName) { if (options == null) { throw new ArgumentNullException("options"); } if (fileName == null) throw new ArgumentNullException("fileName"); // Try opening the file to make sure it exists. This will throw an exception // if it doesn't using (Stream str = File.OpenRead(fileName)) { } string[] filenames = new string[1]; filenames[0] = fileName; return FromFileBatch(options, filenames); } /// <devdoc> /// <para> /// Compiles the specified source code using the specified options, and /// returns the results from the compilation. /// </para> /// </devdoc> protected virtual CompilerResults FromSource(CompilerParameters options, string source) { if (options == null) { throw new ArgumentNullException("options"); } string[] sources = new string[1]; sources[0] = source; return FromSourceBatch(options, sources); } /// <devdoc> /// <para> /// Compiles the specified compile units and /// options, and returns the results from the compilation. /// </para> /// </devdoc> protected virtual CompilerResults FromDomBatch(CompilerParameters options, CodeCompileUnit[] ea) { if (options == null) { throw new ArgumentNullException("options"); } if (ea == null) throw new ArgumentNullException("ea"); string[] filenames = new string[ea.Length]; CompilerResults results = null; for (int i = 0; i < ea.Length; i++) { if (ea[i] == null) continue; // the other two batch methods just work if one element is null, so we'll match that. ResolveReferencedAssemblies(options, ea[i]); filenames[i] = options.TempFiles.AddExtension(i + FileExtension); Stream temp = new FileStream(filenames[i], FileMode.Create, FileAccess.Write, FileShare.Read); try { using (StreamWriter sw = new StreamWriter(temp, Encoding.UTF8)) { ((ICodeGenerator)this).GenerateCodeFromCompileUnit(ea[i], sw, Options); sw.Flush(); } } finally { temp.Dispose(); } } results = FromFileBatch(options, filenames); return results; } /// <devdoc> /// <para> /// Because CodeCompileUnit and CompilerParameters both have a referenced assemblies /// property, they must be reconciled. However, because you can compile multiple /// compile units with one set of options, it will simply merge them. /// </para> /// </devdoc> private void ResolveReferencedAssemblies(CompilerParameters options, CodeCompileUnit e) { if (e.ReferencedAssemblies.Count > 0) { foreach (string assemblyName in e.ReferencedAssemblies) { if (!options.ReferencedAssemblies.Contains(assemblyName)) { options.ReferencedAssemblies.Add(assemblyName); } } } } /// <devdoc> /// <para> /// Compiles the specified files using the specified options, and returns the /// results from the compilation. /// </para> /// </devdoc> protected virtual CompilerResults FromFileBatch(CompilerParameters options, string[] fileNames) { throw new NotImplementedException(); } /// <devdoc> /// <para>Processes the specified line from the specified <see cref='Microsoft.CodeDom.Compiler.CompilerResults'/> .</para> /// </devdoc> protected abstract void ProcessCompilerOutputLine(CompilerResults results, string line); /// <devdoc> /// <para> /// Gets the command arguments from the specified <see cref='Microsoft.CodeDom.Compiler.CompilerParameters'/>. /// </para> /// </devdoc> protected abstract string CmdArgsFromParameters(CompilerParameters options); /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected virtual string GetResponseFileCmdArgs(CompilerParameters options, string cmdArgs) { string responseFileName = options.TempFiles.AddExtension("cmdline"); Stream temp = new FileStream(responseFileName, FileMode.Create, FileAccess.Write, FileShare.Read); try { using (StreamWriter sw = new StreamWriter(temp, Encoding.UTF8)) { sw.Write(cmdArgs); sw.Flush(); } } finally { temp.Dispose(); } return "@\"" + responseFileName + "\""; } /// <devdoc> /// <para> /// Compiles the specified source code strings using the specified options, and /// returns the results from the compilation. /// </para> /// </devdoc> protected virtual CompilerResults FromSourceBatch(CompilerParameters options, string[] sources) { if (options == null) { throw new ArgumentNullException("options"); } if (sources == null) throw new ArgumentNullException("sources"); string[] filenames = new string[sources.Length]; CompilerResults results = null; for (int i = 0; i < sources.Length; i++) { string name = options.TempFiles.AddExtension(i + FileExtension); Stream temp = new FileStream(name, FileMode.Create, FileAccess.Write, FileShare.Read); try { using (StreamWriter sw = new StreamWriter(temp, Encoding.UTF8)) { sw.Write(sources[i]); sw.Flush(); } } finally { temp.Dispose(); } filenames[i] = name; } results = FromFileBatch(options, filenames); return results; } /// <devdoc> /// <para>Joins the specified string arrays.</para> /// </devdoc> protected static string JoinStringArray(string[] sa, string separator) { if (sa == null || sa.Length == 0) return String.Empty; if (sa.Length == 1) { return "\"" + sa[0] + "\""; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < sa.Length - 1; i++) { sb.Append("\""); sb.Append(sa[i]); sb.Append("\""); sb.Append(separator); } sb.Append("\""); sb.Append(sa[sa.Length - 1]); sb.Append("\""); return sb.ToString(); } } }
/* * Naiad ver. 0.5 * Copyright (c) Microsoft Corporation * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT * LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR * A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Microsoft.Research.Peloponnese.Shared; using Microsoft.Research.Naiad; using Microsoft.Research.Naiad.Dataflow; using Microsoft.Research.Naiad.Frameworks.Lindi; using Microsoft.Research.Naiad.Frameworks.WorkGenerator; namespace Microsoft.Research.Naiad.Frameworks.Storage.Dfs { /// <summary> /// The Dfs framework includes base classes to support reading and writing Hdfs files, and is intended to be extensible to other /// block-based file systems /// </summary> class NamespaceDoc { } #region helper classes /// <summary> /// Work item describing an Dfs block to be read at a worker. /// </summary> /// <remarks> /// This is currently somewhat HDFS-specific, and would probably be generalized if another file /// system were added /// </remarks> [Serializable] public class DfsBlock { /// <summary> /// path of the file being read /// </summary> public Uri path; /// <summary> /// total length of the file /// </summary> public long fileLength; /// <summary> /// offset of the block in the file /// </summary> public long offset; /// <summary> /// length of the block to read /// </summary> public long length; /// <summary> /// address and port of the preferred datanode to use to read the block from; this saves one redirection /// through the namenode during the webhdfs protocol /// </summary> public IPEndPoint dataNodeAddress; } #endregion #region base implementation for Dfs work coordinators /// <summary> /// base class for Dfs coordinators, that expands directories into sets of files to read, and keeps track /// of the mapping from IPAddresses to IPEndpoints /// </summary> /// <remarks> /// This is currently somewhat HDFS-specific, and would probably be generalized if another file /// system were added /// </remarks> /// <typeparam name="TWorkDescription">the type used by workers to identify themselves, e.g. including their IP addresses</typeparam> public abstract class DfsBaseCoordinator<TWorkDescription> : MatchingCoordinator<Uri, IPEndPoint, TWorkDescription, TWorkDescription, IPAddress[]> { /// <summary> /// The client for doing basic DFS operations. /// </summary> /// <remarks> /// This is currently an HDFS base client that supports either Java or WebHdfs protocols, but expects an HDFS-like way /// of operating that would be generalized for other DFSs /// </remarks> protected readonly HdfsClientBase client; /// <summary> /// mapping of IP address to datanode endpoint. The MatchingCoordinator queues are indexed by datanode endpoint /// so we know how to read the block once it is removed from a queue, but the workers identify themselves by IP /// address, so we need to be able to look up the corresponding queue given an IP address /// </summary> private readonly Dictionary<IPAddress, IPEndPoint> dataNodes; /// <summary> /// called whenever a queue is added: keep our index of addresses up to date /// </summary> /// <param name="queue">new queue</param> protected override void NotifyQueueAddition(IPEndPoint queue) { // we are assuming there is only one datanode per ip address this.dataNodes.Add(queue.Address, queue); } /// <summary> /// called whenever a queue is removed: keep our index of addresses up to date /// </summary> /// <param name="queue">queue being removed</param> protected override void NotifyQueueRemoval(IPEndPoint queue) { this.dataNodes.Remove(queue.Address); } /// <summary> /// Called when a worker announces that it is ready for another work item, to find a work item on the /// worker's matching queue, if any. The worker may have multiple IP addresses, so it returns them all, /// and if any matches an address the datanode is listening on, then the worker is matched to that datanode /// </summary> /// <param name="workerAddresses">the IP addresses of the worker's network interfaces</param> /// <param name="matchingDataNode">the datanode endpoint of a matching queue, if any</param> /// <returns>the matching queue, if there is one, otherwise null</returns> protected override MatchQueue MapWorkerToQueue(IPAddress[] workerAddresses, ref IPEndPoint matchingDataNode) { // look at each ip address that the worker can use, to see if any has a matching queue with work waiting foreach (IPAddress choice in workerAddresses) { // if there is a matching datanode, store it in matchingDataNode if (this.dataNodes.TryGetValue(choice, out matchingDataNode)) { // if there is a matching datanode then there must be a queue with that datanode, so return it return this.waitingWork[matchingDataNode]; } } // there is no matching queue return null; } /// <summary> /// given an hdfs file, return a sequence of work items, each with a set of matching categories /// </summary> /// <remarks> /// this is currently HDFS-specific, although the HdfsFile class could easily be extended to support /// other DFSs /// </remarks> /// <param name="file">file to expand</param> /// <returns>a sequence of work items, each with a set of matching categories</returns> protected abstract IEnumerable<Match> EnumerateFileWork(HdfsFile file); /// <summary> /// given an input string of a file or directory, expand it into a set of files, and then expand each file /// into a set of matches using the derived-class implementation of EnumerateFileWork /// </summary> /// <param name="fileOrDirectory">dfs file or directory to be read</param> /// <returns>set of work item matches for the file or directory</returns> protected override IEnumerable<Match> EnumerateWork(Uri fileOrDirectory) { return client .ExpandFileOrDirectoryToFile(fileOrDirectory) .SelectMany(file => EnumerateFileWork(file)); } /// <summary> /// return a new coordinator for a dfs reader /// </summary> /// <param name="client">hdfs client</param> public DfsBaseCoordinator(HdfsClientBase client) { this.client = client; this.dataNodes = new Dictionary<IPAddress, IPEndPoint>(); } } #endregion #region DfsBaseCoordinator implementation for the file-based dfs work coordinator /// <summary> /// base coordinator for workers that read an entire hdfs file at a time, rather than split the file into blocks. /// For each file the coordinator tries to match it to a worker that holds a large proportion of the relevant data /// </summary> public class DfsFileCoordinator : DfsBaseCoordinator<DfsBlock> { /// <summary> /// Return the length of a particular block in a file. All blocks except the last one are the same length /// </summary> /// <param name="index">index of the block in the file</param> /// <param name="file">file being read</param> /// <returns>length in bytes of the requested block</returns> private long BlockLength(int index, HdfsFile file) { // start location of the block in the file long offset = (long)index * file.blockSize; // number of bytes after the start of the block long bytesAfterBlockStart = file.length - offset; // either the standard block length, or the length of the final block if it is shorter return Math.Min(bytesAfterBlockStart, file.blockSize); } /// <summary> /// given a file, determine how much of that file's data are stored on each datanode. Return every datanode that stores a /// threshold percentage of the file's data as a candidate match for that file /// </summary> /// <param name="file">file to be matched</param> /// <returns>a match including a (possibly-empty) set of candidate data nodes</returns> protected override IEnumerable<Match> EnumerateFileWork(HdfsFile file) { long numberOfBlocks = (file.length + file.blockSize - 1) / file.blockSize; long threshold; if (numberOfBlocks > 4) { // this is a 'real' multi-block file; only take a datanode that contains at least a third of it threshold = file.length / 3; } else { // this file either has a single block or only a few: only return a matching node if it stores the whole file. // this will select the node that wrote (all the blocks in) the file rather than one of the replicas, in the case of a file with only a // couple of blocks threshold = file.length; } Match match = new Match { categories = this.client.GetBlockLocations(file) // first flatten the list of block locations, into a sequence of pairs of 'endpoint,length' each indicating that length // bytes are stored at endpoint .SelectMany((endpoints, index) => endpoints.Select(endpoint => new KeyValuePair<IPEndPoint, long>(endpoint, BlockLength(index, file)))) // then group by endpoint .GroupBy(x => x.Key) // within each group, sum the bytes to determine how many bytes in total are stored at each endpoint .Select(g => new KeyValuePair<IPEndPoint, long>(g.Key, g.Select(elt => elt.Value).Sum())) // keep only endpoints that store more than 33% of the file .Where(x => x.Value >= threshold) // return the flattened array of candidate endpoints, if any .Select(x => x.Key).ToArray(), // if there isn't a matching worker, use null as the default endpoint, meaning the read will be redirected to the // name node. Set the block to indicate the entire file workStub = new DfsBlock { path = file.path, fileLength = file.length, offset = 0, length = file.length, dataNodeAddress = null } }; yield return match; } /// <summary> /// if the work item was matched to a worker on the same computer, fill in the datanode endpoint before sending the work item /// </summary> /// <param name="usedMatchingQueue">true if the item was matched to a worker</param> /// <param name="endpoint">endpoint corresponding to the matched worker, if usedMatchingQueue==true</param> /// <param name="stub">work item with no endpoint filled in</param> /// <returns>work item with the endpoint filled in, if there was a match</returns> protected override DfsBlock ExpandWorkItem(bool usedMatchingQueue, IPEndPoint endpoint, DfsBlock stub) { if (usedMatchingQueue) { stub.dataNodeAddress = endpoint; } return stub; } /// <summary> /// create a new coordinator for file-at-a-time dfs reads /// </summary> /// <param name="client">hdfs client</param> public DfsFileCoordinator(HdfsClientBase client) : base(client) { } } #endregion #region IWorker implementation for the Hdfs file-based reader worker /// <summary> /// base worker implementation for the worker to read Hdfs files an entire file at a time, rather than block by block /// </summary> /// <typeparam name="TOutput">the type of records to be read</typeparam> public class DfsFileWorker<TOutput> : IWorker<DfsBlock, IPAddress[], TOutput> { /// <summary> /// a cache of the local IP interfaces, read on startup from DNS /// </summary> private readonly IPAddress[] localAddresses; /// <summary> /// the function that takes a stream and returns batches of records /// </summary> private readonly Func<Stream, IEnumerable<ArraySegment<TOutput>>> deserialize; /// <summary> /// the Hdfs client used to read files /// </summary> protected readonly HdfsClientBase client; /// <summary> /// Return a description of the worker that the coordinator will use when matching work items to workers. This is called /// once before any work item has been assigned, and once after each work item is performed. /// </summary> /// <returns>The IP addresses that the worker node is listening on, to be matched to file block locations for trying /// to schedule local reads</returns> public IPAddress[] DescribeWorker() { return this.localAddresses; } /// <summary> /// Execute a work item, reading an HDFS file and generating a sequence of output records /// </summary> /// <param name="workItem">The work item to be executed, corresponding to an entire Hdfs file</param> /// <returns>A sequence of array segments, each containing a sequence of records to be output</returns> public IEnumerable<ArraySegment<TOutput>> DoWork(DfsBlock workItem) { // ask the Hdfs client for a stream corresponding to the file. Use a 1k buffer for byte-at-a-time reads. using (Stream reader = client.GetDfsStreamReader(workItem.path, workItem.offset, workItem.length, 1024, workItem.dataNodeAddress)) { foreach (ArraySegment<TOutput> segment in this.deserialize(reader)) { yield return segment; } } } /// <summary> /// create a worker for a file-at-a-time hdfs reader /// </summary> /// <param name="client">Hdfs client used to read files</param> /// <param name="deserialize">function to take a stream consisting of an entire webhdfs file, and return a sequence /// of batches, each containing an arraysegment of output records</param> public DfsFileWorker( HdfsClientBase client, Func<Stream, IEnumerable<ArraySegment<TOutput>>> deserialize) { // cache all the addresses the local node is listening on this.localAddresses = Dns.GetHostAddresses(Dns.GetHostName()); this.deserialize = deserialize; this.client = client; } } #endregion #region DfsBaseCoordinator implementation for the block-based dfs work coordinator /// <summary> /// Implementation of a MatchingCoordinator that manages work for reading dfs files in parallel, split by blocks /// </summary> /// <typeparam name="TItem">The concrete type of work item, which may include metadata specific to a particular /// serializer or file type</typeparam> public abstract class DfsBlockCoordinator<TItem> : DfsBaseCoordinator<TItem> where TItem : DfsBlock { /// <summary> /// For a given file, map a sequence of locations to a sequence of "base" matches, where the workStub /// component of the match has any filetype-specific metadata filled in and the categories component of the /// match has been set to the locations of that block. The HdfsBlock fields will /// all be filled in later after this sequence has been returned /// </summary> /// <param name="file">The file being read</param> /// <param name="blocks">The block locations for the file</param> /// <returns>A sequence of Matches with the categories set, and any file-specific metadata set</returns> protected abstract IEnumerable<Match> MakeBaseMatches(HdfsFile file, IEnumerable<IPEndPoint[]> blocks); /// <summary> /// called to convert an input file into a list of blocks /// </summary> /// <param name="file">the input file</param> /// <returns>the blocks in the file, along with a set of datanodes where each block is stored</returns> protected override IEnumerable<Match> EnumerateFileWork(HdfsFile file) { // get the blocks in the file, and convert each block to a base match, with file-specific metadata // filled in to the DfsBlock IEnumerable<Match> rawMatches = MakeBaseMatches(file, this.client.GetBlockLocations(file)); // fill in the rest of the DfsBlock fields return rawMatches.Select((match, index) => { match.workStub.path = file.path; match.workStub.fileLength = file.length; // all the blocks are the same size match.workStub.offset = (long)index * file.blockSize; long bytesRemaining = file.length - match.workStub.offset; match.workStub.length = Math.Min(file.blockSize, bytesRemaining); // this address will be used if the block is going to be read by a worker on a remote machine // otherwise the correct address will be filled in when the worker is chosen match.workStub.dataNodeAddress = match.categories.First(); return match; }); } /// <summary> /// Called when a work item is going to be sent to a worker. If usedMatchingQueue is true then dataNode /// is the endpoint of the dataNode that matches the worker /// </summary> /// <param name="usedMatchingQueue">true if the work item was pulled from a queue whose datanode is on /// the same computer as the worker</param> /// <param name="dataNode">datanode endpoint if the work item was pulled from a matching queue</param> /// <param name="stub">work item stub to fill in</param> /// <returns>work item with the datanode address filled in correctly</returns> protected override TItem ExpandWorkItem(bool usedMatchingQueue, IPEndPoint dataNode, TItem stub) { if (usedMatchingQueue) { // the worker is on the same machine as a datanode that is storing the block, so read from // that datanode stub.dataNodeAddress = dataNode; } // else the worker is on a machine that isn't storing the block, so just use the default datanode // that was stored in the stub in EnumerateBlocks return stub; } /// <summary> /// return a new coordinator for a block-based HDFS reader /// </summary> /// <param name="client">hdfs client used to read files and metadata</param> public DfsBlockCoordinator(HdfsClientBase client) : base(client) { } } #endregion #region IWorker implementation for the dfs block-based worker /// <summary> /// IWorker implementation for the dfs worker that reads data from blocks. This is further specialized to different file /// formats by passing in functions for syncing to record boundaries and deserializing data /// </summary> /// <typeparam name="TItem">The work item passed by the matching coordinator, which inherits from DfsBlock but may contain /// metadata used in syncing to record boundaries or deserializing</typeparam> /// <typeparam name="TOutput">The type of deserialized records produced by the worker</typeparam> public class DfsBlockWorker<TItem, TOutput> : IWorker<TItem, IPAddress[], TOutput> where TItem : DfsBlock { /// <summary> /// a cache of the local IP interfaces, read on startup from DNS /// </summary> private readonly IPAddress[] localAddresses; /// <summary> /// the number of bytes to use for each WebHdfs request when seeking past the end of the block for the start of the following /// record. If records are expected to be small, this should also be small to avoid pre-fetching a lot of the next block /// </summary> private readonly int syncRequestLength; /// <summary> /// the function used to sync to the next record in a stream /// </summary> private readonly Action<TItem, Stream> syncToNextRecord; /// <summary> /// the function used to deserialize records from a stream /// </summary> private readonly Func<TItem, Stream, IEnumerable<ArraySegment<TOutput>>> deserialize; /// <summary> /// the client used for reading Hdfs data /// </summary> protected readonly HdfsClientBase client; /// <summary> /// the IWorker implementation used to identify this worker to the WebHdfs coordinator, so that it can be sent work items /// of blocks stored at the same machine /// </summary> /// <returns>the IP addresses of this computer as reported by DNS</returns> public IPAddress[] DescribeWorker() { return this.localAddresses; } /// <summary> /// Find the start of the first record that begins after the end of the block we have been instructed to read. This indicates /// the end of the range of data that this block corresponds to /// </summary> /// <param name="workItem">the block we are reading</param> /// <returns></returns> private long FindSpillExtent(TItem workItem) { // compute the number of bytes remaining in the file past the end of our block long spillBytesRemaining = workItem.fileLength - workItem.offset - workItem.length; if (spillBytesRemaining <= 0) { // this is the last block, so our range runs exactly to the end of the block return workItem.length; } // get a stream that starts immediately after the end of the block, and continues until the end of the file. using (Stream spillReader = client.GetDfsStreamReader( workItem.path, // read from the end of this block for the rest of the file workItem.offset + workItem.length, spillBytesRemaining, // use small requests if we expect records to be fairly small, so we don't prefetch and buffer a lot of data in the next block this.syncRequestLength)) { // call into the format-specific function to find the start of the next record. Potentially this spins all the way to the end of the // stream this.syncToNextRecord(workItem, spillReader); // return the offset of the next record after the block, relative to the start of the block return workItem.length + spillReader.Position; } } /// <summary> /// find the range of valid records in the block (those that start within the block), deserialize them, and return them in batches /// </summary> /// <param name="workItem">a description of the block to read</param> /// <returns>a sequence of batches of output records</returns> public IEnumerable<ArraySegment<TOutput>> DoWork(TItem workItem) { //Console.WriteLine("Starting work for " + workItem.path.AbsoluteUri + " " + workItem.offset + " " + workItem.length); // find the number of bytes from the start of the block to the end of the range, i.e. the start of the first record // that begins after the end of the block long endOfRange = FindSpillExtent(workItem); // create a reader for the range. Use the size of the range as the size of each underlying WebHdfs request so we // will make a single webhdfs request for all of the data that is stored in this block. using (Stream blockReader = client.GetDfsStreamReader(workItem.path, workItem.offset, endOfRange, this.syncRequestLength)) { if (workItem.offset > 0) { // unless we are the first block, scan forward from the start of the block to find the start of the next record, // since the (partial) record at the beginning of the block will be read by the preceding block reader. If no records // start within the block, the stream will end up positioned at endOfRange, so we won't deserialize anything this.syncToNextRecord(workItem, blockReader); } // deserialize all the records in the range foreach (ArraySegment<TOutput> segment in this.deserialize(workItem, blockReader)) { yield return segment; } } } /// <summary> /// create a worker to read dfs files broken into blocks /// </summary> /// <param name="syncRequestLength">size of each dfs request when seeking past the end of the block for the start of the /// next record. If records are expected to be small this should also be small, to avoid prefetching and buffering a lot of the /// next block's data</param> /// <param name="syncToNextRecord">action to sync to the start of the next record. The first argument is the block item /// being read, which may contain metadata about sync markers. The second argument is the stream to scan.</param> /// <param name="deserialize">function to deserialize records in a stream</param> /// <param name="client">client used to read hdfs data</param> public DfsBlockWorker( int syncRequestLength, Action<TItem, Stream> syncToNextRecord, Func<TItem, Stream, IEnumerable<ArraySegment<TOutput>>> deserialize, HdfsClientBase client) { // cache the local IP addresses this.localAddresses = Dns.GetHostAddresses(Dns.GetHostName()); this.syncRequestLength = syncRequestLength; this.syncToNextRecord = syncToNextRecord; this.deserialize = deserialize; this.client = client; } } #endregion #region Hdfs text reader classes /// <summary> /// the coordinator class for a text reader. No additional metadata is needed to describe a block, so this just uses DfsBlocks /// directly as work items /// </summary> public class DfsTextCoordinator : DfsBlockCoordinator<DfsBlock> { /// <summary> /// For a given file, map a sequence of locations to a sequence of "base" matches. The workStub /// component of the match doesn't need any file-specific metadata filled in. The categories component of the /// match is set to the locations of that block. The DfsBlock fields will /// all be filled in after this sequence has been returned /// </summary> /// <param name="file">The file being read</param> /// <param name="blocks">The block locations for the file</param> /// <returns>A sequence of Matches with the categories set, and any file-specific metadata set</returns> protected override IEnumerable<Match> MakeBaseMatches(HdfsFile file, IEnumerable<IPEndPoint[]> blocks) { return blocks.Select(endpoints => new Match { workStub = new DfsBlock(), categories = endpoints }); } /// <summary> /// create a coordinator for reading Dfs files with fixed-length blocks, made of text records /// </summary> /// <param name="client">client used for reading Hdfs data and metadata</param> public DfsTextCoordinator(HdfsClientBase client) : base(client) { } } /// <summary> /// the worker class for a text reader for files with fixed-length blocks and text records. It uses DfsBlocks as work /// items, and parses data into lines represented as strings /// </summary> public class DfsTextWorker : DfsBlockWorker<DfsBlock, string> { /// <summary> /// sync forwards in a stream leaving it positioned on the first character after an end-of-line mark. Supports '\r\n', '\n' and /// '\r' as end-of-line. '\r' is considered the end of a line if it is followed by any character other than '\n'. /// </summary> /// <remarks> /// this assumes the stream is seekable, and that seeking backward by one character is efficient /// </remarks> /// <param name="stream">stream to scan forward in</param> static private void SyncToNextLine(Stream stream) { while (true) { int currentByte = stream.ReadByte(); if (currentByte == -1) { // we reached the end of the stream without seeing a line terminator, so leave the stream positioned at its end return; } else if (currentByte == '\n') { // we saw a line terminator, and are now positioned to read the first character of the next line return; } else if (currentByte == '\r') { // we saw a carriage return. If the next character is a newline then the next line starts after that, // otherwise we are currently positioned on it. So read the next character, to check int followingByte = stream.ReadByte(); if (followingByte == -1) { // we reached the end of the stream just after the CR, so leave the stream positioned at its end return; } else if (followingByte == '\n') { // we saw '\r\n' and are now positioned at the first character after '\n' return; } else { // we have moved one character too many; back up before returning so we are positioned on the first // character after the '\r' stream.Seek(-1, SeekOrigin.Current); } } } } /// <summary> /// Deserialize all the lines in a stream, which is assumed to be positioned on the start of a line. Return the lines /// in batches /// </summary> /// <param name="stream">stream to deserialize</param> /// <param name="batchSize">number of lines to return per batch</param> /// <returns>sequence of batches of lines</returns> static private IEnumerable<ArraySegment<string>> Deserialize(Stream stream, int batchSize) { using (StreamReader reader = new StreamReader(stream, Encoding.UTF8, true, 1024*1024)) { // count how much of the batch array we have filled int index; do { // array to store the current batch string[] batch = new string[batchSize]; for (index = 0; index < batchSize; ++index) { string line = reader.ReadLine(); if (line == null) { // we reached the end of the stream break; } // fill in the next line in the batch batch[index] = line; } if (index > 0) { // return all the lines that got filled in yield return new ArraySegment<string>(batch, 0, index); } // if we didn't fill a complete batch then the stream ended, so exit } while (index == batchSize); } } /// <summary> /// create a worker for deserializing lines of text from an Hdfs file /// </summary> /// <param name="client">Hdfs client to use for reading data</param> /// <param name="batchSize">number of lines to return at a time</param> public DfsTextWorker(HdfsClientBase client, int batchSize) : base( // use 4k blocks when scanning past the end of the block to find the end of the final line 4 * 1024, (item, stream) => SyncToNextLine(stream), (item, stream) => Deserialize(stream, batchSize), client) { } } #endregion }
/* * This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson, * the work of Kim Sheffield and the fyiReporting project. * * Prior Copyrights: * _________________________________________________________ * |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others| * | (http://reportfu.org) | * ========================================================= * _________________________________________________________ * |Copyright (C) 2004-2008 fyiReporting Software, LLC | * |For additional information, email info@fyireporting.com | * |or visit the website www.fyiReporting.com. | * ========================================================= * * License: * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections; using System.IO; using System.Reflection; using System.Text; using Reporting.Rdl; namespace Reporting.Rdl { /// <summary> /// The VBFunctions class holds a number of static functions for support VB functions. /// </summary> sealed public class VBFunctions { /// <summary> /// Obtains the year /// </summary> /// <param name="dt"></param> /// <returns>int year</returns> static public int Year(DateTime dt) { return dt.Year; } /// <summary> /// Returns the integer day of week: 1=Sunday, 2=Monday, ..., 7=Saturday /// </summary> /// <param name="dt"></param> /// <returns></returns> static public int Weekday(DateTime dt) { int dow; switch (dt.DayOfWeek) { case DayOfWeek.Sunday: dow=1; break; case DayOfWeek.Monday: dow=2; break; case DayOfWeek.Tuesday: dow=3; break; case DayOfWeek.Wednesday: dow=4; break; case DayOfWeek.Thursday: dow=5; break; case DayOfWeek.Friday: dow=6; break; case DayOfWeek.Saturday: dow=7; break; default: // should never happen dow=1; break; } return dow; } /// <summary> /// Returns the name of the day of week /// </summary> /// <param name="d"></param> /// <returns></returns> static public string WeekdayName(int d) { return WeekdayName(d, false); } /// <summary> /// Returns the name of the day of week /// </summary> /// <param name="d"></param> /// <param name="bAbbreviation">true for abbreviated name</param> /// <returns></returns> static public string WeekdayName(int d, bool bAbbreviation) { DateTime dt = new DateTime(2005, 5, d); // May 1, 2005 is a Sunday string wdn = bAbbreviation? string.Format("{0:ddd}", dt):string.Format("{0:dddd}", dt); return wdn; } /// <summary> /// Get the day of the month. /// </summary> /// <param name="dt"></param> /// <returns></returns> static public int Day(DateTime dt) { return dt.Day; } /// <summary> /// Gets the integer month /// </summary> /// <param name="dt"></param> /// <returns></returns> static public int Month(DateTime dt) { return dt.Month; } /// <summary> /// Get the month name /// </summary> /// <param name="m"></param> /// <returns></returns> static public string MonthName(int m) { return MonthName(m, false); } /// <summary> /// Gets the month name; optionally abbreviated /// </summary> /// <param name="m"></param> /// <param name="bAbbreviation"></param> /// <returns></returns> static public string MonthName(int m, bool bAbbreviation) { DateTime dt = new DateTime(2005, m, 1); string mdn = bAbbreviation? string.Format("{0:MMM}", dt):string.Format("{0:MMMM}", dt); return mdn; } /// <summary> /// Gets the hour /// </summary> /// <param name="dt"></param> /// <returns></returns> static public int Hour(DateTime dt) { return dt.Hour; } /// <summary> /// Get the minute /// </summary> /// <param name="dt"></param> /// <returns></returns> static public int Minute(DateTime dt) { return dt.Minute; } /// <summary> /// Get the second /// </summary> /// <param name="dt"></param> /// <returns></returns> static public int Second(DateTime dt) { return dt.Second; } /// <summary> /// Gets the current local date on this computer /// </summary> /// <returns></returns> static public DateTime Today() { DateTime dt = DateTime.Now; return new DateTime(dt.Year, dt.Month, dt.Day, 0, 0, 0, 0); } /// <summary> /// Converts the first letter in a string to ANSI code /// </summary> /// <param name="o"></param> /// <returns></returns> static public int Asc(string o) { if (o == null || o.Length == 0) return 0; return Convert.ToInt32(o[0]); } /// <summary> /// Converts an expression to Boolean /// </summary> /// <param name="o"></param> /// <returns></returns> static public bool CBool(object o) { return Convert.ToBoolean(o); } /// <summary> /// Converts an expression to type Byte /// </summary> /// <param name="o"></param> /// <returns></returns> static public Byte CByte(string o) { return Convert.ToByte(o); } /// <summary> /// Converts an expression to type Currency - really Decimal /// </summary> /// <param name="o"></param> /// <returns></returns> static public decimal CCur(string o) { return Convert.ToDecimal(o); } /// <summary> /// Converts an expression to type Date /// </summary> /// <param name="o"></param> /// <returns></returns> static public DateTime CDate(string o) { return Convert.ToDateTime(o); } /// <summary> /// Converts the specified ANSI code to a character /// </summary> /// <param name="o"></param> /// <returns></returns> static public char Chr(int o) { return Convert.ToChar(o); } /// <summary> /// Converts the expression to integer /// </summary> /// <param name="o"></param> /// <returns></returns> static public int CInt(object o) { return Convert.ToInt32(o); } /// <summary> /// Converts the expression to long /// </summary> /// <param name="o"></param> /// <returns></returns> static public long CLng(object o) { return Convert.ToInt64(o); } /// <summary> /// Converts the expression to Single /// </summary> /// <param name="o"></param> /// <returns></returns> static public Single CSng(object o) { return Convert.ToSingle(o); } /// <summary> /// Converts the expression to String /// </summary> /// <param name="o"></param> /// <returns></returns> static public string CStr(object o) { return Convert.ToString(o); } /// <summary> /// Returns the hexadecimal value of a specified number /// </summary> /// <param name="o"></param> /// <returns></returns> static public string Hex(long o) { return Convert.ToString(o, 16); } /// <summary> /// Returns the octal value of a specified number /// </summary> /// <param name="o"></param> /// <returns></returns> static public string Oct(long o) { return Convert.ToString(o, 8); } /// <summary> /// Converts the passed parameter to double /// </summary> /// <param name="o"></param> /// <returns></returns> static public double CDbl(Object o) { return Convert.ToDouble(o); } static public DateTime DateAdd(string interval, double number, string date) { return DateAdd(interval, number, DateTime.Parse(date)); } /// <summary> /// Returns a date to which a specified time interval has been added. /// </summary> /// <param name="interval">String expression that is the interval you want to add.</param> /// <param name="number">Numeric expression that is the number of interval you want to add. The numeric expression can either be positive, for dates in the future, or negative, for dates in the past.</param> /// <param name="date">The date to which interval is added.</param> /// <returns></returns> static public DateTime DateAdd(string interval, double number, DateTime date) { switch (interval) { case "yyyy": // year date = date.AddYears((int) Math.Round(number, 0)); break; case "m": // month date = date.AddMonths((int)Math.Round(number, 0)); break; case "d": // day date = date.AddDays(number); break; case "h": // hour date = date.AddHours(number); break; case "n": // minute date = date.AddMinutes(number); break; case "s": // second date = date.AddSeconds(number); break; case "y": // day of year date = date.AddDays(number); break; case "q": // quarter date = date.AddMonths((int)Math.Round(number, 0) * 3); break; case "w": // weekday date = date.AddDays(number); break; case "ww": // week of year date = date.AddDays((int)Math.Round(number, 0) * 7); break; default: throw new ArgumentException(string.Format("Interval '{0}' is invalid or unsupported.", interval)); } return date; } /// <summary> /// 1 based offset of string2 in string1 /// </summary> /// <param name="string1"></param> /// <param name="string2"></param> /// <returns></returns> static public int InStr(string string1, string string2) { return InStr(1, string1, string2, 0); } /// <summary> /// 1 based offset of string2 in string1 /// </summary> /// <param name="start"></param> /// <param name="string1"></param> /// <param name="string2"></param> /// <returns></returns> static public int InStr(int start, string string1, string string2) { return InStr(start, string1, string2, 0); } /// <summary> /// 1 based offset of string2 in string1; optionally case insensitive /// </summary> /// <param name="string1"></param> /// <param name="string2"></param> /// <param name="compare">1 if you want case insensitive compare</param> /// <returns></returns> static public int InStr(string string1, string string2, int compare) { return InStr(1, string1, string2, compare); } /// <summary> /// 1 based offset of string2 in string1; optionally case insensitive /// </summary> /// <param name="start"></param> /// <param name="string1"></param> /// <param name="string2"></param> /// <param name="compare"></param> /// <returns></returns> static public int InStr(int start, string string1, string string2, int compare) { if (string1 == null || string2 == null || string1.Length == 0 || start > string1.Length || start < 1) return 0; if (string2.Length == 0) return start; // Make start zero based start--; if (start < 0) start=0; if (compare == 1) // Make case insensitive comparison? { // yes; just make both strings lower case string1 = string1.ToLower(); string2 = string2.ToLower(); } int i = string1.IndexOf(string2, start); return i+1; // result is 1 based } /// <summary> /// 1 based offset of string2 in string1 starting from end of string /// </summary> /// <param name="string1"></param> /// <param name="string2"></param> /// <returns></returns> static public int InStrRev(string string1, string string2) { return InStrRev(string1, string2, -1, 0); } /// <summary> /// 1 based offset of string2 in string1 starting from end of string - start /// </summary> /// <param name="string1"></param> /// <param name="string2"></param> /// <param name="start"></param> /// <returns></returns> static public int InStrRev(string string1, string string2, int start) { return InStrRev(string1, string2, start, 0); } /// <summary> /// 1 based offset of string2 in string1 starting from end of string - start optionally case insensitive /// </summary> /// <param name="string1"></param> /// <param name="string2"></param> /// <param name="start"></param> /// <param name="compare">1 for case insensitive comparison</param> /// <returns></returns> static public int InStrRev(string string1, string string2, int start, int compare) { if (string1 == null || string2 == null || string1.Length == 0 || string2.Length > string1.Length) return 0; // TODO this is the brute force method of searching; should use better algorithm bool bCaseSensitive = compare == 1; int inc= start == -1? string1.Length: start; if (inc > string1.Length) inc = string1.Length; while (inc >= string2.Length) // go thru the string backwards; but string still needs to long enough to hold find string { int i=string2.Length-1; for ( ; i >= 0; i--) // match the find string backwards as well { if (bCaseSensitive) { if (Char.ToLower(string1[inc-string2.Length+i]) != string2[i]) break; } else { if (string1[inc-string2.Length+i] != string2[i]) break; } } if (i < 0) // We got a match return inc+1-string2.Length; inc--; // No match try next character } return 0; } /// <summary> /// IsNumeric returns True if the data type of Expression is Boolean, Byte, Decimal, Double, Integer, Long, /// SByte, Short, Single, UInteger, ULong, or UShort. /// It also returns True if Expression is a Char, String, or Object that can be successfully converted to a number. /// /// IsNumeric returns False if Expression is of data type Date. It returns False if Expression is a /// Char, String, or Object that cannot be successfully converted to a number. /// </summary> /// <param name="v"></param> /// <returns></returns> static public bool IsNumeric(object expression) { if (expression == null) return false; if (expression is string || expression is char) { } else if (expression is bool || expression is byte || expression is sbyte || expression is decimal || expression is double || expression is float || expression is Int16 || expression is Int32 || expression is Int64 || expression is UInt16 || expression is UInt32 || expression is UInt64) return true; try { Convert.ToDouble(expression); return true; } catch { return false; } } /// <summary> /// Returns the lower case of the passed string /// </summary> /// <param name="str"></param> /// <returns></returns> static public string LCase(string str) { return str == null? null: str.ToLower(); } /// <summary> /// Returns the left n characters from the string /// </summary> /// <param name="str"></param> /// <param name="count"></param> /// <returns></returns> static public string Left(string str, int count) { if (str == null || count >= str.Length) return str; else return str.Substring(0, count); } /// <summary> /// Returns the length of the string /// </summary> /// <param name="str"></param> /// <returns></returns> static public int Len(string str) { return str == null? 0: str.Length; } /// <summary> /// Removes leading blanks from string /// </summary> /// <param name="str"></param> /// <returns></returns> static public string LTrim(string str) { if (str == null || str.Length == 0) return str; return str.TrimStart(' '); } /// <summary> /// Returns the portion of the string denoted by the start. /// </summary> /// <param name="str"></param> /// <param name="start">1 based starting position</param> /// <returns></returns> static public string Mid(string str, int start) { if (str == null) return null; if (start > str.Length) return ""; return str.Substring(start - 1); } /// <summary> /// Returns the portion of the string denoted by the start and length. /// </summary> /// <param name="str"></param> /// <param name="start">1 based starting position</param> /// <param name="length">length to extract</param> /// <returns></returns> static public string Mid(string str, int start, int length) { if (str == null) return null; if (start > str.Length) return ""; if (str.Length < start - 1 + length) return str.Substring(start - 1); // Length specified is too large return str.Substring(start-1, length); } //Replace(string,find,replacewith[,start[,count[,compare]]]) /// <summary> /// Returns string replacing all instances of the searched for text with the replace text. /// </summary> /// <param name="str"></param> /// <param name="find"></param> /// <param name="replacewith"></param> /// <returns></returns> static public string Replace(string str, string find, string replacewith) { return Replace(str, find, replacewith, 1, -1, 0); } /// <summary> /// Returns string replacing all instances of the searched for text starting at position /// start with the replace text. /// </summary> /// <param name="str"></param> /// <param name="find"></param> /// <param name="replacewith"></param> /// <param name="start"></param> /// <returns></returns> static public string Replace(string str, string find, string replacewith, int start) { return Replace(str, find, replacewith, start, -1, 0); } /// <summary> /// Returns string replacing 'count' instances of the searched for text starting at position /// start with the replace text. /// </summary> /// <param name="str"></param> /// <param name="find"></param> /// <param name="replacewith"></param> /// <param name="start"></param> /// <param name="count"></param> /// <returns></returns> static public string Replace(string str, string find, string replacewith, int start, int count) { return Replace(str, find, replacewith, start, count, 0); } /// <summary> /// Returns string replacing 'count' instances of the searched for text (optionally /// case insensitive) starting at position start with the replace text. /// </summary> /// <param name="str"></param> /// <param name="find"></param> /// <param name="replacewith"></param> /// <param name="start"></param> /// <param name="count"></param> /// <param name="compare">1 for case insensitive search</param> /// <returns></returns> static public string Replace(string str, string find, string replacewith, int start, int count, int compare) { if (str == null || find == null || find.Length == 0 || count == 0) return str; if (count == -1) // user want all changed? count = int.MaxValue; StringBuilder sb = new StringBuilder(str); bool bCaseSensitive = compare != 0; // determine if case sensitive; compare = 0 for case sensitive if (bCaseSensitive) find = find.ToLower(); int inc=0; bool bReplace = (replacewith != null && replacewith.Length > 0); // TODO this is the brute force method of searching; should use better algorithm while (inc <= sb.Length - find.Length) { int i=0; for ( ; i < find.Length; i++) { if (bCaseSensitive) { if (Char.ToLower(sb[inc+i]) != find[i]) break; } else { if (sb[inc+i] != find[i]) break; } } if (i == find.Length) // We got a match { // replace the found string with the replacement string sb.Remove(inc, find.Length); if (bReplace) { sb.Insert(inc, replacewith); inc += (replacewith.Length + 1); } count--; if (count == 0) // have we done as many replaces as requested? return sb.ToString(); // yes, return } else inc++; // No match try next character } return sb.ToString(); } /// <summary> /// Returns the rightmost length of string. /// </summary> /// <param name="str"></param> /// <param name="length"></param> /// <returns></returns> static public string Right(string str, int length) { if (str == null || str.Length <= length) return str; if (length <= 0) return ""; return str.Substring(str.Length - length); } /// <summary> /// Removes trailing blanks from string. /// </summary> /// <param name="str"></param> /// <returns></returns> static public string RTrim(string str) { if (str == null || str.Length == 0) return str; return str.TrimEnd(' '); } /// <summary> /// Returns blank string of the specified length /// </summary> /// <param name="length"></param> /// <returns></returns> static public string Space(int length) { return String(length, ' '); } //StrComp(string1,string2[,compare]) /// <summary> /// Compares the strings. When string1 &lt; string2: -1, string1 = string2: 0, string1 > string2: 1 /// </summary> /// <param name="string1"></param> /// <param name="string2"></param> /// <returns></returns> static public int StrComp(string string1, string string2) { return StrComp(string1, string2, 0); } /// <summary> /// Compares the strings; optionally with case insensitivity. When string1 &lt; string2: -1, string1 = string2: 0, string1 > string2: 1 /// </summary> /// <param name="string1"></param> /// <param name="string2"></param> /// <param name="compare">1 for case insensitive comparison</param> /// <returns></returns> static public int StrComp(string string1, string string2, int compare) { if (string1 == null || string2 == null) return 0; // not technically correct; should return null return compare == 0? string1.CompareTo(string2): string1.ToLower().CompareTo(string2.ToLower()); } /// <summary> /// Return string with the character repeated for the length /// </summary> /// <param name="length"></param> /// <param name="c"></param> /// <returns></returns> static public string String(int length, string c) { if (length <= 0 || c == null || c.Length == 0) return ""; return String(length, c[0]); } /// <summary> /// Return string with the character repeated for the length /// </summary> /// <param name="length"></param> /// <param name="c"></param> /// <returns></returns> static public string String(int length, char c) { if (length <= 0) return ""; StringBuilder sb = new StringBuilder(length, length); for (int i = 0; i < length; i++) sb.Append(c); return sb.ToString(); } /// <summary> /// Returns a string with the characters reversed. /// </summary> /// <param name="str"></param> /// <returns></returns> static public string StrReverse(string str) { if (str == null || str.Length < 2) return str; StringBuilder sb = new StringBuilder(str, str.Length); int i = str.Length-1; foreach (char c in str) { sb[i--] = c; } return sb.ToString(); } /// <summary> /// Removes whitespace from beginning and end of string. /// </summary> /// <param name="str"></param> /// <returns></returns> static public string Trim(string str) { if (str == null || str.Length == 0) return str; return str.Trim(' '); } /// <summary> /// Returns the uppercase version of the string /// </summary> /// <param name="str"></param> /// <returns></returns> static public string UCase(string str) { return str == null? null: str.ToUpper(); } /// <summary> /// Rounds a number to zero decimal places /// </summary> /// <param name="n">Number to round</param> /// <returns></returns> static public double Round(double n) { return Math.Round(n); } /// <summary> /// Rounds a number to the specified decimal places /// </summary> /// <param name="n">Number to round</param> /// <param name="decimals">Number of decimal places</param> /// <returns></returns> static public double Round(double n, int decimals) { return Math.Round(n, decimals); } /// <summary> /// Rounds a number to zero decimal places /// </summary> /// <param name="n">Number to round</param> /// <returns></returns> static public decimal Round(decimal n) { return Math.Round(n); } /// <summary> /// Rounds a number to the specified decimal places /// </summary> /// <param name="n">Number to round</param> /// <param name="decimals">Number of decimal places</param> /// <returns></returns> static public decimal Round(decimal n, int decimals) { return Math.Round(n, decimals); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Apress.WebApi.Recipes.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
#if DNX451 using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; using OmniSharp.Models; using OmniSharp.Options; using OmniSharp.Roslyn.CSharp.Services.Refactoring; using OmniSharp.Services; using OmniSharp.Tests; using Xunit; namespace OmniSharp.Roslyn.CSharp.Tests { public class FixUsingsFacts { string fileName = "test.cs"; [Fact] public async Task FixUsings_AddsUsingSingle() { const string fileContents = @"namespace nsA { public class classX{} } namespace OmniSharp { public class class1 { public method1() { var c1 = new classX(); } } }"; string expectedFileContents = @"using nsA; namespace nsA { public class classX{} } namespace OmniSharp { public class class1 { public method1() { var c1 = new classX(); } } }"; await AssertBufferContents(fileContents, expectedFileContents); } [Fact] public async Task FixUsings_AddsUsingSingleForFrameworkMethod() { const string fileContents = @"namespace OmniSharp { public class class1 { public void method1() { Console.WriteLine(""abc""); } } }"; string expectedFileContents = @"using System; namespace OmniSharp { public class class1 { public void method1() { Console.WriteLine(""abc""); } } }"; await AssertBufferContents(fileContents, expectedFileContents); } [Fact] public async Task FixUsings_AddsUsingSingleForFrameworkClass() { const string fileContents = @"namespace OmniSharp { public class class1 { public void method1()() { var s = new StringBuilder(); } } }"; string expectedFileContents = @"using System.Text; namespace OmniSharp { public class class1 { public void method1()() { var s = new StringBuilder(); } } }"; await AssertBufferContents(fileContents, expectedFileContents); } [Fact] public async Task FixUsings_AddsUsingMultiple() { const string fileContents = @"namespace nsA { public class classX{} } namespace nsB { public class classY{} } namespace OmniSharp { public class class1 { public method1() { var c1 = new classX(); var c2 = new classY(); } } }"; string expectedFileContents = @"using nsA; using nsB; namespace nsA { public class classX{} } namespace nsB { public class classY{} } namespace OmniSharp { public class class1 { public method1() { var c1 = new classX(); var c2 = new classY(); } } }"; await AssertBufferContents(fileContents, expectedFileContents); } [Fact] public async Task FixUsings_AddsUsingMultipleForFramework() { const string fileContents = @"namespace OmniSharp { public class class1 { public void method1() { Console.WriteLine(""abc""); var sb = new StringBuilder(); } } }"; string expectedFileContents = @"using System; using System.Text; namespace OmniSharp { public class class1 { public void method1() { Console.WriteLine(""abc""); var sb = new StringBuilder(); } } }"; await AssertBufferContents(fileContents, expectedFileContents); } [Fact] public async Task FixUsings_ReturnsAmbiguousResult() { const string fileContents = @" namespace nsA { public class classX{} } namespace nsB { public class classX{} } namespace OmniSharp { public class class1 { public method1() { var c1 = new $classX(); } } }"; var classLineColumn = TestHelpers.GetLineAndColumnFromDollar(TestHelpers.RemovePercentMarker(fileContents)); var fileContentNoDollarMarker = TestHelpers.RemoveDollarMarker(fileContents); var expectedUnresolved = new List<QuickFix>(); expectedUnresolved.Add(new QuickFix() { Line = classLineColumn.Line, Column = classLineColumn.Column, FileName = fileName, Text = "`classX` is ambiguous" }); await AssertUnresolvedReferences(fileContentNoDollarMarker, expectedUnresolved); } [Fact] public async Task FixUsings_ReturnsNoUsingsForAmbiguousResult() { const string fileContents = @"namespace nsA { public class classX{} } namespace nsB { public class classX{} } namespace OmniSharp { public class class1 { public method1() { var c1 = new classX(); } } }"; await AssertBufferContents(fileContents, fileContents); } [Fact] public async Task FixUsings_AddsUsingForExtension() { const string fileContents = @"namespace nsA { public static class StringExtension { public static void Whatever(this string astring) {} } } namespace OmniSharp { public class class1 { public method1() { ""string"".Whatever(); } } }"; string expectedFileContents = @"using nsA; namespace nsA { public static class StringExtension { public static void Whatever(this string astring) {} } } namespace OmniSharp { public class class1 { public method1() { ""string"".Whatever(); } } }"; await AssertBufferContents(fileContents, expectedFileContents); } [Fact] public async Task FixUsings_AddsUsingLinqMethodSyntax() { const string fileContents = @"namespace OmniSharp { public class class1 { public void method1() { List<string> first = new List<string>(); var testing = first.Where(s => s == ""abc""); } } }"; string expectedFileContents = @"using System.Collections.Generic; using System.Linq; namespace OmniSharp { public class class1 { public void method1() { List<string> first = new List<string>(); var testing = first.Where(s => s == ""abc""); } } }"; await AssertBufferContents(fileContents, expectedFileContents); } [Fact] public async Task FixUsings_AddsUsingLinqQuerySyntax() { const string fileContents = @"namespace OmniSharp { public class class1 { public void method1() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var lowNums = from n in numbers where n < 5 select n; } } }"; string expectedFileContents = @"using System.Linq; namespace OmniSharp { public class class1 { public void method1() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var lowNums = from n in numbers where n < 5 select n; } } }"; await AssertBufferContents(fileContents, expectedFileContents); } [Fact] public async Task FixUsings_RemoveDuplicateUsing() { const string fileContents = @"using System; using System; namespace OmniSharp { public class class1 { public void method1() { Console.WriteLine(""test""); } } }"; const string expectedFileContents = @"using System; namespace OmniSharp { public class class1 { public void method1() { Console.WriteLine(""test""); } } }"; await AssertBufferContents(fileContents, expectedFileContents); } [Fact] public async Task FixUsings_RemoveUnusedUsing() { const string fileContents = @"using System; using System.Linq; namespace OmniSharp { public class class1 { public void method1() { Console.WriteLine(""test""); } } }"; const string expectedFileContents = @"using System; namespace OmniSharp { public class class1 { public void method1() { Console.WriteLine(""test""); } } }"; await AssertBufferContents(fileContents, expectedFileContents); } private async Task AssertBufferContents(string fileContents, string expectedFileContents) { var response = await RunFixUsings(fileContents); Assert.Equal(expectedFileContents, response.Buffer); } private async Task AssertUnresolvedReferences(string fileContents, List<QuickFix> expectedUnresolved) { var response = await RunFixUsings(fileContents); var qfList = response.AmbiguousResults.ToList(); Assert.Equal(qfList.Count(), expectedUnresolved.Count()); var i = 0; foreach (var expectedQuickFix in expectedUnresolved) { Assert.Equal(qfList[i].Line, expectedQuickFix.Line); Assert.Equal(qfList[i].Column, expectedQuickFix.Column); Assert.Equal(qfList[i].FileName, expectedQuickFix.FileName); Assert.Equal(qfList[i].Text, expectedQuickFix.Text); i++; } } private async Task<FixUsingsResponse> RunFixUsings(string fileContents) { var host = TestHelpers.CreatePluginHost(new[] { typeof(FixUsingService).GetTypeInfo().Assembly }); var workspace = await TestHelpers.CreateSimpleWorkspace(host, fileContents, fileName); var fakeOptions = new FakeOmniSharpOptions(); fakeOptions.Options = new OmniSharpOptions(); fakeOptions.Options.FormattingOptions = new FormattingOptions() { NewLine = "\n" }; var providers = host.GetExports<ICodeActionProvider>(); var controller = new FixUsingService(workspace, providers); var request = new FixUsingsRequest { FileName = fileName, Buffer = fileContents }; return await controller.Handle(request); } } } #endif
using System; using System.Net; using ICSharpCode.SharpZipLib; using ICSharpCode.SharpZipLib.Zip; using ICSharpCode.SharpZipLib.Zip.Compression.Streams; using ICSharpCode.SharpZipLib.Zip.Compression; using ICSharpCode.SharpZipLib.BZip2; using System.Collections; using System.IO; using System.Text; using ICSharpCode.SharpZipLib.Checksums; namespace RemoteZip { /// <summary> /// Summary description for ZipDownloader. /// </summary> public class RemoteZipFile : IEnumerable { ZipEntry[] entries; string baseUrl; int MaxFileOffset; public RemoteZipFile() { } /* end of central dir signature 4 bytes (0x06054b50) number of this disk 2 bytes number of the disk with the start of the central directory 2 bytes total number of entries in the central directory on this disk 2 bytes total number of entries in the central directory 2 bytes size of the central directory 4 bytes offset of start of central directory with respect to the starting disk number 4 bytes .ZIP file comment length 2 bytes .ZIP file comment (variable size) */ /// <summary> /// TODO: case when the whole file is smaller than 64K /// TODO: handle non HTTP case /// </summary> /// <param name="url"></param> /// <returns></returns> public bool Load(string url) { int CentralOffset, CentralSize; int TotalEntries; if (!FindCentralDirectory(url, out CentralOffset, out CentralSize, out TotalEntries)) return false; MaxFileOffset = CentralOffset; // now retrieve the Central Directory baseUrl = url; entries = new ZipEntry[TotalEntries]; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.AddRange(CentralOffset, CentralOffset + CentralSize); HttpWebResponse res = (HttpWebResponse)req.GetResponse(); Stream s = res.GetResponseStream(); try { // code taken from SharpZipLib with modification for not seekable stream // and adjustement for Central Directory entry for (int i = 0; i < TotalEntries; i++) { if (ReadLeInt(s) != ZipConstants.CENSIG) { throw new ZipException("Wrong Central Directory signature"); } // skip 6 bytes: version made (W), version ext (W), flags (W) ReadLeInt(s); ReadLeShort(s); int method = ReadLeShort(s); int dostime = ReadLeInt(s); int crc = ReadLeInt(s); int csize = ReadLeInt(s); int size = ReadLeInt(s); int nameLen = ReadLeShort(s); int extraLen = ReadLeShort(s); int commentLen = ReadLeShort(s); // skip 8 bytes: disk number start, internal file attribs, external file attribs (DW) ReadLeInt(s); ReadLeInt(s); int offset = ReadLeInt(s); byte[] buffer = new byte[Math.Max(nameLen, commentLen)]; ReadAll(buffer, 0, nameLen, s); string name = ZipConstants.ConvertToString(buffer); ZipEntry entry = new ZipEntry(name); entry.CompressionMethod = (CompressionMethod)method; entry.Crc = crc & 0xffffffffL; entry.Size = size & 0xffffffffL; entry.CompressedSize = csize & 0xffffffffL; entry.DosTime = (uint)dostime; if (extraLen > 0) { byte[] extra = new byte[extraLen]; ReadAll(extra, 0, extraLen, s); entry.ExtraData = extra; } if (commentLen > 0) { ReadAll(buffer, 0, commentLen, s); entry.Comment = ZipConstants.ConvertToString(buffer); } entry.ZipFileIndex = i; entry.Offset = offset; entries[i] = entry; OnProgress((i * 100) / TotalEntries); } } finally { s.Close(); res.Close(); } OnProgress(100); return true; } /// <summary> /// OnProgress during Central Header loading /// </summary> /// <param name="pct"></param> public virtual void OnProgress(int pct) { } /// <summary> /// Checks if there is a local header at the current position in the stream and skips it /// </summary> /// <param name="baseStream"></param> /// <param name="entry"></param> void SkipLocalHeader(Stream baseStream, ZipEntry entry) { lock (baseStream) { if (ReadLeInt(baseStream) != ZipConstants.LOCSIG) { throw new ZipException("Wrong Local header signature"); } Skip(baseStream, 10 + 12); int namelen = ReadLeShort(baseStream); int extralen = ReadLeShort(baseStream); Skip(baseStream, namelen + extralen); } } /// <summary> /// Finds the Central Header in the Zip file. We can minimize the number of requests and /// the bytes taken /// /// Actually we do: 256, 1024, 65536 /// </summary> /// <param name="baseurl"></param> /// <returns></returns> bool FindCentralDirectory(string url, out int Offset, out int Size, out int Entries) { int currentLength = 256; Entries = 0; Size = 0; Offset = -1; while (true) { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.AddRange(-(currentLength + 22)); HttpWebResponse res = (HttpWebResponse)req.GetResponse(); // copy the buffer because we need a back seekable buffer byte[] bb = new byte[res.ContentLength]; int endSize = ReadAll(bb, 0, (int)res.ContentLength, res.GetResponseStream()); res.Close(); // scan for the central block. The position of the central block // is end-comment-22 //< // 50 4B 05 06 int pos = endSize - 22; int state = 0; while (pos >= 0) { if (bb[pos] == 0x50) { if (bb[pos + 1] == 0x4b && bb[pos + 2] == 0x05 && bb[pos + 3] == 0x06) break; // found!! pos -= 4; } else pos--; } if (pos < 0) { if (currentLength == 65536) break; if (currentLength == 1024) currentLength = 65536; else if (currentLength == 256) currentLength = 1024; else break; } else { // found it!! so at offset pos+3*4 there is Size, and pos+4*4 // BinaryReader is so elegant but now it's too much Size = MakeInt(bb, pos + 12); Offset = MakeInt(bb, pos + 16); Entries = MakeShort(bb, pos + 10); return true; } } return false; } /// <summary> /// Get a Stream for reading the specified entry /// </summary> /// <param name="entry"></param> /// <returns></returns> public Stream GetInputStream(ZipEntry entry) { if (entry.Size == 0) return null; if (entries == null) { throw new InvalidOperationException("ZipFile has closed"); } long index = entry.ZipFileIndex; if (index < 0 || index >= entries.Length || entries[index].Name != entry.Name) { throw new IndexOutOfRangeException(); } // WARNING // should parse the Local Header to get the data address // Maximum Size of the Local Header is ... 16+64K*2 // // So the HTTP request should ask for the big local header, but actually the // additional data is not downloaded. // Optionally use an additional Request to be really precise HttpWebRequest req = (HttpWebRequest)WebRequest.Create(baseUrl); int limit = (int)(entry.Offset + entry.CompressedSize + 16 + 65536 * 2); if (limit >= MaxFileOffset) limit = MaxFileOffset - 1; req.AddRange((int)entry.Offset, limit); HttpWebResponse res = (HttpWebResponse)req.GetResponse(); Stream baseStream = res.GetResponseStream(); // skips all the header SkipLocalHeader(baseStream, entries[index]); CompressionMethod method = entries[index].CompressionMethod; Stream istr = new PartialInputStream(baseStream, res, entries[index].CompressedSize); switch (method) { case CompressionMethod.Stored: return istr; case CompressionMethod.Deflated: return new InflaterInputStream(istr, new Inflater(true)); case (CompressionMethod)12: return new BZip2InputStream(istr); default: throw new ZipException("Unknown compression method " + method); } } /// <summary> /// Read an unsigned short in little endian byte order. /// </summary> /// <exception name="System.IO.IOException"> /// if a i/o error occured. /// </exception> /// <exception name="System.IO.EndOfStreamException"> /// if the file ends prematurely /// </exception> int ReadLeShort(Stream s) { return s.ReadByte() | s.ReadByte() << 8; } /// <summary> /// Read an int in little endian byte order. /// </summary> /// <exception name="System.IO.IOException"> /// if a i/o error occured. /// </exception> /// <exception name="System.IO.EndOfStreamException"> /// if the file ends prematurely /// </exception> int ReadLeInt(Stream s) { return ReadLeShort(s) | ReadLeShort(s) << 16; } static void Skip(Stream s, int n) { for (int i = 0; i < n; i++) s.ReadByte(); } static int ReadAll(byte[] bb, int p, int sst, Stream s) { int ss = 0; while (ss < sst) { int r = s.Read(bb, p, sst - ss); if (r <= 0) return ss; ss += r; p += r; } return ss; } public static int MakeInt(byte[] bb, int pos) { return bb[pos + 0] | (bb[pos + 1] << 8) | (bb[pos + 2] << 16) | (bb[pos + 3] << 24); } public static int MakeShort(byte[] bb, int pos) { return bb[pos + 0] | (bb[pos + 1] << 8); } public int Size { get { return entries == null ? 0 : entries.Length; } } /// <summary> /// Returns an IEnumerator of all Zip entries in this Zip file. /// </summary> public IEnumerator GetEnumerator() { if (entries == null) { throw new InvalidOperationException("ZipFile has closed"); } return new ZipEntryEnumeration(entries); } public ZipEntry this[int index] { get { return entries[index]; } } class ZipEntryEnumeration : IEnumerator { ZipEntry[] array; int ptr = -1; public ZipEntryEnumeration(ZipEntry[] arr) { array = arr; } public object Current { get { return array[ptr]; } } public void Reset() { ptr = -1; } public bool MoveNext() { return (++ptr < array.Length); } } class PartialInputStream : InflaterInputStream { Stream baseStream; long filepos; long end; HttpWebResponse request; public PartialInputStream(Stream baseStream, HttpWebResponse request, long len) : base(baseStream) { this.baseStream = baseStream; filepos = 0; end = len; this.request = request; } public override int Available { get { long amount = end - filepos; if (amount > Int32.MaxValue) { return Int32.MaxValue; } return (int)amount; } } public override int ReadByte() { if (filepos == end) { return -1; } lock (baseStream) { filepos++; return baseStream.ReadByte(); } } public override int Read(byte[] b, int off, int len) { if (len > end - filepos) { len = (int)(end - filepos); if (len == 0) { return 0; } } lock (baseStream) { int count = ReadAll(b, off, len, baseStream); if (count > 0) { filepos += len; } return count; } } public long SkipBytes(long amount) { if (amount < 0) { throw new ArgumentOutOfRangeException(); } if (amount > end - filepos) { amount = end - filepos; } filepos += amount; for (int i = 0; i < amount; i++) baseStream.ReadByte(); return amount; } public override void Close() { request.Close(); baseStream.Close(); } } } /// <summary> /// This is a FilterOutputStream that writes the files into a zip /// archive one after another. It has a special method to start a new /// zip entry. The zip entries contains information about the file name /// size, compressed size, CRC, etc. /// /// It includes support for STORED and DEFLATED and BZIP2 entries. /// This class is not thread safe. /// /// author of the original java version : Jochen Hoenicke /// </summary> /// <example> This sample shows how to create a zip file /// <code> /// using System; /// using System.IO; /// /// using NZlib.Zip; /// /// class MainClass /// { /// public static void Main(string[] args) /// { /// string[] filenames = Directory.GetFiles(args[0]); /// /// ZipOutputStream s = new ZipOutputStream(File.Create(args[1])); /// /// s.SetLevel(5); // 0 - store only to 9 - means best compression /// /// foreach (string file in filenames) { /// FileStream fs = File.OpenRead(file); /// /// byte[] buffer = new byte[fs.Length]; /// fs.Read(buffer, 0, buffer.Length); /// /// ZipEntry entry = new ZipEntry(file); /// /// s.PutNextEntry(entry); /// /// s.Write(buffer, 0, buffer.Length); /// /// } /// /// s.Finish(); /// s.Close(); /// } /// } /// </code> /// </example> public class ZipOutputStream : DeflaterOutputStream { private ArrayList entries = new ArrayList(); private Crc32 crc = new Crc32(); private ZipEntry curEntry = null; private long startPosition = 0; private Stream additionalStream = null; private CompressionMethod curMethod; private int size; private int offset = 0; private byte[] zipComment = new byte[0]; private int defaultMethod = DEFLATED; /// <summary> /// Our Zip version is hard coded to 1.0 resp. 2.0 /// </summary> private const int ZIP_STORED_VERSION = 10; private const int ZIP_DEFLATED_VERSION = 20; /// <summary> /// Compression method. This method doesn't compress at all. /// </summary> public const int STORED = 0; /// <summary> /// Compression method. This method uses the Deflater. /// </summary> public const int DEFLATED = 8; public const int BZIP2 = 12; /// <summary> /// Creates a new Zip output stream, writing a zip archive. /// </summary> /// <param name="baseOutputStream"> /// the output stream to which the zip archive is written. /// </param> public ZipOutputStream(Stream baseOutputStream) : base(baseOutputStream, new Deflater(Deflater.DEFAULT_COMPRESSION, true)) { } /// <summary> /// Set the zip file comment. /// </summary> /// <param name="comment"> /// the comment. /// </param> /// <exception name ="ArgumentException"> /// if UTF8 encoding of comment is longer than 0xffff bytes. /// </exception> public void SetComment(string comment) { byte[] commentBytes = ZipConstants.ConvertToArray(comment); if (commentBytes.Length > 0xffff) { throw new ArgumentException("Comment too long."); } zipComment = commentBytes; } } }
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using erl.Oracle.TnsNames.Antlr4.Runtime.Misc; using erl.Oracle.TnsNames.Antlr4.Runtime.Sharpen; namespace erl.Oracle.TnsNames.Antlr4.Runtime.Atn { public class ATNConfigSet { /** Indicates that the set of configurations is read-only. Do not * allow any code to manipulate the set; DFA states will point at * the sets and they must not change. This does not protect the other * fields; in particular, conflictingAlts is set after * we've made this readonly. */ protected bool readOnly = false; /** * All configs but hashed by (s, i, _, pi) not including context. Wiped out * when we go readonly as this set becomes a DFA state. */ public ConfigHashSet configLookup; /** Track the elements as they are added to the set; supports get(i) */ public ArrayList<ATNConfig> configs = new ArrayList<ATNConfig>(7); // TODO: these fields make me pretty uncomfortable but nice to pack up info together, saves recomputation // TODO: can we track conflicts as they are added to save scanning configs later? public int uniqueAlt; /** Currently this is only used when we detect SLL conflict; this does * not necessarily represent the ambiguous alternatives. In fact, * I should also point out that this seems to include predicated alternatives * that have predicates that evaluate to false. Computed in computeTargetState(). */ public BitSet conflictingAlts; // Used in parser and lexer. In lexer, it indicates we hit a pred // while computing a closure operation. Don't make a DFA state from this. public bool hasSemanticContext; public bool dipsIntoOuterContext; /** Indicates that this configuration set is part of a full context * LL prediction. It will be used to determine how to merge $. With SLL * it's a wildcard whereas it is not for LL context merge. */ public readonly bool fullCtx; private int cachedHashCode = -1; public ATNConfigSet(bool fullCtx) { configLookup = new ConfigHashSet(); this.fullCtx = fullCtx; } public ATNConfigSet() : this(true) { } public ATNConfigSet(ATNConfigSet old) : this(old.fullCtx) { AddAll(old.configs); this.uniqueAlt = old.uniqueAlt; this.conflictingAlts = old.conflictingAlts; this.hasSemanticContext = old.hasSemanticContext; this.dipsIntoOuterContext = old.dipsIntoOuterContext; } public bool Add(ATNConfig config) { return Add(config, null); } /** * Adding a new config means merging contexts with existing configs for * {@code (s, i, pi, _)}, where {@code s} is the * {@link ATNConfig#state}, {@code i} is the {@link ATNConfig#alt}, and * {@code pi} is the {@link ATNConfig#semanticContext}. We use * {@code (s,i,pi)} as key. * * <p>This method updates {@link #dipsIntoOuterContext} and * {@link #hasSemanticContext} when necessary.</p> */ public bool Add(ATNConfig config, MergeCache mergeCache) { if (readOnly) throw new Exception("This set is readonly"); if (config.semanticContext != SemanticContext.NONE) { hasSemanticContext = true; } if (config.OuterContextDepth > 0) { dipsIntoOuterContext = true; } ATNConfig existing = configLookup.GetOrAdd(config); if (existing == config) { // we added this new one cachedHashCode = -1; configs.Add(config); // track order here return true; } // a previous (s,i,pi,_), merge with it and save result bool rootIsWildcard = !fullCtx; PredictionContext merged = PredictionContext.Merge(existing.context, config.context, rootIsWildcard, mergeCache); // no need to check for existing.context, config.context in cache // since only way to create new graphs is "call rule" and here. We // cache at both places. existing.reachesIntoOuterContext = Math.Max(existing.reachesIntoOuterContext, config.reachesIntoOuterContext); // make sure to preserve the precedence filter suppression during the merge if (config.IsPrecedenceFilterSuppressed) { existing.SetPrecedenceFilterSuppressed(true); } existing.context = merged; // replace context; no need to alt mapping return true; } /** Return a List holding list of configs */ public List<ATNConfig> Elements { get { return configs; } } public HashSet<ATNState> GetStates() { HashSet<ATNState> states = new HashSet<ATNState>(); foreach (ATNConfig c in configs) { states.Add(c.state); } return states; } /** * Gets the complete set of represented alternatives for the configuration * set. * * @return the set of represented alternatives in this configuration set * * @since 4.3 */ public BitSet GetAlts() { BitSet alts = new BitSet(); foreach (ATNConfig config in configs) { alts.Set(config.alt); } return alts; } public List<SemanticContext> GetPredicates() { List<SemanticContext> preds = new List<SemanticContext>(); foreach (ATNConfig c in configs) { if (c.semanticContext != SemanticContext.NONE) { preds.Add(c.semanticContext); } } return preds; } public ATNConfig Get(int i) { return configs[i]; } public void OptimizeConfigs(ATNSimulator interpreter) { if (readOnly) throw new Exception("This set is readonly"); if (configLookup.Count == 0) return; foreach (ATNConfig config in configs) { // int before = PredictionContext.getAllContextNodes(config.context).size(); config.context = interpreter.getCachedContext(config.context); // int after = PredictionContext.getAllContextNodes(config.context).size(); // System.out.println("configs "+before+"->"+after); } } public bool AddAll(ICollection<ATNConfig> coll) { foreach (ATNConfig c in coll) Add(c); return false; } public override bool Equals(Object o) { if (o == this) { return true; } else if (!(o is ATNConfigSet)) { return false; } // System.out.print("equals " + this + ", " + o+" = "); ATNConfigSet other = (ATNConfigSet)o; bool same = configs != null && configs.Equals(other.configs) && // includes stack context this.fullCtx == other.fullCtx && this.uniqueAlt == other.uniqueAlt && this.conflictingAlts == other.conflictingAlts && this.hasSemanticContext == other.hasSemanticContext && this.dipsIntoOuterContext == other.dipsIntoOuterContext; // System.out.println(same); return same; } public override int GetHashCode() { if (IsReadOnly) { if (cachedHashCode == -1) { cachedHashCode = configs.GetHashCode(); } return cachedHashCode; } return configs.GetHashCode(); } public int Count { get { return configs.Count; } } public bool Empty { get { return configs.Count == 0; } } public bool Contains(Object o) { if (configLookup == null) { throw new Exception("This method is not implemented for readonly sets."); } return configLookup.ContainsKey((ATNConfig)o); } public void Clear() { if (readOnly) throw new Exception("This set is readonly"); configs.Clear(); cachedHashCode = -1; configLookup.Clear(); } public bool IsReadOnly { get { return readOnly; } set { this.readOnly = value; configLookup = null; // can't mod, no need for lookup cache } } public override String ToString() { StringBuilder buf = new StringBuilder(); buf.Append('['); List<ATNConfig> cfgs = Elements; if (cfgs.Count > 0) { foreach (ATNConfig c in cfgs) { buf.Append(c.ToString()); buf.Append(", "); } buf.Length = buf.Length - 2; } buf.Append(']'); if (hasSemanticContext) buf.Append(",hasSemanticContext=") .Append(hasSemanticContext); if (uniqueAlt != ATN.INVALID_ALT_NUMBER) buf.Append(",uniqueAlt=") .Append(uniqueAlt); if (conflictingAlts != null) buf.Append(",conflictingAlts=") .Append(conflictingAlts); if (dipsIntoOuterContext) buf.Append(",dipsIntoOuterContext"); return buf.ToString(); } } public class OrderedATNConfigSet : ATNConfigSet { public OrderedATNConfigSet() { this.configLookup = new LexerConfigHashSet(); } public class LexerConfigHashSet : ConfigHashSet { public LexerConfigHashSet() : base(new ObjectEqualityComparator()) { } } } public class ObjectEqualityComparator : IEqualityComparer<ATNConfig> { public int GetHashCode(ATNConfig o) { if (o == null) return 0; else return o.GetHashCode(); } public bool Equals(ATNConfig a, ATNConfig b) { if (a == b) return true; if (a == null || b == null) return false; return a.Equals(b); } } /** * The reason that we need this is because we don't want the hash map to use * the standard hash code and equals. We need all configurations with the same * {@code (s,i,_,semctx)} to be equal. Unfortunately, this key effectively doubles * the number of objects associated with ATNConfigs. The other solution is to * use a hash table that lets us specify the equals/hashcode operation. */ public class ConfigHashSet : Dictionary<ATNConfig, ATNConfig> { public ConfigHashSet(IEqualityComparer<ATNConfig> comparer) : base(comparer) { } public ConfigHashSet() : base(new ConfigEqualityComparator()) { } public ATNConfig GetOrAdd(ATNConfig config) { ATNConfig existing; if (this.TryGetValue(config, out existing)) return existing; else { this.Put(config, config); return config; } } } public class ConfigEqualityComparator : IEqualityComparer<ATNConfig> { public int GetHashCode(ATNConfig o) { int hashCode = 7; hashCode = 31 * hashCode + o.state.stateNumber; hashCode = 31 * hashCode + o.alt; hashCode = 31 * hashCode + o.semanticContext.GetHashCode(); return hashCode; } public bool Equals(ATNConfig a, ATNConfig b) { if (a == b) return true; if (a == null || b == null) return false; return a.state.stateNumber == b.state.stateNumber && a.alt == b.alt && a.semanticContext.Equals(b.semanticContext); } } }
// 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.Threading; using System.Threading.Tasks; namespace System.IO { // This class implements a text reader that reads from a string. public class StringReader : TextReader { private string _s; private int _pos; private int _length; public StringReader(string s) { if (s == null) { throw new ArgumentNullException(nameof(s)); } _s = s; _length = s.Length; } public override void Close() { Dispose(true); } protected override void Dispose(bool disposing) { _s = null; _pos = 0; _length = 0; base.Dispose(disposing); } // Returns the next available character without actually reading it from // the underlying string. The current position of the StringReader is not // changed by this operation. The returned value is -1 if no further // characters are available. // public override int Peek() { if (_s == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed); } if (_pos == _length) { return -1; } return _s[_pos]; } // Reads the next character from the underlying string. The returned value // is -1 if no further characters are available. // public override int Read() { if (_s == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed); } if (_pos == _length) { return -1; } return _s[_pos++]; } // Reads a block of characters. This method will read up to count // characters from this StringReader into the buffer character // array starting at position index. Returns the actual number of // characters read, or zero if the end of the string is reached. // public override int Read(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } if (_s == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed); } int n = _length - _pos; if (n > 0) { if (n > count) { n = count; } _s.CopyTo(_pos, buffer, index, n); _pos += n; } return n; } public override int Read(Span<char> buffer) { if (GetType() != typeof(StringReader)) { // This overload was added affter the Read(char[], ...) overload, and so in case // a derived type may have overridden it, we need to delegate to it, which the base does. return base.Read(buffer); } if (_s == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed); } int n = _length - _pos; if (n > 0) { if (n > buffer.Length) { n = buffer.Length; } _s.AsReadOnlySpan().Slice(_pos, n).CopyTo(buffer); _pos += n; } return n; } public override int ReadBlock(Span<char> buffer) => Read(buffer); public override string ReadToEnd() { if (_s == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed); } string s; if (_pos == 0) { s = _s; } else { s = _s.Substring(_pos, _length - _pos); } _pos = _length; return s; } // Reads a line. A line is defined as a sequence of characters followed by // a carriage return ('\r'), a line feed ('\n'), or a carriage return // immediately followed by a line feed. The resulting string does not // contain the terminating carriage return and/or line feed. The returned // value is null if the end of the underlying string has been reached. // public override string ReadLine() { if (_s == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed); } int i = _pos; while (i < _length) { char ch = _s[i]; if (ch == '\r' || ch == '\n') { string result = _s.Substring(_pos, i - _pos); _pos = i + 1; if (ch == '\r' && _pos < _length && _s[_pos] == '\n') { _pos++; } return result; } i++; } if (i > _pos) { string result = _s.Substring(_pos, i - _pos); _pos = i; return result; } return null; } #region Task based Async APIs public override Task<string> ReadLineAsync() { return Task.FromResult(ReadLine()); } public override Task<string> ReadToEndAsync() { return Task.FromResult(ReadToEnd()); } public override Task<int> ReadBlockAsync(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return Task.FromResult(ReadBlock(buffer, index, count)); } public override ValueTask<int> ReadBlockAsync(Memory<char> buffer, CancellationToken cancellationToken = default) => cancellationToken.IsCancellationRequested ? new ValueTask<int>(Task.FromCanceled<int>(cancellationToken)) : new ValueTask<int>(ReadBlock(buffer.Span)); public override Task<int> ReadAsync(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return Task.FromResult(Read(buffer, index, count)); } public override ValueTask<int> ReadAsync(Memory<char> buffer, CancellationToken cancellationToken = default) => cancellationToken.IsCancellationRequested ? new ValueTask<int>(Task.FromCanceled<int>(cancellationToken)) : new ValueTask<int>(Read(buffer.Span)); #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Security.Principal; using System.Threading.Tasks; using IdentityModel; using IdentityServer4.Events; using IdentityServer4.Quickstart.UI; using IdentityServer4.Services; using IdentityServer4.Stores; using IdentityServer4.Test; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace Host.Quickstart.Account { [SecurityHeaders] [AllowAnonymous] public class ExternalController : Controller { private readonly TestUserStore _users; private readonly IIdentityServerInteractionService _interaction; private readonly IClientStore _clientStore; private readonly IEventService _events; public ExternalController( IIdentityServerInteractionService interaction, IClientStore clientStore, IEventService events, TestUserStore users = null) { // if the TestUserStore is not in DI, then we'll just use the global users collection // this is where you would plug in your own custom identity management library (e.g. ASP.NET Identity) _users = users ?? new TestUserStore(TestUsers.Users); _interaction = interaction; _clientStore = clientStore; _events = events; } /// <summary> /// initiate roundtrip to external authentication provider /// </summary> [HttpGet] public async Task<IActionResult> Challenge(string provider, string returnUrl) { if (string.IsNullOrEmpty(returnUrl)) returnUrl = "~/"; // validate returnUrl - either it is a valid OIDC URL or back to a local page if (Url.IsLocalUrl(returnUrl) == false && _interaction.IsValidReturnUrl(returnUrl) == false) { // user might have clicked on a malicious link - should be logged throw new Exception("invalid return URL"); } if (AccountOptions.WindowsAuthenticationSchemeName == provider) { // windows authentication needs special handling return await ProcessWindowsLoginAsync(returnUrl); } else { // start challenge and roundtrip the return URL and scheme var props = new AuthenticationProperties { RedirectUri = Url.Action(nameof(Callback)), Items = { { "returnUrl", returnUrl }, { "scheme", provider }, } }; return Challenge(props, provider); } } /// <summary> /// Post processing of external authentication /// </summary> [HttpGet] public async Task<IActionResult> Callback() { // read external identity from the temporary cookie var result = await HttpContext.AuthenticateAsync(IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme); if (result?.Succeeded != true) { throw new Exception("External authentication error"); } // lookup our user and external provider info var (user, provider, providerUserId, claims) = FindUserFromExternalProvider(result); if (user == null) { // this might be where you might initiate a custom workflow for user registration // in this sample we don't show how that would be done, as our sample implementation // simply auto-provisions new external user user = AutoProvisionUser(provider, providerUserId, claims); } // this allows us to collect any additonal claims or properties // for the specific prtotocols used and store them in the local auth cookie. // this is typically used to store data needed for signout from those protocols. var additionalLocalClaims = new List<Claim>(); var localSignInProps = new AuthenticationProperties(); ProcessLoginCallbackForOidc(result, additionalLocalClaims, localSignInProps); ProcessLoginCallbackForWsFed(result, additionalLocalClaims, localSignInProps); ProcessLoginCallbackForSaml2p(result, additionalLocalClaims, localSignInProps); // issue authentication cookie for user await _events.RaiseAsync(new UserLoginSuccessEvent(provider, providerUserId, user.SubjectId, user.Username)); await HttpContext.SignInAsync(user.SubjectId, user.Username, provider, localSignInProps, additionalLocalClaims.ToArray()); // delete temporary cookie used during external authentication await HttpContext.SignOutAsync(IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme); // retrieve return URL var returnUrl = result.Properties.Items["returnUrl"] ?? "~/"; // check if external login is in the context of an OIDC request var context = await _interaction.GetAuthorizationContextAsync(returnUrl); if (context != null) { if (await _clientStore.IsPkceClientAsync(context.ClientId)) { // if the client is PKCE then we assume it's native, so this change in how to // return the response is for better UX for the end user. return View("Redirect", new RedirectViewModel { RedirectUrl = returnUrl }); } } return Redirect(returnUrl); } private async Task<IActionResult> ProcessWindowsLoginAsync(string returnUrl) { // see if windows auth has already been requested and succeeded var result = await HttpContext.AuthenticateAsync(AccountOptions.WindowsAuthenticationSchemeName); if (result?.Principal is WindowsPrincipal wp) { // we will issue the external cookie and then redirect the // user back to the external callback, in essence, treating windows // auth the same as any other external authentication mechanism var props = new AuthenticationProperties() { RedirectUri = Url.Action("Callback"), Items = { { "returnUrl", returnUrl }, { "scheme", AccountOptions.WindowsAuthenticationSchemeName }, } }; var id = new ClaimsIdentity(AccountOptions.WindowsAuthenticationSchemeName); id.AddClaim(new Claim(JwtClaimTypes.Subject, wp.Identity.Name)); id.AddClaim(new Claim(JwtClaimTypes.Name, wp.Identity.Name)); // add the groups as claims -- be careful if the number of groups is too large if (AccountOptions.IncludeWindowsGroups) { var wi = wp.Identity as WindowsIdentity; var groups = wi.Groups.Translate(typeof(NTAccount)); var roles = groups.Select(x => new Claim(JwtClaimTypes.Role, x.Value)); id.AddClaims(roles); } await HttpContext.SignInAsync( IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme, new ClaimsPrincipal(id), props); return Redirect(props.RedirectUri); } else { // trigger windows auth // since windows auth don't support the redirect uri, // this URL is re-triggered when we call challenge return Challenge(AccountOptions.WindowsAuthenticationSchemeName); } } private (TestUser user, string provider, string providerUserId, IEnumerable<Claim> claims) FindUserFromExternalProvider(AuthenticateResult result) { var externalUser = result.Principal; // try to determine the unique id of the external user (issued by the provider) // the most common claim type for that are the sub claim and the NameIdentifier // depending on the external provider, some other claim type might be used var userIdClaim = externalUser.FindFirst(JwtClaimTypes.Subject) ?? externalUser.FindFirst(ClaimTypes.NameIdentifier) ?? throw new Exception("Unknown userid"); // remove the user id claim so we don't include it as an extra claim if/when we provision the user var claims = externalUser.Claims.ToList(); claims.Remove(userIdClaim); var provider = result.Properties.Items["scheme"]; var providerUserId = userIdClaim.Value; // find external user var user = _users.FindByExternalProvider(provider, providerUserId); return (user, provider, providerUserId, claims); } private TestUser AutoProvisionUser(string provider, string providerUserId, IEnumerable<Claim> claims) { var user = _users.AutoProvisionUser(provider, providerUserId, claims.ToList()); return user; } private void ProcessLoginCallbackForOidc(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps) { // if the external system sent a session id claim, copy it over // so we can use it for single sign-out var sid = externalResult.Principal.Claims.FirstOrDefault(x => x.Type == JwtClaimTypes.SessionId); if (sid != null) { localClaims.Add(new Claim(JwtClaimTypes.SessionId, sid.Value)); } // if the external provider issued an id_token, we'll keep it for signout var id_token = externalResult.Properties.GetTokenValue("id_token"); if (id_token != null) { localSignInProps.StoreTokens(new[] { new AuthenticationToken { Name = "id_token", Value = id_token } }); } } private void ProcessLoginCallbackForWsFed(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps) { } private void ProcessLoginCallbackForSaml2p(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps) { } } }
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Diagnostics; using System.IO; using System.Linq; using BitCoinSharp.Collections; using BitCoinSharp.IO; using log4net; using Org.BouncyCastle.Math; namespace BitCoinSharp { /// <summary> /// Stores the block chain to disk. /// </summary> /// <remarks> /// This implementation is designed to have constant memory usage, regardless of the size of the block chain being /// stored. It exploits operating system level buffering and the fact that get() requests are, in normal usage, /// localized in chain space.<p /> /// Blocks are stored sequentially. Most blocks are fetched out of a small in-memory cache. The slowest part is /// traversing difficulty transition points, which requires seeking backwards over around 2000 blocks. On a Google /// Nexus S phone this takes a couple of seconds. On a MacBook Pro it takes around 50msec.<p /> /// The store has much room for optimization. Expanding the size of the cache will likely allow us to traverse /// difficulty transitions without using too much memory and without hitting the disk at all, for the case of initial /// block chain download. Storing the hashes on disk would allow us to avoid deserialization and hashing which is /// expensive on Android. /// </remarks> public class BoundedOverheadBlockStore : IBlockStore { private static readonly ILog _log = LogManager.GetLogger(typeof (BoundedOverheadBlockStore)); private const byte _fileFormatVersion = 1; // We keep some recently found blocks in the blockCache. It can help to optimize some cases where we are // looking up blocks we recently stored or requested. When the cache gets too big older entries are deleted. private readonly OrderedDictionary<Sha256Hash, StoredBlock> _blockCache = new OrderedDictionary<Sha256Hash, StoredBlock>(); // Use a separate cache to track get() misses. This is to efficiently handle the case of an unconnected block // during chain download. Each new block will do a get() on the unconnected block so if we haven't seen it yet we // must efficiently respond. // // We don't care about the value in this cache. It is always notFoundMarker. Unfortunately LinkedHashSet does not // provide the removeEldestEntry control. private readonly StoredBlock _notFoundMarker; private readonly OrderedDictionary<Sha256Hash, StoredBlock> _notFoundCache = new OrderedDictionary<Sha256Hash, StoredBlock>(); private Sha256Hash _chainHead; private readonly NetworkParameters _params; private FileStream _channel; private class Record { // A BigInteger representing the total amount of work done so far on this chain. As of May 2011 it takes 8 // bytes to represent this field, so 16 bytes should be plenty for a long time. private const int _chainWorkBytes = 16; private readonly byte[] _emptyBytes = new byte[_chainWorkBytes]; private uint _height; // 4 bytes private readonly byte[] _chainWork; // 16 bytes private readonly byte[] _blockHeader; // 80 bytes public const int Size = 4 + _chainWorkBytes + Block.HeaderSize; public Record() { _height = 0; _chainWork = new byte[_chainWorkBytes]; _blockHeader = new byte[Block.HeaderSize]; } // This should be static but the language does not allow for it. /// <exception cref="System.IO.IOException" /> public void Write(Stream channel, StoredBlock block) { using (var buf = ByteBuffer.Allocate(Size)) { buf.PutInt((int) block.Height); var chainWorkBytes = block.ChainWork.ToByteArray(); Debug.Assert(chainWorkBytes.Length <= _chainWorkBytes, "Ran out of space to store chain work!"); if (chainWorkBytes.Length < _chainWorkBytes) { // Pad to the right size. buf.Put(_emptyBytes, 0, _chainWorkBytes - chainWorkBytes.Length); } buf.Put(chainWorkBytes); buf.Put(block.Header.BitcoinSerialize()); buf.Position = 0; channel.Position = channel.Length; channel.Write(buf.ToArray()); channel.Position = channel.Length - Size; } } /// <exception cref="System.IO.IOException" /> public bool Read(Stream channel, long position, ByteBuffer buffer) { buffer.Position = 0; var originalPos = channel.Position; channel.Position = position; var data = new byte[buffer.Length]; var bytesRead = channel.Read(data); buffer.Clear(); buffer.Write(data); channel.Position = originalPos; if (bytesRead < Size) return false; buffer.Position = 0; _height = (uint) buffer.GetInt(); buffer.Get(_chainWork); buffer.Get(_blockHeader); return true; } public BigInteger ChainWork { get { return new BigInteger(1, _chainWork); } } /// <exception cref="BitCoinSharp.ProtocolException" /> public Block GetHeader(NetworkParameters @params) { return new Block(@params, _blockHeader); } public uint Height { get { return _height; } } /// <exception cref="BitCoinSharp.ProtocolException" /> public StoredBlock ToStoredBlock(NetworkParameters @params) { return new StoredBlock(GetHeader(@params), ChainWork, Height); } } /// <exception cref="BitCoinSharp.BlockStoreException" /> public BoundedOverheadBlockStore(NetworkParameters @params, FileInfo file) { _params = @params; _notFoundMarker = new StoredBlock(null, null, uint.MaxValue); try { Load(file); } catch (IOException e) { _log.Error("failed to load block store from file", e); CreateNewStore(@params, file); } } /// <exception cref="BitCoinSharp.BlockStoreException" /> private void CreateNewStore(NetworkParameters @params, FileInfo file) { // Create a new block store if the file wasn't found or anything went wrong whilst reading. _blockCache.Clear(); try { if (_channel != null) { _channel.Dispose(); _channel = null; } file.Delete(); _channel = file.Create(); // Create fresh. _channel.Write(_fileFormatVersion); } catch (IOException e1) { // We could not load a block store nor could we create a new one! throw new BlockStoreException(e1); } try { // Set up the genesis block. When we start out fresh, it is by definition the top of the chain. var genesis = @params.GenesisBlock.CloneAsHeader(); var storedGenesis = new StoredBlock(genesis, genesis.GetWork(), 0); _chainHead = new Sha256Hash(storedGenesis.Header.Hash); _channel.Write(_chainHead.Hash); Put(storedGenesis); } catch (IOException e) { throw new BlockStoreException(e); } } /// <exception cref="System.IO.IOException" /> /// <exception cref="BitCoinSharp.BlockStoreException" /> private void Load(FileInfo file) { _log.InfoFormat("Reading block store from {0}", file); if (_channel != null) { _channel.Dispose(); } _channel = file.OpenRead(); // Read a version byte. var version = _channel.Read(); if (version == -1) { // No such file or the file was empty. throw new FileNotFoundException(file.Name + " does not exist or is empty"); } if (version != _fileFormatVersion) { throw new BlockStoreException("Bad version number: " + version); } // Chain head pointer is the first thing in the file. var chainHeadHash = new byte[32]; _channel.Read(chainHeadHash); _chainHead = new Sha256Hash(chainHeadHash); _log.InfoFormat("Read chain head from disk: {0}", _chainHead); _channel.Position = _channel.Length - Record.Size; } // TODO: This is ugly, fix! private readonly Record _dummyRecord = new Record(); /// <exception cref="BitCoinSharp.BlockStoreException" /> public void Put(StoredBlock block) { lock (this) { try { var hash = new Sha256Hash(block.Header.Hash); // Append to the end of the file. _dummyRecord.Write(_channel, block); _blockCache[hash] = block; while (_blockCache.Count > 100) { _blockCache.RemoveAt(0); } } catch (IOException e) { throw new BlockStoreException(e); } } } /// <exception cref="BitCoinSharp.BlockStoreException" /> public StoredBlock Get(byte[] hashBytes) { lock (this) { // Check the memory cache first. var hash = new Sha256Hash(hashBytes); StoredBlock fromMem; if (_blockCache.TryGetValue(hash, out fromMem)) { return fromMem; } if (_notFoundCache.TryGetValue(hash, out fromMem) && fromMem == _notFoundMarker) { return null; } try { var fromDisk = GetRecord(hash); StoredBlock block = null; if (fromDisk == null) { _notFoundCache[hash] = _notFoundMarker; while (_notFoundCache.Count > 100) { _notFoundCache.RemoveAt(0); } } else { block = fromDisk.ToStoredBlock(_params); _blockCache[hash] = block; while (_blockCache.Count > 100) { _blockCache.RemoveAt(0); } } return block; } catch (IOException e) { throw new BlockStoreException(e); } catch (ProtocolException e) { throw new BlockStoreException(e); } } } private ByteBuffer _buf = ByteBuffer.Allocate(Record.Size); /// <exception cref="BitCoinSharp.BlockStoreException" /> /// <exception cref="System.IO.IOException" /> /// <exception cref="BitCoinSharp.ProtocolException" /> private Record GetRecord(Sha256Hash hash) { var startPos = _channel.Position; // Use our own file pointer within the tight loop as updating channel positions is really expensive. var pos = startPos; var record = new Record(); do { if (!record.Read(_channel, pos, _buf)) throw new IOException("Failed to read buffer"); if (record.GetHeader(_params).Hash.SequenceEqual(hash.Hash)) { // Found it. Update file position for next time. _channel.Position = pos; return record; } // Did not find it. if (pos == 1 + 32) { // At the start so wrap around to the end. pos = _channel.Length - Record.Size; } else { // Move backwards. pos = pos - Record.Size; Debug.Assert(pos >= 1 + 32, pos.ToString()); } } while (pos != startPos); // Was never stored. _channel.Position = pos; return null; } /// <exception cref="BitCoinSharp.BlockStoreException" /> public StoredBlock GetChainHead() { lock (this) { return Get(_chainHead.Hash); } } /// <exception cref="BitCoinSharp.BlockStoreException" /> public void SetChainHead(StoredBlock chainHead) { lock (this) { try { var hash = chainHead.Header.Hash; _chainHead = new Sha256Hash(hash); // Write out new hash to the first 32 bytes of the file past one (first byte is version number). var originalPos = _channel.Position; _channel.Position = 1; _channel.Write(hash, 0, hash.Length); _channel.Position = originalPos; } catch (IOException e) { throw new BlockStoreException(e); } } } #region IDisposable Members public void Dispose() { if (_channel != null) { _channel.Dispose(); _channel = null; } if (_buf != null) { _buf.Dispose(); _buf = null; } } #endregion } }
using System; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Http.ModelBinding; using System.Web.Security; using Microsoft.AspNet.Identity; using umbraco.cms.businesslogic.packager; using Umbraco.Core; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Models.Identity; using Umbraco.Core.Security; using Umbraco.Core.Services; using Umbraco.Web.Models; using Umbraco.Web.Security; using IUser = Umbraco.Core.Models.Membership.IUser; namespace Umbraco.Web.Editors { internal class PasswordChanger { private readonly ILogger _logger; private readonly IUserService _userService; private readonly HttpContextBase _httpContext; public PasswordChanger(ILogger logger, IUserService userService, HttpContextBase httpContext) { _logger = logger; _userService = userService; _httpContext = httpContext; } /// <summary> /// Changes the password for a user based on the many different rules and config options /// </summary> /// <param name="currentUser">The user performing the password save action</param> /// <param name="savingUser">The user who's password is being changed</param> /// <param name="passwordModel"></param> /// <param name="userMgr"></param> /// <returns></returns> public async Task<Attempt<PasswordChangedModel>> ChangePasswordWithIdentityAsync( IUser currentUser, IUser savingUser, ChangingPasswordModel passwordModel, BackOfficeUserManager<BackOfficeIdentityUser> userMgr) { if (passwordModel == null) throw new ArgumentNullException("passwordModel"); if (userMgr == null) throw new ArgumentNullException("userMgr"); //check if this identity implementation is powered by an underlying membership provider (it will be in most cases) var membershipPasswordHasher = userMgr.PasswordHasher as IMembershipProviderPasswordHasher; //check if this identity implementation is powered by an IUserAwarePasswordHasher (it will be by default in 7.7+ but not for upgrades) var userAwarePasswordHasher = userMgr.PasswordHasher as IUserAwarePasswordHasher<BackOfficeIdentityUser, int>; if (membershipPasswordHasher != null && userAwarePasswordHasher == null) { //if this isn't using an IUserAwarePasswordHasher, then fallback to the old way if (membershipPasswordHasher.MembershipProvider.RequiresQuestionAndAnswer) throw new NotSupportedException("Currently the user editor does not support providers that have RequiresQuestionAndAnswer specified"); return ChangePasswordWithMembershipProvider(savingUser.Username, passwordModel, membershipPasswordHasher.MembershipProvider); } //if we are here, then a IUserAwarePasswordHasher is available, however we cannot proceed in that case if for some odd reason //the user has configured the membership provider to not be hashed. This will actually never occur because the BackOfficeUserManager //will throw if it's not hashed, but we should make sure to check anyways (i.e. in case we want to unit test!) if (membershipPasswordHasher != null && membershipPasswordHasher.MembershipProvider.PasswordFormat != MembershipPasswordFormat.Hashed) { throw new InvalidOperationException("The membership provider cannot have a password format of " + membershipPasswordHasher.MembershipProvider.PasswordFormat + " and be configured with secured hashed passwords"); } //Are we resetting the password?? In ASP.NET Identity APIs, this flag indicates that an admin user is changing another user's password //without knowing the original password. if (passwordModel.Reset.HasValue && passwordModel.Reset.Value) { //if it's the current user, the current user cannot reset their own password if (currentUser.Username == savingUser.Username) { return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Password reset is not allowed", new[] { "resetPassword" }) }); } //if the current user has access to reset/manually change the password if (currentUser.HasSectionAccess(Umbraco.Core.Constants.Applications.Users) == false) { return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("The current user is not authorized", new[] { "resetPassword" }) }); } //ok, we should be able to reset it var resetToken = await userMgr.GeneratePasswordResetTokenAsync(savingUser.Id); var newPass = passwordModel.NewPassword.IsNullOrWhiteSpace() ? userMgr.GeneratePassword() : passwordModel.NewPassword; var resetResult = await userMgr.ResetPasswordAsync(savingUser.Id, resetToken, newPass); if (resetResult.Succeeded == false) { var errors = string.Join(". ", resetResult.Errors); _logger.Warn<PasswordChanger>(string.Format("Could not reset user password {0}", errors)); return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not reset password, errors: " + errors, new[] { "resetPassword" }) }); } return Attempt.Succeed(new PasswordChangedModel()); } //we're not resetting it so we need to try to change it. if (passwordModel.NewPassword.IsNullOrWhiteSpace()) { return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Cannot set an empty password", new[] { "value" }) }); } //we cannot arbitrarily change the password without knowing the old one and no old password was supplied - need to return an error //TODO: What if the current user is admin? We should allow manually changing then? if (passwordModel.OldPassword.IsNullOrWhiteSpace()) { //if password retrieval is not enabled but there is no old password we cannot continue return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Password cannot be changed without the old password", new[] { "oldPassword" }) }); } if (passwordModel.OldPassword.IsNullOrWhiteSpace() == false) { //if an old password is suplied try to change it var changeResult = await userMgr.ChangePasswordAsync(savingUser.Id, passwordModel.OldPassword, passwordModel.NewPassword); if (changeResult.Succeeded == false) { var errors = string.Join(". ", changeResult.Errors); _logger.Warn<PasswordChanger>(string.Format("Could not change user password {0}", errors)); return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password, errors: " + errors, new[] { "oldPassword" }) }); } return Attempt.Succeed(new PasswordChangedModel()); } //We shouldn't really get here return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password, invalid information supplied", new[] { "value" }) }); } /// <summary> /// Changes password for a member/user given the membership provider and the password change model /// </summary> /// <param name="username">The username of the user having their password changed</param> /// <param name="passwordModel"></param> /// <param name="membershipProvider"></param> /// <returns></returns> public Attempt<PasswordChangedModel> ChangePasswordWithMembershipProvider(string username, ChangingPasswordModel passwordModel, MembershipProvider membershipProvider) { // YES! It is completely insane how many options you have to take into account based on the membership provider. yikes! if (passwordModel == null) throw new ArgumentNullException("passwordModel"); if (membershipProvider == null) throw new ArgumentNullException("membershipProvider"); BackOfficeUserManager<BackOfficeIdentityUser> backofficeUserManager = null; var userId = -1; if (membershipProvider.IsUmbracoUsersProvider()) { backofficeUserManager = _httpContext.GetOwinContext().GetBackOfficeUserManager(); if (backofficeUserManager != null) { var profile = _userService.GetProfileByUserName(username); if (profile != null) int.TryParse(profile.Id.ToString(), out userId); } } //Are we resetting the password?? if (passwordModel.Reset.HasValue && passwordModel.Reset.Value) { var canReset = membershipProvider.CanResetPassword(_userService); if (canReset == false) { return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Password reset is not enabled", new[] { "resetPassword" }) }); } if (membershipProvider.RequiresQuestionAndAnswer && passwordModel.Answer.IsNullOrWhiteSpace()) { return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Password reset requires a password answer", new[] { "resetPassword" }) }); } //ok, we should be able to reset it try { var newPass = membershipProvider.ResetPassword( username, membershipProvider.RequiresQuestionAndAnswer ? passwordModel.Answer : null); if (membershipProvider.IsUmbracoUsersProvider() && backofficeUserManager != null && userId >= 0) backofficeUserManager.RaisePasswordResetEvent(userId); //return the generated pword return Attempt.Succeed(new PasswordChangedModel { ResetPassword = newPass }); } catch (Exception ex) { _logger.WarnWithException<PasswordChanger>("Could not reset member password", ex); return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not reset password, error: " + ex.Message + " (see log for full details)", new[] { "resetPassword" }) }); } } //we're not resetting it so we need to try to change it. if (passwordModel.NewPassword.IsNullOrWhiteSpace()) { return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Cannot set an empty password", new[] { "value" }) }); } //This is an edge case and is only necessary for backwards compatibility: var umbracoBaseProvider = membershipProvider as MembershipProviderBase; if (umbracoBaseProvider != null && umbracoBaseProvider.AllowManuallyChangingPassword) { //this provider allows manually changing the password without the old password, so we can just do it try { var result = umbracoBaseProvider.ChangePassword(username, "", passwordModel.NewPassword); return result == false ? Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password, invalid username or password", new[] { "value" }) }) : Attempt.Succeed(new PasswordChangedModel()); } catch (Exception ex) { _logger.WarnWithException<PasswordChanger>("Could not change member password", ex); return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password, error: " + ex.Message + " (see log for full details)", new[] { "value" }) }); } } //The provider does not support manually chaning the password but no old password supplied - need to return an error if (passwordModel.OldPassword.IsNullOrWhiteSpace() && membershipProvider.EnablePasswordRetrieval == false) { //if password retrieval is not enabled but there is no old password we cannot continue return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Password cannot be changed without the old password", new[] { "oldPassword" }) }); } if (passwordModel.OldPassword.IsNullOrWhiteSpace() == false) { //if an old password is suplied try to change it try { var result = membershipProvider.ChangePassword(username, passwordModel.OldPassword, passwordModel.NewPassword); if (result && backofficeUserManager != null && userId >= 0) backofficeUserManager.RaisePasswordChangedEvent(userId); return result == false ? Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password, invalid username or password", new[] { "oldPassword" }) }) : Attempt.Succeed(new PasswordChangedModel()); } catch (Exception ex) { _logger.WarnWithException<PasswordChanger>("Could not change member password", ex); return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password, error: " + ex.Message + " (see log for full details)", new[] { "value" }) }); } } if (membershipProvider.EnablePasswordRetrieval == false) { //we cannot continue if we cannot get the current password return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Password cannot be changed without the old password", new[] { "oldPassword" }) }); } if (membershipProvider.RequiresQuestionAndAnswer && passwordModel.Answer.IsNullOrWhiteSpace()) { //if the question answer is required but there isn't one, we cannot continue return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Password cannot be changed without the password answer", new[] { "value" }) }); } //lets try to get the old one so we can change it try { var oldPassword = membershipProvider.GetPassword( username, membershipProvider.RequiresQuestionAndAnswer ? passwordModel.Answer : null); try { var result = membershipProvider.ChangePassword(username, oldPassword, passwordModel.NewPassword); return result == false ? Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password", new[] { "value" }) }) : Attempt.Succeed(new PasswordChangedModel()); } catch (Exception ex1) { _logger.WarnWithException<PasswordChanger>("Could not change member password", ex1); return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password, error: " + ex1.Message + " (see log for full details)", new[] { "value" }) }); } } catch (Exception ex2) { _logger.WarnWithException<PasswordChanger>("Could not retrieve member password", ex2); return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password, error: " + ex2.Message + " (see log for full details)", new[] { "value" }) }); } } } }
/* * 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.IO; using System.Runtime.Remoting; using System.Runtime.Remoting.Lifetime; using System.Threading; using System.Collections; using System.Collections.Generic; using System.Security.Policy; using System.Reflection; using System.Globalization; using System.Xml; using OpenMetaverse; using log4net; using Nini.Config; using Amib.Threading; using OpenSim.Framework; using OpenSim.Region.CoreModules; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.ScriptEngine.Shared; using OpenSim.Region.ScriptEngine.Shared.Api; using OpenSim.Region.ScriptEngine.Shared.Api.Runtime; using OpenSim.Region.ScriptEngine.Shared.ScriptBase; using OpenSim.Region.ScriptEngine.Shared.CodeTools; using OpenSim.Region.ScriptEngine.Interfaces; namespace OpenSim.Region.ScriptEngine.Shared.Instance { public class ScriptInstance : MarshalByRefObject, IScriptInstance { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IScriptEngine m_Engine; private IScriptWorkItem m_CurrentResult = null; private Queue m_EventQueue = new Queue(32); private bool m_RunEvents = false; private UUID m_ItemID; private uint m_LocalID; private UUID m_ObjectID; private UUID m_AssetID; private IScript m_Script; private UUID m_AppDomain; private DetectParams[] m_DetectParams; private bool m_TimerQueued; private DateTime m_EventStart; private bool m_InEvent; private string m_PrimName; private string m_ScriptName; private string m_Assembly; private int m_StartParam = 0; private string m_CurrentEvent = String.Empty; private bool m_InSelfDelete = false; private int m_MaxScriptQueue; private bool m_SaveState = true; private bool m_ShuttingDown = false; private int m_ControlEventsInQueue = 0; private int m_LastControlLevel = 0; private bool m_CollisionInQueue = false; private TaskInventoryItem m_thisScriptTask; // The following is for setting a minimum delay between events private double m_minEventDelay = 0; private long m_eventDelayTicks = 0; private long m_nextEventTimeTicks = 0; private bool m_startOnInit = true; private UUID m_AttachedAvatar = UUID.Zero; private StateSource m_stateSource; private bool m_postOnRez; private bool m_startedFromSavedState = false; private string m_CurrentState = String.Empty; private UUID m_RegionID = UUID.Zero; private Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> m_LineMap; public Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> LineMap { get { return m_LineMap; } set { m_LineMap = value; } } private Dictionary<string,IScriptApi> m_Apis = new Dictionary<string,IScriptApi>(); // Script state private string m_State="default"; public Object[] PluginData = new Object[0]; /// <summary> /// Used by llMinEventDelay to suppress events happening any faster than this speed. /// This currently restricts all events in one go. Not sure if each event type has /// its own check so take the simple route first. /// </summary> public double MinEventDelay { get { return m_minEventDelay; } set { if (value > 0.001) m_minEventDelay = value; else m_minEventDelay = 0.0; m_eventDelayTicks = (long)(m_minEventDelay * 10000000L); m_nextEventTimeTicks = DateTime.Now.Ticks; } } public bool Running { get { return m_RunEvents; } set { m_RunEvents = value; } } public bool ShuttingDown { get { return m_ShuttingDown; } set { m_ShuttingDown = value; } } public string State { get { return m_State; } set { m_State = value; } } public IScriptEngine Engine { get { return m_Engine; } } public UUID AppDomain { get { return m_AppDomain; } set { m_AppDomain = value; } } public string PrimName { get { return m_PrimName; } } public string ScriptName { get { return m_ScriptName; } } public UUID ItemID { get { return m_ItemID; } } public UUID ObjectID { get { return m_ObjectID; } } public uint LocalID { get { return m_LocalID; } } public UUID AssetID { get { return m_AssetID; } } public Queue EventQueue { get { return m_EventQueue; } } public void ClearQueue() { m_TimerQueued = false; m_EventQueue.Clear(); } public int StartParam { get { return m_StartParam; } set { m_StartParam = value; } } public TaskInventoryItem ScriptTask { get { return m_thisScriptTask; } } public ScriptInstance(IScriptEngine engine, SceneObjectPart part, UUID itemID, UUID assetID, string assembly, AppDomain dom, string primName, string scriptName, int startParam, bool postOnRez, StateSource stateSource, int maxScriptQueue) { m_Engine = engine; m_LocalID = part.LocalId; m_ObjectID = part.UUID; m_ItemID = itemID; m_AssetID = assetID; m_PrimName = primName; m_ScriptName = scriptName; m_Assembly = assembly; m_StartParam = startParam; m_MaxScriptQueue = maxScriptQueue; m_stateSource = stateSource; m_postOnRez = postOnRez; m_AttachedAvatar = part.AttachedAvatar; m_RegionID = part.ParentGroup.Scene.RegionInfo.RegionID; if (part != null) { lock (part.TaskInventory) { if (part.TaskInventory.ContainsKey(m_ItemID)) { m_thisScriptTask = part.TaskInventory[m_ItemID]; } } } ApiManager am = new ApiManager(); foreach (string api in am.GetApis()) { m_Apis[api] = am.CreateApi(api); m_Apis[api].Initialize(engine, part, m_LocalID, itemID); } try { m_Script = (IScript)dom.CreateInstanceAndUnwrap( Path.GetFileNameWithoutExtension(assembly), "SecondLife.Script"); ILease lease = (ILease)RemotingServices.GetLifetimeService(m_Script as ScriptBaseClass); // lease.Register(this); } catch (Exception) { // m_log.ErrorFormat("[Script] Error loading assembly {0}\n"+e.ToString(), assembly); } try { foreach (KeyValuePair<string,IScriptApi> kv in m_Apis) { m_Script.InitApi(kv.Key, kv.Value); } // // m_log.Debug("[Script] Script instance created"); part.SetScriptEvents(m_ItemID, (int)m_Script.GetStateEventFlags(State)); } catch (Exception) { // m_log.Error("[Script] Error loading script instance\n"+e.ToString()); return; } m_SaveState = true; string savedState = Path.Combine(Path.GetDirectoryName(assembly), m_ItemID.ToString() + ".state"); if (File.Exists(savedState)) { string xml = String.Empty; try { FileInfo fi = new FileInfo(savedState); int size=(int)fi.Length; if (size < 512000) { using (FileStream fs = File.Open(savedState, FileMode.Open, FileAccess.Read, FileShare.None)) { System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); Byte[] data = new Byte[size]; fs.Read(data, 0, size); xml = enc.GetString(data); ScriptSerializer.Deserialize(xml, this); AsyncCommandManager.CreateFromData(m_Engine, m_LocalID, m_ItemID, m_ObjectID, PluginData); // m_log.DebugFormat("[Script] Successfully retrieved state for script {0}.{1}", m_PrimName, m_ScriptName); part.SetScriptEvents(m_ItemID, (int)m_Script.GetStateEventFlags(State)); if (m_RunEvents && (!m_ShuttingDown)) { m_RunEvents = false; } else { m_RunEvents = false; m_startOnInit = false; } // we get new rez events on sim restart, too // but if there is state, then we fire the change // event // We loaded state, don't force a re-save m_SaveState = false; m_startedFromSavedState = true; } } else { // m_log.Error("[Script] Unable to load script state: Memory limit exceeded"); } } catch (Exception) { // m_log.ErrorFormat("[Script] Unable to load script state from xml: {0}\n"+e.ToString(), xml); } } else { ScenePresence presence = m_Engine.World.GetScenePresence(part.OwnerID); if (presence != null && (!postOnRez)) presence.ControllingClient.SendAgentAlertMessage("Compile successful", false); // // m_log.ErrorFormat("[Script] Unable to load script state, file not found"); } } public void Init() { if (!m_startOnInit) return; if (m_startedFromSavedState) { Start(); if (m_postOnRez) { PostEvent(new EventParams("on_rez", new Object[] {new LSL_Types.LSLInteger(m_StartParam)}, new DetectParams[0])); } if (m_stateSource == StateSource.AttachedRez) { PostEvent(new EventParams("attach", new object[] { new LSL_Types.LSLString(m_AttachedAvatar.ToString()) }, new DetectParams[0])); } else if (m_stateSource == StateSource.NewRez) { // m_log.Debug("[Script] Posted changed(CHANGED_REGION_RESTART) to script"); PostEvent(new EventParams("changed", new Object[] {new LSL_Types.LSLInteger(256)}, new DetectParams[0])); } else if (m_stateSource == StateSource.PrimCrossing) { // CHANGED_REGION PostEvent(new EventParams("changed", new Object[] {new LSL_Types.LSLInteger(512)}, new DetectParams[0])); } } else { Start(); PostEvent(new EventParams("state_entry", new Object[0], new DetectParams[0])); if (m_postOnRez) { PostEvent(new EventParams("on_rez", new Object[] {new LSL_Types.LSLInteger(m_StartParam)}, new DetectParams[0])); } if (m_stateSource == StateSource.AttachedRez) { PostEvent(new EventParams("attach", new object[] { new LSL_Types.LSLString(m_AttachedAvatar.ToString()) }, new DetectParams[0])); } } } private void ReleaseControls() { SceneObjectPart part = m_Engine.World.GetSceneObjectPart(m_LocalID); if (part != null) { int permsMask; UUID permsGranter; lock (part.TaskInventory) { if (!part.TaskInventory.ContainsKey(m_ItemID)) return; permsGranter = part.TaskInventory[m_ItemID].PermsGranter; permsMask = part.TaskInventory[m_ItemID].PermsMask; } if ((permsMask & ScriptBaseClass.PERMISSION_TAKE_CONTROLS) != 0) { ScenePresence presence = m_Engine.World.GetScenePresence(permsGranter); if (presence != null) presence.UnRegisterControlEventsToScript(m_LocalID, m_ItemID); } } } public void DestroyScriptInstance() { ReleaseControls(); AsyncCommandManager.RemoveScript(m_Engine, m_LocalID, m_ItemID); } public void RemoveState() { string savedState = Path.Combine(Path.GetDirectoryName(m_Assembly), m_ItemID.ToString() + ".state"); try { File.Delete(savedState); } catch(Exception) { } } public void VarDump(Dictionary<string, object> vars) { // m_log.Info("Variable dump for script "+ m_ItemID.ToString()); // foreach (KeyValuePair<string, object> v in vars) // { // m_log.Info("Variable: "+v.Key+" = "+v.Value.ToString()); // } } public void Start() { lock (m_EventQueue) { if (Running) return; m_RunEvents = true; if (m_EventQueue.Count > 0) { if (m_CurrentResult == null) m_CurrentResult = m_Engine.QueueEventHandler(this); // else // m_log.Error("[Script] Tried to start a script that was already queued"); } } } public bool Stop(int timeout) { IScriptWorkItem result; lock (m_EventQueue) { if (!Running) return true; if (m_CurrentResult == null) { m_RunEvents = false; return true; } if (m_CurrentResult.Cancel()) { m_CurrentResult = null; m_RunEvents = false; return true; } result = m_CurrentResult; m_RunEvents = false; } if (result.Wait(new TimeSpan((long)timeout * 100000))) { return true; } lock (m_EventQueue) { result = m_CurrentResult; } if (result == null) return true; if (!m_InSelfDelete) result.Abort(); lock (m_EventQueue) { m_CurrentResult = null; } return true; } public void SetState(string state) { if (state == State) return; PostEvent(new EventParams("state_exit", new Object[0], new DetectParams[0])); PostEvent(new EventParams("state", new Object[] { state }, new DetectParams[0])); PostEvent(new EventParams("state_entry", new Object[0], new DetectParams[0])); throw new EventAbortException(); } public void PostEvent(EventParams data) { // m_log.DebugFormat("[Script] Posted event {2} in state {3} to {0}.{1}", // m_PrimName, m_ScriptName, data.EventName, m_State); if (!Running) return; // If min event delay is set then ignore any events untill the time has expired // This currently only allows 1 event of any type in the given time period. // This may need extending to allow for a time for each individual event type. if (m_eventDelayTicks != 0) { if (DateTime.Now.Ticks < m_nextEventTimeTicks) return; m_nextEventTimeTicks = DateTime.Now.Ticks + m_eventDelayTicks; } lock (m_EventQueue) { if (m_EventQueue.Count >= m_MaxScriptQueue) return; if (data.EventName == "timer") { if (m_TimerQueued) return; m_TimerQueued = true; } if (data.EventName == "control") { int held = ((LSL_Types.LSLInteger)data.Params[1]).value; // int changed = ((LSL_Types.LSLInteger)data.Params[2]).value; // If the last message was a 0 (nothing held) // and this one is also nothing held, drop it // if (m_LastControlLevel == held && held == 0) return; // If there is one or more queued, then queue // only changed ones, else queue unconditionally // if (m_ControlEventsInQueue > 0) { if (m_LastControlLevel == held) return; } m_LastControlLevel = held; m_ControlEventsInQueue++; } if (data.EventName == "collision") { if (m_CollisionInQueue) return; if (data.DetectParams == null) return; m_CollisionInQueue = true; } m_EventQueue.Enqueue(data); if (m_CurrentResult == null) { m_CurrentResult = m_Engine.QueueEventHandler(this); } } } /// <summary> /// Process the next event queued for this script /// </summary> /// <returns></returns> public object EventProcessor() { lock (m_Script) { EventParams data = null; lock (m_EventQueue) { data = (EventParams) m_EventQueue.Dequeue(); if (data == null) // Shouldn't happen { if ((m_EventQueue.Count > 0) && m_RunEvents && (!m_ShuttingDown)) { m_CurrentResult = m_Engine.QueueEventHandler(this); } else { m_CurrentResult = null; } return 0; } if (data.EventName == "timer") m_TimerQueued = false; if (data.EventName == "control") { if (m_ControlEventsInQueue > 0) m_ControlEventsInQueue--; } if (data.EventName == "collision") m_CollisionInQueue = false; } //m_log.DebugFormat("[XENGINE]: Processing event {0} for {1}", data.EventName, this); m_DetectParams = data.DetectParams; if (data.EventName == "state") // Hardcoded state change { // m_log.DebugFormat("[Script] Script {0}.{1} state set to {2}", // m_PrimName, m_ScriptName, data.Params[0].ToString()); m_State=data.Params[0].ToString(); AsyncCommandManager.RemoveScript(m_Engine, m_LocalID, m_ItemID); SceneObjectPart part = m_Engine.World.GetSceneObjectPart( m_LocalID); if (part != null) { part.SetScriptEvents(m_ItemID, (int)m_Script.GetStateEventFlags(State)); } } else { if (m_Engine.World.PipeEventsForScript(m_LocalID) || data.EventName == "control") // Don't freeze avies! { SceneObjectPart part = m_Engine.World.GetSceneObjectPart( m_LocalID); // m_log.DebugFormat("[Script] Delivered event {2} in state {3} to {0}.{1}", // m_PrimName, m_ScriptName, data.EventName, m_State); try { m_CurrentEvent = data.EventName; m_EventStart = DateTime.Now; m_InEvent = true; m_Script.ExecuteEvent(State, data.EventName, data.Params); m_InEvent = false; m_CurrentEvent = String.Empty; if (m_SaveState) { // This will be the very first event we deliver // (state_entry) in default state // SaveState(m_Assembly); m_SaveState = false; } } catch (Exception e) { // m_log.DebugFormat("[SCRIPT] Exception: {0}", e.Message); m_InEvent = false; m_CurrentEvent = String.Empty; if ((!(e is TargetInvocationException) || (!(e.InnerException is SelfDeleteException) && !(e.InnerException is ScriptDeleteException))) && !(e is ThreadAbortException)) { try { // DISPLAY ERROR INWORLD string text = FormatException(e); if (text.Length > 1000) text = text.Substring(0, 1000); m_Engine.World.SimChat(Utils.StringToBytes(text), ChatTypeEnum.DebugChannel, 2147483647, part.AbsolutePosition, part.Name, part.UUID, false); } catch (Exception) { } // catch (Exception e2) // LEGIT: User Scripting // { // m_log.Error("[SCRIPT]: "+ // "Error displaying error in-world: " + // e2.ToString()); // m_log.Error("[SCRIPT]: " + // "Errormessage: Error compiling script:\r\n" + // e.ToString()); // } } else if ((e is TargetInvocationException) && (e.InnerException is SelfDeleteException)) { m_InSelfDelete = true; if (part != null && part.ParentGroup != null) m_Engine.World.DeleteSceneObject(part.ParentGroup, false); } else if ((e is TargetInvocationException) && (e.InnerException is ScriptDeleteException)) { m_InSelfDelete = true; if (part != null && part.ParentGroup != null) part.Inventory.RemoveInventoryItem(m_ItemID); } } } } lock (m_EventQueue) { if ((m_EventQueue.Count > 0) && m_RunEvents && (!m_ShuttingDown)) { m_CurrentResult = m_Engine.QueueEventHandler(this); } else { m_CurrentResult = null; } } m_DetectParams = null; return 0; } } public int EventTime() { if (!m_InEvent) return 0; return (DateTime.Now - m_EventStart).Seconds; } public void ResetScript() { if (m_Script == null) return; bool running = Running; RemoveState(); ReleaseControls(); Stop(0); SceneObjectPart part=m_Engine.World.GetSceneObjectPart(m_LocalID); part.Inventory.GetInventoryItem(m_ItemID).PermsMask = 0; part.Inventory.GetInventoryItem(m_ItemID).PermsGranter = UUID.Zero; AsyncCommandManager.RemoveScript(m_Engine, m_LocalID, m_ItemID); m_EventQueue.Clear(); m_Script.ResetVars(); m_State = "default"; part.SetScriptEvents(m_ItemID, (int)m_Script.GetStateEventFlags(State)); if (running) Start(); m_SaveState = true; PostEvent(new EventParams("state_entry", new Object[0], new DetectParams[0])); } public void ApiResetScript() { // bool running = Running; RemoveState(); ReleaseControls(); m_Script.ResetVars(); SceneObjectPart part=m_Engine.World.GetSceneObjectPart(m_LocalID); part.Inventory.GetInventoryItem(m_ItemID).PermsMask = 0; part.Inventory.GetInventoryItem(m_ItemID).PermsGranter = UUID.Zero; AsyncCommandManager.RemoveScript(m_Engine, m_LocalID, m_ItemID); m_EventQueue.Clear(); m_Script.ResetVars(); m_State = "default"; part.SetScriptEvents(m_ItemID, (int)m_Script.GetStateEventFlags(State)); if (m_CurrentEvent != "state_entry") { m_SaveState = true; PostEvent(new EventParams("state_entry", new Object[0], new DetectParams[0])); throw new EventAbortException(); } } public Dictionary<string, object> GetVars() { return m_Script.GetVars(); } public void SetVars(Dictionary<string, object> vars) { m_Script.SetVars(vars); } public DetectParams GetDetectParams(int idx) { if (m_DetectParams == null) return null; if (idx < 0 || idx >= m_DetectParams.Length) return null; return m_DetectParams[idx]; } public UUID GetDetectID(int idx) { if (m_DetectParams == null) return UUID.Zero; if (idx < 0 || idx >= m_DetectParams.Length) return UUID.Zero; return m_DetectParams[idx].Key; } public void SaveState(string assembly) { // If we're currently in an event, just tell it to save upon return // if (m_InEvent) { m_SaveState = true; return; } PluginData = AsyncCommandManager.GetSerializationData(m_Engine, m_ItemID); string xml = ScriptSerializer.Serialize(this); if (m_CurrentState != xml) { try { FileStream fs = File.Create(Path.Combine(Path.GetDirectoryName(assembly), m_ItemID.ToString() + ".state")); System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); Byte[] buf = enc.GetBytes(xml); fs.Write(buf, 0, buf.Length); fs.Close(); } catch(Exception) { // m_log.Error("Unable to save xml\n"+e.ToString()); } //if (!File.Exists(Path.Combine(Path.GetDirectoryName(assembly), m_ItemID.ToString() + ".state"))) //{ // throw new Exception("Completed persistence save, but no file was created"); //} m_CurrentState = xml; } } public IScriptApi GetApi(string name) { if (m_Apis.ContainsKey(name)) return m_Apis[name]; return null; } public override string ToString() { return String.Format("{0} {1} on {2}", m_ScriptName, m_ItemID, m_PrimName); } string FormatException(Exception e) { if (e.InnerException == null) // Not a normal runtime error return e.ToString(); string message = "Runtime error:\n" + e.InnerException.StackTrace; string[] lines = message.Split(new char[] {'\n'}); foreach (string line in lines) { if (line.Contains("SecondLife.Script")) { int idx = line.IndexOf(':'); if (idx != -1) { string val = line.Substring(idx+1); int lineNum = 0; if (int.TryParse(val, out lineNum)) { KeyValuePair<int, int> pos = Compiler.FindErrorPosition( lineNum, 0, LineMap); int scriptLine = pos.Key; int col = pos.Value; if (scriptLine == 0) scriptLine++; if (col == 0) col++; message = string.Format("Runtime error:\n" + "Line ({0}): {1}", scriptLine - 1, e.InnerException.Message); System.Console.WriteLine(e.ToString()+"\n"); return message; } } } } // m_log.ErrorFormat("Scripting exception:"); // m_log.ErrorFormat(e.ToString()); return e.ToString(); } public string GetAssemblyName() { return m_Assembly; } public string GetXMLState() { bool run = Running; Stop(100); Running = run; // We should not be doing this, but since we are about to // dispose this, it really doesn't make a difference // This is meant to work around a Windows only race // m_InEvent = false; // Force an update of the in-memory plugin data // PluginData = AsyncCommandManager.GetSerializationData(m_Engine, m_ItemID); return ScriptSerializer.Serialize(this); } public UUID RegionID { get { return m_RegionID; } } public bool CanBeDeleted() { return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Reflection.Internal; namespace System.Reflection.Metadata.Ecma335 { internal struct DocumentTableReader { internal readonly int NumberOfRows; private readonly bool _isGuidHeapRefSizeSmall; private readonly bool _isBlobHeapRefSizeSmall; private const int NameOffset = 0; private readonly int _hashAlgorithmOffset; private readonly int _hashOffset; private readonly int _languageOffset; internal readonly int RowSize; internal readonly MemoryBlock Block; internal DocumentTableReader( int numberOfRows, int guidHeapRefSize, int blobHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) { NumberOfRows = numberOfRows; _isGuidHeapRefSizeSmall = guidHeapRefSize == 2; _isBlobHeapRefSizeSmall = blobHeapRefSize == 2; _hashAlgorithmOffset = NameOffset + blobHeapRefSize; _hashOffset = _hashAlgorithmOffset + guidHeapRefSize; _languageOffset = _hashOffset + blobHeapRefSize; RowSize = _languageOffset + guidHeapRefSize; Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); } internal DocumentNameBlobHandle GetName(DocumentHandle handle) { int rowOffset = (handle.RowId - 1) * RowSize; return DocumentNameBlobHandle.FromOffset(Block.PeekHeapReference(rowOffset + NameOffset, _isBlobHeapRefSizeSmall)); } internal GuidHandle GetHashAlgorithm(DocumentHandle handle) { int rowOffset = (handle.RowId - 1) * RowSize; return GuidHandle.FromIndex(Block.PeekHeapReference(rowOffset + _hashAlgorithmOffset, _isGuidHeapRefSizeSmall)); } internal BlobHandle GetHash(DocumentHandle handle) { int rowOffset = (handle.RowId - 1) * RowSize; return BlobHandle.FromOffset(Block.PeekHeapReference(rowOffset + _hashOffset, _isBlobHeapRefSizeSmall)); } internal GuidHandle GetLanguage(DocumentHandle handle) { int rowOffset = (handle.RowId - 1) * RowSize; return GuidHandle.FromIndex(Block.PeekHeapReference(rowOffset + _languageOffset, _isGuidHeapRefSizeSmall)); } } internal struct MethodDebugInformationTableReader { internal readonly int NumberOfRows; private readonly bool _isDocumentRefSmall; private readonly bool _isBlobHeapRefSizeSmall; private const int DocumentOffset = 0; private readonly int _sequencePointsOffset; internal readonly int RowSize; internal readonly MemoryBlock Block; internal MethodDebugInformationTableReader( int numberOfRows, int documentRefSize, int blobHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) { NumberOfRows = numberOfRows; _isDocumentRefSmall = documentRefSize == 2; _isBlobHeapRefSizeSmall = blobHeapRefSize == 2; _sequencePointsOffset = DocumentOffset + documentRefSize; RowSize = _sequencePointsOffset + blobHeapRefSize; Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); } internal DocumentHandle GetDocument(MethodDebugInformationHandle handle) { int rowOffset = (handle.RowId - 1) * RowSize; return DocumentHandle.FromRowId(Block.PeekReference(rowOffset + DocumentOffset, _isDocumentRefSmall)); } internal BlobHandle GetSequencePoints(MethodDebugInformationHandle handle) { int rowOffset = (handle.RowId - 1) * RowSize; return BlobHandle.FromOffset(Block.PeekHeapReference(rowOffset + _sequencePointsOffset, _isBlobHeapRefSizeSmall)); } } internal struct LocalScopeTableReader { internal readonly int NumberOfRows; private readonly bool _isMethodRefSmall; private readonly bool _isImportScopeRefSmall; private readonly bool _isLocalConstantRefSmall; private readonly bool _isLocalVariableRefSmall; private const int MethodOffset = 0; private readonly int _importScopeOffset; private readonly int _variableListOffset; private readonly int _constantListOffset; private readonly int _startOffsetOffset; private readonly int _lengthOffset; internal readonly int RowSize; internal readonly MemoryBlock Block; internal LocalScopeTableReader( int numberOfRows, bool declaredSorted, int methodRefSize, int importScopeRefSize, int localVariableRefSize, int localConstantRefSize, MemoryBlock containingBlock, int containingBlockOffset) { NumberOfRows = numberOfRows; _isMethodRefSmall = methodRefSize == 2; _isImportScopeRefSmall = importScopeRefSize == 2; _isLocalVariableRefSmall = localVariableRefSize == 2; _isLocalConstantRefSmall = localConstantRefSize == 2; _importScopeOffset = MethodOffset + methodRefSize; _variableListOffset = _importScopeOffset + importScopeRefSize; _constantListOffset = _variableListOffset + localVariableRefSize; _startOffsetOffset = _constantListOffset + localConstantRefSize; _lengthOffset = _startOffsetOffset + sizeof(uint); RowSize = _lengthOffset + sizeof(uint); Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); if (numberOfRows > 0 && !declaredSorted) { Throw.TableNotSorted(TableIndex.LocalScope); } } internal MethodDefinitionHandle GetMethod(int rowId) { int rowOffset = (rowId - 1) * RowSize; return MethodDefinitionHandle.FromRowId(Block.PeekReference(rowOffset + MethodOffset, _isMethodRefSmall)); } internal ImportScopeHandle GetImportScope(LocalScopeHandle handle) { int rowOffset = (handle.RowId - 1) * RowSize; return ImportScopeHandle.FromRowId(Block.PeekReference(rowOffset + _importScopeOffset, _isImportScopeRefSmall)); } internal int GetVariableStart(int rowId) { int rowOffset = (rowId - 1) * RowSize; return Block.PeekReference(rowOffset + _variableListOffset, _isLocalVariableRefSmall); } internal int GetConstantStart(int rowId) { int rowOffset = (rowId - 1) * RowSize; return Block.PeekReference(rowOffset + _constantListOffset, _isLocalConstantRefSmall); } internal int GetStartOffset(int rowId) { int rowOffset = (rowId - 1) * RowSize; return Block.PeekInt32(rowOffset + _startOffsetOffset); } internal int GetLength(int rowId) { int rowOffset = (rowId - 1) * RowSize; return Block.PeekInt32(rowOffset + _lengthOffset); } internal int GetEndOffset(int rowId) { int rowOffset = (rowId - 1) * RowSize; long result = Block.PeekUInt32(rowOffset + _startOffsetOffset) + Block.PeekUInt32(rowOffset + _lengthOffset); if (unchecked((int)result) != result) { MemoryBlock.ThrowValueOverflow(); } return (int)result; } internal void GetLocalScopeRange(int methodDefRid, out int firstScopeRowId, out int lastScopeRowId) { int startRowNumber, endRowNumber; Block.BinarySearchReferenceRange( NumberOfRows, RowSize, MethodOffset, (uint)methodDefRid, _isMethodRefSmall, out startRowNumber, out endRowNumber ); if (startRowNumber == -1) { firstScopeRowId = 1; lastScopeRowId = 0; } else { firstScopeRowId = startRowNumber + 1; lastScopeRowId = endRowNumber + 1; } } } internal struct LocalVariableTableReader { internal readonly int NumberOfRows; private readonly bool _isStringHeapRefSizeSmall; private readonly int _attributesOffset; private readonly int _indexOffset; private readonly int _nameOffset; internal readonly int RowSize; internal readonly MemoryBlock Block; internal LocalVariableTableReader( int numberOfRows, int stringHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset ) { NumberOfRows = numberOfRows; _isStringHeapRefSizeSmall = stringHeapRefSize == 2; _attributesOffset = 0; _indexOffset = _attributesOffset + sizeof(ushort); _nameOffset = _indexOffset + sizeof(ushort); RowSize = _nameOffset + stringHeapRefSize; Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); } internal LocalVariableAttributes GetAttributes(LocalVariableHandle handle) { int rowOffset = (handle.RowId - 1) * RowSize; return (LocalVariableAttributes)Block.PeekUInt16(rowOffset + _attributesOffset); } internal ushort GetIndex(LocalVariableHandle handle) { int rowOffset = (handle.RowId - 1) * RowSize; return Block.PeekUInt16(rowOffset + _indexOffset); } internal StringHandle GetName(LocalVariableHandle handle) { int rowOffset = (handle.RowId - 1) * RowSize; return StringHandle.FromOffset(Block.PeekHeapReference(rowOffset + _nameOffset, _isStringHeapRefSizeSmall)); } } internal struct LocalConstantTableReader { internal readonly int NumberOfRows; private readonly bool _isStringHeapRefSizeSmall; private readonly bool _isBlobHeapRefSizeSmall; private const int NameOffset = 0; private readonly int _signatureOffset; internal readonly int RowSize; internal readonly MemoryBlock Block; internal LocalConstantTableReader( int numberOfRows, int stringHeapRefSize, int blobHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) { NumberOfRows = numberOfRows; _isStringHeapRefSizeSmall = stringHeapRefSize == 2; _isBlobHeapRefSizeSmall = blobHeapRefSize == 2; _signatureOffset = NameOffset + stringHeapRefSize; RowSize = _signatureOffset + blobHeapRefSize; Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); } internal StringHandle GetName(LocalConstantHandle handle) { int rowOffset = (handle.RowId - 1) * RowSize; return StringHandle.FromOffset(Block.PeekHeapReference(rowOffset + NameOffset, _isStringHeapRefSizeSmall)); } internal BlobHandle GetSignature(LocalConstantHandle handle) { int rowOffset = (handle.RowId - 1) * RowSize; return BlobHandle.FromOffset(Block.PeekHeapReference(rowOffset + _signatureOffset, _isBlobHeapRefSizeSmall)); } } internal struct StateMachineMethodTableReader { internal readonly int NumberOfRows; private readonly bool _isMethodRefSizeSmall; private const int MoveNextMethodOffset = 0; private readonly int _kickoffMethodOffset; internal readonly int RowSize; internal readonly MemoryBlock Block; internal StateMachineMethodTableReader( int numberOfRows, bool declaredSorted, int methodRefSize, MemoryBlock containingBlock, int containingBlockOffset) { NumberOfRows = numberOfRows; _isMethodRefSizeSmall = methodRefSize == 2; _kickoffMethodOffset = methodRefSize; RowSize = _kickoffMethodOffset + methodRefSize; Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); if (numberOfRows > 0 && !declaredSorted) { Throw.TableNotSorted(TableIndex.StateMachineMethod); } } internal MethodDefinitionHandle FindKickoffMethod(int moveNextMethodRowId) { int foundRowNumber = this.Block.BinarySearchReference( this.NumberOfRows, this.RowSize, MoveNextMethodOffset, (uint)moveNextMethodRowId, _isMethodRefSizeSmall); if (foundRowNumber < 0) { return default(MethodDefinitionHandle); } return GetKickoffMethod(foundRowNumber + 1); } private MethodDefinitionHandle GetKickoffMethod(int rowId) { int rowOffset = (rowId - 1) * RowSize; return MethodDefinitionHandle.FromRowId(Block.PeekReference(rowOffset + _kickoffMethodOffset, _isMethodRefSizeSmall)); } } internal struct ImportScopeTableReader { internal readonly int NumberOfRows; private readonly bool _isImportScopeRefSizeSmall; private readonly bool _isBlobHeapRefSizeSmall; private const int ParentOffset = 0; private readonly int _importsOffset; internal readonly int RowSize; internal readonly MemoryBlock Block; internal ImportScopeTableReader( int numberOfRows, int importScopeRefSize, int blobHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) { NumberOfRows = numberOfRows; _isImportScopeRefSizeSmall = importScopeRefSize == 2; _isBlobHeapRefSizeSmall = blobHeapRefSize == 2; _importsOffset = ParentOffset + importScopeRefSize; RowSize = _importsOffset + blobHeapRefSize; Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); } internal ImportScopeHandle GetParent(ImportScopeHandle handle) { int rowOffset = (handle.RowId - 1) * RowSize; return ImportScopeHandle.FromRowId(Block.PeekReference(rowOffset + ParentOffset, _isImportScopeRefSizeSmall)); } internal BlobHandle GetImports(ImportScopeHandle handle) { int rowOffset = (handle.RowId - 1) * RowSize; return BlobHandle.FromOffset(Block.PeekHeapReference(rowOffset + _importsOffset, _isBlobHeapRefSizeSmall)); } } internal struct CustomDebugInformationTableReader { internal readonly int NumberOfRows; private readonly bool _isHasCustomDebugInformationRefSizeSmall; private readonly bool _isGuidHeapRefSizeSmall; private readonly bool _isBlobHeapRefSizeSmall; private const int ParentOffset = 0; private readonly int _kindOffset; private readonly int _valueOffset; internal readonly int RowSize; internal readonly MemoryBlock Block; internal CustomDebugInformationTableReader( int numberOfRows, bool declaredSorted, int hasCustomDebugInformationRefSize, int guidHeapRefSize, int blobHeapRefSize, MemoryBlock containingBlock, int containingBlockOffset) { NumberOfRows = numberOfRows; _isHasCustomDebugInformationRefSizeSmall = hasCustomDebugInformationRefSize == 2; _isGuidHeapRefSizeSmall = guidHeapRefSize == 2; _isBlobHeapRefSizeSmall = blobHeapRefSize == 2; _kindOffset = ParentOffset + hasCustomDebugInformationRefSize; _valueOffset = _kindOffset + guidHeapRefSize; RowSize = _valueOffset + blobHeapRefSize; Block = containingBlock.GetMemoryBlockAt(containingBlockOffset, RowSize * numberOfRows); if (numberOfRows > 0 && !declaredSorted) { Throw.TableNotSorted(TableIndex.CustomDebugInformation); } } internal EntityHandle GetParent(CustomDebugInformationHandle handle) { int rowOffset = (handle.RowId - 1) * RowSize; return HasCustomDebugInformationTag.ConvertToHandle(Block.PeekTaggedReference(rowOffset + ParentOffset, _isHasCustomDebugInformationRefSizeSmall)); } internal GuidHandle GetKind(CustomDebugInformationHandle handle) { int rowOffset = (handle.RowId - 1) * RowSize; return GuidHandle.FromIndex(Block.PeekHeapReference(rowOffset + _kindOffset, _isGuidHeapRefSizeSmall)); } internal BlobHandle GetValue(CustomDebugInformationHandle handle) { int rowOffset = (handle.RowId - 1) * RowSize; return BlobHandle.FromOffset(Block.PeekHeapReference(rowOffset + _valueOffset, _isBlobHeapRefSizeSmall)); } internal void GetRange(EntityHandle parentHandle, out int firstImplRowId, out int lastImplRowId) { int startRowNumber, endRowNumber; Block.BinarySearchReferenceRange( NumberOfRows, RowSize, ParentOffset, HasCustomDebugInformationTag.ConvertToTag(parentHandle), _isHasCustomDebugInformationRefSizeSmall, out startRowNumber, out endRowNumber ); if (startRowNumber == -1) { firstImplRowId = 1; lastImplRowId = 0; } else { firstImplRowId = startRowNumber + 1; lastImplRowId = endRowNumber + 1; } } private bool CheckSorted() { return Block.IsOrderedByReferenceAscending(RowSize, ParentOffset, _isHasCustomDebugInformationRefSizeSmall); } } }
// Copyright (c) 2009 David Koontz // Please direct any bugs/comments/suggestions to david@koontzfamily.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 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 UnityEngine; public class EventParamMappings { public static Dictionary<iTweenEvent.TweenType, Dictionary<string, Type>> mappings = new Dictionary<iTweenEvent.TweenType, Dictionary<string, Type>>(); static EventParamMappings() { // AUDIO FROM mappings.Add(iTweenEvent.TweenType.AudioFrom, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.AudioFrom]["audiosource"] = typeof(AudioSource); mappings[iTweenEvent.TweenType.AudioFrom]["volume"] = typeof(float); mappings[iTweenEvent.TweenType.AudioFrom]["pitch"] = typeof(float); mappings[iTweenEvent.TweenType.AudioFrom]["time"] = typeof(float); mappings[iTweenEvent.TweenType.AudioFrom]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.AudioFrom]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.AudioFrom]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.AudioFrom]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.AudioFrom]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.AudioFrom]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.AudioFrom]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.AudioFrom]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.AudioFrom]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.AudioFrom]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.AudioFrom]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.AudioFrom]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.AudioFrom]["ignoretimescale"] = typeof(bool); // AUDIO TO mappings.Add(iTweenEvent.TweenType.AudioTo, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.AudioTo]["audiosource"] = typeof(AudioSource); mappings[iTweenEvent.TweenType.AudioTo]["volume"] = typeof(float); mappings[iTweenEvent.TweenType.AudioTo]["pitch"] = typeof(float); mappings[iTweenEvent.TweenType.AudioTo]["time"] = typeof(float); mappings[iTweenEvent.TweenType.AudioTo]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.AudioTo]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.AudioTo]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.AudioTo]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.AudioTo]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.AudioTo]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.AudioTo]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.AudioTo]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.AudioTo]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.AudioTo]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.AudioTo]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.AudioTo]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.AudioTo]["ignoretimescale"] = typeof(bool); // AUDIO UPDATE mappings.Add(iTweenEvent.TweenType.AudioUpdate, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.AudioUpdate]["audiosource"] = typeof(AudioSource); mappings[iTweenEvent.TweenType.AudioUpdate]["volume"] = typeof(float); mappings[iTweenEvent.TweenType.AudioUpdate]["pitch"] = typeof(float); mappings[iTweenEvent.TweenType.AudioUpdate]["time"] = typeof(float); // CAMERA FADE FROM mappings.Add(iTweenEvent.TweenType.CameraFadeFrom, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.CameraFadeFrom]["amount"] = typeof(float); mappings[iTweenEvent.TweenType.CameraFadeFrom]["time"] = typeof(float); mappings[iTweenEvent.TweenType.CameraFadeFrom]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.CameraFadeFrom]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.CameraFadeFrom]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.CameraFadeFrom]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.CameraFadeFrom]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.CameraFadeFrom]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.CameraFadeFrom]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.CameraFadeFrom]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.CameraFadeFrom]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.CameraFadeFrom]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.CameraFadeFrom]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.CameraFadeFrom]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.CameraFadeFrom]["ignoretimescale"] = typeof(bool); // CAMERA FADE TO mappings.Add(iTweenEvent.TweenType.CameraFadeTo, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.CameraFadeTo]["amount"] = typeof(float); mappings[iTweenEvent.TweenType.CameraFadeTo]["time"] = typeof(float); mappings[iTweenEvent.TweenType.CameraFadeTo]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.CameraFadeTo]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.CameraFadeTo]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.CameraFadeTo]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.CameraFadeTo]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.CameraFadeTo]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.CameraFadeTo]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.CameraFadeTo]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.CameraFadeTo]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.CameraFadeTo]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.CameraFadeTo]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.CameraFadeTo]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.CameraFadeTo]["ignoretimescale"] = typeof(bool); // COLOR FROM mappings.Add(iTweenEvent.TweenType.ColorFrom, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.ColorFrom]["color"] = typeof(Color); mappings[iTweenEvent.TweenType.ColorFrom]["r"] = typeof(float); mappings[iTweenEvent.TweenType.ColorFrom]["g"] = typeof(float); mappings[iTweenEvent.TweenType.ColorFrom]["b"] = typeof(float); mappings[iTweenEvent.TweenType.ColorFrom]["a"] = typeof(float); mappings[iTweenEvent.TweenType.ColorFrom]["namedcolorvalue"] = typeof(string); mappings[iTweenEvent.TweenType.ColorFrom]["includechildren"] = typeof(bool); mappings[iTweenEvent.TweenType.ColorFrom]["time"] = typeof(float); mappings[iTweenEvent.TweenType.ColorFrom]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.ColorFrom]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.ColorFrom]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.ColorFrom]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.ColorFrom]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ColorFrom]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.ColorFrom]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.ColorFrom]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ColorFrom]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.ColorFrom]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.ColorFrom]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ColorFrom]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.ColorFrom]["ignoretimescale"] = typeof(bool); // COLOR TO mappings.Add(iTweenEvent.TweenType.ColorTo, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.ColorTo]["color"] = typeof(Color); mappings[iTweenEvent.TweenType.ColorTo]["r"] = typeof(float); mappings[iTweenEvent.TweenType.ColorTo]["g"] = typeof(float); mappings[iTweenEvent.TweenType.ColorTo]["b"] = typeof(float); mappings[iTweenEvent.TweenType.ColorTo]["a"] = typeof(float); mappings[iTweenEvent.TweenType.ColorTo]["namedcolorvalue"] = typeof(string); mappings[iTweenEvent.TweenType.ColorTo]["includechildren"] = typeof(bool); mappings[iTweenEvent.TweenType.ColorTo]["time"] = typeof(float); mappings[iTweenEvent.TweenType.ColorTo]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.ColorTo]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.ColorTo]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.ColorTo]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.ColorTo]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ColorTo]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.ColorTo]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.ColorTo]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ColorTo]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.ColorTo]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.ColorTo]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ColorTo]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.ColorTo]["ignoretimescale"] = typeof(bool); // COLOR UPDATE mappings.Add(iTweenEvent.TweenType.ColorUpdate, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.ColorUpdate]["color"] = typeof(Color); mappings[iTweenEvent.TweenType.ColorUpdate]["r"] = typeof(float); mappings[iTweenEvent.TweenType.ColorUpdate]["g"] = typeof(float); mappings[iTweenEvent.TweenType.ColorUpdate]["b"] = typeof(float); mappings[iTweenEvent.TweenType.ColorUpdate]["a"] = typeof(float); mappings[iTweenEvent.TweenType.ColorUpdate]["namedcolorvalue"] = typeof(string); mappings[iTweenEvent.TweenType.ColorUpdate]["includechildren"] = typeof(bool); mappings[iTweenEvent.TweenType.ColorUpdate]["time"] = typeof(float); // FADE FROM mappings.Add(iTweenEvent.TweenType.FadeFrom, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.FadeFrom]["alpha"] = typeof(float); mappings[iTweenEvent.TweenType.FadeFrom]["amount"] = typeof(float); mappings[iTweenEvent.TweenType.FadeFrom]["includechildren"] = typeof(bool); mappings[iTweenEvent.TweenType.FadeFrom]["time"] = typeof(float); mappings[iTweenEvent.TweenType.FadeFrom]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.FadeFrom]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.FadeFrom]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.FadeFrom]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.FadeFrom]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.FadeFrom]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.FadeFrom]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.FadeFrom]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.FadeFrom]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.FadeFrom]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.FadeFrom]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.FadeFrom]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.FadeFrom]["ignoretimescale"] = typeof(bool); // FADE TO mappings.Add(iTweenEvent.TweenType.FadeTo, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.FadeTo]["alpha"] = typeof(float); mappings[iTweenEvent.TweenType.FadeTo]["amount"] = typeof(float); mappings[iTweenEvent.TweenType.FadeTo]["includechildren"] = typeof(bool); mappings[iTweenEvent.TweenType.FadeTo]["time"] = typeof(float); mappings[iTweenEvent.TweenType.FadeTo]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.FadeTo]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.FadeTo]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.FadeTo]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.FadeTo]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.FadeTo]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.FadeTo]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.FadeTo]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.FadeTo]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.FadeTo]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.FadeTo]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.FadeTo]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.FadeTo]["ignoretimescale"] = typeof(bool); // FADE UPDATE mappings.Add(iTweenEvent.TweenType.FadeUpdate, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.FadeUpdate]["alpha"] = typeof(float); mappings[iTweenEvent.TweenType.FadeUpdate]["includechildren"] = typeof(bool); mappings[iTweenEvent.TweenType.FadeUpdate]["time"] = typeof(float); // LOOK FROM mappings.Add(iTweenEvent.TweenType.LookFrom, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.LookFrom]["looktarget"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.LookFrom]["axis"] = typeof(string); mappings[iTweenEvent.TweenType.LookFrom]["time"] = typeof(float); mappings[iTweenEvent.TweenType.LookFrom]["speed"] = typeof(float); mappings[iTweenEvent.TweenType.LookFrom]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.LookFrom]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.LookFrom]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.LookFrom]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.LookFrom]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.LookFrom]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.LookFrom]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.LookFrom]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.LookFrom]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.LookFrom]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.LookFrom]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.LookFrom]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.LookFrom]["ignoretimescale"] = typeof(bool); // LOOK TO mappings.Add(iTweenEvent.TweenType.LookTo, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.LookTo]["looktarget"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.LookTo]["axis"] = typeof(string); mappings[iTweenEvent.TweenType.LookTo]["time"] = typeof(float); mappings[iTweenEvent.TweenType.LookTo]["speed"] = typeof(float); mappings[iTweenEvent.TweenType.LookTo]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.LookTo]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.LookTo]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.LookTo]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.LookTo]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.LookTo]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.LookTo]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.LookTo]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.LookTo]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.LookTo]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.LookTo]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.LookTo]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.LookTo]["ignoretimescale"] = typeof(bool); // LOOK UPDATE mappings.Add(iTweenEvent.TweenType.LookUpdate, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.LookUpdate]["looktarget"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.LookUpdate]["axis"] = typeof(string); mappings[iTweenEvent.TweenType.LookUpdate]["time"] = typeof(float); // MOVE ADD mappings.Add(iTweenEvent.TweenType.MoveAdd, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.MoveAdd]["amount"] = typeof(Vector3); mappings[iTweenEvent.TweenType.MoveAdd]["x"] = typeof(float); mappings[iTweenEvent.TweenType.MoveAdd]["y"] = typeof(float); mappings[iTweenEvent.TweenType.MoveAdd]["z"] = typeof(float); mappings[iTweenEvent.TweenType.MoveAdd]["orienttopath"] = typeof(bool); mappings[iTweenEvent.TweenType.MoveAdd]["looktarget"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.MoveAdd]["looktime"] = typeof(float); mappings[iTweenEvent.TweenType.MoveAdd]["axis"] = typeof(string); mappings[iTweenEvent.TweenType.MoveAdd]["space"] = typeof(Space); mappings[iTweenEvent.TweenType.MoveAdd]["time"] = typeof(float); mappings[iTweenEvent.TweenType.MoveAdd]["speed"] = typeof(float); mappings[iTweenEvent.TweenType.MoveAdd]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.MoveAdd]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.MoveAdd]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.MoveAdd]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.MoveAdd]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.MoveAdd]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.MoveAdd]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.MoveAdd]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.MoveAdd]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.MoveAdd]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.MoveAdd]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.MoveAdd]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.MoveAdd]["ignoretimescale"] = typeof(bool); // MOVE BY mappings.Add(iTweenEvent.TweenType.MoveBy, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.MoveBy]["time"] = typeof(float); mappings[iTweenEvent.TweenType.MoveBy]["speed"] = typeof(float); mappings[iTweenEvent.TweenType.MoveBy]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.MoveBy]["amount"] = typeof(Vector3); mappings[iTweenEvent.TweenType.MoveBy]["x"] = typeof(float); mappings[iTweenEvent.TweenType.MoveBy]["y"] = typeof(float); mappings[iTweenEvent.TweenType.MoveBy]["z"] = typeof(float); mappings[iTweenEvent.TweenType.MoveBy]["orienttopath"] = typeof(bool); mappings[iTweenEvent.TweenType.MoveBy]["looktarget"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.MoveBy]["looktime"] = typeof(float); mappings[iTweenEvent.TweenType.MoveBy]["axis"] = typeof(string); mappings[iTweenEvent.TweenType.MoveBy]["space"] = typeof(Space); mappings[iTweenEvent.TweenType.MoveBy]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.MoveBy]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.MoveBy]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.MoveBy]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.MoveBy]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.MoveBy]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.MoveBy]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.MoveBy]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.MoveBy]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.MoveBy]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.MoveBy]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.MoveBy]["ignoretimescale"] = typeof(bool); // MOVE FROM mappings.Add(iTweenEvent.TweenType.MoveFrom, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.MoveFrom]["position"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.MoveFrom]["path"] = typeof(Vector3OrTransformArray); mappings[iTweenEvent.TweenType.MoveFrom]["movetopath"] = typeof(bool); mappings[iTweenEvent.TweenType.MoveFrom]["x"] = typeof(float); mappings[iTweenEvent.TweenType.MoveFrom]["y"] = typeof(float); mappings[iTweenEvent.TweenType.MoveFrom]["z"] = typeof(float); mappings[iTweenEvent.TweenType.MoveFrom]["orienttopath"] = typeof(bool); mappings[iTweenEvent.TweenType.MoveFrom]["looktarget"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.MoveFrom]["looktime"] = typeof(float); mappings[iTweenEvent.TweenType.MoveFrom]["lookahead"] = typeof(float); mappings[iTweenEvent.TweenType.MoveFrom]["axis"] = typeof(string); mappings[iTweenEvent.TweenType.MoveFrom]["islocal"] = typeof(bool); mappings[iTweenEvent.TweenType.MoveFrom]["time"] = typeof(float); mappings[iTweenEvent.TweenType.MoveFrom]["speed"] = typeof(float); mappings[iTweenEvent.TweenType.MoveFrom]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.MoveFrom]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.MoveFrom]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.MoveFrom]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.MoveFrom]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.MoveFrom]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.MoveFrom]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.MoveFrom]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.MoveFrom]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.MoveFrom]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.MoveFrom]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.MoveFrom]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.MoveFrom]["ignoretimescale"] = typeof(bool); // MOVE TO mappings.Add(iTweenEvent.TweenType.MoveTo, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.MoveTo]["position"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.MoveTo]["path"] = typeof(Vector3OrTransformArray); mappings[iTweenEvent.TweenType.MoveTo]["movetopath"] = typeof(bool); mappings[iTweenEvent.TweenType.MoveTo]["x"] = typeof(float); mappings[iTweenEvent.TweenType.MoveTo]["y"] = typeof(float); mappings[iTweenEvent.TweenType.MoveTo]["z"] = typeof(float); mappings[iTweenEvent.TweenType.MoveTo]["orienttopath"] = typeof(bool); mappings[iTweenEvent.TweenType.MoveTo]["looktarget"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.MoveTo]["looktime"] = typeof(float); mappings[iTweenEvent.TweenType.MoveTo]["lookahead"] = typeof(float); mappings[iTweenEvent.TweenType.MoveTo]["axis"] = typeof(string); mappings[iTweenEvent.TweenType.MoveTo]["islocal"] = typeof(bool); mappings[iTweenEvent.TweenType.MoveTo]["time"] = typeof(float); mappings[iTweenEvent.TweenType.MoveTo]["speed"] = typeof(float); mappings[iTweenEvent.TweenType.MoveTo]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.MoveTo]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.MoveTo]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.MoveTo]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.MoveTo]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.MoveTo]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.MoveTo]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.MoveTo]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.MoveTo]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.MoveTo]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.MoveTo]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.MoveTo]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.MoveTo]["ignoretimescale"] = typeof(bool); // MOVE UPDATE mappings.Add(iTweenEvent.TweenType.MoveUpdate, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.MoveUpdate]["position"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.MoveUpdate]["x"] = typeof(float); mappings[iTweenEvent.TweenType.MoveUpdate]["y"] = typeof(float); mappings[iTweenEvent.TweenType.MoveUpdate]["z"] = typeof(float); mappings[iTweenEvent.TweenType.MoveUpdate]["orienttopath"] = typeof(bool); mappings[iTweenEvent.TweenType.MoveUpdate]["looktarget"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.MoveUpdate]["looktime"] = typeof(float); mappings[iTweenEvent.TweenType.MoveUpdate]["axis"] = typeof(string); mappings[iTweenEvent.TweenType.MoveUpdate]["islocal"] = typeof(bool); mappings[iTweenEvent.TweenType.MoveUpdate]["time"] = typeof(float); // PUNCH POSITION mappings.Add(iTweenEvent.TweenType.PunchPosition, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.PunchPosition]["position"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.PunchPosition]["amount"] = typeof(Vector3); mappings[iTweenEvent.TweenType.PunchPosition]["x"] = typeof(float); mappings[iTweenEvent.TweenType.PunchPosition]["y"] = typeof(float); mappings[iTweenEvent.TweenType.PunchPosition]["z"] = typeof(float); mappings[iTweenEvent.TweenType.PunchPosition]["space"] = typeof(Space); mappings[iTweenEvent.TweenType.PunchPosition]["looktarget"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.PunchPosition]["looktime"] = typeof(float); mappings[iTweenEvent.TweenType.PunchPosition]["axis"] = typeof(string); mappings[iTweenEvent.TweenType.PunchPosition]["time"] = typeof(float); mappings[iTweenEvent.TweenType.PunchPosition]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.PunchPosition]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.PunchPosition]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.PunchPosition]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.PunchPosition]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.PunchPosition]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.PunchPosition]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.PunchPosition]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.PunchPosition]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.PunchPosition]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.PunchPosition]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.PunchPosition]["ignoretimescale"] = typeof(bool); // PUNCH ROTATION mappings.Add(iTweenEvent.TweenType.PunchRotation, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.PunchRotation]["position"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.PunchRotation]["amount"] = typeof(Vector3); mappings[iTweenEvent.TweenType.PunchRotation]["x"] = typeof(float); mappings[iTweenEvent.TweenType.PunchRotation]["y"] = typeof(float); mappings[iTweenEvent.TweenType.PunchRotation]["z"] = typeof(float); mappings[iTweenEvent.TweenType.PunchRotation]["space"] = typeof(Space); mappings[iTweenEvent.TweenType.PunchRotation]["time"] = typeof(float); mappings[iTweenEvent.TweenType.PunchRotation]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.PunchRotation]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.PunchRotation]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.PunchRotation]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.PunchRotation]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.PunchRotation]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.PunchRotation]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.PunchRotation]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.PunchRotation]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.PunchRotation]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.PunchRotation]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.PunchRotation]["ignoretimescale"] = typeof(bool); // PUNCH SCALE mappings.Add(iTweenEvent.TweenType.PunchScale, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.PunchScale]["position"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.PunchScale]["amount"] = typeof(Vector3); mappings[iTweenEvent.TweenType.PunchScale]["x"] = typeof(float); mappings[iTweenEvent.TweenType.PunchScale]["y"] = typeof(float); mappings[iTweenEvent.TweenType.PunchScale]["z"] = typeof(float); mappings[iTweenEvent.TweenType.PunchScale]["time"] = typeof(float); mappings[iTweenEvent.TweenType.PunchScale]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.PunchScale]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.PunchScale]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.PunchScale]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.PunchScale]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.PunchScale]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.PunchScale]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.PunchScale]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.PunchScale]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.PunchScale]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.PunchScale]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.PunchScale]["ignoretimescale"] = typeof(bool); // ROTATE ADD mappings.Add(iTweenEvent.TweenType.RotateAdd, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.RotateAdd]["amount"] = typeof(Vector3); mappings[iTweenEvent.TweenType.RotateAdd]["x"] = typeof(float); mappings[iTweenEvent.TweenType.RotateAdd]["y"] = typeof(float); mappings[iTweenEvent.TweenType.RotateAdd]["z"] = typeof(float); mappings[iTweenEvent.TweenType.RotateAdd]["space"] = typeof(Space); mappings[iTweenEvent.TweenType.RotateAdd]["time"] = typeof(float); mappings[iTweenEvent.TweenType.RotateAdd]["speed"] = typeof(float); mappings[iTweenEvent.TweenType.RotateAdd]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.RotateAdd]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.RotateAdd]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.RotateAdd]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.RotateAdd]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.RotateAdd]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.RotateAdd]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.RotateAdd]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.RotateAdd]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.RotateAdd]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.RotateAdd]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.RotateAdd]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.RotateAdd]["ignoretimescale"] = typeof(bool); // ROTATE BY mappings.Add(iTweenEvent.TweenType.RotateBy, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.RotateBy]["amount"] = typeof(Vector3); mappings[iTweenEvent.TweenType.RotateBy]["x"] = typeof(float); mappings[iTweenEvent.TweenType.RotateBy]["y"] = typeof(float); mappings[iTweenEvent.TweenType.RotateBy]["z"] = typeof(float); mappings[iTweenEvent.TweenType.RotateBy]["space"] = typeof(Space); mappings[iTweenEvent.TweenType.RotateBy]["time"] = typeof(float); mappings[iTweenEvent.TweenType.RotateBy]["speed"] = typeof(float); mappings[iTweenEvent.TweenType.RotateBy]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.RotateBy]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.RotateBy]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.RotateBy]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.RotateBy]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.RotateBy]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.RotateBy]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.RotateBy]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.RotateBy]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.RotateBy]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.RotateBy]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.RotateBy]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.RotateBy]["ignoretimescale"] = typeof(bool); // ROTATE FROM mappings.Add(iTweenEvent.TweenType.RotateFrom, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.RotateFrom]["rotation"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.RotateFrom]["x"] = typeof(float); mappings[iTweenEvent.TweenType.RotateFrom]["y"] = typeof(float); mappings[iTweenEvent.TweenType.RotateFrom]["z"] = typeof(float); mappings[iTweenEvent.TweenType.RotateFrom]["islocal"] = typeof(bool); mappings[iTweenEvent.TweenType.RotateFrom]["time"] = typeof(float); mappings[iTweenEvent.TweenType.RotateFrom]["speed"] = typeof(float); mappings[iTweenEvent.TweenType.RotateFrom]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.RotateFrom]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.RotateFrom]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.RotateFrom]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.RotateFrom]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.RotateFrom]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.RotateFrom]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.RotateFrom]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.RotateFrom]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.RotateFrom]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.RotateFrom]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.RotateFrom]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.RotateFrom]["ignoretimescale"] = typeof(bool); // ROTATE TO mappings.Add(iTweenEvent.TweenType.RotateTo, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.RotateTo]["rotation"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.RotateTo]["x"] = typeof(float); mappings[iTweenEvent.TweenType.RotateTo]["y"] = typeof(float); mappings[iTweenEvent.TweenType.RotateTo]["z"] = typeof(float); mappings[iTweenEvent.TweenType.RotateTo]["islocal"] = typeof(bool); mappings[iTweenEvent.TweenType.RotateTo]["time"] = typeof(float); mappings[iTweenEvent.TweenType.RotateTo]["speed"] = typeof(float); mappings[iTweenEvent.TweenType.RotateTo]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.RotateTo]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.RotateTo]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.RotateTo]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.RotateTo]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.RotateTo]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.RotateTo]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.RotateTo]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.RotateTo]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.RotateTo]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.RotateTo]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.RotateTo]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.RotateTo]["ignoretimescale"] = typeof(bool); // ROTATE UPDATE mappings.Add(iTweenEvent.TweenType.RotateUpdate, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.RotateUpdate]["rotation"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.RotateUpdate]["x"] = typeof(float); mappings[iTweenEvent.TweenType.RotateUpdate]["y"] = typeof(float); mappings[iTweenEvent.TweenType.RotateUpdate]["z"] = typeof(float); mappings[iTweenEvent.TweenType.RotateUpdate]["islocal"] = typeof(bool); mappings[iTweenEvent.TweenType.RotateUpdate]["time"] = typeof(float); // SCALE ADD mappings.Add(iTweenEvent.TweenType.ScaleAdd, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.ScaleAdd]["amount"] = typeof(Vector3); mappings[iTweenEvent.TweenType.ScaleAdd]["x"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleAdd]["y"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleAdd]["z"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleAdd]["time"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleAdd]["speed"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleAdd]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleAdd]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.ScaleAdd]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.ScaleAdd]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleAdd]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ScaleAdd]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleAdd]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleAdd]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ScaleAdd]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleAdd]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleAdd]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ScaleAdd]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleAdd]["ignoretimescale"] = typeof(bool); // SCALE BY mappings.Add(iTweenEvent.TweenType.ScaleBy, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.ScaleBy]["amount"] = typeof(Vector3); mappings[iTweenEvent.TweenType.ScaleBy]["x"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleBy]["y"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleBy]["z"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleBy]["time"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleBy]["speed"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleBy]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleBy]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.ScaleBy]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.ScaleBy]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleBy]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ScaleBy]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleBy]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleBy]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ScaleBy]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleBy]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleBy]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ScaleBy]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleBy]["ignoretimescale"] = typeof(bool); // SCALE FROM mappings.Add(iTweenEvent.TweenType.ScaleFrom, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.ScaleFrom]["scale"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.ScaleFrom]["x"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleFrom]["y"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleFrom]["z"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleFrom]["time"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleFrom]["speed"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleFrom]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleFrom]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.ScaleFrom]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.ScaleFrom]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleFrom]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ScaleFrom]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleFrom]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleFrom]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ScaleFrom]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleFrom]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleFrom]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ScaleFrom]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleFrom]["ignoretimescale"] = typeof(bool); // SCALE TO mappings.Add(iTweenEvent.TweenType.ScaleTo, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.ScaleTo]["scale"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.ScaleTo]["x"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleTo]["y"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleTo]["z"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleTo]["time"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleTo]["speed"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleTo]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleTo]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.ScaleTo]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.ScaleTo]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleTo]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ScaleTo]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleTo]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleTo]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ScaleTo]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleTo]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleTo]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ScaleTo]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleTo]["ignoretimescale"] = typeof(bool); // SCALE UPDATE mappings.Add(iTweenEvent.TweenType.ScaleUpdate, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.ScaleUpdate]["scale"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.ScaleUpdate]["x"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleUpdate]["y"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleUpdate]["z"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleUpdate]["time"] = typeof(float); // SHAKE POSITION mappings.Add(iTweenEvent.TweenType.ShakePosition, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.ShakePosition]["amount"] = typeof(Vector3); mappings[iTweenEvent.TweenType.ShakePosition]["x"] = typeof(float); mappings[iTweenEvent.TweenType.ShakePosition]["y"] = typeof(float); mappings[iTweenEvent.TweenType.ShakePosition]["z"] = typeof(float); mappings[iTweenEvent.TweenType.ShakePosition]["space"] = typeof(Space); mappings[iTweenEvent.TweenType.ShakePosition]["orienttopath"] = typeof(bool); mappings[iTweenEvent.TweenType.ShakePosition]["looktarget"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.ShakePosition]["looktime"] = typeof(float); mappings[iTweenEvent.TweenType.ShakePosition]["axis"] = typeof(string); mappings[iTweenEvent.TweenType.ShakePosition]["time"] = typeof(float); mappings[iTweenEvent.TweenType.ShakePosition]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.ShakePosition]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.ShakePosition]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.ShakePosition]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ShakePosition]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.ShakePosition]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.ShakePosition]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ShakePosition]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.ShakePosition]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.ShakePosition]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ShakePosition]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.ShakePosition]["ignoretimescale"] = typeof(bool); // SHAKE ROTATION mappings.Add(iTweenEvent.TweenType.ShakeRotation, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.ShakeRotation]["amount"] = typeof(Vector3); mappings[iTweenEvent.TweenType.ShakeRotation]["x"] = typeof(float); mappings[iTweenEvent.TweenType.ShakeRotation]["y"] = typeof(float); mappings[iTweenEvent.TweenType.ShakeRotation]["z"] = typeof(float); mappings[iTweenEvent.TweenType.ShakeRotation]["space"] = typeof(Space); mappings[iTweenEvent.TweenType.ShakeRotation]["time"] = typeof(float); mappings[iTweenEvent.TweenType.ShakeRotation]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.ShakeRotation]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.ShakeRotation]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.ShakeRotation]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ShakeRotation]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.ShakeRotation]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.ShakeRotation]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ShakeRotation]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.ShakeRotation]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.ShakeRotation]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ShakeRotation]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.ShakeRotation]["ignoretimescale"] = typeof(bool); // SHAKE SCALE mappings.Add(iTweenEvent.TweenType.ShakeScale, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.ShakeScale]["amount"] = typeof(Vector3); mappings[iTweenEvent.TweenType.ShakeScale]["x"] = typeof(float); mappings[iTweenEvent.TweenType.ShakeScale]["y"] = typeof(float); mappings[iTweenEvent.TweenType.ShakeScale]["z"] = typeof(float); mappings[iTweenEvent.TweenType.ShakeScale]["time"] = typeof(float); mappings[iTweenEvent.TweenType.ShakeScale]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.ShakeScale]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.ShakeScale]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.ShakeScale]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ShakeScale]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.ShakeScale]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.ShakeScale]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ShakeScale]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.ShakeScale]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.ShakeScale]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ShakeScale]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.ShakeScale]["ignoretimescale"] = typeof(bool); // STAB mappings.Add(iTweenEvent.TweenType.Stab, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.Stab]["audioclip"] = typeof(AudioClip); mappings[iTweenEvent.TweenType.Stab]["audiosource"] = typeof(AudioSource); mappings[iTweenEvent.TweenType.Stab]["volume"] = typeof(float); mappings[iTweenEvent.TweenType.Stab]["pitch"] = typeof(float); mappings[iTweenEvent.TweenType.Stab]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.Stab]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.Stab]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.Stab]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.Stab]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.Stab]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.Stab]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.Stab]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.Stab]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.Stab]["oncompleteparams"] = typeof(string); } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace ExporterWeb.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
/** * 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.IO; using System.Text; using System.Collections.Generic; using Thrift.Transport; using System.Globalization; namespace Thrift.Protocol { /// <summary> /// JSON protocol implementation for thrift. /// /// This is a full-featured protocol supporting Write and Read. /// /// Please see the C++ class header for a detailed description of the /// protocol's wire format. /// /// Adapted from the Java version. /// </summary> public class TJSONProtocol : TProtocol { /// <summary> /// Factory for JSON protocol objects /// </summary> public class Factory : TProtocolFactory { public TProtocol GetProtocol(TTransport trans) { return new TJSONProtocol(trans); } } private static readonly byte[] COMMA = new byte[] { (byte)',' }; private static readonly byte[] COLON = new byte[] { (byte)':' }; private static readonly byte[] LBRACE = new byte[] { (byte)'{' }; private static readonly byte[] RBRACE = new byte[] { (byte)'}' }; private static readonly byte[] LBRACKET = new byte[] { (byte)'[' }; private static readonly byte[] RBRACKET = new byte[] { (byte)']' }; private static readonly byte[] QUOTE = new byte[] { (byte)'"' }; private static readonly byte[] BACKSLASH = new byte[] { (byte)'\\' }; private readonly byte[] ESCSEQ = new byte[] { (byte)'\\', (byte)'u', (byte)'0', (byte)'0' }; private const long VERSION = 1; private readonly byte[] JSON_CHAR_TABLE = { 0, 0, 0, 0, 0, 0, 0, 0,(byte)'b',(byte)'t',(byte)'n', 0,(byte)'f',(byte)'r', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1,(byte)'"', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, }; private readonly char[] ESCAPE_CHARS = "\"\\/bfnrt".ToCharArray(); private readonly byte[] ESCAPE_CHAR_VALS = { (byte)'"', (byte)'\\', (byte)'/', (byte)'\b', (byte)'\f', (byte)'\n', (byte)'\r', (byte)'\t', }; private const int DEF_STRING_SIZE = 16; private static readonly byte[] NAME_BOOL = new byte[] { (byte)'t', (byte)'f' }; private static readonly byte[] NAME_BYTE = new byte[] { (byte)'i', (byte)'8' }; private static readonly byte[] NAME_I16 = new byte[] { (byte)'i', (byte)'1', (byte)'6' }; private static readonly byte[] NAME_I32 = new byte[] { (byte)'i', (byte)'3', (byte)'2' }; private static readonly byte[] NAME_I64 = new byte[] { (byte)'i', (byte)'6', (byte)'4' }; private static readonly byte[] NAME_DOUBLE = new byte[] { (byte)'d', (byte)'b', (byte)'l' }; private static readonly byte[] NAME_STRUCT = new byte[] { (byte)'r', (byte)'e', (byte)'c' }; private static readonly byte[] NAME_STRING = new byte[] { (byte)'s', (byte)'t', (byte)'r' }; private static readonly byte[] NAME_MAP = new byte[] { (byte)'m', (byte)'a', (byte)'p' }; private static readonly byte[] NAME_LIST = new byte[] { (byte)'l', (byte)'s', (byte)'t' }; private static readonly byte[] NAME_SET = new byte[] { (byte)'s', (byte)'e', (byte)'t' }; private static byte[] GetTypeNameForTypeID(TType typeID) { switch (typeID) { case TType.Bool: return NAME_BOOL; case TType.Byte: return NAME_BYTE; case TType.I16: return NAME_I16; case TType.I32: return NAME_I32; case TType.I64: return NAME_I64; case TType.Double: return NAME_DOUBLE; case TType.String: return NAME_STRING; case TType.Struct: return NAME_STRUCT; case TType.Map: return NAME_MAP; case TType.Set: return NAME_SET; case TType.List: return NAME_LIST; default: throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED, "Unrecognized type"); } } private static TType GetTypeIDForTypeName(byte[] name) { TType result = TType.Stop; if (name.Length > 1) { switch (name[0]) { case (byte)'d': result = TType.Double; break; case (byte)'i': switch (name[1]) { case (byte)'8': result = TType.Byte; break; case (byte)'1': result = TType.I16; break; case (byte)'3': result = TType.I32; break; case (byte)'6': result = TType.I64; break; } break; case (byte)'l': result = TType.List; break; case (byte)'m': result = TType.Map; break; case (byte)'r': result = TType.Struct; break; case (byte)'s': if (name[1] == (byte)'t') { result = TType.String; } else if (name[1] == (byte)'e') { result = TType.Set; } break; case (byte)'t': result = TType.Bool; break; } } if (result == TType.Stop) { throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED, "Unrecognized type"); } return result; } ///<summary> /// Base class for tracking JSON contexts that may require /// inserting/Reading additional JSON syntax characters /// This base context does nothing. ///</summary> protected class JSONBaseContext { protected TJSONProtocol proto; public JSONBaseContext(TJSONProtocol proto) { this.proto = proto; } public virtual void Write() { } public virtual void Read() { } public virtual bool EscapeNumbers() { return false; } } ///<summary> /// Context for JSON lists. Will insert/Read commas before each item except /// for the first one ///</summary> protected class JSONListContext : JSONBaseContext { public JSONListContext(TJSONProtocol protocol) : base(protocol) { } private bool first = true; public override void Write() { if (first) { first = false; } else { proto.trans.Write(COMMA); } } public override void Read() { if (first) { first = false; } else { proto.ReadJSONSyntaxChar(COMMA); } } } ///<summary> /// Context for JSON records. Will insert/Read colons before the value portion /// of each record pair, and commas before each key except the first. In /// addition, will indicate that numbers in the key position need to be /// escaped in quotes (since JSON keys must be strings). ///</summary> protected class JSONPairContext : JSONBaseContext { public JSONPairContext(TJSONProtocol proto) : base(proto) { } private bool first = true; private bool colon = true; public override void Write() { if (first) { first = false; colon = true; } else { proto.trans.Write(colon ? COLON : COMMA); colon = !colon; } } public override void Read() { if (first) { first = false; colon = true; } else { proto.ReadJSONSyntaxChar(colon ? COLON : COMMA); colon = !colon; } } public override bool EscapeNumbers() { return colon; } } ///<summary> /// Holds up to one byte from the transport ///</summary> protected class LookaheadReader { protected TJSONProtocol proto; public LookaheadReader(TJSONProtocol proto) { this.proto = proto; } private bool hasData; private readonly byte[] data = new byte[1]; ///<summary> /// Return and consume the next byte to be Read, either taking it from the /// data buffer if present or getting it from the transport otherwise. ///</summary> public byte Read() { if (hasData) { hasData = false; } else { proto.trans.ReadAll(data, 0, 1); } return data[0]; } ///<summary> /// Return the next byte to be Read without consuming, filling the data /// buffer if it has not been filled alReady. ///</summary> public byte Peek() { if (!hasData) { proto.trans.ReadAll(data, 0, 1); } hasData = true; return data[0]; } } // Default encoding protected Encoding utf8Encoding = UTF8Encoding.UTF8; // Stack of nested contexts that we may be in protected Stack<JSONBaseContext> contextStack = new Stack<JSONBaseContext>(); // Current context that we are in protected JSONBaseContext context; // Reader that manages a 1-byte buffer protected LookaheadReader reader; ///<summary> /// Push a new JSON context onto the stack. ///</summary> protected void PushContext(JSONBaseContext c) { contextStack.Push(context); context = c; } ///<summary> /// Pop the last JSON context off the stack ///</summary> protected void PopContext() { context = contextStack.Pop(); } ///<summary> /// TJSONProtocol Constructor ///</summary> public TJSONProtocol(TTransport trans) : base(trans) { context = new JSONBaseContext(this); reader = new LookaheadReader(this); } // Temporary buffer used by several methods private readonly byte[] tempBuffer = new byte[4]; ///<summary> /// Read a byte that must match b[0]; otherwise an exception is thrown. /// Marked protected to avoid synthetic accessor in JSONListContext.Read /// and JSONPairContext.Read ///</summary> protected void ReadJSONSyntaxChar(byte[] b) { byte ch = reader.Read(); if (ch != b[0]) { throw new TProtocolException(TProtocolException.INVALID_DATA, "Unexpected character:" + (char)ch); } } ///<summary> /// Convert a byte containing a hex char ('0'-'9' or 'a'-'f') into its /// corresponding hex value ///</summary> private static byte HexVal(byte ch) { if ((ch >= '0') && (ch <= '9')) { return (byte)((char)ch - '0'); } else if ((ch >= 'a') && (ch <= 'f')) { ch += 10; return (byte)((char)ch - 'a'); } else { throw new TProtocolException(TProtocolException.INVALID_DATA, "Expected hex character"); } } ///<summary> /// Convert a byte containing a hex value to its corresponding hex character ///</summary> private static byte HexChar(byte val) { val &= 0x0F; if (val < 10) { return (byte)((char)val + '0'); } else { val -= 10; return (byte)((char)val + 'a'); } } ///<summary> /// Write the bytes in array buf as a JSON characters, escaping as needed ///</summary> private void WriteJSONString(byte[] b) { context.Write(); trans.Write(QUOTE); int len = b.Length; for (int i = 0; i < len; i++) { if ((b[i] & 0x00FF) >= 0x30) { if (b[i] == BACKSLASH[0]) { trans.Write(BACKSLASH); trans.Write(BACKSLASH); } else { trans.Write(b, i, 1); } } else { tempBuffer[0] = JSON_CHAR_TABLE[b[i]]; if (tempBuffer[0] == 1) { trans.Write(b, i, 1); } else if (tempBuffer[0] > 1) { trans.Write(BACKSLASH); trans.Write(tempBuffer, 0, 1); } else { trans.Write(ESCSEQ); tempBuffer[0] = HexChar((byte)(b[i] >> 4)); tempBuffer[1] = HexChar(b[i]); trans.Write(tempBuffer, 0, 2); } } } trans.Write(QUOTE); } ///<summary> /// Write out number as a JSON value. If the context dictates so, it will be /// wrapped in quotes to output as a JSON string. ///</summary> private void WriteJSONInteger(long num) { context.Write(); string str = num.ToString(); bool escapeNum = context.EscapeNumbers(); if (escapeNum) trans.Write(QUOTE); trans.Write(utf8Encoding.GetBytes(str)); if (escapeNum) trans.Write(QUOTE); } ///<summary> /// Write out a double as a JSON value. If it is NaN or infinity or if the /// context dictates escaping, Write out as JSON string. ///</summary> private void WriteJSONDouble(double num) { context.Write(); string str = num.ToString(CultureInfo.InvariantCulture); bool special = false; switch (str[0]) { case 'N': // NaN case 'I': // Infinity special = true; break; case '-': if (str[1] == 'I') { // -Infinity special = true; } break; } bool escapeNum = special || context.EscapeNumbers(); if (escapeNum) trans.Write(QUOTE); trans.Write(utf8Encoding.GetBytes(str)); if (escapeNum) trans.Write(QUOTE); } ///<summary> /// Write out contents of byte array b as a JSON string with base-64 encoded /// data ///</summary> private void WriteJSONBase64(byte[] b) { context.Write(); trans.Write(QUOTE); int len = b.Length; int off = 0; while (len >= 3) { // Encode 3 bytes at a time TBase64Utils.encode(b, off, 3, tempBuffer, 0); trans.Write(tempBuffer, 0, 4); off += 3; len -= 3; } if (len > 0) { // Encode remainder TBase64Utils.encode(b, off, len, tempBuffer, 0); trans.Write(tempBuffer, 0, len + 1); } trans.Write(QUOTE); } private void WriteJSONObjectStart() { context.Write(); trans.Write(LBRACE); PushContext(new JSONPairContext(this)); } private void WriteJSONObjectEnd() { PopContext(); trans.Write(RBRACE); } private void WriteJSONArrayStart() { context.Write(); trans.Write(LBRACKET); PushContext(new JSONListContext(this)); } private void WriteJSONArrayEnd() { PopContext(); trans.Write(RBRACKET); } public override void WriteMessageBegin(TMessage message) { WriteJSONArrayStart(); WriteJSONInteger(VERSION); byte[] b = utf8Encoding.GetBytes(message.Name); WriteJSONString(b); WriteJSONInteger((long)message.Type); WriteJSONInteger(message.SeqID); } public override void WriteMessageEnd() { WriteJSONArrayEnd(); } public override void WriteStructBegin(TStruct str) { WriteJSONObjectStart(); } public override void WriteStructEnd() { WriteJSONObjectEnd(); } public override void WriteFieldBegin(TField field) { WriteJSONInteger(field.ID); WriteJSONObjectStart(); WriteJSONString(GetTypeNameForTypeID(field.Type)); } public override void WriteFieldEnd() { WriteJSONObjectEnd(); } public override void WriteFieldStop() { } public override void WriteMapBegin(TMap map) { WriteJSONArrayStart(); WriteJSONString(GetTypeNameForTypeID(map.KeyType)); WriteJSONString(GetTypeNameForTypeID(map.ValueType)); WriteJSONInteger(map.Count); WriteJSONObjectStart(); } public override void WriteMapEnd() { WriteJSONObjectEnd(); WriteJSONArrayEnd(); } public override void WriteListBegin(TList list) { WriteJSONArrayStart(); WriteJSONString(GetTypeNameForTypeID(list.ElementType)); WriteJSONInteger(list.Count); } public override void WriteListEnd() { WriteJSONArrayEnd(); } public override void WriteSetBegin(TSet set) { WriteJSONArrayStart(); WriteJSONString(GetTypeNameForTypeID(set.ElementType)); WriteJSONInteger(set.Count); } public override void WriteSetEnd() { WriteJSONArrayEnd(); } public override void WriteBool(bool b) { WriteJSONInteger(b ? (long)1 : (long)0); } public override void WriteByte(sbyte b) { WriteJSONInteger((long)b); } public override void WriteI16(short i16) { WriteJSONInteger((long)i16); } public override void WriteI32(int i32) { WriteJSONInteger((long)i32); } public override void WriteI64(long i64) { WriteJSONInteger(i64); } public override void WriteDouble(double dub) { WriteJSONDouble(dub); } public override void WriteString(string str) { byte[] b = utf8Encoding.GetBytes(str); WriteJSONString(b); } public override void WriteBinary(byte[] bin) { WriteJSONBase64(bin); } /** * Reading methods. */ ///<summary> /// Read in a JSON string, unescaping as appropriate.. Skip Reading from the /// context if skipContext is true. ///</summary> private byte[] ReadJSONString(bool skipContext) { MemoryStream buffer = new MemoryStream(); if (!skipContext) { context.Read(); } ReadJSONSyntaxChar(QUOTE); while (true) { byte ch = reader.Read(); if (ch == QUOTE[0]) { break; } // escaped? if (ch != ESCSEQ[0]) { buffer.Write(new byte[] { (byte)ch }, 0, 1); continue; } // distinguish between \uXXXX and \? ch = reader.Read(); if (ch != ESCSEQ[1]) // control chars like \n { int off = Array.IndexOf(ESCAPE_CHARS, (char)ch); if (off == -1) { throw new TProtocolException(TProtocolException.INVALID_DATA, "Expected control char"); } ch = ESCAPE_CHAR_VALS[off]; buffer.Write(new byte[] { (byte)ch }, 0, 1); continue; } // it's \uXXXX trans.ReadAll(tempBuffer, 0, 4); var wch = (short)((HexVal((byte)tempBuffer[0]) << 12) + (HexVal((byte)tempBuffer[1]) << 8) + (HexVal((byte)tempBuffer[2]) << 4) + HexVal(tempBuffer[3])); var tmp = utf8Encoding.GetBytes(new char[] { (char)wch }); buffer.Write(tmp, 0, tmp.Length); } return buffer.ToArray(); } ///<summary> /// Return true if the given byte could be a valid part of a JSON number. ///</summary> private bool IsJSONNumeric(byte b) { switch (b) { case (byte)'+': case (byte)'-': case (byte)'.': case (byte)'0': case (byte)'1': case (byte)'2': case (byte)'3': case (byte)'4': case (byte)'5': case (byte)'6': case (byte)'7': case (byte)'8': case (byte)'9': case (byte)'E': case (byte)'e': return true; } return false; } ///<summary> /// Read in a sequence of characters that are all valid in JSON numbers. Does /// not do a complete regex check to validate that this is actually a number. ////</summary> private string ReadJSONNumericChars() { StringBuilder strbld = new StringBuilder(); while (true) { byte ch = reader.Peek(); if (!IsJSONNumeric(ch)) { break; } strbld.Append((char)reader.Read()); } return strbld.ToString(); } ///<summary> /// Read in a JSON number. If the context dictates, Read in enclosing quotes. ///</summary> private long ReadJSONInteger() { context.Read(); if (context.EscapeNumbers()) { ReadJSONSyntaxChar(QUOTE); } string str = ReadJSONNumericChars(); if (context.EscapeNumbers()) { ReadJSONSyntaxChar(QUOTE); } try { return long.Parse(str); } catch (FormatException) { throw new TProtocolException(TProtocolException.INVALID_DATA, "Bad data encounted in numeric data"); } } ///<summary> /// Read in a JSON double value. Throw if the value is not wrapped in quotes /// when expected or if wrapped in quotes when not expected. ///</summary> private double ReadJSONDouble() { context.Read(); if (reader.Peek() == QUOTE[0]) { byte[] arr = ReadJSONString(true); double dub = double.Parse(utf8Encoding.GetString(arr,0,arr.Length), CultureInfo.InvariantCulture); if (!context.EscapeNumbers() && !double.IsNaN(dub) && !double.IsInfinity(dub)) { // Throw exception -- we should not be in a string in this case throw new TProtocolException(TProtocolException.INVALID_DATA, "Numeric data unexpectedly quoted"); } return dub; } else { if (context.EscapeNumbers()) { // This will throw - we should have had a quote if escapeNum == true ReadJSONSyntaxChar(QUOTE); } try { return double.Parse(ReadJSONNumericChars(), CultureInfo.InvariantCulture); } catch (FormatException) { throw new TProtocolException(TProtocolException.INVALID_DATA, "Bad data encounted in numeric data"); } } } //<summary> /// Read in a JSON string containing base-64 encoded data and decode it. ///</summary> private byte[] ReadJSONBase64() { byte[] b = ReadJSONString(false); int len = b.Length; int off = 0; int size = 0; // reduce len to ignore fill bytes while ((len > 0) && (b[len - 1] == '=')) { --len; } // read & decode full byte triplets = 4 source bytes while (len > 4) { // Decode 4 bytes at a time TBase64Utils.decode(b, off, 4, b, size); // NB: decoded in place off += 4; len -= 4; size += 3; } // Don't decode if we hit the end or got a single leftover byte (invalid // base64 but legal for skip of regular string type) if (len > 1) { // Decode remainder TBase64Utils.decode(b, off, len, b, size); // NB: decoded in place size += len - 1; } // Sadly we must copy the byte[] (any way around this?) byte[] result = new byte[size]; Array.Copy(b, 0, result, 0, size); return result; } private void ReadJSONObjectStart() { context.Read(); ReadJSONSyntaxChar(LBRACE); PushContext(new JSONPairContext(this)); } private void ReadJSONObjectEnd() { ReadJSONSyntaxChar(RBRACE); PopContext(); } private void ReadJSONArrayStart() { context.Read(); ReadJSONSyntaxChar(LBRACKET); PushContext(new JSONListContext(this)); } private void ReadJSONArrayEnd() { ReadJSONSyntaxChar(RBRACKET); PopContext(); } public override TMessage ReadMessageBegin() { TMessage message = new TMessage(); ReadJSONArrayStart(); if (ReadJSONInteger() != VERSION) { throw new TProtocolException(TProtocolException.BAD_VERSION, "Message contained bad version."); } var buf = ReadJSONString(false); message.Name = utf8Encoding.GetString(buf,0,buf.Length); message.Type = (TMessageType)ReadJSONInteger(); message.SeqID = (int)ReadJSONInteger(); return message; } public override void ReadMessageEnd() { ReadJSONArrayEnd(); } public override TStruct ReadStructBegin() { ReadJSONObjectStart(); return new TStruct(); } public override void ReadStructEnd() { ReadJSONObjectEnd(); } public override TField ReadFieldBegin() { TField field = new TField(); byte ch = reader.Peek(); if (ch == RBRACE[0]) { field.Type = TType.Stop; } else { field.ID = (short)ReadJSONInteger(); ReadJSONObjectStart(); field.Type = GetTypeIDForTypeName(ReadJSONString(false)); } return field; } public override void ReadFieldEnd() { ReadJSONObjectEnd(); } public override TMap ReadMapBegin() { TMap map = new TMap(); ReadJSONArrayStart(); map.KeyType = GetTypeIDForTypeName(ReadJSONString(false)); map.ValueType = GetTypeIDForTypeName(ReadJSONString(false)); map.Count = (int)ReadJSONInteger(); ReadJSONObjectStart(); return map; } public override void ReadMapEnd() { ReadJSONObjectEnd(); ReadJSONArrayEnd(); } public override TList ReadListBegin() { TList list = new TList(); ReadJSONArrayStart(); list.ElementType = GetTypeIDForTypeName(ReadJSONString(false)); list.Count = (int)ReadJSONInteger(); return list; } public override void ReadListEnd() { ReadJSONArrayEnd(); } public override TSet ReadSetBegin() { TSet set = new TSet(); ReadJSONArrayStart(); set.ElementType = GetTypeIDForTypeName(ReadJSONString(false)); set.Count = (int)ReadJSONInteger(); return set; } public override void ReadSetEnd() { ReadJSONArrayEnd(); } public override bool ReadBool() { return (ReadJSONInteger() == 0 ? false : true); } public override sbyte ReadByte() { return (sbyte)ReadJSONInteger(); } public override short ReadI16() { return (short)ReadJSONInteger(); } public override int ReadI32() { return (int)ReadJSONInteger(); } public override long ReadI64() { return (long)ReadJSONInteger(); } public override double ReadDouble() { return ReadJSONDouble(); } public override string ReadString() { var buf = ReadJSONString(false); return utf8Encoding.GetString(buf,0,buf.Length); } public override byte[] ReadBinary() { return ReadJSONBase64(); } } }
// 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.Runtime.InteropServices; namespace System.Drawing { public static partial class SystemFonts { private unsafe static bool GetNonClientMetrics(out NativeMethods.NONCLIENTMETRICS metrics) { metrics = new NativeMethods.NONCLIENTMETRICS { cbSize = (uint)sizeof(NativeMethods.NONCLIENTMETRICS) }; fixed (void* m = &metrics) { return UnsafeNativeMethods.SystemParametersInfo(NativeMethods.SPI_GETNONCLIENTMETRICS, metrics.cbSize, m, 0); } } public static Font CaptionFont { get { Font captionFont = null; if (GetNonClientMetrics(out NativeMethods.NONCLIENTMETRICS metrics)) { captionFont = GetFontFromData(metrics.lfCaptionFont); captionFont.SetSystemFontName(nameof(CaptionFont)); } return captionFont; } } public static Font SmallCaptionFont { get { Font smcaptionFont = null; if (GetNonClientMetrics(out NativeMethods.NONCLIENTMETRICS metrics)) { smcaptionFont = GetFontFromData(metrics.lfSmCaptionFont); smcaptionFont.SetSystemFontName(nameof(SmallCaptionFont)); } return smcaptionFont; } } public static Font MenuFont { get { Font menuFont = null; if (GetNonClientMetrics(out NativeMethods.NONCLIENTMETRICS metrics)) { menuFont = GetFontFromData(metrics.lfMenuFont); menuFont.SetSystemFontName(nameof(MenuFont)); } return menuFont; } } public static Font StatusFont { get { Font statusFont = null; if (GetNonClientMetrics(out NativeMethods.NONCLIENTMETRICS metrics)) { statusFont = GetFontFromData(metrics.lfStatusFont); statusFont.SetSystemFontName(nameof(StatusFont)); } return statusFont; } } public static Font MessageBoxFont { get { Font messageBoxFont = null; if (GetNonClientMetrics(out NativeMethods.NONCLIENTMETRICS metrics)) { messageBoxFont = GetFontFromData(metrics.lfMessageFont); messageBoxFont.SetSystemFontName(nameof(MessageBoxFont)); } return messageBoxFont; } } private static bool IsCriticalFontException(Exception ex) { return !( // In any of these cases we'll handle the exception. ex is ExternalException || ex is ArgumentException || ex is OutOfMemoryException || // GDI+ throws this one for many reasons other than actual OOM. ex is InvalidOperationException || ex is NotImplementedException || ex is FileNotFoundException); } public static unsafe Font IconTitleFont { get { Font iconTitleFont = null; var itfont = new SafeNativeMethods.LOGFONT(); if (UnsafeNativeMethods.SystemParametersInfo(NativeMethods.SPI_GETICONTITLELOGFONT, (uint)sizeof(SafeNativeMethods.LOGFONT), &itfont, 0)) { iconTitleFont = GetFontFromData(itfont); iconTitleFont.SetSystemFontName(nameof(IconTitleFont)); } return iconTitleFont; } } public static Font DefaultFont { get { Font defaultFont = null; // For Arabic systems, always return Tahoma 8. if ((ushort)UnsafeNativeMethods.GetSystemDefaultLCID() == 0x0001) { try { defaultFont = new Font("Tahoma", 8); } catch (Exception ex) when (!IsCriticalFontException(ex)) { } } // First try DEFAULT_GUI. if (defaultFont == null) { IntPtr handle = UnsafeNativeMethods.GetStockObject(NativeMethods.DEFAULT_GUI_FONT); try { using (Font fontInWorldUnits = Font.FromHfont(handle)) { defaultFont = FontInPoints(fontInWorldUnits); } } catch (ArgumentException) { // This can happen in theory if we end up pulling a non-TrueType font } } // If DEFAULT_GUI didn't work, try Tahoma. if (defaultFont == null) { try { defaultFont = new Font("Tahoma", 8); } catch (ArgumentException) { } } // Use GenericSansSerif as a last resort - this will always work. if (defaultFont == null) { defaultFont = new Font(FontFamily.GenericSansSerif, 8); } if (defaultFont.Unit != GraphicsUnit.Point) { defaultFont = FontInPoints(defaultFont); } Debug.Assert(defaultFont != null, "defaultFont wasn't set."); defaultFont.SetSystemFontName(nameof(DefaultFont)); return defaultFont; } } public static Font DialogFont { get { Font dialogFont = null; if ((ushort)UnsafeNativeMethods.GetSystemDefaultLCID() == 0x0011) { // Always return DefaultFont for Japanese cultures. dialogFont = DefaultFont; } else { try { // Use MS Shell Dlg 2, 8pt for anything other than Japanese. dialogFont = new Font("MS Shell Dlg 2", 8); } catch (ArgumentException) { // This can happen in theory if we end up pulling a non-TrueType font } } if (dialogFont == null) { dialogFont = DefaultFont; } else if (dialogFont.Unit != GraphicsUnit.Point) { dialogFont = FontInPoints(dialogFont); } // For Japanese cultures, SystemFonts.DefaultFont returns a new Font object every time it is invoked. // So for Japanese we return the DefaultFont with its SystemFontName set to DialogFont. dialogFont.SetSystemFontName(nameof(DialogFont)); return dialogFont; } } private static Font FontInPoints(Font font) { return new Font(font.FontFamily, font.SizeInPoints, font.Style, GraphicsUnit.Point, font.GdiCharSet, font.GdiVerticalFont); } private static Font GetFontFromData(SafeNativeMethods.LOGFONT logFont) { Font font = null; try { font = Font.FromLogFont(ref logFont); } catch (Exception ex) when (!IsCriticalFontException(ex)) { } return font == null ? DefaultFont : font.Unit != GraphicsUnit.Point ? FontInPoints(font) : font; } } }
// Copyright 2018 Esri. // // 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 ArcGISRuntime.Samples.Managers; using Esri.ArcGISRuntime.ArcGISServices; using Esri.ArcGISRuntime.Data; using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Symbology; using Esri.ArcGISRuntime.Tasks; using Esri.ArcGISRuntime.Tasks.Offline; using Esri.ArcGISRuntime.UI; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Windows; using Esri.ArcGISRuntime; namespace ArcGISRuntime.WPF.Samples.EditAndSyncFeatures { [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Edit and sync features", category: "Data", description: "Synchronize offline edits with a feature service.", instructions: "Pan and zoom to position the red rectangle around the area you want to take offline. Click \"Generate geodatabase\" to take the area offline. When complete, the map will update to only show the offline area. To edit features, click to select a feature, and click again anywhere else on the map to move the selected feature to the clicked location. To sync the edits with the feature service, click the \"Sync geodatabase\" button.", tags: new[] { "feature service", "geodatabase", "offline", "synchronize" })] [ArcGISRuntime.Samples.Shared.Attributes.OfflineData("e4a398afe9a945f3b0f4dca1e4faccb5")] public partial class EditAndSyncFeatures { // Enumeration to track which phase of the workflow the sample is in. private enum EditState { NotReady, // Geodatabase has not yet been generated. Editing, // A feature is in the process of being moved. Ready // The geodatabase is ready for synchronization or further edits. } // URI for a feature service that supports geodatabase generation. private Uri _featureServiceUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Sync/WildfireSync/FeatureServer"); // Path to the geodatabase file on disk. private string _gdbPath; // Task to be used for generating the geodatabase. private GeodatabaseSyncTask _gdbSyncTask; // Flag to indicate which stage of the edit process we're in. private EditState _readyForEdits = EditState.NotReady; // Hold a reference to the generated geodatabase. private Geodatabase _resultGdb; public EditAndSyncFeatures() { InitializeComponent(); // Create the UI, setup the control references and execute initialization. Initialize(); } private async void Initialize() { // Create a tile cache and load it with the SanFrancisco streets tpk. TileCache tileCache = new TileCache(DataManager.GetDataFolder("e4a398afe9a945f3b0f4dca1e4faccb5", "SanFrancisco.tpkx")); // Create the corresponding layer based on the tile cache. ArcGISTiledLayer tileLayer = new ArcGISTiledLayer(tileCache); // Create the basemap based on the tile cache. Basemap sfBasemap = new Basemap(tileLayer); // Create the map with the tile-based basemap. Map myMap = new Map(sfBasemap); // Assign the map to the MapView. MyMapView.Map = myMap; // Create a new symbol for the extent graphic. SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Red, 2); // Create a graphics overlay for the extent graphic and apply a renderer. GraphicsOverlay extentOverlay = new GraphicsOverlay { Renderer = new SimpleRenderer(lineSymbol) }; // Add graphics overlay to the map view. MyMapView.GraphicsOverlays.Add(extentOverlay); // Set up an event handler for when the viewpoint (extent) changes. MyMapView.ViewpointChanged += MapViewExtentChanged; try { // Create a task for generating a geodatabase (GeodatabaseSyncTask). _gdbSyncTask = await GeodatabaseSyncTask.CreateAsync(_featureServiceUri); // Add all graphics from the service to the map. foreach (IdInfo layer in _gdbSyncTask.ServiceInfo.LayerInfos) { // Get the URL for this particular layer. Uri onlineTableUri = new Uri(_featureServiceUri + "/" + layer.Id); // Create the ServiceFeatureTable. ServiceFeatureTable onlineTable = new ServiceFeatureTable(onlineTableUri); // Wait for the table to load. await onlineTable.LoadAsync(); // Skip tables that aren't for point features.{ if (onlineTable.GeometryType != GeometryType.Point) { continue; } // Add the layer to the map's operational layers if load succeeds. if (onlineTable.LoadStatus == LoadStatus.Loaded) { myMap.OperationalLayers.Add(new FeatureLayer(onlineTable)); } } // Update the graphic - needed in case the user decides not to interact before pressing the button. UpdateMapExtent(); // Enable the generate button. MyGenerateButton.IsEnabled = true; } catch (Exception e) { MessageBox.Show(e.ToString(), "Error"); } } private async void GeoViewTapped(object sender, Esri.ArcGISRuntime.UI.Controls.GeoViewInputEventArgs e) { try { // Disregard if not ready for edits. if (_readyForEdits == EditState.NotReady) { return; } // If an edit is in process, finish it. if (_readyForEdits == EditState.Editing) { // Hold a list of any selected features. List<Feature> selectedFeatures = new List<Feature>(); // Get all selected features then clear selection. foreach (FeatureLayer layer in MyMapView.Map.OperationalLayers) { // Get the selected features. FeatureQueryResult layerFeatures = await layer.GetSelectedFeaturesAsync(); // FeatureQueryResult implements IEnumerable, so it can be treated as a collection of features. selectedFeatures.AddRange(layerFeatures); // Clear the selection. layer.ClearSelection(); } // Update all selected features' geometry. foreach (Feature feature in selectedFeatures) { // Get a reference to the correct feature table for the feature. GeodatabaseFeatureTable table = (GeodatabaseFeatureTable)feature.FeatureTable; // Ensure the geometry type of the table is point. if (table.GeometryType != GeometryType.Point) { continue; } // Set the new geometry. feature.Geometry = e.Location; try { // Update the feature in the table. await table.UpdateFeatureAsync(feature); } catch (ArcGISException) { MessageBox.Show("Feature must be within extent of geodatabase."); } } // Update the edit state. _readyForEdits = EditState.Ready; // Enable the sync button. MySyncButton.IsEnabled = true; // Update the help label. MyHelpLabel.Text = "4. Click 'Sync Geodatabase' or edit more features"; } // Otherwise, start an edit. else { // Define a tolerance for use with identifying the feature. double tolerance = 15 * MyMapView.UnitsPerPixel; // Define the selection envelope. Envelope selectionEnvelope = new Envelope(e.Location.X - tolerance, e.Location.Y - tolerance, e.Location.X + tolerance, e.Location.Y + tolerance); // Define query parameters for feature selection. QueryParameters query = new QueryParameters() { Geometry = selectionEnvelope }; // Track whether any selections were made. bool selectedFeature = false; // Select the feature in all applicable tables. foreach (FeatureLayer layer in MyMapView.Map.OperationalLayers) { FeatureQueryResult res = await layer.SelectFeaturesAsync(query, SelectionMode.New); selectedFeature = selectedFeature || res.Any(); } // Only update state if a feature was selected. if (selectedFeature) { // Set the edit state. _readyForEdits = EditState.Editing; // Update the help label. MyHelpLabel.Text = "3. Tap on the map to move the point"; } } } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error"); } } private void UpdateMapExtent() { // Return if mapview is null. if (MyMapView == null) { return; } // Get the new viewpoint. Viewpoint myViewPoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry); // Return if viewpoint is null. if (myViewPoint == null) { return; } // Get the updated extent for the new viewpoint. Envelope extent = myViewPoint.TargetGeometry as Envelope; // Return if extent is null. if (extent == null) { return; } // Create an envelope that is a bit smaller than the extent. EnvelopeBuilder envelopeBldr = new EnvelopeBuilder(extent); envelopeBldr.Expand(0.80); // Get the (only) graphics overlay in the map view. GraphicsOverlay extentOverlay = MyMapView.GraphicsOverlays.FirstOrDefault(); // Return if the extent overlay is null. if (extentOverlay == null) { return; } // Get the extent graphic. Graphic extentGraphic = extentOverlay.Graphics.FirstOrDefault(); // Create the extent graphic and add it to the overlay if it doesn't exist. if (extentGraphic == null) { extentGraphic = new Graphic(envelopeBldr.ToGeometry()); extentOverlay.Graphics.Add(extentGraphic); } else { // Otherwise, simply update the graphic's geometry. extentGraphic.Geometry = envelopeBldr.ToGeometry(); } } private async Task StartGeodatabaseGeneration() { // Create a task for generating a geodatabase (GeodatabaseSyncTask). _gdbSyncTask = await GeodatabaseSyncTask.CreateAsync(_featureServiceUri); // Get the (only) graphic in the map view. Graphic redPreviewBox = MyMapView.GraphicsOverlays.First().Graphics.First(); // Get the current extent of the red preview box. Envelope extent = redPreviewBox.Geometry as Envelope; // Get the default parameters for the generate geodatabase task. GenerateGeodatabaseParameters generateParams = await _gdbSyncTask.CreateDefaultGenerateGeodatabaseParametersAsync(extent); // Create a generate geodatabase job. GenerateGeodatabaseJob generateGdbJob = _gdbSyncTask.GenerateGeodatabase(generateParams, _gdbPath); // Handle the progress changed event with an inline (lambda) function to show the progress bar. generateGdbJob.ProgressChanged += (sender, e) => { // Update the progress bar. UpdateProgressBar(generateGdbJob.Progress); }; // Show the progress bar. MyProgressBar.Visibility = Visibility.Visible; // Start the job. generateGdbJob.Start(); // Get the result of the job. _resultGdb = await generateGdbJob.GetResultAsync(); // Hide the progress bar. MyProgressBar.Visibility = Visibility.Collapsed; // Do the rest of the work. HandleGenerationCompleted(generateGdbJob); } private async void HandleGenerationCompleted(GenerateGeodatabaseJob job) { // If the job completed successfully, add the geodatabase to the map, replacing the layer from the service. if (job.Status == JobStatus.Succeeded) { // Remove the existing layers. MyMapView.Map.OperationalLayers.Clear(); // Loop through all feature tables in the geodatabase and add a new layer to the map. foreach (GeodatabaseFeatureTable table in _resultGdb.GeodatabaseFeatureTables) { // Skip non-point tables. await table.LoadAsync(); if (table.GeometryType != GeometryType.Point) { continue; } // Create a new feature layer for the table. FeatureLayer layer = new FeatureLayer(table); // Add the new layer to the map. MyMapView.Map.OperationalLayers.Add(layer); } // Enable editing features. _readyForEdits = EditState.Ready; // Update help label. MyHelpLabel.Text = "2. Tap a point feature to select"; } else { // Create a message to show the user. string message = "Generate geodatabase job failed"; // Show an error message (if there is one). if (job.Error != null) { message += ": " + job.Error.Message; } else { // If no error, show messages from the job. foreach (JobMessage m in job.Messages) { // Get the text from the JobMessage and add it to the output string. message += "\n" + m.Message; } } // Show the message. MessageBox.Show(message); } } private async Task SyncGeodatabase() { // Return if not ready. if (_readyForEdits != EditState.Ready) { return; } // Disable the sync button. MySyncButton.IsEnabled = false; // Create parameters for the sync task. SyncGeodatabaseParameters parameters = new SyncGeodatabaseParameters() { GeodatabaseSyncDirection = SyncDirection.Bidirectional, RollbackOnFailure = false }; // Get the layer ID for each feature table in the geodatabase, then add to the sync job. foreach (GeodatabaseFeatureTable table in _resultGdb.GeodatabaseFeatureTables) { // Get the ID for the layer. long id = table.ServiceLayerId; // Create the SyncLayerOption. SyncLayerOption option = new SyncLayerOption(id); // Add the option. parameters.LayerOptions.Add(option); } // Create job. SyncGeodatabaseJob job = _gdbSyncTask.SyncGeodatabase(parameters, _resultGdb); // Subscribe to progress updates. job.ProgressChanged += (o, e) => { // Update the progress bar. UpdateProgressBar(job.Progress); }; // Show the progress bar. MyProgressBar.Visibility = Visibility.Visible; // Start the sync job. job.Start(); // Wait for the result. await job.GetResultAsync(); // Hide the progress bar. MyProgressBar.Visibility = Visibility.Hidden; // Do the remainder of the work. HandleSyncCompleted(job); // Re-enable the sync button. MySyncButton.IsEnabled = true; } private void HandleSyncCompleted(SyncGeodatabaseJob job) { // Tell the user about job completion. if (job.Status == JobStatus.Succeeded) { // Update the progress bar's value. UpdateProgressBar(0); MessageBox.Show("Sync task completed"); } // See if the job failed. if (job.Status == JobStatus.Failed) { // Create a message to show the user. string message = "Sync geodatabase job failed"; // Show an error message (if there is one). if (job.Error != null) { message += ": " + job.Error.Message; } else { // If no error, show messages from the job. foreach (JobMessage m in job.Messages) { // Get the text from the JobMessage and add it to the output string. message += "\n" + m.Message; } } // Show the message. MessageBox.Show(message); } } private async void GenerateButton_Clicked(object sender, RoutedEventArgs e) { // Fix the selection graphic extent. MyMapView.ViewpointChanged -= MapViewExtentChanged; // Update the Geodatabase path for the new run. try { _gdbPath = Path.Combine(Environment.ExpandEnvironmentVariables("%TEMP%"), Path.GetTempFileName() + ".geodatabase"); // Prevent duplicate clicks. MyGenerateButton.IsEnabled = false; // Call the cross-platform geodatabase generation method. await StartGeodatabaseGeneration(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } private void MapViewExtentChanged(object sender, EventArgs e) { // Call the cross-platform map extent update method. UpdateMapExtent(); } private void UpdateProgressBar(int progress) { // Due to the nature of the threading implementation, // the dispatcher needs to be used to interact with the UI. // The dispatcher takes an Action, provided here as a lambda function. Dispatcher.Invoke(() => { // Update the progress bar value. MyProgressBar.Value = progress; }); } private async void SyncButton_Click(object sender, RoutedEventArgs e) { try { await SyncGeodatabase(); } catch (Exception ex) { MessageBox.Show(ex.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. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void DecryptLastByte() { var test = new AesBinaryOpTest__DecryptLastByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Aes.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Aes.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Aes.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Aes.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Aes.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Aes.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Aes.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Aes.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class AesBinaryOpTest__DecryptLastByte { private struct TestStruct { public Vector128<Byte> _fld1; public Vector128<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); return testStruct; } public void RunStructFldScenario(AesBinaryOpTest__DecryptLastByte testClass) { var result = Aes.DecryptLast(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(AesBinaryOpTest__DecryptLastByte testClass) { fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) { var result = Aes.DecryptLast( Aes.LoadVector128((Byte*)(pFld1)), Aes.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[16] {0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01, 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88}; private static Byte[] _data2 = new Byte[16] {0xff, 0xdd, 0xbb, 0x99, 0x77, 0x55, 0x33, 0x11, 0xee, 0xcc, 0xaa, 0x88, 0x66, 0x44, 0x22, 0x00}; private static Byte[] _expectedRet = new Byte[16] {0x9e, 0xbf, 0x72, 0x90, 0x7d, 0xd5, 0xca, 0x36, 0x93, 0xa4, 0xa4, 0x1f, 0x98, 0xdd, 0x10, 0xf2}; private static Vector128<Byte> _clsVar1; private static Vector128<Byte> _clsVar2; private Vector128<Byte> _fld1; private Vector128<Byte> _fld2; private SimpleBinaryOpTest__DataTable<Byte, Byte, Byte> _dataTable; static AesBinaryOpTest__DecryptLastByte() { Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); } public AesBinaryOpTest__DecryptLastByte() { Succeeded = true; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); _dataTable = new SimpleBinaryOpTest__DataTable<Byte, Byte, Byte>(_data1, _data2, new Byte[RetElementCount], LargestVectorSize); } public bool IsSupported => Aes.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Aes.DecryptLast( Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Aes.DecryptLast( Aes.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), Aes.LoadVector128((Byte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Aes.DecryptLast( Aes.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)), Aes.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Aes).GetMethod(nameof(Aes.DecryptLast), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Aes).GetMethod(nameof(Aes.DecryptLast), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Aes.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), Aes.LoadVector128((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Aes).GetMethod(nameof(Aes.DecryptLast), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Aes.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)), Aes.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Aes.DecryptLast( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Byte>* pClsVar1 = &_clsVar1) fixed (Vector128<Byte>* pClsVar2 = &_clsVar2) { var result = Aes.DecryptLast( Aes.LoadVector128((Byte*)(pClsVar1)), Aes.LoadVector128((Byte*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr); var result = Aes.DecryptLast(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Aes.LoadVector128((Byte*)(_dataTable.inArray1Ptr)); var right = Aes.LoadVector128((Byte*)(_dataTable.inArray2Ptr)); var result = Aes.DecryptLast(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Aes.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)); var right = Aes.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)); var result = Aes.DecryptLast(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new AesBinaryOpTest__DecryptLastByte(); var result = Aes.DecryptLast(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new AesBinaryOpTest__DecryptLastByte(); fixed (Vector128<Byte>* pFld1 = &test._fld1) fixed (Vector128<Byte>* pFld2 = &test._fld2) { var result = Aes.DecryptLast( Aes.LoadVector128((Byte*)(pFld1)), Aes.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Aes.DecryptLast(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) { var result = Aes.DecryptLast( Aes.LoadVector128((Byte*)(pFld1)), Aes.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Aes.DecryptLast(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Aes.DecryptLast( Aes.LoadVector128((Byte*)(&test._fld1)), Aes.LoadVector128((Byte*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(void* result, [CallerMemberName] string method = "") { Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(outArray, method); } private void ValidateResult(Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < result.Length; i++) { if (result[i] != _expectedRet[i] ) { succeeded = false; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Aes)}.{nameof(Aes.DecryptLast)}<Byte>(Vector128<Byte>, Vector128<Byte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" expectedRet: ({string.Join(", ", _expectedRet)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Linq; using Zenject.ReflectionBaking.Mono.Cecil; using Zenject.ReflectionBaking.Mono.Cecil.Cil; using NUnit.Framework; namespace Zenject.ReflectionBaking.Mono.Cecil.Tests { [TestFixture] public class MethodBodyTests : BaseTestFixture { [Test] public void MultiplyMethod () { TestIL ("hello.il", module => { var foo = module.GetType ("Foo"); Assert.IsNotNull (foo); var bar = foo.GetMethod ("Bar"); Assert.IsNotNull (bar); Assert.IsTrue (bar.IsIL); AssertCode (@" .locals init (System.Int32 V_0) IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: mul IL_0003: stloc.0 IL_0004: ldloc.0 IL_0005: call System.Void Foo::Baz(System.Int32) IL_000a: ret ", bar); }); } [Test] public void PrintStringEmpty () { TestIL ("hello.il", module => { var foo = module.GetType ("Foo"); Assert.IsNotNull (foo); var print_empty = foo.GetMethod ("PrintEmpty"); Assert.IsNotNull (print_empty); AssertCode (@" .locals () IL_0000: ldsfld System.String System.String::Empty IL_0005: call System.Void System.Console::WriteLine(System.String) IL_000a: ret ", print_empty); }); } [Test] public void Branch () { TestModule ("libhello.dll", module => { var lib = module.GetType ("Library"); Assert.IsNotNull (lib); var method = lib.GetMethod ("GetHelloString"); Assert.IsNotNull (method); AssertCode (@" .locals init (System.String V_0) IL_0000: nop IL_0001: ldstr ""hello world of tomorrow"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret ", method); }); } [Test] public void Switch () { TestModule ("switch.exe", module => { var program = module.GetType ("Program"); Assert.IsNotNull (program); var method = program.GetMethod ("Main"); Assert.IsNotNull (method); AssertCode (@" .locals init (System.Int32 V_0) IL_0000: ldarg.0 IL_0001: ldlen IL_0002: conv.i4 IL_0003: stloc.0 IL_0004: ldloc.0 IL_0005: ldc.i4.8 IL_0006: bgt.s IL_0026 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: sub IL_000b: switch (IL_0032, IL_0034, IL_0038, IL_0034) IL_0020: ldloc.0 IL_0021: ldc.i4.8 IL_0022: beq.s IL_0036 IL_0024: br.s IL_0038 IL_0026: ldloc.0 IL_0027: ldc.i4.s 16 IL_0029: beq.s IL_0036 IL_002b: ldloc.0 IL_002c: ldc.i4.s 32 IL_002e: beq.s IL_0036 IL_0030: br.s IL_0038 IL_0032: ldc.i4.0 IL_0033: ret IL_0034: ldc.i4.1 IL_0035: ret IL_0036: ldc.i4.2 IL_0037: ret IL_0038: ldc.i4.s 42 IL_003a: ret ", method); }); } [Test] public void MethodSpec () { TestIL ("methodspecs.il", module => { var tamtam = module.GetType ("Tamtam"); var bar = tamtam.GetMethod ("Bar"); Assert.IsNotNull (bar); AssertCode (@" .locals () IL_0000: ldc.i4.2 IL_0001: call System.Void Tamtam::Foo<System.Int32>(TFoo) IL_0006: ret ", bar); }); } [Test] public void NestedTryCatchFinally () { TestModule ("catch.exe", module => { var program = module.GetType ("Program"); var main = program.GetMethod ("Main"); Assert.IsNotNull (main); AssertCode (@" .locals () IL_0000: call System.Void Program::Foo() IL_0005: leave.s IL_000d IL_0007: call System.Void Program::Baz() IL_000c: endfinally IL_000d: leave.s IL_001f IL_000f: pop IL_0010: call System.Void Program::Bar() IL_0015: leave.s IL_001f IL_0017: pop IL_0018: call System.Void Program::Bar() IL_001d: leave.s IL_001f IL_001f: leave.s IL_0027 IL_0021: call System.Void Program::Baz() IL_0026: endfinally IL_0027: ret .try IL_0000 to IL_0007 finally handler IL_0007 to IL_000d .try IL_0000 to IL_000f catch System.ArgumentException handler IL_000f to IL_0017 .try IL_0000 to IL_000f catch System.Exception handler IL_0017 to IL_001f .try IL_0000 to IL_0021 finally handler IL_0021 to IL_0027 ", main); }); } [Test] public void FunctionPointersAndCallSites () { TestModule ("fptr.exe", module => { var type = module.Types [0]; var start = type.GetMethod ("Start"); Assert.IsNotNull (start); AssertCode (@" .locals init () IL_0000: ldc.i4.1 IL_0001: call method System.Int32 *(System.Int32) MakeDecision::Decide() IL_0006: calli System.Int32(System.Int32) IL_000b: call System.Void System.Console::WriteLine(System.Int32) IL_0010: ldc.i4.1 IL_0011: call method System.Int32 *(System.Int32) MakeDecision::Decide() IL_0016: calli System.Int32(System.Int32) IL_001b: call System.Void System.Console::WriteLine(System.Int32) IL_0020: ldc.i4.1 IL_0021: call method System.Int32 *(System.Int32) MakeDecision::Decide() IL_0026: calli System.Int32(System.Int32) IL_002b: call System.Void System.Console::WriteLine(System.Int32) IL_0030: ret ", start); }, verify: false); } [Test] public void ThisParameter () { TestIL ("hello.il", module => { var type = module.GetType ("Foo"); var method = type.GetMethod ("Gazonk"); Assert.IsNotNull (method); AssertCode (@" .locals () IL_0000: ldarg 0 IL_0004: pop IL_0005: ret ", method); Assert.AreEqual (method.Body.ThisParameter.ParameterType, type); Assert.AreEqual (method.Body.ThisParameter, method.Body.Instructions [0].Operand); }); } [Test] public void ThisParameterStaticMethod () { var static_method = typeof (ModuleDefinition).ToDefinition ().Methods.Where (m => m.IsStatic).First (); Assert.IsNull (static_method.Body.ThisParameter); } [Test] public void ThisParameterPrimitive () { var int32 = typeof (int).ToDefinition (); var int_to_string = int32.Methods.Where (m => m.Name == "ToString" && m.Parameters.Count == 0).First(); Assert.IsNotNull (int_to_string); var this_parameter_type = int_to_string.Body.ThisParameter.ParameterType; Assert.IsTrue (this_parameter_type.IsPointer); var element_type = ((PointerType) this_parameter_type).ElementType; Assert.AreEqual (int32, element_type); } [Test] public void ThisParameterValueType () { var token = typeof (MetadataToken).ToDefinition (); var token_to_string = token.Methods.Where (m => m.Name == "ToString" && m.Parameters.Count == 0).First (); Assert.IsNotNull (token_to_string); var this_parameter_type = token_to_string.Body.ThisParameter.ParameterType; Assert.IsTrue (this_parameter_type.IsPointer); var element_type = ((PointerType) this_parameter_type).ElementType; Assert.AreEqual (token, element_type); } [Test] public void ThisParameterObject () { var module = typeof (MethodBodyTests).ToDefinition ().Module; var @object = module.TypeSystem.Object.Resolve (); var method = @object.Methods.Where (m => m.HasBody).First (); var type = method.Body.ThisParameter.ParameterType; Assert.IsFalse (type.IsValueType); Assert.IsFalse (type.IsPrimitive); Assert.IsFalse (type.IsPointer); } [Test] public void FilterMaxStack () { TestIL ("hello.il", module => { var type = module.GetType ("Foo"); var method = type.GetMethod ("TestFilter"); Assert.IsNotNull (method); Assert.AreEqual (2, method.Body.MaxStackSize); }); } [Test] public void Iterator () { TestModule ("iterator.exe", module => { var method = module.GetType ("Program").GetMethod ("GetLittleArgs"); Assert.IsNotNull (method.Body); }); } [Test] public void LoadString () { TestCSharp ("CustomAttributes.cs", module => { var type = module.GetType ("FooAttribute"); var get_fiou = type.GetMethod ("get_Fiou"); Assert.IsNotNull (get_fiou); var ldstr = get_fiou.Body.Instructions.Where (i => i.OpCode == OpCodes.Ldstr).First (); Assert.AreEqual ("fiou", ldstr.Operand); }); } [Test] public void UnattachedMethodBody () { var system_void = typeof (void).ToDefinition (); var method = new MethodDefinition ("NewMethod", MethodAttributes.Assembly | MethodAttributes.Static, system_void); var body = new MethodBody (method); var il = body.GetILProcessor (); il.Emit (OpCodes.Ret); method.Body = body; Assert.AreEqual (body, method.Body); } static void AssertCode (string expected, MethodDefinition method) { Assert.IsTrue (method.HasBody); Assert.IsNotNull (method.Body); Assert.AreEqual (Normalize (expected), Normalize (Formatter.FormatMethodBody (method))); } static string Normalize (string str) { return str.Trim ().Replace ("\r\n", "\n"); } [Test] public void AddInstruction () { var object_ref = new TypeReference ("System", "Object", null, null, false); var method = new MethodDefinition ("foo", MethodAttributes.Static, object_ref); var body = new MethodBody (method); var il = body.GetILProcessor (); var first = il.Create (OpCodes.Nop); var second = il.Create (OpCodes.Nop); body.Instructions.Add (first); body.Instructions.Add (second); Assert.IsNull (first.Previous); Assert.AreEqual (second, first.Next); Assert.AreEqual (first, second.Previous); Assert.IsNull (second.Next); } [Test] public void InsertInstruction () { var object_ref = new TypeReference ("System", "Object", null, null, false); var method = new MethodDefinition ("foo", MethodAttributes.Static, object_ref); var body = new MethodBody (method); var il = body.GetILProcessor (); var first = il.Create (OpCodes.Nop); var second = il.Create (OpCodes.Nop); var third = il.Create (OpCodes.Nop); body.Instructions.Add (first); body.Instructions.Add (third); Assert.IsNull (first.Previous); Assert.AreEqual (third, first.Next); Assert.AreEqual (first, third.Previous); Assert.IsNull (third.Next); body.Instructions.Insert (1, second); Assert.IsNull (first.Previous); Assert.AreEqual (second, first.Next); Assert.AreEqual (first, second.Previous); Assert.AreEqual (third, second.Next); Assert.AreEqual (second, third.Previous); Assert.IsNull (third.Next); } [Test] public void InsertAfterLastInstruction () { var object_ref = new TypeReference ("System", "Object", null, null, false); var method = new MethodDefinition ("foo", MethodAttributes.Static, object_ref); var body = new MethodBody (method); var il = body.GetILProcessor (); var first = il.Create (OpCodes.Nop); var second = il.Create (OpCodes.Nop); var third = il.Create (OpCodes.Nop); body.Instructions.Add (first); body.Instructions.Add (second); Assert.IsNull (first.Previous); Assert.AreEqual (second, first.Next); Assert.AreEqual (first, second.Previous); Assert.IsNull (second.Next); body.Instructions.Insert (2, third); Assert.IsNull (first.Previous); Assert.AreEqual (second, first.Next); Assert.AreEqual (first, second.Previous); Assert.AreEqual (third, second.Next); Assert.AreEqual (second, third.Previous); Assert.IsNull (third.Next); } [Test] public void RemoveInstruction () { var object_ref = new TypeReference ("System", "Object", null, null, false); var method = new MethodDefinition ("foo", MethodAttributes.Static, object_ref); var body = new MethodBody (method); var il = body.GetILProcessor (); var first = il.Create (OpCodes.Nop); var second = il.Create (OpCodes.Nop); var third = il.Create (OpCodes.Nop); body.Instructions.Add (first); body.Instructions.Add (second); body.Instructions.Add (third); Assert.IsNull (first.Previous); Assert.AreEqual (second, first.Next); Assert.AreEqual (first, second.Previous); Assert.AreEqual (third, second.Next); Assert.AreEqual (second, third.Previous); Assert.IsNull (third.Next); body.Instructions.Remove (second); Assert.IsNull (first.Previous); Assert.AreEqual (third, first.Next); Assert.AreEqual (first, third.Previous); Assert.IsNull (third.Next); } } }
// Copyright 2014 The Rector & Visitors of the University of Virginia // // 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 Xamarin.Forms; using Sensus.Exceptions; using Sensus.UI.UiProperties; using Newtonsoft.Json; using System.Threading; using System.Collections.Generic; using System.Linq; using Sensus; using Xamarin; using Sensus.UI.Inputs; // register the input effect group [assembly: ResolutionGroupName(Input.EFFECT_RESOLUTION_GROUP_NAME)] namespace Sensus.UI.Inputs { public abstract class Input { public const string EFFECT_RESOLUTION_GROUP_NAME = "InputEffects"; private string _name; private string _id; private string _groupId; private string _labelText; private int _labelFontSize; private View _view; private bool _displayNumber; private bool _complete; private bool _needsToBeStored; private double? _latitude; private double? _longitude; private DateTimeOffset? _locationUpdateTimestamp; private bool _required; private bool _viewed; private DateTimeOffset? _completionTimestamp; private List<InputDisplayCondition> _displayConditions; private Color? _backgroundColor; private Thickness? _padding; private bool _frame; private List<InputCompletionRecord> _completionRecords; private DateTimeOffset? _submissionTimestamp; [EntryStringUiProperty("Name:", true, 0)] public string Name { get { return _name; } set { _name = value; } } public string Id { get { return _id; } set { _id = value; } } public string GroupId { get { return _groupId; } set { _groupId = value; } } [EntryStringUiProperty("Label Text:", true, 1)] public string LabelText { get { return _labelText; } set { _labelText = value; } } public int LabelFontSize { get { return _labelFontSize; } set { _labelFontSize = value; } } public bool DisplayNumber { get { return _displayNumber; } set { _displayNumber = value; } } [JsonIgnore] public abstract object Value { get; } /// <summary> /// Gets or sets a value indicating whether the user has interacted with this <see cref="Input"/>, /// leaving it in a state of completion. Contrast with Valid, which merely indicates that the /// state of the input will not prevent the user from moving through an input request (e.g., in the case /// of inputs that are not required). /// </summary> /// <value><c>true</c> if complete; otherwise, <c>false</c>.</value> [JsonIgnore] public bool Complete { get { return _complete; } protected set { _complete = value; DateTimeOffset timestamp = DateTimeOffset.UtcNow; object inputValue = null; _completionTimestamp = null; if (_complete) { _completionTimestamp = timestamp; // get a deep copy of the value. some inputs have list values, and simply using the list reference wouldn't track the history, since the most up-to-date list would be used for all history values. inputValue = JsonConvert.DeserializeObject<object>(JsonConvert.SerializeObject(Value, SensusServiceHelper.JSON_SERIALIZER_SETTINGS), SensusServiceHelper.JSON_SERIALIZER_SETTINGS); } if (StoreCompletionRecords) _completionRecords.Add(new InputCompletionRecord(timestamp, inputValue)); } } /// <summary> /// Gets a value indicating whether this <see cref="Input"/> is valid. A valid input is one that /// is complete, one that has been viewed but is not required, or one that isn't displayed. In short, it is an /// input state that should not prevent the user from proceeding through an input request. /// </summary> /// <value><c>true</c> if valid; otherwise, <c>false</c>.</value> [JsonIgnore] public bool Valid { get { return _complete || _viewed && !_required || !Display; } } public bool NeedsToBeStored { get { return _needsToBeStored; } set { _needsToBeStored = value; } } public double? Latitude { get { return _latitude; } set { _latitude = value; } } public double? Longitude { get { return _longitude; } set { _longitude = value; } } public DateTimeOffset? LocationUpdateTimestamp { get { return _locationUpdateTimestamp; } set { _locationUpdateTimestamp = value; } } [JsonIgnore] public abstract bool Enabled { get; set; } [JsonIgnore] public abstract string DefaultName { get; } [OnOffUiProperty(null, true, 5)] public bool Required { get { return _required; } set { _required = value; } } public bool Viewed { get { return _viewed; } set { _viewed = value; } } [JsonIgnore] public DateTimeOffset? CompletionTimestamp { get { return _completionTimestamp; } } public List<InputDisplayCondition> DisplayConditions { get { return _displayConditions; } } public Color? BackgroundColor { get { return _backgroundColor; } set { _backgroundColor = value; } } public Thickness? Padding { get { return _padding; } set { _padding = value; } } public bool Frame { get { return _frame; } set { _frame = value; } } public List<InputCompletionRecord> CompletionRecords { get { return _completionRecords; } } public virtual bool StoreCompletionRecords { get { return true; } } [JsonIgnore] public bool Display { get { List<InputDisplayCondition> conjuncts = _displayConditions.Where(displayCondition => displayCondition.Conjunctive).ToList(); if (conjuncts.Count > 0 && conjuncts.Any(displayCondition => !displayCondition.Satisfied)) return false; List<InputDisplayCondition> disjuncts = _displayConditions.Where(displayCondition => !displayCondition.Conjunctive).ToList(); if (disjuncts.Count > 0 && disjuncts.All(displayCondition => !displayCondition.Satisfied)) return false; return true; } } public DateTimeOffset? SubmissionTimestamp { get { return _submissionTimestamp; } set { _submissionTimestamp = value; } } public Input() { _name = DefaultName; _id = Guid.NewGuid().ToString(); _displayNumber = true; _complete = false; _needsToBeStored = true; _required = true; _viewed = false; _completionTimestamp = null; _labelFontSize = 20; _displayConditions = new List<InputDisplayCondition>(); _backgroundColor = null; _padding = null; _frame = true; _completionRecords = new List<InputCompletionRecord>(); _submissionTimestamp = null; } public Input(string labelText) : this() { _labelText = labelText; } public Input(string labelText, int labelFontSize) : this(labelText) { _labelFontSize = labelFontSize; } public Input(string name, string labelText) : this(labelText) { _name = name; } protected Label CreateLabel(int index) { return new Label { Text = GetLabelText(index), FontSize = _labelFontSize // set the style ID on the label so that we can retrieve it when unit testing #if UNIT_TESTING , StyleId = Name + " Label" #endif }; } protected string GetLabelText(int index) { return string.IsNullOrWhiteSpace(_labelText) ? "" : (_required ? "*" : "") + (index > 0 && _displayNumber ? index + ") " : "") + _labelText; } public virtual View GetView(int index) { return _view; } protected virtual void SetView(View value) { ContentView viewContainer = new ContentView { Content = value }; if (_backgroundColor != null) viewContainer.BackgroundColor = _backgroundColor.GetValueOrDefault(); if (_padding != null) viewContainer.Padding = _padding.GetValueOrDefault(); _view = viewContainer; } public void Reset() { _view = null; _complete = false; _needsToBeStored = true; _latitude = null; _longitude = null; _locationUpdateTimestamp = null; _viewed = false; _completionTimestamp = null; _backgroundColor = null; _padding = null; } public virtual bool ValueMatches(object conditionValue, bool conjunctive) { // if either is null, both must be null to be equal if (Value == null || conditionValue == null) return Value == null && conditionValue == null; // if they're of the same type, compare else if (Value.GetType().Equals(conditionValue.GetType())) return Value.Equals(conditionValue); else { // this should never happen try { Insights.Report(new Exception("Called Input.ValueMatches with conditionValue of type " + conditionValue.GetType() + ". Comparing with value of type " + Value.GetType() + "."), Insights.Severity.Critical); } catch (Exception) { } return false; } } public override string ToString() { return _name + (_name == DefaultName ? "" : " -- " + DefaultName) + (_required ? "*" : ""); } public Input Copy(bool newId) { Input copy = JsonConvert.DeserializeObject<Input>(JsonConvert.SerializeObject(this, SensusServiceHelper.JSON_SERIALIZER_SETTINGS), SensusServiceHelper.JSON_SERIALIZER_SETTINGS); copy.Reset(); // the reset on the previous line only resets the state of the input. it does not assign it a new/unique ID, which all inputs require. if (newId) { copy.Id = Guid.NewGuid().ToString(); } return copy; } } }
namespace Nwc.XmlRpc { using System; using System.IO; using System.Net.Sockets; using System.Collections; ///<summary>Very basic HTTP request handler.</summary> ///<remarks>This class is designed to accept a TcpClient and treat it as an HTTP request. /// It will do some basic header parsing and manage the input and output streams associated /// with the request.</remarks> public class SimpleHttpRequest { private String _httpMethod = null; private String _protocol; private String _filePathFile = null; private String _filePathDir = null; private String __filePath; private TcpClient _client; private StreamReader _input; private StreamWriter _output; private Hashtable _headers; /// <summary>A constructor which accepts the TcpClient.</summary> /// <remarks>It creates the associated input and output streams, determines the request type, /// and parses the remaining HTTP header.</remarks> /// <param name="client">The <c>TcpClient</c> associated with the HTTP connection.</param> public SimpleHttpRequest(TcpClient client) { _client = client; _output = new StreamWriter(client.GetStream()); _input = new StreamReader(client.GetStream()); GetRequestMethod(); GetRequestHeaders(); } /// <summary>The output <c>StreamWriter</c> associated with the request.</summary> public StreamWriter Output { get { return _output; } } /// <summary>The input <c>StreamReader</c> associated with the request.</summary> public StreamReader Input { get { return _input; } } /// <summary>The <c>TcpClient</c> with the request.</summary> public TcpClient Client { get { return _client; } } private String _filePath { get { return __filePath; } set { __filePath = value; _filePathDir = null; _filePathFile = null; } } /// <summary>The type of HTTP request (i.e. PUT, GET, etc.).</summary> public String HttpMethod { get { return _httpMethod; } } /// <summary>The level of the HTTP protocol.</summary> public String Protocol { get { return _protocol; } } /// <summary>The "path" which is part of any HTTP request.</summary> public String FilePath { get { return _filePath; } } /// <summary>The file portion of the "path" which is part of any HTTP request.</summary> public String FilePathFile { get { if (_filePathFile != null) return _filePathFile; int i = FilePath.LastIndexOf("/"); if (i == -1) return ""; i++; _filePathFile = FilePath.Substring(i, FilePath.Length - i); return _filePathFile; } } /// <summary>The directory portion of the "path" which is part of any HTTP request.</summary> public String FilePathDir { get { if (_filePathDir != null) return _filePathDir; int i = FilePath.LastIndexOf("/"); if (i == -1) return ""; i++; _filePathDir = FilePath.Substring(0, i); return _filePathDir; } } private void GetRequestMethod() { string req = _input.ReadLine(); if (req == null) throw new ApplicationException("Void request."); if (0 == String.Compare("GET ", req.Substring (0, 4), true)) _httpMethod = "GET"; else if (0 == String.Compare("POST ", req.Substring (0, 5), true)) _httpMethod = "POST"; else throw new InvalidOperationException("Unrecognized method in query: " + req); req = req.TrimEnd (); int idx = req.IndexOf(' ') + 1; if (idx >= req.Length) throw new ApplicationException ("What do you want?"); string page_protocol = req.Substring(idx); int idx2 = page_protocol.IndexOf(' '); if (idx2 == -1) idx2 = page_protocol.Length; _filePath = page_protocol.Substring(0, idx2).Trim(); _protocol = page_protocol.Substring(idx2).Trim(); } private void GetRequestHeaders() { String line; int idx; _headers = new Hashtable(); while ((line = _input.ReadLine ()) != "") { if (line == null) { break; } idx = line.IndexOf (':'); if (idx == -1 || idx == line.Length - 1) { Logger.WriteEntry("Malformed header line: " + line, LogLevel.Information); continue; } String key = line.Substring (0, idx); String value = line.Substring (idx + 1); try { _headers.Add(key, value); } catch (Exception) { Logger.WriteEntry("Duplicate header key in line: " + line, LogLevel.Information); } } } /// <summary> /// Format the object contents into a useful string representation. /// </summary> ///<returns><c>String</c> representation of the <c>SimpleHttpRequest</c> as the <i>HttpMethod FilePath Protocol</i>.</returns> override public String ToString() { return HttpMethod + " " + FilePath + " " + Protocol; } /// <summary> /// Close the <c>SimpleHttpRequest</c>. This flushes and closes all associated io streams. /// </summary> public void Close() { _output.Flush(); _output.Close(); _input.Close(); _client.Close(); } } }
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 SharePoint.Utilities { 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 } }
/* * 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; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Security; using System.Timers; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using RegionFlags = OpenMetaverse.RegionFlags; namespace OpenSim.Region.CoreModules.World.Estate { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "EstateManagementModule")] public class EstateManagementModule : IEstateModule, INonSharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Timer m_regionChangeTimer = new Timer(); public Scene Scene { get; private set; } public IUserManagement UserManager { get; private set; } protected EstateManagementCommands m_commands; /// <summary> /// If false, region restart requests from the client are blocked even if they are otherwise legitimate. /// </summary> public bool AllowRegionRestartFromClient { get; set; } private EstateTerrainXferHandler TerrainUploader; public TelehubManager m_Telehub; public event ChangeDelegate OnRegionInfoChange; public event ChangeDelegate OnEstateInfoChange; public event MessageDelegate OnEstateMessage; private int m_delayCount = 0; #region Region Module interface public string Name { get { return "EstateManagementModule"; } } public Type ReplaceableInterface { get { return null; } } public void Initialise(IConfigSource source) { AllowRegionRestartFromClient = true; IConfig config = source.Configs["EstateManagement"]; if (config != null) AllowRegionRestartFromClient = config.GetBoolean("AllowRegionRestartFromClient", true); } public void AddRegion(Scene scene) { Scene = scene; Scene.RegisterModuleInterface<IEstateModule>(this); Scene.EventManager.OnNewClient += EventManager_OnNewClient; Scene.EventManager.OnRequestChangeWaterHeight += changeWaterHeight; m_Telehub = new TelehubManager(scene); m_commands = new EstateManagementCommands(this); m_commands.Initialise(); } public void RemoveRegion(Scene scene) {} public void RegionLoaded(Scene scene) { // Sets up the sun module based no the saved Estate and Region Settings // DO NOT REMOVE or the sun will stop working scene.TriggerEstateSunUpdate(); UserManager = scene.RequestModuleInterface<IUserManagement>(); } public void Close() { m_commands.Close(); } #endregion #region Packet Data Responders private void clientSendDetailedEstateData(IClientAPI remote_client, UUID invoice) { sendDetailedEstateData(remote_client, invoice); sendEstateLists(remote_client, invoice); } private void sendDetailedEstateData(IClientAPI remote_client, UUID invoice) { uint sun = 0; if (Scene.RegionInfo.EstateSettings.FixedSun) sun = (uint)(Scene.RegionInfo.EstateSettings.SunPosition * 1024.0) + 0x1800; UUID estateOwner; estateOwner = Scene.RegionInfo.EstateSettings.EstateOwner; if (Scene.Permissions.IsGod(remote_client.AgentId)) estateOwner = remote_client.AgentId; remote_client.SendDetailedEstateData(invoice, Scene.RegionInfo.EstateSettings.EstateName, Scene.RegionInfo.EstateSettings.EstateID, Scene.RegionInfo.EstateSettings.ParentEstateID, GetEstateFlags(), sun, Scene.RegionInfo.RegionSettings.Covenant, (uint) Scene.RegionInfo.RegionSettings.CovenantChangedDateTime, Scene.RegionInfo.EstateSettings.AbuseEmail, estateOwner); } private void sendEstateLists(IClientAPI remote_client, UUID invoice) { remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.EstateManagers, Scene.RegionInfo.EstateSettings.EstateManagers, Scene.RegionInfo.EstateSettings.EstateID); remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AccessOptions, Scene.RegionInfo.EstateSettings.EstateAccess, Scene.RegionInfo.EstateSettings.EstateID); remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AllowedGroups, Scene.RegionInfo.EstateSettings.EstateGroups, Scene.RegionInfo.EstateSettings.EstateID); remote_client.SendBannedUserList(invoice, Scene.RegionInfo.EstateSettings.EstateBans, Scene.RegionInfo.EstateSettings.EstateID); } private void estateSetRegionInfoHandler(bool blockTerraform, bool noFly, bool allowDamage, bool blockLandResell, int maxAgents, float objectBonusFactor, int matureLevel, bool restrictPushObject, bool allowParcelChanges) { if (blockTerraform) Scene.RegionInfo.RegionSettings.BlockTerraform = true; else Scene.RegionInfo.RegionSettings.BlockTerraform = false; if (noFly) Scene.RegionInfo.RegionSettings.BlockFly = true; else Scene.RegionInfo.RegionSettings.BlockFly = false; if (allowDamage) Scene.RegionInfo.RegionSettings.AllowDamage = true; else Scene.RegionInfo.RegionSettings.AllowDamage = false; if (blockLandResell) Scene.RegionInfo.RegionSettings.AllowLandResell = false; else Scene.RegionInfo.RegionSettings.AllowLandResell = true; if((byte)maxAgents <= Scene.RegionInfo.AgentCapacity) Scene.RegionInfo.RegionSettings.AgentLimit = (byte) maxAgents; else Scene.RegionInfo.RegionSettings.AgentLimit = Scene.RegionInfo.AgentCapacity; Scene.RegionInfo.RegionSettings.ObjectBonus = objectBonusFactor; if (matureLevel <= 13) Scene.RegionInfo.RegionSettings.Maturity = 0; else if (matureLevel <= 21) Scene.RegionInfo.RegionSettings.Maturity = 1; else Scene.RegionInfo.RegionSettings.Maturity = 2; if (restrictPushObject) Scene.RegionInfo.RegionSettings.RestrictPushing = true; else Scene.RegionInfo.RegionSettings.RestrictPushing = false; if (allowParcelChanges) Scene.RegionInfo.RegionSettings.AllowLandJoinDivide = true; else Scene.RegionInfo.RegionSettings.AllowLandJoinDivide = false; Scene.RegionInfo.RegionSettings.Save(); TriggerRegionInfoChange(); sendRegionInfoPacketToAll(); } public void setEstateTerrainBaseTexture(int level, UUID texture) { setEstateTerrainBaseTexture(null, level, texture); sendRegionHandshakeToAll(); } public void setEstateTerrainBaseTexture(IClientAPI remoteClient, int level, UUID texture) { if (texture == UUID.Zero) return; switch (level) { case 0: Scene.RegionInfo.RegionSettings.TerrainTexture1 = texture; break; case 1: Scene.RegionInfo.RegionSettings.TerrainTexture2 = texture; break; case 2: Scene.RegionInfo.RegionSettings.TerrainTexture3 = texture; break; case 3: Scene.RegionInfo.RegionSettings.TerrainTexture4 = texture; break; } Scene.RegionInfo.RegionSettings.Save(); TriggerRegionInfoChange(); sendRegionInfoPacketToAll(); } public void setEstateTerrainTextureHeights(int corner, float lowValue, float highValue) { setEstateTerrainTextureHeights(null, corner, lowValue, highValue); } public void setEstateTerrainTextureHeights(IClientAPI client, int corner, float lowValue, float highValue) { switch (corner) { case 0: Scene.RegionInfo.RegionSettings.Elevation1SW = lowValue; Scene.RegionInfo.RegionSettings.Elevation2SW = highValue; break; case 1: Scene.RegionInfo.RegionSettings.Elevation1NW = lowValue; Scene.RegionInfo.RegionSettings.Elevation2NW = highValue; break; case 2: Scene.RegionInfo.RegionSettings.Elevation1SE = lowValue; Scene.RegionInfo.RegionSettings.Elevation2SE = highValue; break; case 3: Scene.RegionInfo.RegionSettings.Elevation1NE = lowValue; Scene.RegionInfo.RegionSettings.Elevation2NE = highValue; break; } Scene.RegionInfo.RegionSettings.Save(); TriggerRegionInfoChange(); sendRegionHandshakeToAll(); sendRegionInfoPacketToAll(); } private void handleCommitEstateTerrainTextureRequest(IClientAPI remoteClient) { // sendRegionHandshakeToAll(); } public void setRegionTerrainSettings(float WaterHeight, float TerrainRaiseLimit, float TerrainLowerLimit, bool UseEstateSun, bool UseFixedSun, float SunHour, bool UseGlobal, bool EstateFixedSun, float EstateSunHour) { // Water Height Scene.RegionInfo.RegionSettings.WaterHeight = WaterHeight; // Terraforming limits Scene.RegionInfo.RegionSettings.TerrainRaiseLimit = TerrainRaiseLimit; Scene.RegionInfo.RegionSettings.TerrainLowerLimit = TerrainLowerLimit; // Time of day / fixed sun Scene.RegionInfo.RegionSettings.UseEstateSun = UseEstateSun; Scene.RegionInfo.RegionSettings.FixedSun = UseFixedSun; Scene.RegionInfo.RegionSettings.SunPosition = SunHour; Scene.TriggerEstateSunUpdate(); //m_log.Debug("[ESTATE]: UFS: " + UseFixedSun.ToString()); //m_log.Debug("[ESTATE]: SunHour: " + SunHour.ToString()); sendRegionInfoPacketToAll(); Scene.RegionInfo.RegionSettings.Save(); TriggerRegionInfoChange(); } private void handleEstateRestartSimRequest(IClientAPI remoteClient, int timeInSeconds) { if (!AllowRegionRestartFromClient) { remoteClient.SendAlertMessage("Region restart has been disabled on this simulator."); return; } IRestartModule restartModule = Scene.RequestModuleInterface<IRestartModule>(); if (restartModule != null) { List<int> times = new List<int>(); while (timeInSeconds > 0) { times.Add(timeInSeconds); if (timeInSeconds > 300) timeInSeconds -= 120; else if (timeInSeconds > 30) timeInSeconds -= 30; else timeInSeconds -= 15; } restartModule.ScheduleRestart(UUID.Zero, "Region will restart in {0}", times.ToArray(), false); m_log.InfoFormat( "User {0} requested restart of region {1} in {2} seconds", remoteClient.Name, Scene.Name, times.Count != 0 ? times[0] : 0); } } private void handleChangeEstateCovenantRequest(IClientAPI remoteClient, UUID estateCovenantID) { // m_log.DebugFormat( // "[ESTATE MANAGEMENT MODULE]: Handling request from {0} to change estate covenant to {1}", // remoteClient.Name, estateCovenantID); Scene.RegionInfo.RegionSettings.Covenant = estateCovenantID; Scene.RegionInfo.RegionSettings.CovenantChangedDateTime = Util.UnixTimeSinceEpoch(); Scene.RegionInfo.RegionSettings.Save(); TriggerRegionInfoChange(); } private void handleEstateAccessDeltaRequest(IClientAPI remote_client, UUID invoice, int estateAccessType, UUID user) { // EstateAccessDelta handles Estate Managers, Sim Access, Sim Banlist, allowed Groups.. etc. if (user == Scene.RegionInfo.EstateSettings.EstateOwner) return; // never process EO if ((estateAccessType & 4) != 0) // User add { if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true)) { if ((estateAccessType & 1) != 0) // All estates { List<int> estateIDs = Scene.EstateDataService.GetEstatesByOwner(Scene.RegionInfo.EstateSettings.EstateOwner); EstateSettings estateSettings; foreach (int estateID in estateIDs) { if (estateID != Scene.RegionInfo.EstateSettings.EstateID) { estateSettings = Scene.EstateDataService.LoadEstateSettings(estateID); estateSettings.AddEstateUser(user); estateSettings.Save(); } } } Scene.RegionInfo.EstateSettings.AddEstateUser(user); Scene.RegionInfo.EstateSettings.Save(); TriggerEstateInfoChange(); remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AccessOptions, Scene.RegionInfo.EstateSettings.EstateAccess, Scene.RegionInfo.EstateSettings.EstateID); } else { remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions"); } } if ((estateAccessType & 8) != 0) // User remove { if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true)) { if ((estateAccessType & 1) != 0) // All estates { List<int> estateIDs = Scene.EstateDataService.GetEstatesByOwner(Scene.RegionInfo.EstateSettings.EstateOwner); EstateSettings estateSettings; foreach (int estateID in estateIDs) { if (estateID != Scene.RegionInfo.EstateSettings.EstateID) { estateSettings = Scene.EstateDataService.LoadEstateSettings(estateID); estateSettings.RemoveEstateUser(user); estateSettings.Save(); } } } Scene.RegionInfo.EstateSettings.RemoveEstateUser(user); Scene.RegionInfo.EstateSettings.Save(); TriggerEstateInfoChange(); remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AccessOptions, Scene.RegionInfo.EstateSettings.EstateAccess, Scene.RegionInfo.EstateSettings.EstateID); } else { remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions"); } } if ((estateAccessType & 16) != 0) // Group add { if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true)) { if ((estateAccessType & 1) != 0) // All estates { List<int> estateIDs = Scene.EstateDataService.GetEstatesByOwner(Scene.RegionInfo.EstateSettings.EstateOwner); EstateSettings estateSettings; foreach (int estateID in estateIDs) { if (estateID != Scene.RegionInfo.EstateSettings.EstateID) { estateSettings = Scene.EstateDataService.LoadEstateSettings(estateID); estateSettings.AddEstateGroup(user); estateSettings.Save(); } } } Scene.RegionInfo.EstateSettings.AddEstateGroup(user); Scene.RegionInfo.EstateSettings.Save(); TriggerEstateInfoChange(); remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AllowedGroups, Scene.RegionInfo.EstateSettings.EstateGroups, Scene.RegionInfo.EstateSettings.EstateID); } else { remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions"); } } if ((estateAccessType & 32) != 0) // Group remove { if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true)) { if ((estateAccessType & 1) != 0) // All estates { List<int> estateIDs = Scene.EstateDataService.GetEstatesByOwner(Scene.RegionInfo.EstateSettings.EstateOwner); EstateSettings estateSettings; foreach (int estateID in estateIDs) { if (estateID != Scene.RegionInfo.EstateSettings.EstateID) { estateSettings = Scene.EstateDataService.LoadEstateSettings(estateID); estateSettings.RemoveEstateGroup(user); estateSettings.Save(); } } } Scene.RegionInfo.EstateSettings.RemoveEstateGroup(user); Scene.RegionInfo.EstateSettings.Save(); TriggerEstateInfoChange(); remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AllowedGroups, Scene.RegionInfo.EstateSettings.EstateGroups, Scene.RegionInfo.EstateSettings.EstateID); } else { remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions"); } } if ((estateAccessType & 64) != 0) // Ban add { if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, false)) { EstateBan[] banlistcheck = Scene.RegionInfo.EstateSettings.EstateBans; bool alreadyInList = false; for (int i = 0; i < banlistcheck.Length; i++) { if (user == banlistcheck[i].BannedUserID) { alreadyInList = true; break; } } if (!alreadyInList) { if ((estateAccessType & 1) != 0) // All estates { List<int> estateIDs = Scene.EstateDataService.GetEstatesByOwner(Scene.RegionInfo.EstateSettings.EstateOwner); EstateSettings estateSettings; foreach (int estateID in estateIDs) { if (estateID != Scene.RegionInfo.EstateSettings.EstateID) { EstateBan bitem = new EstateBan(); bitem.BannedUserID = user; bitem.EstateID = (uint)estateID; bitem.BannedHostAddress = "0.0.0.0"; bitem.BannedHostIPMask = "0.0.0.0"; estateSettings = Scene.EstateDataService.LoadEstateSettings(estateID); estateSettings.AddBan(bitem); estateSettings.Save(); } } } EstateBan item = new EstateBan(); item.BannedUserID = user; item.EstateID = Scene.RegionInfo.EstateSettings.EstateID; item.BannedHostAddress = "0.0.0.0"; item.BannedHostIPMask = "0.0.0.0"; Scene.RegionInfo.EstateSettings.AddBan(item); Scene.RegionInfo.EstateSettings.Save(); TriggerEstateInfoChange(); ScenePresence s = Scene.GetScenePresence(user); if (s != null) { if (!s.IsChildAgent) { if (!Scene.TeleportClientHome(user, s.ControllingClient)) { s.ControllingClient.Kick("Your access to the region was revoked and TP home failed - you have been logged out."); Scene.CloseAgent(s.UUID, false); } } } } else { remote_client.SendAlertMessage("User is already on the region ban list"); } //Scene.RegionInfo.regionBanlist.Add(Manager(user); remote_client.SendBannedUserList(invoice, Scene.RegionInfo.EstateSettings.EstateBans, Scene.RegionInfo.EstateSettings.EstateID); } else { remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions"); } } if ((estateAccessType & 128) != 0) // Ban remove { if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, false)) { EstateBan[] banlistcheck = Scene.RegionInfo.EstateSettings.EstateBans; bool alreadyInList = false; EstateBan listitem = null; for (int i = 0; i < banlistcheck.Length; i++) { if (user == banlistcheck[i].BannedUserID) { alreadyInList = true; listitem = banlistcheck[i]; break; } } if (alreadyInList && listitem != null) { if ((estateAccessType & 1) != 0) // All estates { List<int> estateIDs = Scene.EstateDataService.GetEstatesByOwner(Scene.RegionInfo.EstateSettings.EstateOwner); EstateSettings estateSettings; foreach (int estateID in estateIDs) { if (estateID != Scene.RegionInfo.EstateSettings.EstateID) { estateSettings = Scene.EstateDataService.LoadEstateSettings(estateID); estateSettings.RemoveBan(user); estateSettings.Save(); } } } Scene.RegionInfo.EstateSettings.RemoveBan(listitem.BannedUserID); Scene.RegionInfo.EstateSettings.Save(); TriggerEstateInfoChange(); } else { remote_client.SendAlertMessage("User is not on the region ban list"); } //Scene.RegionInfo.regionBanlist.Add(Manager(user); remote_client.SendBannedUserList(invoice, Scene.RegionInfo.EstateSettings.EstateBans, Scene.RegionInfo.EstateSettings.EstateID); } else { remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions"); } } if ((estateAccessType & 256) != 0) // Manager add { if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true)) { if ((estateAccessType & 1) != 0) // All estates { List<int> estateIDs = Scene.EstateDataService.GetEstatesByOwner(Scene.RegionInfo.EstateSettings.EstateOwner); EstateSettings estateSettings; foreach (int estateID in estateIDs) { if (estateID != Scene.RegionInfo.EstateSettings.EstateID) { estateSettings = Scene.EstateDataService.LoadEstateSettings(estateID); estateSettings.AddEstateManager(user); estateSettings.Save(); } } } Scene.RegionInfo.EstateSettings.AddEstateManager(user); Scene.RegionInfo.EstateSettings.Save(); TriggerEstateInfoChange(); remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.EstateManagers, Scene.RegionInfo.EstateSettings.EstateManagers, Scene.RegionInfo.EstateSettings.EstateID); } else { remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions"); } } if ((estateAccessType & 512) != 0) // Manager remove { if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true)) { if ((estateAccessType & 1) != 0) // All estates { List<int> estateIDs = Scene.EstateDataService.GetEstatesByOwner(Scene.RegionInfo.EstateSettings.EstateOwner); EstateSettings estateSettings; foreach (int estateID in estateIDs) { if (estateID != Scene.RegionInfo.EstateSettings.EstateID) { estateSettings = Scene.EstateDataService.LoadEstateSettings(estateID); estateSettings.RemoveEstateManager(user); estateSettings.Save(); } } } Scene.RegionInfo.EstateSettings.RemoveEstateManager(user); Scene.RegionInfo.EstateSettings.Save(); TriggerEstateInfoChange(); remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.EstateManagers, Scene.RegionInfo.EstateSettings.EstateManagers, Scene.RegionInfo.EstateSettings.EstateID); } else { remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions"); } } } public void HandleOnEstateManageTelehub(IClientAPI client, UUID invoice, UUID senderID, string cmd, uint param1) { SceneObjectPart part; switch (cmd) { case "info ui": break; case "connect": // Add the Telehub part = Scene.GetSceneObjectPart((uint)param1); if (part == null) return; SceneObjectGroup grp = part.ParentGroup; m_Telehub.Connect(grp); break; case "delete": // Disconnect Telehub m_Telehub.Disconnect(); break; case "spawnpoint add": // Add SpawnPoint to the Telehub part = Scene.GetSceneObjectPart((uint)param1); if (part == null) return; m_Telehub.AddSpawnPoint(part.AbsolutePosition); break; case "spawnpoint remove": // Remove SpawnPoint from Telehub m_Telehub.RemoveSpawnPoint((int)param1); break; default: break; } if (client != null) SendTelehubInfo(client); } private void SendSimulatorBlueBoxMessage( IClientAPI remote_client, UUID invoice, UUID senderID, UUID sessionID, string senderName, string message) { IDialogModule dm = Scene.RequestModuleInterface<IDialogModule>(); if (dm != null) dm.SendNotificationToUsersInRegion(senderID, senderName, message); } private void SendEstateBlueBoxMessage( IClientAPI remote_client, UUID invoice, UUID senderID, UUID sessionID, string senderName, string message) { TriggerEstateMessage(senderID, senderName, message); } private void handleEstateDebugRegionRequest( IClientAPI remote_client, UUID invoice, UUID senderID, bool disableScripts, bool disableCollisions, bool disablePhysics) { Scene.RegionInfo.RegionSettings.DisablePhysics = disablePhysics; Scene.RegionInfo.RegionSettings.DisableScripts = disableScripts; Scene.RegionInfo.RegionSettings.DisableCollisions = disableCollisions; Scene.RegionInfo.RegionSettings.Save(); TriggerRegionInfoChange(); ISceneCommandsModule scm = Scene.RequestModuleInterface<ISceneCommandsModule>(); if (scm != null) { scm.SetSceneDebugOptions( new Dictionary<string, string>() { { "scripting", (!disableScripts).ToString() }, { "collisions", (!disableCollisions).ToString() }, { "physics", (!disablePhysics).ToString() } } ); } } private void handleEstateTeleportOneUserHomeRequest(IClientAPI remover_client, UUID invoice, UUID senderID, UUID prey) { if (!Scene.Permissions.CanIssueEstateCommand(remover_client.AgentId, false)) return; if (prey != UUID.Zero) { ScenePresence s = Scene.GetScenePresence(prey); if (s != null) { if (!Scene.TeleportClientHome(prey, s.ControllingClient)) { s.ControllingClient.Kick("You were teleported home by the region owner, but the TP failed - you have been logged out."); Scene.CloseAgent(s.UUID, false); } } } } private void handleEstateTeleportAllUsersHomeRequest(IClientAPI remover_client, UUID invoice, UUID senderID) { if (!Scene.Permissions.CanIssueEstateCommand(remover_client.AgentId, false)) return; Scene.ForEachRootClient(delegate(IClientAPI client) { if (client.AgentId != senderID) { // make sure they are still there, we could be working down a long list // Also make sure they are actually in the region ScenePresence p; if(Scene.TryGetScenePresence(client.AgentId, out p)) { if (!Scene.TeleportClientHome(p.UUID, p.ControllingClient)) { p.ControllingClient.Kick("You were teleported home by the region owner, but the TP failed - you have been logged out."); Scene.CloseAgent(p.UUID, false); } } } }); } private void AbortTerrainXferHandler(IClientAPI remoteClient, ulong XferID) { if (TerrainUploader != null) { lock (TerrainUploader) { if (XferID == TerrainUploader.XferID) { remoteClient.OnXferReceive -= TerrainUploader.XferReceive; remoteClient.OnAbortXfer -= AbortTerrainXferHandler; TerrainUploader.TerrainUploadDone -= HandleTerrainApplication; TerrainUploader = null; remoteClient.SendAlertMessage("Terrain Upload aborted by the client"); } } } } private void HandleTerrainApplication(string filename, byte[] terrainData, IClientAPI remoteClient) { lock (TerrainUploader) { remoteClient.OnXferReceive -= TerrainUploader.XferReceive; remoteClient.OnAbortXfer -= AbortTerrainXferHandler; TerrainUploader.TerrainUploadDone -= HandleTerrainApplication; TerrainUploader = null; } remoteClient.SendAlertMessage("Terrain Upload Complete. Loading...."); ITerrainModule terr = Scene.RequestModuleInterface<ITerrainModule>(); if (terr != null) { m_log.Warn("[CLIENT]: Got Request to Send Terrain in region " + Scene.RegionInfo.RegionName); try { MemoryStream terrainStream = new MemoryStream(terrainData); terr.LoadFromStream(filename, terrainStream); terrainStream.Close(); FileInfo x = new FileInfo(filename); remoteClient.SendAlertMessage("Your terrain was loaded as a " + x.Extension + " file. It may take a few moments to appear."); } catch (IOException e) { m_log.ErrorFormat("[TERRAIN]: Error Saving a terrain file uploaded via the estate tools. It gave us the following error: {0}", e.ToString()); remoteClient.SendAlertMessage("There was an IO Exception loading your terrain. Please check free space."); return; } catch (SecurityException e) { m_log.ErrorFormat("[TERRAIN]: Error Saving a terrain file uploaded via the estate tools. It gave us the following error: {0}", e.ToString()); remoteClient.SendAlertMessage("There was a security Exception loading your terrain. Please check the security on the simulator drive"); return; } catch (UnauthorizedAccessException e) { m_log.ErrorFormat("[TERRAIN]: Error Saving a terrain file uploaded via the estate tools. It gave us the following error: {0}", e.ToString()); remoteClient.SendAlertMessage("There was a security Exception loading your terrain. Please check the security on the simulator drive"); return; } catch (Exception e) { m_log.ErrorFormat("[TERRAIN]: Error loading a terrain file uploaded via the estate tools. It gave us the following error: {0}", e.ToString()); remoteClient.SendAlertMessage("There was a general error loading your terrain. Please fix the terrain file and try again"); } } else { remoteClient.SendAlertMessage("Unable to apply terrain. Cannot get an instance of the terrain module"); } } private void handleUploadTerrain(IClientAPI remote_client, string clientFileName) { if (TerrainUploader == null) { TerrainUploader = new EstateTerrainXferHandler(remote_client, clientFileName); lock (TerrainUploader) { remote_client.OnXferReceive += TerrainUploader.XferReceive; remote_client.OnAbortXfer += AbortTerrainXferHandler; TerrainUploader.TerrainUploadDone += HandleTerrainApplication; } TerrainUploader.RequestStartXfer(remote_client); } else { remote_client.SendAlertMessage("Another Terrain Upload is in progress. Please wait your turn!"); } } private void handleTerrainRequest(IClientAPI remote_client, string clientFileName) { // Save terrain here ITerrainModule terr = Scene.RequestModuleInterface<ITerrainModule>(); if (terr != null) { m_log.Warn("[CLIENT]: Got Request to Send Terrain in region " + Scene.RegionInfo.RegionName); if (File.Exists(Util.dataDir() + "/terrain.raw")) { File.Delete(Util.dataDir() + "/terrain.raw"); } terr.SaveToFile(Util.dataDir() + "/terrain.raw"); FileStream input = new FileStream(Util.dataDir() + "/terrain.raw", FileMode.Open); byte[] bdata = new byte[input.Length]; input.Read(bdata, 0, (int)input.Length); remote_client.SendAlertMessage("Terrain file written, starting download..."); Scene.XferManager.AddNewFile("terrain.raw", bdata); // Tell client about it m_log.Warn("[CLIENT]: Sending Terrain to " + remote_client.Name); remote_client.SendInitiateDownload("terrain.raw", clientFileName); } } private void HandleRegionInfoRequest(IClientAPI remote_client) { RegionInfoForEstateMenuArgs args = new RegionInfoForEstateMenuArgs(); args.billableFactor = Scene.RegionInfo.EstateSettings.BillableFactor; args.estateID = Scene.RegionInfo.EstateSettings.EstateID; args.maxAgents = (byte)Scene.RegionInfo.RegionSettings.AgentLimit; args.objectBonusFactor = (float)Scene.RegionInfo.RegionSettings.ObjectBonus; args.parentEstateID = Scene.RegionInfo.EstateSettings.ParentEstateID; args.pricePerMeter = Scene.RegionInfo.EstateSettings.PricePerMeter; args.redirectGridX = Scene.RegionInfo.EstateSettings.RedirectGridX; args.redirectGridY = Scene.RegionInfo.EstateSettings.RedirectGridY; args.regionFlags = GetRegionFlags(); args.simAccess = Scene.RegionInfo.AccessLevel; args.sunHour = (float)Scene.RegionInfo.RegionSettings.SunPosition; args.terrainLowerLimit = (float)Scene.RegionInfo.RegionSettings.TerrainLowerLimit; args.terrainRaiseLimit = (float)Scene.RegionInfo.RegionSettings.TerrainRaiseLimit; args.useEstateSun = Scene.RegionInfo.RegionSettings.UseEstateSun; args.waterHeight = (float)Scene.RegionInfo.RegionSettings.WaterHeight; args.simName = Scene.RegionInfo.RegionName; args.regionType = Scene.RegionInfo.RegionType; remote_client.SendRegionInfoToEstateMenu(args); } private void HandleEstateCovenantRequest(IClientAPI remote_client) { remote_client.SendEstateCovenantInformation(Scene.RegionInfo.RegionSettings.Covenant); } private void HandleLandStatRequest(int parcelID, uint reportType, uint requestFlags, string filter, IClientAPI remoteClient) { if (!Scene.Permissions.CanIssueEstateCommand(remoteClient.AgentId, false)) return; Dictionary<uint, float> sceneData = null; if (reportType == 1) { sceneData = Scene.PhysicsScene.GetTopColliders(); } else if (reportType == 0) { IScriptModule scriptModule = Scene.RequestModuleInterface<IScriptModule>(); if (scriptModule != null) sceneData = scriptModule.GetObjectScriptsExecutionTimes(); } List<LandStatReportItem> SceneReport = new List<LandStatReportItem>(); if (sceneData != null) { var sortedSceneData = sceneData.Select( item => new { Measurement = item.Value, Part = Scene.GetSceneObjectPart(item.Key) }); sortedSceneData.OrderBy(item => item.Measurement); int items = 0; foreach (var entry in sortedSceneData) { // The object may have been deleted since we received the data. if (entry.Part == null) continue; // Don't show scripts that haven't executed or where execution time is below one microsecond in // order to produce a more readable report. if (entry.Measurement < 0.001) continue; items++; SceneObjectGroup so = entry.Part.ParentGroup; LandStatReportItem lsri = new LandStatReportItem(); lsri.LocationX = so.AbsolutePosition.X; lsri.LocationY = so.AbsolutePosition.Y; lsri.LocationZ = so.AbsolutePosition.Z; lsri.Score = entry.Measurement; lsri.TaskID = so.UUID; lsri.TaskLocalID = so.LocalId; lsri.TaskName = entry.Part.Name; lsri.OwnerName = UserManager.GetUserName(so.OwnerID); if (filter.Length != 0) { if ((lsri.OwnerName.Contains(filter) || lsri.TaskName.Contains(filter))) { } else { continue; } } SceneReport.Add(lsri); if (items >= 100) break; } } remoteClient.SendLandStatReply(reportType, requestFlags, (uint)SceneReport.Count,SceneReport.ToArray()); } #endregion #region Outgoing Packets public void sendRegionInfoPacketToAll() { Scene.ForEachRootClient(delegate(IClientAPI client) { HandleRegionInfoRequest(client); }); } public void sendRegionHandshake(IClientAPI remoteClient) { RegionHandshakeArgs args = new RegionHandshakeArgs(); args.isEstateManager = Scene.RegionInfo.EstateSettings.IsEstateManagerOrOwner(remoteClient.AgentId); if (Scene.RegionInfo.EstateSettings.EstateOwner != UUID.Zero && Scene.RegionInfo.EstateSettings.EstateOwner == remoteClient.AgentId) args.isEstateManager = true; args.billableFactor = Scene.RegionInfo.EstateSettings.BillableFactor; args.terrainStartHeight0 = (float)Scene.RegionInfo.RegionSettings.Elevation1SW; args.terrainHeightRange0 = (float)Scene.RegionInfo.RegionSettings.Elevation2SW; args.terrainStartHeight1 = (float)Scene.RegionInfo.RegionSettings.Elevation1NW; args.terrainHeightRange1 = (float)Scene.RegionInfo.RegionSettings.Elevation2NW; args.terrainStartHeight2 = (float)Scene.RegionInfo.RegionSettings.Elevation1SE; args.terrainHeightRange2 = (float)Scene.RegionInfo.RegionSettings.Elevation2SE; args.terrainStartHeight3 = (float)Scene.RegionInfo.RegionSettings.Elevation1NE; args.terrainHeightRange3 = (float)Scene.RegionInfo.RegionSettings.Elevation2NE; args.simAccess = Scene.RegionInfo.AccessLevel; args.waterHeight = (float)Scene.RegionInfo.RegionSettings.WaterHeight; args.regionFlags = GetRegionFlags(); args.regionName = Scene.RegionInfo.RegionName; args.SimOwner = Scene.RegionInfo.EstateSettings.EstateOwner; args.terrainBase0 = UUID.Zero; args.terrainBase1 = UUID.Zero; args.terrainBase2 = UUID.Zero; args.terrainBase3 = UUID.Zero; args.terrainDetail0 = Scene.RegionInfo.RegionSettings.TerrainTexture1; args.terrainDetail1 = Scene.RegionInfo.RegionSettings.TerrainTexture2; args.terrainDetail2 = Scene.RegionInfo.RegionSettings.TerrainTexture3; args.terrainDetail3 = Scene.RegionInfo.RegionSettings.TerrainTexture4; // m_log.DebugFormat("[ESTATE MANAGEMENT MODULE]: Sending terrain texture 1 {0} for region {1}", args.terrainDetail0, Scene.RegionInfo.RegionName); // m_log.DebugFormat("[ESTATE MANAGEMENT MODULE]: Sending terrain texture 2 {0} for region {1}", args.terrainDetail1, Scene.RegionInfo.RegionName); // m_log.DebugFormat("[ESTATE MANAGEMENT MODULE]: Sending terrain texture 3 {0} for region {1}", args.terrainDetail2, Scene.RegionInfo.RegionName); // m_log.DebugFormat("[ESTATE MANAGEMENT MODULE]: Sending terrain texture 4 {0} for region {1}", args.terrainDetail3, Scene.RegionInfo.RegionName); remoteClient.SendRegionHandshake(Scene.RegionInfo,args); } public void sendRegionHandshakeToAll() { Scene.ForEachClient(sendRegionHandshake); } public void handleEstateChangeInfo(IClientAPI remoteClient, UUID invoice, UUID senderID, UInt32 parms1, UInt32 parms2) { if (parms2 == 0) { Scene.RegionInfo.EstateSettings.UseGlobalTime = true; Scene.RegionInfo.EstateSettings.SunPosition = 0.0; } else { Scene.RegionInfo.EstateSettings.UseGlobalTime = false; Scene.RegionInfo.EstateSettings.SunPosition = (parms2 - 0x1800)/1024.0; // Warning: FixedSun should be set to True, otherwise this sun position won't be used. } if ((parms1 & 0x00000010) != 0) Scene.RegionInfo.EstateSettings.FixedSun = true; else Scene.RegionInfo.EstateSettings.FixedSun = false; if ((parms1 & 0x00008000) != 0) Scene.RegionInfo.EstateSettings.PublicAccess = true; else Scene.RegionInfo.EstateSettings.PublicAccess = false; if ((parms1 & 0x10000000) != 0) Scene.RegionInfo.EstateSettings.AllowVoice = true; else Scene.RegionInfo.EstateSettings.AllowVoice = false; if ((parms1 & 0x00100000) != 0) Scene.RegionInfo.EstateSettings.AllowDirectTeleport = true; else Scene.RegionInfo.EstateSettings.AllowDirectTeleport = false; if ((parms1 & 0x00800000) != 0) Scene.RegionInfo.EstateSettings.DenyAnonymous = true; else Scene.RegionInfo.EstateSettings.DenyAnonymous = false; if ((parms1 & 0x01000000) != 0) Scene.RegionInfo.EstateSettings.DenyIdentified = true; else Scene.RegionInfo.EstateSettings.DenyIdentified = false; if ((parms1 & 0x02000000) != 0) Scene.RegionInfo.EstateSettings.DenyTransacted = true; else Scene.RegionInfo.EstateSettings.DenyTransacted = false; if ((parms1 & 0x40000000) != 0) Scene.RegionInfo.EstateSettings.DenyMinors = true; else Scene.RegionInfo.EstateSettings.DenyMinors = false; Scene.RegionInfo.EstateSettings.Save(); TriggerEstateInfoChange(); Scene.TriggerEstateSunUpdate(); sendDetailedEstateData(remoteClient, invoice); } #endregion #region Other Functions public void changeWaterHeight(float height) { setRegionTerrainSettings(height, (float)Scene.RegionInfo.RegionSettings.TerrainRaiseLimit, (float)Scene.RegionInfo.RegionSettings.TerrainLowerLimit, Scene.RegionInfo.RegionSettings.UseEstateSun, Scene.RegionInfo.RegionSettings.FixedSun, (float)Scene.RegionInfo.RegionSettings.SunPosition, Scene.RegionInfo.EstateSettings.UseGlobalTime, Scene.RegionInfo.EstateSettings.FixedSun, (float)Scene.RegionInfo.EstateSettings.SunPosition); sendRegionInfoPacketToAll(); } #endregion private void EventManager_OnNewClient(IClientAPI client) { client.OnDetailedEstateDataRequest += clientSendDetailedEstateData; client.OnSetEstateFlagsRequest += estateSetRegionInfoHandler; // client.OnSetEstateTerrainBaseTexture += setEstateTerrainBaseTexture; client.OnSetEstateTerrainDetailTexture += setEstateTerrainBaseTexture; client.OnSetEstateTerrainTextureHeights += setEstateTerrainTextureHeights; client.OnCommitEstateTerrainTextureRequest += handleCommitEstateTerrainTextureRequest; client.OnSetRegionTerrainSettings += setRegionTerrainSettings; client.OnEstateRestartSimRequest += handleEstateRestartSimRequest; client.OnEstateChangeCovenantRequest += handleChangeEstateCovenantRequest; client.OnEstateChangeInfo += handleEstateChangeInfo; client.OnEstateManageTelehub += HandleOnEstateManageTelehub; client.OnUpdateEstateAccessDeltaRequest += handleEstateAccessDeltaRequest; client.OnSimulatorBlueBoxMessageRequest += SendSimulatorBlueBoxMessage; client.OnEstateBlueBoxMessageRequest += SendEstateBlueBoxMessage; client.OnEstateDebugRegionRequest += handleEstateDebugRegionRequest; client.OnEstateTeleportOneUserHomeRequest += handleEstateTeleportOneUserHomeRequest; client.OnEstateTeleportAllUsersHomeRequest += handleEstateTeleportAllUsersHomeRequest; client.OnRequestTerrain += handleTerrainRequest; client.OnUploadTerrain += handleUploadTerrain; client.OnRegionInfoRequest += HandleRegionInfoRequest; client.OnEstateCovenantRequest += HandleEstateCovenantRequest; client.OnLandStatRequest += HandleLandStatRequest; sendRegionHandshake(client); } public uint GetRegionFlags() { RegionFlags flags = RegionFlags.None; // Fully implemented // if (Scene.RegionInfo.RegionSettings.AllowDamage) flags |= RegionFlags.AllowDamage; if (Scene.RegionInfo.RegionSettings.BlockTerraform) flags |= RegionFlags.BlockTerraform; if (!Scene.RegionInfo.RegionSettings.AllowLandResell) flags |= RegionFlags.BlockLandResell; if (Scene.RegionInfo.RegionSettings.DisableCollisions) flags |= RegionFlags.SkipCollisions; if (Scene.RegionInfo.RegionSettings.DisableScripts) flags |= RegionFlags.SkipScripts; if (Scene.RegionInfo.RegionSettings.DisablePhysics) flags |= RegionFlags.SkipPhysics; if (Scene.RegionInfo.RegionSettings.BlockFly) flags |= RegionFlags.NoFly; if (Scene.RegionInfo.RegionSettings.RestrictPushing) flags |= RegionFlags.RestrictPushObject; if (Scene.RegionInfo.RegionSettings.AllowLandJoinDivide) flags |= RegionFlags.AllowParcelChanges; if (Scene.RegionInfo.RegionSettings.BlockShowInSearch) flags |= RegionFlags.BlockParcelSearch; if (Scene.RegionInfo.RegionSettings.FixedSun) flags |= RegionFlags.SunFixed; if (Scene.RegionInfo.RegionSettings.Sandbox) flags |= RegionFlags.Sandbox; if (Scene.RegionInfo.EstateSettings.AllowVoice) flags |= RegionFlags.AllowVoice; if (Scene.RegionInfo.EstateSettings.AllowLandmark) flags |= RegionFlags.AllowLandmark; if (Scene.RegionInfo.EstateSettings.AllowSetHome) flags |= RegionFlags.AllowSetHome; if (Scene.RegionInfo.EstateSettings.BlockDwell) flags |= RegionFlags.BlockDwell; if (Scene.RegionInfo.EstateSettings.ResetHomeOnTeleport) flags |= RegionFlags.ResetHomeOnTeleport; // TODO: SkipUpdateInterestList // Omitted // // Omitted: NullLayer (what is that?) // Omitted: SkipAgentAction (what does it do?) return (uint)flags; } public uint GetEstateFlags() { RegionFlags flags = RegionFlags.None; if (Scene.RegionInfo.EstateSettings.FixedSun) flags |= RegionFlags.SunFixed; if (Scene.RegionInfo.EstateSettings.PublicAccess) flags |= (RegionFlags.PublicAllowed | RegionFlags.ExternallyVisible); if (Scene.RegionInfo.EstateSettings.AllowVoice) flags |= RegionFlags.AllowVoice; if (Scene.RegionInfo.EstateSettings.AllowDirectTeleport) flags |= RegionFlags.AllowDirectTeleport; if (Scene.RegionInfo.EstateSettings.DenyAnonymous) flags |= RegionFlags.DenyAnonymous; if (Scene.RegionInfo.EstateSettings.DenyIdentified) flags |= RegionFlags.DenyIdentified; if (Scene.RegionInfo.EstateSettings.DenyTransacted) flags |= RegionFlags.DenyTransacted; if (Scene.RegionInfo.EstateSettings.AbuseEmailToEstateOwner) flags |= RegionFlags.AbuseEmailToEstateOwner; if (Scene.RegionInfo.EstateSettings.BlockDwell) flags |= RegionFlags.BlockDwell; if (Scene.RegionInfo.EstateSettings.EstateSkipScripts) flags |= RegionFlags.EstateSkipScripts; if (Scene.RegionInfo.EstateSettings.ResetHomeOnTeleport) flags |= RegionFlags.ResetHomeOnTeleport; if (Scene.RegionInfo.EstateSettings.TaxFree) flags |= RegionFlags.TaxFree; if (Scene.RegionInfo.EstateSettings.AllowLandmark) flags |= RegionFlags.AllowLandmark; if (Scene.RegionInfo.EstateSettings.AllowParcelChanges) flags |= RegionFlags.AllowParcelChanges; if (Scene.RegionInfo.EstateSettings.AllowSetHome) flags |= RegionFlags.AllowSetHome; if (Scene.RegionInfo.EstateSettings.DenyMinors) flags |= (RegionFlags)(1 << 30); return (uint)flags; } public bool IsManager(UUID avatarID) { if (avatarID == Scene.RegionInfo.EstateSettings.EstateOwner) return true; List<UUID> ems = new List<UUID>(Scene.RegionInfo.EstateSettings.EstateManagers); if (ems.Contains(avatarID)) return true; return false; } public void TriggerRegionInfoChange() { m_regionChangeTimer.Stop(); m_regionChangeTimer.Start(); } protected void RaiseRegionInfoChange(object sender, ElapsedEventArgs e) { ChangeDelegate change = OnRegionInfoChange; if (change != null) change(Scene.RegionInfo.RegionID); } public void TriggerEstateInfoChange() { ChangeDelegate change = OnEstateInfoChange; if (change != null) change(Scene.RegionInfo.RegionID); } public void TriggerEstateMessage(UUID fromID, string fromName, string message) { MessageDelegate onmessage = OnEstateMessage; if (onmessage != null) onmessage(Scene.RegionInfo.RegionID, fromID, fromName, message); } private void SendTelehubInfo(IClientAPI client) { RegionSettings settings = this.Scene.RegionInfo.RegionSettings; SceneObjectGroup telehub = null; if (settings.TelehubObject != UUID.Zero && (telehub = Scene.GetSceneObjectGroup(settings.TelehubObject)) != null) { List<Vector3> spawnPoints = new List<Vector3>(); foreach (SpawnPoint sp in settings.SpawnPoints()) { spawnPoints.Add(sp.GetLocation(Vector3.Zero, Quaternion.Identity)); } client.SendTelehubInfo(settings.TelehubObject, telehub.Name, telehub.AbsolutePosition, telehub.GroupRotation, spawnPoints); } else { client.SendTelehubInfo(UUID.Zero, String.Empty, Vector3.Zero, Quaternion.Identity, new List<Vector3>()); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Globalization; using System.Runtime.CompilerServices; using System.Web; using System.Xml; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Configuration; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Models.Css; using Umbraco.Core.Models.EntityBase; using Umbraco.Core.Models.Rdbms; using Umbraco.Core.Persistence.Querying; using umbraco.cms.businesslogic.cache; using umbraco.BusinessLogic; using umbraco.DataLayer; using System.Web.Security; using System.Text; using System.Security.Cryptography; using System.Linq; using Umbraco.Core.Security; namespace umbraco.cms.businesslogic.member { /// <summary> /// The Member class represents a member of the public website (not to be confused with umbraco users) /// /// Members are used when creating communities and collaborative applications using umbraco, or if there are a /// need for identifying or authentifying the visitor. (extranets, protected/private areas of the public website) /// /// Inherits generic datafields from it's baseclass content. /// </summary> [Obsolete("Use the MemberService and the Umbraco.Core.Models.Member models instead")] public class Member : Content { #region Constants and static members public static readonly string UmbracoMemberProviderName = Constants.Conventions.Member.UmbracoMemberProviderName; public static readonly string UmbracoRoleProviderName = Constants.Conventions.Member.UmbracoRoleProviderName; public static readonly Guid _objectType = new Guid(Constants.ObjectTypes.Member); // zb-00004 #29956 : refactor cookies names & handling private const string _sQLOptimizedMany = @" select umbracoNode.id, umbracoNode.uniqueId, umbracoNode.level, umbracoNode.parentId, umbracoNode.path, umbracoNode.sortOrder, umbracoNode.createDate, umbracoNode.nodeUser, umbracoNode.text, cmsMember.Email, cmsMember.LoginName, cmsMember.Password from umbracoNode inner join cmsContent on cmsContent.nodeId = umbracoNode.id inner join cmsMember on cmsMember.nodeId = cmsContent.nodeId where umbracoNode.nodeObjectType = @nodeObjectType AND {0} order by {1}"; #endregion #region Private members private Hashtable _groups = null; protected internal IMember MemberItem; #endregion #region Constructors internal Member(IMember member) : base(member) { SetupNode(member); } /// <summary> /// Initializes a new instance of the Member class. /// </summary> /// <param name="id">Identifier</param> public Member(int id) : base(id) { } /// <summary> /// Initializes a new instance of the Member class. /// </summary> /// <param name="id">Identifier</param> public Member(Guid id) : base(id) { } /// <summary> /// Initializes a new instance of the Member class, with an option to only initialize /// the data used by the tree in the umbraco console. /// </summary> /// <param name="id">Identifier</param> /// <param name="noSetup"></param> public Member(int id, bool noSetup) : base(id, noSetup) { } public Member(Guid id, bool noSetup) : base(id, noSetup) { } #endregion #region Static methods /// <summary> /// A list of all members in the current umbraco install /// /// Note: is ressource intensive, use with care. /// </summary> public static Member[] GetAll { get { return GetAllAsList().ToArray(); } } public static IEnumerable<Member> GetAllAsList() { int totalRecs; return ApplicationContext.Current.Services.MemberService.GetAll(0, int.MaxValue, out totalRecs) .Select(x => new Member(x)) .ToArray(); } /// <summary> /// Retrieves a list of members thats not start with a-z /// </summary> /// <returns>array of members</returns> public static Member[] getAllOtherMembers() { //NOTE: This hasn't been ported to the new service layer because it is an edge case, it is only used to render the tree nodes but in v7 we plan on // changing how the members are shown and not having to worry about letters. var ids = new List<int>(); using (var dr = SqlHelper.ExecuteReader( string.Format(_sQLOptimizedMany.Trim(), "LOWER(SUBSTRING(text, 1, 1)) NOT IN ('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')", "umbracoNode.text"), SqlHelper.CreateParameter("@nodeObjectType", Member._objectType))) { while (dr.Read()) { ids.Add(dr.GetInt("id")); } } if (ids.Any()) { return ApplicationContext.Current.Services.MemberService.GetAllMembers(ids.ToArray()) .Select(x => new Member(x)) .ToArray(); } return new Member[] { }; } /// <summary> /// Retrieves a list of members by the first letter in their name. /// </summary> /// <param name="letter">The first letter</param> /// <returns></returns> public static Member[] getMemberFromFirstLetter(char letter) { int totalRecs; return ApplicationContext.Current.Services.MemberService.FindMembersByDisplayName( letter.ToString(CultureInfo.InvariantCulture), 0, int.MaxValue, out totalRecs, StringPropertyMatchType.StartsWith) .Select(x => new Member(x)) .ToArray(); } public static Member[] GetMemberByName(string usernameToMatch, bool matchByNameInsteadOfLogin) { int totalRecs; if (matchByNameInsteadOfLogin) { var found = ApplicationContext.Current.Services.MemberService.FindMembersByDisplayName( usernameToMatch, 0, int.MaxValue, out totalRecs, StringPropertyMatchType.StartsWith); return found.Select(x => new Member(x)).ToArray(); } else { var found = ApplicationContext.Current.Services.MemberService.FindByUsername( usernameToMatch, 0, int.MaxValue, out totalRecs, StringPropertyMatchType.StartsWith); return found.Select(x => new Member(x)).ToArray(); } } /// <summary> /// Creates a new member /// </summary> /// <param name="Name">Membername</param> /// <param name="mbt">Member type</param> /// <param name="u">The umbraco usercontext</param> /// <returns>The new member</returns> public static Member MakeNew(string Name, MemberType mbt, User u) { return MakeNew(Name, "", "", mbt, u); } /// <summary> /// Creates a new member /// </summary> /// <param name="Name">Membername</param> /// <param name="mbt">Member type</param> /// <param name="u">The umbraco usercontext</param> /// <param name="Email">The email of the user</param> /// <returns>The new member</returns> public static Member MakeNew(string Name, string Email, MemberType mbt, User u) { return MakeNew(Name, "", Email, mbt, u); } /// <summary> /// Creates a new member /// </summary> /// <param name="Name">Membername</param> /// <param name="mbt">Member type</param> /// <param name="u">The umbraco usercontext</param> /// <param name="Email">The email of the user</param> /// <returns>The new member</returns> [MethodImpl(MethodImplOptions.Synchronized)] public static Member MakeNew(string Name, string LoginName, string Email, MemberType mbt, User u) { if (mbt == null) throw new ArgumentNullException("mbt"); var loginName = (string.IsNullOrEmpty(LoginName) == false) ? LoginName : Name; var provider = MembershipProviderExtensions.GetMembersMembershipProvider(); //NOTE: This check is ONLY for backwards compatibility, this check shouldn't really be here it is up to the Membership provider // logic to deal with this but it was here before so we can't really change that. // Test for e-mail if (Email != "" && GetMemberFromEmail(Email) != null && provider.RequiresUniqueEmail) throw new Exception(string.Format("Duplicate Email! A member with the e-mail {0} already exists", Email)); if (GetMemberFromLoginName(loginName) != null) throw new Exception(string.Format("Duplicate User name! A member with the user name {0} already exists", loginName)); var model = ApplicationContext.Current.Services.MemberService.CreateMemberWithIdentity( loginName, Email.ToLower(), Name, mbt.MemberTypeItem); //The content object will only have the 'WasCancelled' flag set to 'True' if the 'Saving' event has been cancelled, so we return null. if (((Entity)model).WasCancelled) return null; var legacy = new Member(model); var e = new NewEventArgs(); legacy.OnNew(e); legacy.Save(); return legacy; } /// <summary> /// Retrieve a member given the loginname /// /// Used when authentifying the Member /// </summary> /// <param name="loginName">The unique Loginname</param> /// <returns>The member with the specified loginname - null if no Member with the login exists</returns> public static Member GetMemberFromLoginName(string loginName) { Mandate.ParameterNotNullOrEmpty(loginName, "loginName"); var found = ApplicationContext.Current.Services.MemberService.GetByUsername(loginName); if (found == null) return null; return new Member(found); } /// <summary> /// Retrieve a Member given an email, the first if there multiple members with same email /// /// Used when authentifying the Member /// </summary> /// <param name="email">The email of the member</param> /// <returns>The member with the specified email - null if no Member with the email exists</returns> public static Member GetMemberFromEmail(string email) { if (string.IsNullOrEmpty(email)) return null; var found = ApplicationContext.Current.Services.MemberService.GetByEmail(email); if (found == null) return null; return new Member(found); } /// <summary> /// Retrieve Members given an email /// /// Used when authentifying a Member /// </summary> /// <param name="email">The email of the member(s)</param> /// <returns>The members with the specified email</returns> public static Member[] GetMembersFromEmail(string email) { if (string.IsNullOrEmpty(email)) return null; int totalRecs; var found = ApplicationContext.Current.Services.MemberService.FindByEmail( email, 0, int.MaxValue, out totalRecs, StringPropertyMatchType.Exact); return found.Select(x => new Member(x)).ToArray(); } /// <summary> /// Retrieve a Member given the credentials /// /// Used when authentifying the member /// </summary> /// <param name="loginName">Member login</param> /// <param name="password">Member password</param> /// <returns>The member with the credentials - null if none exists</returns> [Obsolete("Use the MembershipProvider methods to validate a member")] public static Member GetMemberFromLoginNameAndPassword(string loginName, string password) { if (IsMember(loginName)) { var provider = MembershipProviderExtensions.GetMembersMembershipProvider(); // validate user via provider if (provider.ValidateUser(loginName, password)) { return GetMemberFromLoginName(loginName); } else { LogHelper.Debug<Member>("Incorrect login/password attempt or member is locked out or not approved (" + loginName + ")", true); return null; } } else { LogHelper.Debug<Member>("No member with loginname: " + loginName + " Exists", true); return null; } } [Obsolete("This method will not work if the password format is encrypted since the encryption that is performed is not static and a new value will be created each time the same string is encrypted")] public static Member GetMemberFromLoginAndEncodedPassword(string loginName, string password) { var o = SqlHelper.ExecuteScalar<object>( "select nodeID from cmsMember where LoginName = @loginName and Password = @password", SqlHelper.CreateParameter("loginName", loginName), SqlHelper.CreateParameter("password", password)); if (o == null) return null; int tmpId; if (!int.TryParse(o.ToString(), out tmpId)) return null; return new Member(tmpId); } [Obsolete("Use MembershipProviderExtensions.IsUmbracoMembershipProvider instead")] public static bool InUmbracoMemberMode() { var provider = MembershipProviderExtensions.GetMembersMembershipProvider(); return provider.IsUmbracoMembershipProvider(); } public static bool IsUsingUmbracoRoles() { return Roles.Provider.Name == UmbracoRoleProviderName; } /// <summary> /// Helper method - checks if a Member with the LoginName exists /// </summary> /// <param name="loginName">Member login</param> /// <returns>True if the member exists</returns> public static bool IsMember(string loginName) { Mandate.ParameterNotNullOrEmpty(loginName, "loginName"); return ApplicationContext.Current.Services.MemberService.Exists(loginName); } /// <summary> /// Deletes all members of the membertype specified /// /// Used when a membertype is deleted /// /// Use with care /// </summary> /// <param name="dt">The membertype which are being deleted</param> public static void DeleteFromType(MemberType dt) { ApplicationContext.Current.Services.MemberService.DeleteMembersOfType(dt.Id); } #endregion #region Public Properties public override int sortOrder { get { return MemberItem == null ? base.sortOrder : MemberItem.SortOrder; } set { if (MemberItem == null) { base.sortOrder = value; } else { MemberItem.SortOrder = value; } } } public override int Level { get { return MemberItem == null ? base.Level : MemberItem.Level; } set { if (MemberItem == null) { base.Level = value; } else { MemberItem.Level = value; } } } public override int ParentId { get { return MemberItem == null ? base.ParentId : MemberItem.ParentId; } } public override string Path { get { return MemberItem == null ? base.Path : MemberItem.Path; } set { if (MemberItem == null) { base.Path = value; } else { MemberItem.Path = value; } } } [Obsolete("Obsolete, Use Name property on Umbraco.Core.Models.Content", false)] public override string Text { get { return MemberItem.Name; } set { value = value.Trim(); MemberItem.Name = value; } } /// <summary> /// The members password, used when logging in on the public website /// </summary> [Obsolete("Do not use this property, use GetPassword and ChangePassword instead, if using ChangePassword ensure that the password is encrypted or hashed based on the active membership provider")] public string Password { get { return MemberItem.RawPasswordValue; } set { // We need to use the provider for this in order for hashing, etc. support // To write directly to the db use the ChangePassword method // this is not pretty but nessecary due to a design flaw (the membership provider should have been a part of the cms project) var helper = new MemberShipHelper(); var provider = MembershipProviderExtensions.GetMembersMembershipProvider(); MemberItem.RawPasswordValue = helper.EncodePassword(value, provider.PasswordFormat); } } /// <summary> /// The loginname of the member, used when logging in /// </summary> public string LoginName { get { return MemberItem.Username; } set { if (string.IsNullOrEmpty(value)) throw new ArgumentException("The loginname must be different from an empty string", "LoginName"); if (value.Contains(",")) throw new ArgumentException("The parameter 'LoginName' must not contain commas."); MemberItem.Username = value; } } /// <summary> /// A list of groups the member are member of /// </summary> public Hashtable Groups { get { if (_groups == null) PopulateGroups(); return _groups; } } /// <summary> /// The members email /// </summary> public string Email { get { return MemberItem.Email.IsNullOrWhiteSpace() ? string.Empty : MemberItem.Email.ToLower(); } set { MemberItem.Email = value == null ? "" : value.ToLower(); } } #endregion #region Public Methods [Obsolete("Obsolete", false)] protected override void setupNode() { if (Id == -1) { base.setupNode(); return; } var content = ApplicationContext.Current.Services.MemberService.GetById(Id); if (content == null) throw new ArgumentException(string.Format("No Member exists with id '{0}'", Id)); SetupNode(content); } private void SetupNode(IMember content) { MemberItem = content; //Also need to set the ContentBase item to this one so all the propery values load from it ContentBase = MemberItem; //Setting private properties from IContentBase replacing CMSNode.setupNode() / CMSNode.PopulateCMSNodeFromReader() base.PopulateCMSNodeFromUmbracoEntity(MemberItem, _objectType); //If the version is empty we update with the latest version from the current IContent. if (Version == Guid.Empty) Version = MemberItem.Version; } /// <summary> /// Used to persist object changes to the database /// </summary> /// <param name="raiseEvents"></param> public void Save(bool raiseEvents) { var provider = MembershipProviderExtensions.GetMembersMembershipProvider(); //Due to backwards compatibility with this API we need to check for duplicate emails here if required. // This check should not be done here, as this logic is based on the MembershipProvider var requireUniqueEmail = provider.RequiresUniqueEmail; //check if there's anyone with this email in the db that isn't us var membersFromEmail = GetMembersFromEmail(Email); if (requireUniqueEmail && membersFromEmail != null && membersFromEmail.Any(x => x.Id != Id)) { throw new Exception(string.Format("Duplicate Email! A member with the e-mail {0} already exists", Email)); } var e = new SaveEventArgs(); if (raiseEvents) { FireBeforeSave(e); } foreach (var property in GenericProperties) { MemberItem.SetValue(property.PropertyType.Alias, property.Value); } if (e.Cancel == false) { ApplicationContext.Current.Services.MemberService.Save(MemberItem, raiseEvents); //base.VersionDate = MemberItem.UpdateDate; base.Save(); if (raiseEvents) { FireAfterSave(e); } } } /// <summary> /// Used to persist object changes to the database. In Version3.0 it's just a stub for future compatibility /// </summary> public override void Save() { Save(true); } /// <summary> /// Xmlrepresentation of a member /// </summary> /// <param name="xd">The xmldocument context</param> /// <param name="Deep">Recursive - should always be set to false</param> /// <returns>A the xmlrepresentation of the current member</returns> public override XmlNode ToXml(XmlDocument xd, bool Deep) { var x = base.ToXml(xd, Deep); if (x.Attributes != null && x.Attributes["loginName"] == null) { x.Attributes.Append(XmlHelper.AddAttribute(xd, "loginName", LoginName)); } if (x.Attributes != null && x.Attributes["email"] == null) { x.Attributes.Append(XmlHelper.AddAttribute(xd, "email", Email)); } if (x.Attributes != null && x.Attributes["key"] == null) { x.Attributes.Append(XmlHelper.AddAttribute(xd, "key", UniqueId.ToString())); } return x; } /// <summary> /// Deltes the current member /// </summary> [Obsolete("Obsolete, Use Umbraco.Core.Services.MemberService.Delete()", false)] public override void delete() { var e = new DeleteEventArgs(); FireBeforeDelete(e); if (!e.Cancel) { if (MemberItem != null) { ApplicationContext.Current.Services.MemberService.Delete(MemberItem); } else { var member = ApplicationContext.Current.Services.MemberService.GetById(Id); ApplicationContext.Current.Services.MemberService.Delete(member); } // Delete all content and cmsnode specific data! base.delete(); FireAfterDelete(e); } } /// <summary> /// Sets the password for the user - ensure it is encrypted or hashed based on the active membership provider - you must /// call Save() after using this method /// </summary> /// <param name="newPassword"></param> public void ChangePassword(string newPassword) { MemberItem.RawPasswordValue = newPassword; } /// <summary> /// Returns the currently stored password - this may be encrypted or hashed string depending on the active membership provider /// </summary> /// <returns></returns> public string GetPassword() { return MemberItem.RawPasswordValue; } /// <summary> /// Adds the member to group with the specified id /// </summary> /// <param name="GroupId">The id of the group which the member is being added to</param> [MethodImpl(MethodImplOptions.Synchronized)] public void AddGroup(int GroupId) { var e = new AddGroupEventArgs(); e.GroupId = GroupId; FireBeforeAddGroup(e); if (!e.Cancel) { var parameters = new IParameter[] { SqlHelper.CreateParameter("@id", Id), SqlHelper.CreateParameter("@groupId", GroupId) }; bool exists = SqlHelper.ExecuteScalar<int>("SELECT COUNT(member) FROM cmsMember2MemberGroup WHERE member = @id AND memberGroup = @groupId", parameters) > 0; if (!exists) SqlHelper.ExecuteNonQuery("INSERT INTO cmsMember2MemberGroup (member, memberGroup) values (@id, @groupId)", parameters); PopulateGroups(); FireAfterAddGroup(e); } } /// <summary> /// Removes the member from the MemberGroup specified /// </summary> /// <param name="GroupId">The MemberGroup from which the Member is removed</param> public void RemoveGroup(int GroupId) { var e = new RemoveGroupEventArgs(); e.GroupId = GroupId; FireBeforeRemoveGroup(e); if (!e.Cancel) { SqlHelper.ExecuteNonQuery( "delete from cmsMember2MemberGroup where member = @id and Membergroup = @groupId", SqlHelper.CreateParameter("@id", Id), SqlHelper.CreateParameter("@groupId", GroupId)); PopulateGroups(); FireAfterRemoveGroup(e); } } #endregion #region Protected methods protected override XmlNode generateXmlWithoutSaving(XmlDocument xd) { XmlNode node = xd.CreateNode(XmlNodeType.Element, "node", ""); XmlPopulate(xd, ref node, false); node.Attributes.Append(xmlHelper.addAttribute(xd, "loginName", LoginName)); node.Attributes.Append(xmlHelper.addAttribute(xd, "email", Email)); return node; } #endregion #region Private methods private void PopulateGroups() { var temp = new Hashtable(); using (var dr = SqlHelper.ExecuteReader( "select memberGroup from cmsMember2MemberGroup where member = @id", SqlHelper.CreateParameter("@id", Id))) { while (dr.Read()) temp.Add(dr.GetInt("memberGroup"), new MemberGroup(dr.GetInt("memberGroup"))); } _groups = temp; } private static string GetCacheKey(int id) { return string.Format("{0}{1}", CacheKeys.MemberBusinessLogicCacheKey, id); } [Obsolete("Only use .NET Membership APIs to handle state now", true)] static void ClearMemberState() { // zb-00004 #29956 : refactor cookies names & handling StateHelper.Cookies.Member.Clear(); FormsAuthentication.SignOut(); } #endregion #region MemberHandle functions /// <summary> /// Method is used when logging a member in. /// /// Adds the member to the cache of logged in members /// /// Uses cookiebased recognition /// /// Can be used in the runtime /// </summary> /// <param name="m">The member to log in</param> [Obsolete("Use Membership APIs and FormsAuthentication to handle member login")] public static void AddMemberToCache(Member m) { if (m != null) { var e = new AddToCacheEventArgs(); m.FireBeforeAddToCache(e); if (!e.Cancel) { // Add cookie with member-id, guid and loginname // zb-00035 #29931 : cleanup member state management // NH 4.7.1: We'll no longer use legacy cookies to handle Umbraco Members //SetMemberState(m); FormsAuthentication.SetAuthCookie(m.LoginName, true); //cache the member var cachedMember = ApplicationContext.Current.ApplicationCache.GetCacheItem( GetCacheKey(m.Id), TimeSpan.FromMinutes(30), () => { // Debug information HttpContext.Current.Trace.Write("member", string.Format("Member added to cache: {0}/{1} ({2})", m.Text, m.LoginName, m.Id)); return m; }); m.FireAfterAddToCache(e); } } } // zb-00035 #29931 : remove old cookie code /// <summary> /// Method is used when logging a member in. /// /// Adds the member to the cache of logged in members /// /// Uses cookie or session based recognition /// /// Can be used in the runtime /// </summary> /// <param name="m">The member to log in</param> /// <param name="UseSession">create a persistent cookie</param> /// <param name="TimespanForCookie">Has no effect</param> [Obsolete("Use the membership api and FormsAuthentication to log users in, this method is no longer used anymore")] public static void AddMemberToCache(Member m, bool UseSession, TimeSpan TimespanForCookie) { if (m != null) { var e = new AddToCacheEventArgs(); m.FireBeforeAddToCache(e); if (!e.Cancel) { // zb-00035 #29931 : cleanup member state management // NH 4.7.1: We'll no longer use Umbraco legacy cookies to handle members //SetMemberState(m, UseSession, TimespanForCookie.TotalDays); FormsAuthentication.SetAuthCookie(m.LoginName, !UseSession); //cache the member var cachedMember = ApplicationContext.Current.ApplicationCache.GetCacheItem( GetCacheKey(m.Id), TimeSpan.FromMinutes(30), () => { // Debug information HttpContext.Current.Trace.Write("member", string.Format("Member added to cache: {0}/{1} ({2})", m.Text, m.LoginName, m.Id)); return m; }); m.FireAfterAddToCache(e); } } } /// <summary> /// Removes the member from the cache /// /// Can be used in the public website /// </summary> /// <param name="m">Member to remove</param> [Obsolete("Obsolete, use the RemoveMemberFromCache(int NodeId) instead", false)] public static void RemoveMemberFromCache(Member m) { RemoveMemberFromCache(m.Id); } /// <summary> /// Removes the member from the cache /// /// Can be used in the public website /// </summary> /// <param name="NodeId">Node Id of the member to remove</param> [Obsolete("Member cache is automatically cleared when members are updated")] public static void RemoveMemberFromCache(int NodeId) { ApplicationContext.Current.ApplicationCache.ClearCacheItem(GetCacheKey(NodeId)); } /// <summary> /// Deletes the member cookie from the browser /// /// Can be used in the public website /// </summary> /// <param name="m">Member</param> [Obsolete("Obsolete, use the ClearMemberFromClient(int NodeId) instead", false)] public static void ClearMemberFromClient(Member m) { if (m != null) ClearMemberFromClient(m.Id); else { // If the member doesn't exists as an object, we'll just make sure that cookies are cleared // zb-00035 #29931 : cleanup member state management ClearMemberState(); } FormsAuthentication.SignOut(); } /// <summary> /// Deletes the member cookie from the browser /// /// Can be used in the public website /// </summary> /// <param name="NodeId">The Node id of the member to clear</param> [Obsolete("Use FormsAuthentication.SignOut instead")] public static void ClearMemberFromClient(int NodeId) { // zb-00035 #29931 : cleanup member state management // NH 4.7.1: We'll no longer use legacy Umbraco cookies to handle members // ClearMemberState(); FormsAuthentication.SignOut(); RemoveMemberFromCache(NodeId); } /// <summary> /// Retrieve a collection of members in the cache /// /// Can be used from the public website /// </summary> /// <returns>A collection of cached members</returns> public static Hashtable CachedMembers() { var h = new Hashtable(); var items = ApplicationContext.Current.ApplicationCache.GetCacheItemsByKeySearch<Member>( CacheKeys.MemberBusinessLogicCacheKey); foreach (var i in items) { h.Add(i.Id, i); } return h; } /// <summary> /// Retrieve a member from the cache /// /// Can be used from the public website /// </summary> /// <param name="id">Id of the member</param> /// <returns>If the member is cached it returns the member - else null</returns> public static Member GetMemberFromCache(int id) { Hashtable members = CachedMembers(); if (members.ContainsKey(id)) return (Member)members[id]; else return null; } /// <summary> /// An indication if the current visitor is logged in /// /// Can be used from the public website /// </summary> /// <returns>True if the the current visitor is logged in</returns> [Obsolete("Use the standard ASP.Net procedures for hanlding FormsAuthentication, simply check the HttpContext.User and HttpContext.User.Identity.IsAuthenticated to determine if a member is logged in or not")] public static bool IsLoggedOn() { return HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated; } /// <summary> /// Gets the current visitors memberid /// </summary> /// <returns>The current visitors members id, if the visitor is not logged in it returns 0</returns> public static int CurrentMemberId() { int currentMemberId = 0; // For backwards compatibility between umbraco members and .net membership if (HttpContext.Current.User.Identity.IsAuthenticated) { var provider = MembershipProviderExtensions.GetMembersMembershipProvider(); var member = provider.GetCurrentUser(); if (member == null) { throw new InvalidOperationException("No member object found with username " + provider.GetCurrentUserName()); } int.TryParse(member.ProviderUserKey.ToString(), out currentMemberId); } return currentMemberId; } /// <summary> /// Get the current member /// </summary> /// <returns>Returns the member, if visitor is not logged in: null</returns> public static Member GetCurrentMember() { try { if (HttpContext.Current.User.Identity.IsAuthenticated) { var provider = MembershipProviderExtensions.GetMembersMembershipProvider(); var member = provider.GetCurrentUser(); if (member == null) { throw new InvalidOperationException("No member object found with username " + provider.GetCurrentUserName()); } int currentMemberId = 0; if (int.TryParse(member.ProviderUserKey.ToString(), out currentMemberId)) { var m = new Member(currentMemberId); return m; } } } catch (Exception ex) { LogHelper.Error<Member>("An error occurred in GetCurrentMember", ex); } return null; } #endregion #region Events /// <summary> /// The save event handler /// </summary> public delegate void SaveEventHandler(Member sender, SaveEventArgs e); /// <summary> /// The new event handler /// </summary> public delegate void NewEventHandler(Member sender, NewEventArgs e); /// <summary> /// The delete event handler /// </summary> public delegate void DeleteEventHandler(Member sender, DeleteEventArgs e); /// <summary> /// The add to cache event handler /// </summary> public delegate void AddingToCacheEventHandler(Member sender, AddToCacheEventArgs e); /// <summary> /// The add group event handler /// </summary> public delegate void AddingGroupEventHandler(Member sender, AddGroupEventArgs e); /// <summary> /// The remove group event handler /// </summary> public delegate void RemovingGroupEventHandler(Member sender, RemoveGroupEventArgs e); /// <summary> /// Occurs when [before save]. /// </summary> new public static event SaveEventHandler BeforeSave; /// <summary> /// Raises the <see cref="E:BeforeSave"/> event. /// </summary> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> new protected virtual void FireBeforeSave(SaveEventArgs e) { if (BeforeSave != null) { BeforeSave(this, e); } } new public static event SaveEventHandler AfterSave; new protected virtual void FireAfterSave(SaveEventArgs e) { if (AfterSave != null) { AfterSave(this, e); } } public static event NewEventHandler New; protected virtual void OnNew(NewEventArgs e) { if (New != null) { New(this, e); } } public static event AddingGroupEventHandler BeforeAddGroup; protected virtual void FireBeforeAddGroup(AddGroupEventArgs e) { if (BeforeAddGroup != null) { BeforeAddGroup(this, e); } } public static event AddingGroupEventHandler AfterAddGroup; protected virtual void FireAfterAddGroup(AddGroupEventArgs e) { if (AfterAddGroup != null) { AfterAddGroup(this, e); } } public static event RemovingGroupEventHandler BeforeRemoveGroup; protected virtual void FireBeforeRemoveGroup(RemoveGroupEventArgs e) { if (BeforeRemoveGroup != null) { BeforeRemoveGroup(this, e); } } public static event RemovingGroupEventHandler AfterRemoveGroup; protected virtual void FireAfterRemoveGroup(RemoveGroupEventArgs e) { if (AfterRemoveGroup != null) { AfterRemoveGroup(this, e); } } public static event AddingToCacheEventHandler BeforeAddToCache; protected virtual void FireBeforeAddToCache(AddToCacheEventArgs e) { if (BeforeAddToCache != null) { BeforeAddToCache(this, e); } } public static event AddingToCacheEventHandler AfterAddToCache; protected virtual void FireAfterAddToCache(AddToCacheEventArgs e) { if (AfterAddToCache != null) { AfterAddToCache(this, e); } } new public static event DeleteEventHandler BeforeDelete; new protected virtual void FireBeforeDelete(DeleteEventArgs e) { if (BeforeDelete != null) { BeforeDelete(this, e); } } new public static event DeleteEventHandler AfterDelete; new protected virtual void FireAfterDelete(DeleteEventArgs e) { if (AfterDelete != null) { AfterDelete(this, e); } } #endregion #region Membership helper class used for encryption methods /// <summary> /// ONLY FOR INTERNAL USE. /// This is needed due to a design flaw where the Umbraco membership provider is located /// in a separate project referencing this project, which means we can't call special methods /// directly on the UmbracoMemberShipMember class. /// This is a helper implementation only to be able to use the encryption functionality /// of the membership provides (which are protected). /// /// ... which means this class should have been marked internal with a Friend reference to the other assembly right?? /// </summary> internal class MemberShipHelper : MembershipProvider { public override string ApplicationName { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public override bool ChangePassword(string username, string oldPassword, string newPassword) { throw new NotImplementedException(); } public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer) { throw new NotImplementedException(); } public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) { throw new NotImplementedException(); } public override bool DeleteUser(string username, bool deleteAllRelatedData) { throw new NotImplementedException(); } public string EncodePassword(string password, MembershipPasswordFormat pwFormat) { string encodedPassword = password; switch (pwFormat) { case MembershipPasswordFormat.Clear: break; case MembershipPasswordFormat.Encrypted: encodedPassword = Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password))); break; case MembershipPasswordFormat.Hashed: HMACSHA1 hash = new HMACSHA1(); hash.Key = Encoding.Unicode.GetBytes(password); encodedPassword = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password))); break; } return encodedPassword; } public override bool EnablePasswordReset { get { throw new NotImplementedException(); } } public override bool EnablePasswordRetrieval { get { throw new NotImplementedException(); } } public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords) { throw new NotImplementedException(); } public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) { throw new NotImplementedException(); } public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) { throw new NotImplementedException(); } public override int GetNumberOfUsersOnline() { throw new NotImplementedException(); } public override string GetPassword(string username, string answer) { throw new NotImplementedException(); } public override MembershipUser GetUser(string username, bool userIsOnline) { throw new NotImplementedException(); } public override MembershipUser GetUser(object providerUserKey, bool userIsOnline) { throw new NotImplementedException(); } public override string GetUserNameByEmail(string email) { throw new NotImplementedException(); } public override int MaxInvalidPasswordAttempts { get { throw new NotImplementedException(); } } public override int MinRequiredNonAlphanumericCharacters { get { throw new NotImplementedException(); } } public override int MinRequiredPasswordLength { get { throw new NotImplementedException(); } } public override int PasswordAttemptWindow { get { throw new NotImplementedException(); } } public override MembershipPasswordFormat PasswordFormat { get { throw new NotImplementedException(); } } public override string PasswordStrengthRegularExpression { get { throw new NotImplementedException(); } } public override bool RequiresQuestionAndAnswer { get { throw new NotImplementedException(); } } public override bool RequiresUniqueEmail { get { throw new NotImplementedException(); } } public override string ResetPassword(string username, string answer) { throw new NotImplementedException(); } public override bool UnlockUser(string userName) { throw new NotImplementedException(); } public override void UpdateUser(MembershipUser user) { throw new NotImplementedException(); } public override bool ValidateUser(string username, string password) { throw new NotImplementedException(); } } #endregion } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests { using System; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Messaging; using Apache.Ignite.Core.Tests.Process; using NUnit.Framework; /// <summary> /// Ignite start/stop tests. /// </summary> [Category(TestUtils.CategoryIntensive)] public class IgniteStartStopTest { /// <summary> /// Test teardown. /// </summary> [TearDown] public void TearDown() { TestUtils.KillProcesses(); Ignition.StopAll(true); } /// <summary> /// /// </summary> [Test] public void TestStartDefault() { var cfg = new IgniteConfiguration {JvmClasspath = TestUtils.CreateTestClasspath()}; var grid = Ignition.Start(cfg); Assert.IsNotNull(grid); Assert.AreEqual(1, grid.GetCluster().GetNodes().Count); } /// <summary> /// /// </summary> [Test] public void TestStartWithConfigPath() { var cfg = new IgniteConfiguration { SpringConfigUrl = "config\\spring-test.xml", JvmClasspath = TestUtils.CreateTestClasspath() }; var grid = Ignition.Start(cfg); Assert.IsNotNull(grid); Assert.AreEqual(1, grid.GetCluster().GetNodes().Count); } /// <summary> /// /// </summary> [Test] public void TestStartGetStop() { var grid1 = Ignition.Start(TestUtils.GetTestConfiguration(name: "grid1")); Assert.AreEqual("grid1", grid1.Name); Assert.AreSame(grid1, Ignition.GetIgnite()); Assert.AreSame(grid1, Ignition.GetAll().Single()); var grid2 = Ignition.Start(TestUtils.GetTestConfiguration(name: "grid2")); Assert.AreEqual("grid2", grid2.Name); Assert.Throws<IgniteException>(() => Ignition.GetIgnite()); var grid3 = Ignition.Start(TestUtils.GetTestConfiguration()); Assert.IsNull(grid3.Name); Assert.AreSame(grid1, Ignition.GetIgnite("grid1")); Assert.AreSame(grid1, Ignition.TryGetIgnite("grid1")); Assert.AreSame(grid2, Ignition.GetIgnite("grid2")); Assert.AreSame(grid2, Ignition.TryGetIgnite("grid2")); Assert.AreSame(grid3, Ignition.GetIgnite(null)); Assert.AreSame(grid3, Ignition.GetIgnite()); Assert.AreSame(grid3, Ignition.TryGetIgnite(null)); Assert.AreSame(grid3, Ignition.TryGetIgnite()); Assert.AreEqual(new[] {grid3, grid1, grid2}, Ignition.GetAll().OrderBy(x => x.Name).ToArray()); Assert.Throws<IgniteException>(() => Ignition.GetIgnite("invalid_name")); Assert.IsNull(Ignition.TryGetIgnite("invalid_name")); Assert.IsTrue(Ignition.Stop("grid1", true)); Assert.Throws<IgniteException>(() => Ignition.GetIgnite("grid1")); grid2.Dispose(); Assert.Throws<IgniteException>(() => Ignition.GetIgnite("grid2")); grid3.Dispose(); Assert.Throws<IgniteException>(() => Ignition.GetIgnite("grid3")); // Restart. Ignition.Start(TestUtils.GetTestConfiguration(name: "grid1")); Ignition.Start(TestUtils.GetTestConfiguration(name: "grid2")); Ignition.Start(TestUtils.GetTestConfiguration()); foreach (var gridName in new [] { "grid1", "grid2", null }) Assert.IsNotNull(Ignition.GetIgnite(gridName)); Ignition.StopAll(true); foreach (var gridName in new [] {"grid1", "grid2", null}) Assert.Throws<IgniteException>(() => Ignition.GetIgnite(gridName)); } /// <summary> /// /// </summary> [Test] public void TestStartTheSameName() { var cfg = TestUtils.GetTestConfiguration(name: "grid1"); var grid1 = Ignition.Start(cfg); Assert.AreEqual("grid1", grid1.Name); var ex = Assert.Throws<IgniteException>(() => Ignition.Start(cfg)); Assert.AreEqual("Ignite instance with this name has already been started: grid1", ex.Message); } /// <summary> /// Tests automatic grid name generation. /// </summary> [Test] public void TestStartUniqueName() { var cfg = TestUtils.GetTestConfiguration(); cfg.AutoGenerateIgniteInstanceName = true; Ignition.Start(cfg); Assert.IsNotNull(Ignition.GetIgnite()); Assert.IsNotNull(Ignition.TryGetIgnite()); Ignition.Start(cfg); Assert.Throws<IgniteException>(() => Ignition.GetIgnite()); Assert.IsNull(Ignition.TryGetIgnite()); Assert.AreEqual(2, Ignition.GetAll().Count); } /// <summary> /// /// </summary> [Test] public void TestUsageAfterStop() { var grid = Ignition.Start(TestUtils.GetTestConfiguration()); Assert.IsNotNull(grid.GetOrCreateCache<int, int>("cache1")); grid.Dispose(); var ex = Assert.Throws<InvalidOperationException>(() => grid.GetCache<int, int>("cache1")); Assert.AreEqual("Grid is in invalid state to perform this operation. " + "It either not started yet or has already being or have stopped " + "[igniteInstanceName=null, state=STOPPED]", ex.Message); } /// <summary> /// /// </summary> [Test] public void TestStartStopLeak() { var cfg = TestUtils.GetTestConfiguration(); for (var i = 0; i < 50; i++) { Console.WriteLine("Iteration: " + i); var grid = Ignition.Start(cfg); UseIgnite(grid); if (i % 2 == 0) // Try to stop ignite from another thread. { TaskRunner.Run(() => grid.Dispose()).Wait(); } else { grid.Dispose(); } GC.Collect(); // At the time of writing java references are cleaned from finalizer, so GC is needed. } } /// <summary> /// Tests the client mode flag. /// </summary> [Test] public void TestClientMode() { var servCfg = new IgniteConfiguration(TestUtils.GetTestConfiguration(name: "serv")); var clientCfg = new IgniteConfiguration(TestUtils.GetTestConfiguration(name: "client")); try { using (var serv = Ignition.Start(servCfg)) // start server-mode ignite first { Assert.IsFalse(serv.GetCluster().GetLocalNode().IsClient); Ignition.ClientMode = true; using (var grid = Ignition.Start(clientCfg)) { Assert.IsTrue(grid.GetCluster().GetLocalNode().IsClient); UseIgnite(grid); } } } finally { Ignition.ClientMode = false; } } /// <summary> /// Uses the ignite. /// </summary> /// <param name="ignite">The ignite.</param> private static void UseIgnite(IIgnite ignite) { // Create objects holding references to java objects. var comp = ignite.GetCompute(); // ReSharper disable once RedundantAssignment comp = comp.WithKeepBinary(); var prj = ignite.GetCluster().ForOldest(); Assert.IsTrue(prj.GetNodes().Count > 0); Assert.IsNotNull(prj.GetCompute()); var cache = ignite.GetOrCreateCache<int, int>("cache1"); Assert.IsNotNull(cache); cache.GetAndPut(1, 1); Assert.AreEqual(1, cache.Get(1)); } /// <summary> /// Tests the processor initialization and grid usage right after topology enter. /// </summary> [Test] public void TestProcessorInit() { var cfg = new IgniteConfiguration { SpringConfigUrl = "Config\\spring-test.xml", JvmOptions = TestUtils.TestJavaOptions(), JvmClasspath = TestUtils.CreateTestClasspath() }; // Start local node var grid = Ignition.Start(cfg); // Start remote node in a separate process // ReSharper disable once UnusedVariable var proc = new IgniteProcess( "-jvmClasspath=" + TestUtils.CreateTestClasspath(), "-springConfigUrl=" + Path.GetFullPath(cfg.SpringConfigUrl), "-J-Xms512m", "-J-Xmx512m"); Assert.IsTrue(proc.Alive); var cts = new CancellationTokenSource(); var token = cts.Token; // Spam message subscriptions on a separate thread // to test race conditions during processor init on remote node var listenTask = TaskRunner.Run(() => { var filter = new MessageListener(); while (!token.IsCancellationRequested) { var listenId = grid.GetMessaging().RemoteListen(filter); grid.GetMessaging().StopRemoteListen(listenId); } // ReSharper disable once FunctionNeverReturns }); // Wait for remote node to join Assert.IsTrue(grid.WaitTopology(2)); // Wait some more for initialization Thread.Sleep(1000); // Cancel listen task and check that it finishes cts.Cancel(); Assert.IsTrue(listenTask.Wait(5000)); } /// <summary> /// Noop message filter. /// </summary> [Serializable] private class MessageListener : IMessageListener<int> { /** <inheritdoc /> */ public bool Invoke(Guid nodeId, int message) { return true; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Nop.Core; using Nop.Core.Caching; using Nop.Core.Configuration; using Nop.Core.Data; using Nop.Core.Domain.Configuration; using Nop.Services.Events; namespace Nop.Services.Configuration { /// <summary> /// Setting manager /// </summary> public partial class SettingService : ISettingService { #region Constants /// <summary> /// Key for caching /// </summary> private const string SETTINGS_ALL_KEY = "Nop.setting.all"; /// <summary> /// Key pattern to clear cache /// </summary> private const string SETTINGS_PATTERN_KEY = "Nop.setting."; #endregion #region Fields private readonly IRepository<Setting> _settingRepository; private readonly IEventPublisher _eventPublisher; private readonly ICacheManager _cacheManager; #endregion #region Ctor /// <summary> /// Ctor /// </summary> /// <param name="cacheManager">Cache manager</param> /// <param name="eventPublisher">Event publisher</param> /// <param name="settingRepository">Setting repository</param> public SettingService(ICacheManager cacheManager, IEventPublisher eventPublisher, IRepository<Setting> settingRepository) { this._cacheManager = cacheManager; this._eventPublisher = eventPublisher; this._settingRepository = settingRepository; } #endregion #region Nested classes [Serializable] public class SettingForCaching { public int Id { get; set; } public string Name { get; set; } public string Value { get; set; } public int StoreId { get; set; } } #endregion #region Utilities /// <summary> /// Gets all settings /// </summary> /// <returns>Settings</returns> protected virtual IDictionary<string, IList<SettingForCaching>> GetAllSettingsCached() { //cache string key = string.Format(SETTINGS_ALL_KEY); return _cacheManager.Get(key, () => { //we use no tracking here for performance optimization //anyway records are loaded only for read-only operations var query = from s in _settingRepository.TableNoTracking orderby s.Name, s.StoreId select s; var settings = query.ToList(); var dictionary = new Dictionary<string, IList<SettingForCaching>>(); foreach (var s in settings) { var resourceName = s.Name.ToLowerInvariant(); var settingForCaching = new SettingForCaching { Id = s.Id, Name = s.Name, Value = s.Value, StoreId = s.StoreId }; if (!dictionary.ContainsKey(resourceName)) { //first setting dictionary.Add(resourceName, new List<SettingForCaching> { settingForCaching }); } else { //already added //most probably it's the setting with the same name but for some certain store (storeId > 0) dictionary[resourceName].Add(settingForCaching); } } return dictionary; }); } #endregion #region Methods /// <summary> /// Adds a setting /// </summary> /// <param name="setting">Setting</param> /// <param name="clearCache">A value indicating whether to clear cache after setting update</param> public virtual void InsertSetting(Setting setting, bool clearCache = true) { if (setting == null) throw new ArgumentNullException("setting"); _settingRepository.Insert(setting); //cache if (clearCache) _cacheManager.RemoveByPattern(SETTINGS_PATTERN_KEY); //event notification _eventPublisher.EntityInserted(setting); } /// <summary> /// Updates a setting /// </summary> /// <param name="setting">Setting</param> /// <param name="clearCache">A value indicating whether to clear cache after setting update</param> public virtual void UpdateSetting(Setting setting, bool clearCache = true) { if (setting == null) throw new ArgumentNullException("setting"); _settingRepository.Update(setting); //cache if (clearCache) _cacheManager.RemoveByPattern(SETTINGS_PATTERN_KEY); //event notification _eventPublisher.EntityUpdated(setting); } /// <summary> /// Deletes a setting /// </summary> /// <param name="setting">Setting</param> public virtual void DeleteSetting(Setting setting) { if (setting == null) throw new ArgumentNullException("setting"); _settingRepository.Delete(setting); //cache _cacheManager.RemoveByPattern(SETTINGS_PATTERN_KEY); //event notification _eventPublisher.EntityDeleted(setting); } /// <summary> /// Gets a setting by identifier /// </summary> /// <param name="settingId">Setting identifier</param> /// <returns>Setting</returns> public virtual Setting GetSettingById(int settingId) { if (settingId == 0) return null; return _settingRepository.GetById(settingId); } /// <summary> /// Get setting by key /// </summary> /// <param name="key">Key</param> /// <param name="storeId">Store identifier</param> /// <param name="loadSharedValueIfNotFound">A value indicating whether a shared (for all stores) value should be loaded if a value specific for a certain is not found</param> /// <returns>Setting</returns> public virtual Setting GetSetting(string key, int storeId = 0, bool loadSharedValueIfNotFound = false) { if (String.IsNullOrEmpty(key)) return null; var settings = GetAllSettingsCached(); key = key.Trim().ToLowerInvariant(); if (settings.ContainsKey(key)) { var settingsByKey = settings[key]; var setting = settingsByKey.FirstOrDefault(x => x.StoreId == storeId); //load shared value? if (setting == null && storeId > 0 && loadSharedValueIfNotFound) setting = settingsByKey.FirstOrDefault(x => x.StoreId == 0); if (setting != null) return GetSettingById(setting.Id); } return null; } /// <summary> /// Get setting value by key /// </summary> /// <typeparam name="T">Type</typeparam> /// <param name="key">Key</param> /// <param name="defaultValue">Default value</param> /// <param name="storeId">Store identifier</param> /// <param name="loadSharedValueIfNotFound">A value indicating whether a shared (for all stores) value should be loaded if a value specific for a certain is not found</param> /// <returns>Setting value</returns> public virtual T GetSettingByKey<T>(string key, T defaultValue = default(T), int storeId = 0, bool loadSharedValueIfNotFound = false) { if (String.IsNullOrEmpty(key)) return defaultValue; var settings = GetAllSettingsCached(); key = key.Trim().ToLowerInvariant(); if (settings.ContainsKey(key)) { var settingsByKey = settings[key]; var setting = settingsByKey.FirstOrDefault(x => x.StoreId == storeId); //load shared value? if (setting == null && storeId > 0 && loadSharedValueIfNotFound) setting = settingsByKey.FirstOrDefault(x => x.StoreId == 0); if (setting != null) return CommonHelper.To<T>(setting.Value); } return defaultValue; } /// <summary> /// Set setting value /// </summary> /// <typeparam name="T">Type</typeparam> /// <param name="key">Key</param> /// <param name="value">Value</param> /// <param name="storeId">Store identifier</param> /// <param name="clearCache">A value indicating whether to clear cache after setting update</param> public virtual void SetSetting<T>(string key, T value, int storeId = 0, bool clearCache = true) { if (key == null) throw new ArgumentNullException("key"); key = key.Trim().ToLowerInvariant(); string valueStr = CommonHelper.GetNopCustomTypeConverter(typeof(T)).ConvertToInvariantString(value); var allSettings = GetAllSettingsCached(); var settingForCaching = allSettings.ContainsKey(key) ? allSettings[key].FirstOrDefault(x => x.StoreId == storeId) : null; if (settingForCaching != null) { //update var setting = GetSettingById(settingForCaching.Id); setting.Value = valueStr; UpdateSetting(setting, clearCache); } else { //insert var setting = new Setting { Name = key, Value = valueStr, StoreId = storeId }; InsertSetting(setting, clearCache); } } /// <summary> /// Gets all settings /// </summary> /// <returns>Settings</returns> public virtual IList<Setting> GetAllSettings() { var query = from s in _settingRepository.Table orderby s.Name, s.StoreId select s; var settings = query.ToList(); return settings; } /// <summary> /// Determines whether a setting exists /// </summary> /// <typeparam name="T">Entity type</typeparam> /// <typeparam name="TPropType">Property type</typeparam> /// <param name="settings">Entity</param> /// <param name="keySelector">Key selector</param> /// <param name="storeId">Store identifier</param> /// <returns>true -setting exists; false - does not exist</returns> public virtual bool SettingExists<T, TPropType>(T settings, Expression<Func<T, TPropType>> keySelector, int storeId = 0) where T : ISettings, new() { string key = settings.GetSettingKey(keySelector); var setting = GetSettingByKey<string>(key, storeId: storeId); return setting != null; } /// <summary> /// Load settings /// </summary> /// <typeparam name="T">Type</typeparam> /// <param name="storeId">Store identifier for which settigns should be loaded</param> public virtual T LoadSetting<T>(int storeId = 0) where T : ISettings, new() { var settings = Activator.CreateInstance<T>(); foreach (var prop in typeof(T).GetProperties()) { // get properties we can read and write to if (!prop.CanRead || !prop.CanWrite) continue; var key = typeof(T).Name + "." + prop.Name; //load by store var setting = GetSettingByKey<string>(key, storeId: storeId, loadSharedValueIfNotFound: true); if (setting == null) continue; if (!CommonHelper.GetNopCustomTypeConverter(prop.PropertyType).CanConvertFrom(typeof(string))) continue; if (!CommonHelper.GetNopCustomTypeConverter(prop.PropertyType).IsValid(setting)) continue; object value = CommonHelper.GetNopCustomTypeConverter(prop.PropertyType).ConvertFromInvariantString(setting); //set property prop.SetValue(settings, value, null); } return settings; } /// <summary> /// Save settings object /// </summary> /// <typeparam name="T">Type</typeparam> /// <param name="storeId">Store identifier</param> /// <param name="settings">Setting instance</param> public virtual void SaveSetting<T>(T settings, int storeId = 0) where T : ISettings, new() { /* We do not clear cache after each setting update. * This behavior can increase performance because cached settings will not be cleared * and loaded from database after each update */ foreach (var prop in typeof(T).GetProperties()) { // get properties we can read and write to if (!prop.CanRead || !prop.CanWrite) continue; if (!CommonHelper.GetNopCustomTypeConverter(prop.PropertyType).CanConvertFrom(typeof(string))) continue; string key = typeof(T).Name + "." + prop.Name; //Duck typing is not supported in C#. That's why we're using dynamic type dynamic value = prop.GetValue(settings, null); if (value != null) SetSetting(key, value, storeId, false); else SetSetting(key, "", storeId, false); } //and now clear cache ClearCache(); } /// <summary> /// Save settings object /// </summary> /// <typeparam name="T">Entity type</typeparam> /// <typeparam name="TPropType">Property type</typeparam> /// <param name="settings">Settings</param> /// <param name="keySelector">Key selector</param> /// <param name="storeId">Store ID</param> /// <param name="clearCache">A value indicating whether to clear cache after setting update</param> public virtual void SaveSetting<T, TPropType>(T settings, Expression<Func<T, TPropType>> keySelector, int storeId = 0, bool clearCache = true) where T : ISettings, new() { var member = keySelector.Body as MemberExpression; if (member == null) { throw new ArgumentException(string.Format( "Expression '{0}' refers to a method, not a property.", keySelector)); } var propInfo = member.Member as PropertyInfo; if (propInfo == null) { throw new ArgumentException(string.Format( "Expression '{0}' refers to a field, not a property.", keySelector)); } string key = settings.GetSettingKey(keySelector); //Duck typing is not supported in C#. That's why we're using dynamic type dynamic value = propInfo.GetValue(settings, null); if (value != null) SetSetting(key, value, storeId, clearCache); else SetSetting(key, "", storeId, clearCache); } /// <summary> /// Delete all settings /// </summary> /// <typeparam name="T">Type</typeparam> public virtual void DeleteSetting<T>() where T : ISettings, new() { var settingsToDelete = new List<Setting>(); var allSettings = GetAllSettings(); foreach (var prop in typeof(T).GetProperties()) { string key = typeof(T).Name + "." + prop.Name; settingsToDelete.AddRange(allSettings.Where(x => x.Name.Equals(key, StringComparison.InvariantCultureIgnoreCase))); } foreach (var setting in settingsToDelete) DeleteSetting(setting); } /// <summary> /// Delete settings object /// </summary> /// <typeparam name="T">Entity type</typeparam> /// <typeparam name="TPropType">Property type</typeparam> /// <param name="settings">Settings</param> /// <param name="keySelector">Key selector</param> /// <param name="storeId">Store ID</param> public virtual void DeleteSetting<T, TPropType>(T settings, Expression<Func<T, TPropType>> keySelector, int storeId = 0) where T : ISettings, new() { string key = settings.GetSettingKey(keySelector); key = key.Trim().ToLowerInvariant(); var allSettings = GetAllSettingsCached(); var settingForCaching = allSettings.ContainsKey(key) ? allSettings[key].FirstOrDefault(x => x.StoreId == storeId) : null; if (settingForCaching != null) { //update var setting = GetSettingById(settingForCaching.Id); DeleteSetting(setting); } } /// <summary> /// Clear cache /// </summary> public virtual void ClearCache() { _cacheManager.RemoveByPattern(SETTINGS_PATTERN_KEY); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ShuffleDouble0() { var test = new ImmBinaryOpTest__ShuffleDouble0(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmBinaryOpTest__ShuffleDouble0 { private struct TestStruct { public Vector128<Double> _fld1; public Vector128<Double> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__ShuffleDouble0 testClass) { var result = Sse2.Shuffle(_fld1, _fld2, 0); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector128<Double> _clsVar1; private static Vector128<Double> _clsVar2; private Vector128<Double> _fld1; private Vector128<Double> _fld2; private SimpleBinaryOpTest__DataTable<Double, Double, Double> _dataTable; static ImmBinaryOpTest__ShuffleDouble0() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); } public ImmBinaryOpTest__ShuffleDouble0() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new SimpleBinaryOpTest__DataTable<Double, Double, Double>(_data1, _data2, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.Shuffle( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr), 0 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.Shuffle( Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)), 0 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.Shuffle( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)), 0 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Shuffle), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr), (byte)0 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Shuffle), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)), (byte)0 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Shuffle), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)), (byte)0 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.Shuffle( _clsVar1, _clsVar2, 0 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr); var result = Sse2.Shuffle(left, right, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.Shuffle(left, right, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.Shuffle(left, right, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__ShuffleDouble0(); var result = Sse2.Shuffle(test._fld1, test._fld2, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.Shuffle(_fld1, _fld2, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.Shuffle(test._fld1, test._fld2, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Double> left, Vector128<Double> right, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.DoubleToInt64Bits(result[0]) != BitConverter.DoubleToInt64Bits(left[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(result[i]) != BitConverter.DoubleToInt64Bits(right[0])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.Shuffle)}<Double>(Vector128<Double>.0, Vector128<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Linq; using Content.Server.Administration.Logs; using Content.Server.Atmos; using Content.Server.Atmos.EntitySystems; using Content.Server.Body.Components; using Content.Server.Popups; using Content.Shared.Alert; using Content.Shared.Atmos; using Content.Shared.Body.Components; using Content.Shared.Damage; using Content.Shared.Database; using Content.Shared.MobState.Components; using JetBrains.Annotations; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Player; using Robust.Shared.Timing; namespace Content.Server.Body.Systems { [UsedImplicitly] public sealed class RespiratorSystem : EntitySystem { [Dependency] private readonly DamageableSystem _damageableSys = default!; [Dependency] private readonly AdminLogSystem _logSys = default!; [Dependency] private readonly BodySystem _bodySystem = default!; [Dependency] private readonly LungSystem _lungSystem = default!; [Dependency] private readonly AtmosphereSystem _atmosSys = default!; [Dependency] private readonly PopupSystem _popupSystem = default!; [Dependency] private readonly AlertsSystem _alertsSystem = default!; [Dependency] private readonly IGameTiming _gameTiming = default!; public override void Initialize() { base.Initialize(); // We want to process lung reagents before we inhale new reagents. UpdatesAfter.Add(typeof(MetabolizerSystem)); } public override void Update(float frameTime) { base.Update(frameTime); foreach (var (respirator, body) in EntityManager.EntityQuery<RespiratorComponent, SharedBodyComponent>()) { var uid = respirator.Owner; if (!EntityManager.TryGetComponent<MobStateComponent>(uid, out var state) || state.IsDead()) { continue; } respirator.AccumulatedFrametime += frameTime; if (respirator.AccumulatedFrametime < respirator.CycleDelay) continue; respirator.AccumulatedFrametime -= respirator.CycleDelay; UpdateSaturation(respirator.Owner, -respirator.CycleDelay, respirator); if (!state.IsIncapacitated()) // cannot breathe in crit. { switch (respirator.Status) { case RespiratorStatus.Inhaling: Inhale(uid, body); respirator.Status = RespiratorStatus.Exhaling; break; case RespiratorStatus.Exhaling: Exhale(uid, body); respirator.Status = RespiratorStatus.Inhaling; break; } } if (respirator.Saturation < respirator.SuffocationThreshold) { if (_gameTiming.CurTime >= respirator.LastGaspPopupTime + respirator.GaspPopupCooldown) { respirator.LastGaspPopupTime = _gameTiming.CurTime; _popupSystem.PopupEntity(Loc.GetString("lung-behavior-gasp"), uid, Filter.Pvs(uid)); } TakeSuffocationDamage(uid, respirator); respirator.SuffocationCycles += 1; continue; } StopSuffocation(uid, respirator); respirator.SuffocationCycles = 0; } } public void Inhale(EntityUid uid, SharedBodyComponent? body=null) { if (!Resolve(uid, ref body, false)) return; var organs = _bodySystem.GetComponentsOnMechanisms<LungComponent>(uid, body).ToArray(); // Inhale gas var ev = new InhaleLocationEvent(); RaiseLocalEvent(uid, ev, false); if (ev.Gas == null) { ev.Gas = _atmosSys.GetTileMixture(Transform(uid).Coordinates); if (ev.Gas == null) return; } var ratio = (Atmospherics.BreathVolume / ev.Gas.Volume); var actualGas = ev.Gas.RemoveRatio(ratio); var lungRatio = 1.0f / organs.Length; var gas = organs.Length == 1 ? actualGas : actualGas.RemoveRatio(lungRatio); foreach (var (lung, _) in organs) { // Merge doesn't remove gas from the giver. _atmosSys.Merge(lung.Air, gas); _lungSystem.GasToReagent(lung.Owner, lung); } } public void Exhale(EntityUid uid, SharedBodyComponent? body=null) { if (!Resolve(uid, ref body, false)) return; var organs = _bodySystem.GetComponentsOnMechanisms<LungComponent>(uid, body).ToArray(); // exhale gas var ev = new ExhaleLocationEvent(); RaiseLocalEvent(uid, ev, false); if (ev.Gas == null) { ev.Gas = _atmosSys.GetTileMixture(Transform(uid).Coordinates); // Walls and grids without atmos comp return null. I guess it makes sense to not be able to exhale in walls, // but this also means you cannot exhale on some grids. ev.Gas ??= GasMixture.SpaceGas; } var outGas = new GasMixture(ev.Gas.Volume); foreach (var (lung, _) in organs) { _atmosSys.Merge(outGas, lung.Air); lung.Air.Clear(); lung.LungSolution.RemoveAllSolution(); } _atmosSys.Merge(ev.Gas, outGas); } private void TakeSuffocationDamage(EntityUid uid, RespiratorComponent respirator) { if (respirator.SuffocationCycles == 2) _logSys.Add(LogType.Asphyxiation, $"{ToPrettyString(uid):entity} started suffocating"); if (respirator.SuffocationCycles >= respirator.SuffocationCycleThreshold) { _alertsSystem.ShowAlert(uid, AlertType.LowOxygen); } _damageableSys.TryChangeDamage(uid, respirator.Damage, true, false); } private void StopSuffocation(EntityUid uid, RespiratorComponent respirator) { if (respirator.SuffocationCycles >= 2) _logSys.Add(LogType.Asphyxiation, $"{ToPrettyString(uid):entity} stopped suffocating"); _alertsSystem.ClearAlert(uid, AlertType.LowOxygen); _damageableSys.TryChangeDamage(uid, respirator.DamageRecovery, true); } public void UpdateSaturation(EntityUid uid, float amount, RespiratorComponent? respirator = null) { if (!Resolve(uid, ref respirator, false)) return; respirator.Saturation += amount; respirator.Saturation = Math.Clamp(respirator.Saturation, respirator.MinSaturation, respirator.MaxSaturation); } } } public sealed class InhaleLocationEvent : EntityEventArgs { public GasMixture? Gas; } public sealed class ExhaleLocationEvent : EntityEventArgs { public GasMixture? Gas; }
//Original Scripts by IIColour (IIColour_Spectrum) using UnityEngine; using System.Collections; using UnityEngine.UI; public class EvolutionHandler : MonoBehaviour { private DialogBoxHandlerNew dialog; private GUIParticleHandler particles; private int pokemonFrame = 0; private int evolutionFrame = 0; private Sprite[] pokemonSpriteAnimation; private Sprite[] evolutionSpriteAnimation; private Image pokemonSprite; private Image evolutionSprite; private Image topBorder; private Image bottomBorder; private Image glow; private Pokemon selectedPokemon; private string evolutionMethod; private int evolutionID; public AudioClip evolutionBGM, evolvingClip, evolvedClip, forgetMoveClip; public Sprite smokeParticle; private bool stopAnimations = false; private bool evolving = true; private bool evolved = false; //Evolution Animation Coroutines private Coroutine c_animateEvolution; private Coroutine c_pokemonGlow; private Coroutine c_glowGrow; private Coroutine c_pokemonPulsate; private Coroutine c_glowPulsate; void Awake() { dialog = transform.GetComponent<DialogBoxHandlerNew>(); particles = transform.GetComponent<GUIParticleHandler>(); pokemonSprite = transform.Find("PokemonSprite").GetComponent<Image>(); evolutionSprite = transform.Find("EvolutionSprite").GetComponent<Image>(); topBorder = transform.Find("TopBorder").GetComponent<Image>(); bottomBorder = transform.Find("BottomBorder").GetComponent<Image>(); glow = transform.Find("Glow").GetComponent<Image>(); } void Start() { gameObject.SetActive(false); } private IEnumerator animatePokemon() { pokemonFrame = 0; evolutionFrame = 0; while (true) { if (pokemonSpriteAnimation.Length > 0) { if (pokemonFrame < pokemonSpriteAnimation.Length - 1) { pokemonFrame += 1; } else { pokemonFrame = 0; } pokemonSprite.sprite = pokemonSpriteAnimation[pokemonFrame]; } if (evolutionSpriteAnimation.Length > 0) { if (evolutionFrame < evolutionSpriteAnimation.Length - 1) { evolutionFrame += 1; } else { evolutionFrame = 0; } evolutionSprite.sprite = evolutionSpriteAnimation[evolutionFrame]; } yield return new WaitForSeconds(0.08f); } } public IEnumerator control(Pokemon pokemonToEvolve, string methodOfEvolution) { selectedPokemon = pokemonToEvolve; evolutionMethod = methodOfEvolution; evolutionID = selectedPokemon.getEvolutionID(evolutionMethod); string selectedPokemonName = selectedPokemon.getName(); pokemonSpriteAnimation = selectedPokemon.GetFrontAnim_(); evolutionSpriteAnimation = Pokemon.GetFrontAnimFromID_(evolutionID, selectedPokemon.getGender(), selectedPokemon.getIsShiny()); pokemonSprite.sprite = pokemonSpriteAnimation[0]; evolutionSprite.sprite = evolutionSpriteAnimation[0]; StartCoroutine(animatePokemon()); pokemonSprite.rectTransform.sizeDelta = new Vector2(128, 128); evolutionSprite.rectTransform.sizeDelta = new Vector2(0, 0); pokemonSprite.color = new Color(0.5f, 0.5f, 0.5f, 0.5f); evolutionSprite.color = new Color(0.5f, 0.5f, 0.5f, 0.5f); topBorder.rectTransform.sizeDelta = new Vector2(342, 0); bottomBorder.rectTransform.sizeDelta = new Vector2(342, 0); glow.rectTransform.sizeDelta = new Vector2(0, 0); stopAnimations = false; StartCoroutine(ScreenFade.main.Fade(true, 1f)); yield return new WaitForSeconds(1f); dialog.DrawDialogBox(); yield return StartCoroutine(dialog.DrawText("What?")); while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back")) { yield return null; } yield return StartCoroutine(dialog.DrawText("\n" + selectedPokemon.getName() + " is evolving!")); while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back")) { yield return null; } dialog.UndrawDialogBox(); evolving = true; AudioClip cry = selectedPokemon.GetCry(); SfxHandler.Play(cry); yield return new WaitForSeconds(cry.length); BgmHandler.main.PlayOverlay(evolutionBGM, 753100); yield return new WaitForSeconds(0.4f); c_animateEvolution = StartCoroutine(animateEvolution()); SfxHandler.Play(evolvingClip); yield return new WaitForSeconds(0.4f); while (evolving) { if (Input.GetButtonDown("Back")) { evolving = false; //fadeTime = sceneTransition.FadeOut(); //yield return new WaitForSeconds(fadeTime); yield return StartCoroutine(ScreenFade.main.Fade(false, ScreenFade.defaultSpeed)); stopAnimateEvolution(); //fadeTime = sceneTransition.FadeIn(); //yield return new WaitForSeconds(fadeTime); yield return StartCoroutine(ScreenFade.main.Fade(true, ScreenFade.defaultSpeed)); dialog.DrawDialogBox(); yield return StartCoroutine(dialog.DrawText("Huh?")); while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back")) { yield return null; } yield return StartCoroutine(dialog.DrawText("\n" + selectedPokemon.getName() + " stopped evolving.")); while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back")) { yield return null; } dialog.UndrawDialogBox(); } yield return null; } if (evolved) { selectedPokemon.evolve(evolutionMethod); yield return new WaitForSeconds(3.2f); cry = selectedPokemon.GetCry(); BgmHandler.main.PlayMFX(cry); yield return new WaitForSeconds(cry.length); AudioClip evoMFX = Resources.Load<AudioClip>("Audio/mfx/GetGreat"); BgmHandler.main.PlayMFXConsecutive(evoMFX); dialog.DrawDialogBox(); yield return StartCoroutine(dialog.DrawTextSilent("Congratulations!")); yield return new WaitForSeconds(0.8f); StartCoroutine( dialog.DrawTextSilent("\nYour " + selectedPokemonName + " evolved into " + PokemonDatabase.getPokemon(evolutionID).getName() + "!")); //wait for MFX to stop float extraTime = (evoMFX.length - 0.8f > 0) ? evoMFX.length - 0.8f : 0; yield return new WaitForSeconds(extraTime); while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back")) { yield return null; } string newMove = selectedPokemon.MoveLearnedAtLevel(selectedPokemon.getLevel()); if (!string.IsNullOrEmpty(newMove) && !selectedPokemon.HasMove(newMove)) { yield return StartCoroutine(LearnMove(selectedPokemon, newMove)); } dialog.UndrawDialogBox(); bool running = true; while (running) { if (Input.GetButtonDown("Select") || Input.GetButtonDown("Back")) { running = false; } yield return null; } yield return new WaitForSeconds(0.4f); } StartCoroutine(ScreenFade.main.Fade(false, 1f)); BgmHandler.main.ResumeMain(1.2f); yield return new WaitForSeconds(1.2f); this.gameObject.SetActive(false); } private void stopAnimateEvolution() { stopAnimations = true; StopCoroutine(c_animateEvolution); if (c_glowGrow != null) { StopCoroutine(c_glowGrow); } if (c_glowPulsate != null) { StopCoroutine(c_glowPulsate); } if (c_pokemonGlow != null) { StopCoroutine(c_pokemonGlow); } if (c_pokemonPulsate != null) { StopCoroutine(c_pokemonPulsate); } particles.cancelAllParticles(); glow.rectTransform.sizeDelta = new Vector2(0, 0); bottomBorder.rectTransform.sizeDelta = new Vector2(342, 0); topBorder.rectTransform.sizeDelta = new Vector2(342, 0); pokemonSprite.rectTransform.sizeDelta = new Vector2(128, 128); evolutionSprite.rectTransform.sizeDelta = new Vector2(0, 0); pokemonSprite.color = new Color(0.5f, 0.5f, 0.5f, 0.5f); BgmHandler.main.PlayOverlay(null, 0, 0.5f); } private IEnumerator animateEvolution() { StartCoroutine(smokeSpiral()); StartCoroutine(borderDescend()); yield return new WaitForSeconds(0.6f); c_pokemonGlow = StartCoroutine(pokemonGlow()); yield return new WaitForSeconds(0.4f); c_glowGrow = StartCoroutine(glowGrow()); yield return new WaitForSeconds(0.4f); evolutionSprite.color = new Color(1, 1, 1, 0.5f); c_pokemonPulsate = StartCoroutine(pokemonPulsate(19)); yield return new WaitForSeconds(0.4f); yield return c_glowPulsate = StartCoroutine(glowPulsate(7)); evolved = true; evolving = false; SfxHandler.Play(evolvedClip); StartCoroutine(glowDissipate()); StartCoroutine(brightnessExplosion()); StartCoroutine(borderRetract()); yield return new WaitForSeconds(0.4f); yield return StartCoroutine(evolutionUnglow()); yield return new WaitForSeconds(0.4f); } private IEnumerator brightnessExplosion() { //GlobalVariables.global.fadeTex = whiteTex; float speed = ScreenFade.slowedSpeed; StartCoroutine(ScreenFade.main.Fade(false, ScreenFade.slowedSpeed, Color.white)); float increment = 0f; while (increment < 1) { increment += (1f / speed) * Time.deltaTime; if (increment > 1) { increment = 1; } yield return null; } StartCoroutine(ScreenFade.main.Fade(true, ScreenFade.slowedSpeed, Color.white)); //sceneTransition.FadeIn(1.2f); } private IEnumerator glowGrow() { float increment = 0f; float speed = 0.8f; float endSize = 96f; glow.color = new Color(0.8f, 0.8f, 0.5f, 0.2f); while (increment < 1) { increment += (1 / speed) * Time.deltaTime; if (increment > 1) { increment = 1; } glow.rectTransform.sizeDelta = new Vector2(endSize * increment, endSize * increment); yield return null; } } private IEnumerator glowDissipate() { float increment = 0f; float speed = 1.5f; float startSize = glow.rectTransform.sizeDelta.x; float sizeDifference = 280f - startSize; while (increment < 1) { increment += (1 / speed) * Time.deltaTime; if (increment > 1) { increment = 1; } glow.rectTransform.sizeDelta = new Vector2(startSize + sizeDifference * increment, startSize + sizeDifference * increment); glow.color = new Color(glow.color.r, glow.color.g, glow.color.b, 0.2f - (0.2f * increment)); yield return null; } } private IEnumerator glowPulsate(int repetitions) { float increment = 0f; float speed = 0.9f; float maxSize = 160f; float minSize = 96f; float sizeDifference = maxSize - minSize; bool glowShrunk = true; for (int i = 0; i < repetitions; i++) { increment = 0f; while (increment < 1) { increment += (1 / speed) * Time.deltaTime; if (increment > 1) { increment = 1; } if (glowShrunk) { glow.rectTransform.sizeDelta = new Vector2(minSize + sizeDifference * increment, minSize + sizeDifference * increment); } else { glow.rectTransform.sizeDelta = new Vector2(maxSize - sizeDifference * increment, maxSize - sizeDifference * increment); } yield return null; } if (glowShrunk) { glowShrunk = false; } else { glowShrunk = true; } } } private IEnumerator pokemonPulsate(int repetitions) { float increment = 0f; float baseSpeed = 1.2f; float speed = baseSpeed; Vector3 originalPosition = pokemonSprite.transform.localPosition; Vector3 centerPosition = new Vector3(0.5f, 0.47f, originalPosition.z); float distance = centerPosition.y - originalPosition.y; bool originalPokemonShrunk = false; for (int i = 0; i < repetitions; i++) { increment = 0f; speed *= 0.85f; while (increment < 1) { if (speed < 0.15f) { speed = 0.15f; } increment += (1 / speed) * Time.deltaTime; if (increment > 1) { increment = 1; } if (originalPokemonShrunk) { pokemonSprite.rectTransform.sizeDelta = new Vector2(128f * increment, 128f * increment); pokemonSprite.transform.localPosition = new Vector3(originalPosition.x, centerPosition.y - (distance * increment), originalPosition.z); evolutionSprite.rectTransform.sizeDelta = new Vector2(128f - 128f * increment, 128f - 128f * increment); evolutionSprite.transform.localPosition = new Vector3(originalPosition.x, originalPosition.y + (distance * increment), originalPosition.z); } else { pokemonSprite.rectTransform.sizeDelta = new Vector2(128f - 128f * increment, 128f - 128f * increment); pokemonSprite.transform.localPosition = new Vector3(originalPosition.x, originalPosition.y + (distance * increment), originalPosition.z); evolutionSprite.rectTransform.sizeDelta = new Vector2(128f * increment, 128f * increment); evolutionSprite.transform.localPosition = new Vector3(originalPosition.x, centerPosition.y - (distance * increment), originalPosition.z); } yield return null; } if (originalPokemonShrunk) { originalPokemonShrunk = false; } else { originalPokemonShrunk = true; } } pokemonSprite.transform.localPosition = originalPosition; evolutionSprite.transform.localPosition = originalPosition; } private IEnumerator pokemonGlow() { float increment = 0f; float speed = 1.8f; while (increment < 1) { increment += (1 / speed) * Time.deltaTime; if (increment > 1) { increment = 1; } pokemonSprite.color = new Color(0.5f + (0.5f * increment), 0.5f + (0.5f * increment), 0.5f + (0.5f * increment), 0.5f); yield return null; } } private IEnumerator evolutionUnglow() { float increment = 0f; float speed = 1.8f; while (increment < 1) { increment += (1 / speed) * Time.deltaTime; if (increment > 1) { increment = 1; } evolutionSprite.color = new Color(1f - (0.5f * increment), 1f - (0.5f * increment), 1f - (0.5f * increment), 0.5f); yield return null; } } private IEnumerator borderDescend() { float increment = 0f; float speed = 0.4f; while (increment < 1) { increment += (1 / speed) * Time.deltaTime; if (increment > 1) { increment = 1; } topBorder.rectTransform.sizeDelta = new Vector2(342, 40 * increment); bottomBorder.rectTransform.sizeDelta = new Vector2(342, 64 * increment); yield return null; } } private IEnumerator borderRetract() { float increment = 0f; float speed = 0.4f; while (increment < 1) { increment += (1 / speed) * Time.deltaTime; if (increment > 1) { increment = 1; } topBorder.rectTransform.sizeDelta = new Vector2(342, 40 - 40 * increment); bottomBorder.rectTransform.sizeDelta = new Vector2(342, 64 - 64 * increment); yield return null; } } private IEnumerator smokeSpiral() { StartCoroutine(smokeTrail(-1, 0.6f, 0.56f, 16f)); yield return new WaitForSeconds(0.08f); StartCoroutine(smokeTrail(1, 0.36f, 0.44f, 18f)); yield return new WaitForSeconds(0.2f); StartCoroutine(smokeTrail(-1, 0.6f, 0.36f, 16f)); yield return new WaitForSeconds(0.26f); StartCoroutine(smokeTrail(1, 0.36f, 0.54f, 16f)); yield return new WaitForSeconds(0.08f); StartCoroutine(smokeTrail(-1, 0.6f, 0.42f, 18f)); yield return new WaitForSeconds(0.2f); StartCoroutine(smokeTrail(1, 0.36f, 0.34f, 16f)); yield return new WaitForSeconds(0.26f); StartCoroutine(smokeTrail(-1, 0.6f, 0.52f, 16f)); yield return new WaitForSeconds(0.08f); StartCoroutine(smokeTrail(1, 0.36f, 0.4f, 18f)); yield return new WaitForSeconds(0.2f); StartCoroutine(smokeTrail(-1, 0.6f, 0.32f, 16f)); yield return new WaitForSeconds(0.26f); StartCoroutine(smokeTrail(-1, 0.6f, 0.5f, 16f)); yield return new WaitForSeconds(0.08f); StartCoroutine(smokeTrail(1, 0.36f, 0.38f, 18f)); yield return new WaitForSeconds(0.2f); StartCoroutine(smokeTrail(-1, 0.6f, 0.3f, 16f)); yield return new WaitForSeconds(0.26f); } private IEnumerator smokeTrail(int direction, float positionX, float positionY, float maxSize) { float positionYmodified; float sizeModified; for (int i = 0; i < 8; i++) { positionYmodified = positionY + Random.Range(-0.03f, 0.03f); sizeModified = (((float) i / 7f) * maxSize + maxSize) / 2f; if (!stopAnimations) { Image particle = particles.createParticle(smokeParticle, ScaleToScreen(positionX, positionYmodified), ScaleToScreen(positionX + Random.Range(0.01f, 0.04f), positionYmodified - 0.02f), sizeModified, 0, 0.6f, 0, sizeModified * 0.33f); if (particle != null) { particle.color = new Color((float) i / 7f * 0.7f, (float) i / 7f * 0.7f, (float) i / 7f * 0.7f, 0.3f + ((float) i / 7f * 0.3f)); } else { Debug.Log("Particle Discarded"); } } if (direction > 0) { positionX += 0.03f; } else { positionX -= 0.03f; } positionY -= 0.0025f; yield return new WaitForSeconds(0.05f); } } private Vector2 ScaleToScreen(float x, float y) { Vector2 vector = new Vector2(x * 342f - 171f, (1 - y) * 192f - 96f); return vector; } private IEnumerator LearnMove(Pokemon selectedPokemon, string move) { int chosenIndex = 1; if (chosenIndex == 1) { bool learning = true; while (learning) { //Moveset is full if (selectedPokemon.getMoveCount() == 4) { dialog.DrawDialogBox(); yield return StartCoroutine( dialog.DrawText(selectedPokemon.getName() + " wants to learn the \nmove " + move + ".")); while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back")) { yield return null; } dialog.DrawDialogBox(); yield return StartCoroutine( dialog.DrawText("However, " + selectedPokemon.getName() + " already \nknows four moves.")); while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back")) { yield return null; } dialog.DrawDialogBox(); yield return StartCoroutine(dialog.DrawText("Should a move be deleted and \nreplaced with " + move + "?")); yield return StartCoroutine(dialog.DrawChoiceBox()); chosenIndex = dialog.chosenIndex; dialog.UndrawChoiceBox(); if (chosenIndex == 1) { dialog.DrawDialogBox(); yield return StartCoroutine(dialog.DrawText("Which move should \nbe forgotten?")); while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back")) { yield return null; } yield return StartCoroutine(ScreenFade.main.Fade(false, ScreenFade.defaultSpeed)); //Set SceneSummary to be active so that it appears Scene.main.Summary.gameObject.SetActive(true); StartCoroutine(Scene.main.Summary.control(new Pokemon[] { selectedPokemon }, learning:learning, newMoveString:move)); //Start an empty loop that will only stop when SceneSummary is no longer active (is closed) while (Scene.main.Summary.gameObject.activeSelf) { yield return null; } string replacedMove = Scene.main.Summary.replacedMove; yield return StartCoroutine(ScreenFade.main.Fade(true, ScreenFade.defaultSpeed)); if (!string.IsNullOrEmpty(replacedMove)) { dialog.DrawDialogBox(); yield return StartCoroutine(dialog.DrawTextSilent("1, ")); yield return new WaitForSeconds(0.4f); yield return StartCoroutine(dialog.DrawTextSilent("2, ")); yield return new WaitForSeconds(0.4f); yield return StartCoroutine(dialog.DrawTextSilent("and... ")); yield return new WaitForSeconds(0.4f); yield return StartCoroutine(dialog.DrawTextSilent("... ")); yield return new WaitForSeconds(0.4f); yield return StartCoroutine(dialog.DrawTextSilent("... ")); yield return new WaitForSeconds(0.4f); SfxHandler.Play(forgetMoveClip); yield return StartCoroutine(dialog.DrawTextSilent("Poof!")); while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back")) { yield return null; } dialog.DrawDialogBox(); yield return StartCoroutine( dialog.DrawText(selectedPokemon.getName() + " forgot how to \nuse " + replacedMove + ".")); while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back")) { yield return null; } dialog.DrawDialogBox(); yield return StartCoroutine(dialog.DrawText("And...")); while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back")) { yield return null; } dialog.DrawDialogBox(); AudioClip mfx = Resources.Load<AudioClip>("Audio/mfx/GetAverage"); BgmHandler.main.PlayMFX(mfx); StartCoroutine(dialog.DrawTextSilent(selectedPokemon.getName() + " learned \n" + move + "!")); yield return new WaitForSeconds(mfx.length); while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back")) { yield return null; } dialog.UndrawDialogBox(); learning = false; } else { //give up? chosenIndex = 0; } } if (chosenIndex == 0) { //NOT ELSE because this may need to run after (chosenIndex == 1) runs dialog.DrawDialogBox(); yield return StartCoroutine(dialog.DrawText("Give up on learning the move \n" + move + "?")); yield return StartCoroutine(dialog.DrawChoiceBox()); chosenIndex = dialog.chosenIndex; dialog.UndrawChoiceBox(); if (chosenIndex == 1) { learning = false; chosenIndex = 0; } } } //Moveset is not full, can fit the new move easily else { selectedPokemon.addMove(move); dialog.DrawDialogBox(); AudioClip mfx = Resources.Load<AudioClip>("Audio/mfx/GetAverage"); BgmHandler.main.PlayMFX(mfx); StartCoroutine(dialog.DrawTextSilent(selectedPokemon.getName() + " learned \n" + move + "!")); yield return new WaitForSeconds(mfx.length); while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back")) { yield return null; } dialog.UndrawDialogBox(); learning = false; } } } if (chosenIndex == 0) { //NOT ELSE because this may need to run after (chosenIndex == 1) runs //cancel learning loop dialog.DrawDialogBox(); yield return StartCoroutine(dialog.DrawText(selectedPokemon.getName() + " did not learn \n" + move + ".")); while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back")) { yield return null; } } } }
using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; using System.Collections; using System.Windows.Forms; using System.IO; namespace l2pvp { public class Clans { public uint id; public string name; public string ally; public bool enemy; public override string ToString() { return name; } } public class skill { public string name; public uint id; public DateTime lastuse; public uint hitTime; public uint reuseDelay; public ManualResetEvent mre; public override string ToString() { return name; } public bool succeed; object skilllock; public skill() { succeed = false; skilllock = new object(); } public bool skillstate() { lock (skilllock) { return succeed; } } public void setstate(bool state) { lock (skilllock) { succeed = state; } } public void setstate(uint hittime, uint reuse, DateTime time, bool state) { lock (skilllock) { hitTime = hittime; lastuse = time; reuseDelay = reuse; succeed = state; mre.Set(); } } } public class GameServer { //constructor public bool usebsoe = false; public bool allbsoe = false; public bool battack; public bool distanceupdates; public BotView bwindow; public bool bPercentRecover = false; public double PercentRecover = 80; public string[] charClasses = { "Human Fighter", "Warrior", "Gladiator", "Warlord", "Human Knight", "Paladin", "Dark Avenger", "Rogue", "Treasure Hunter", "Hawkeye", "Human Mystic", "Human Wizard", "Sorceror", "Necromancer", "Warlock", "Cleric", "Bishop", "Prophet", "Elven Fighter", "Elven Knight", "Temple Knight", "Swordsinger", "Elven Scout", "Plainswalker", "Silver Ranger", "Elven Mystic", "Elven Wizard", "Spellsinger", "Elemental Summoner", "Elven Oracle", "Elven Elder", "Dark Fighter", "Palus Knight", "Shillien Knight", "Bladedancer", "Assassin", "Abyss Walker", "Phantom Ranger", "Dark Elven Mystic", "Dark Elven Wizard", "Spellhowler", "Phantom Summoner", "Shillien Oracle", "Shillien Elder", "Orc Fighter", "Orc Raider", "Destroyer", "Orc Monk", "Tyrant", "Orc Mystic", "Orc Shaman", "Overlord", "Warcryer", "Dwarven Fighter", "Dwarven Scavenger", "Bounty Hunter", "Dwarven Artisan", "Warsmith", "dummyEntry1", "dummyEntry2", "dummyEntry3", "dummyEntry4", "dummyEntry5", "dummyEntry6", "dummyEntry7", "dummyEntry8", "dummyEntry9", "dummyEntry10", "dummyEntry11", "dummyEntry12", "dummyEntry13", "dummyEntry14", "dummyEntry15", "dummyEntry16", "dummyEntry17", "dummyEntry18", "dummyEntry19", "dummyEntry20", "dummyEntry21", "dummyEntry22", "dummyEntry23", "dummyEntry24", "dummyEntry25", "dummyEntry26", "dummyEntry27", "dummyEntry28", "dummyEntry29", "dummyEntry30", "Duelist", "DreadNought", "Phoenix Knight", "Hell Knight", "Sagittarius", "Adventurer", "Archmage", "Soultaker", "Arcana Lord", "Cardinal", "Hierophant", "Eva Templar", "Sword Muse", "Wind Rider", "Moonlight Sentinel", "Mystic Muse", "Elemental Master", "Eva's Saint", "Shillien Templar", "Spectral Dancer", "Ghost Hunter", "Ghost Sentinel", "Storm Screamer", "Spectral Master", "Shillien Saint", "Titan", "Grand Khauatari", "Dominator", "Doomcryer", "Fortune Seeker", "Maestro"}; public enum EffectType { BUFF, CHARGE, DMG_OVER_TIME, HEAL_OVER_TIME, COMBAT_POINT_HEAL_OVER_TIME, MANA_DMG_OVER_TIME, MANA_HEAL_OVER_TIME, RELAXING, STUN, ROOT, SLEEP, HATE, FAKE_DEATH, CONFUSION, CONFUSE_MOB_ONLY, MUTE, FEAR, SILENT_MOVE, SEED, PARALYZE, STUN_SELF, PSYCHICAL_MUTE, REMOVE_TARGET, TARGET_ME } public int sleepeffect = 128; public int root = 512; public int medusastate = 2048; public bool buffs = false; public List<Client> clist; public string global = ""; //Pots public bool cppots = true; public bool ghppots = true; public bool elixir = true; public bool qhp = false; public uint cpelixir = 1000, hpelixir = 2000, ghphp = 400, qhphp = 2500; public List<shots> shotlist; //clans public Dictionary<uint, Clans> clanlist; public Dictionary<uint, Clans> enemyclans; //players public Dictionary<uint, CharInfo> allplayerinfo; public Dictionary<uint, CharInfo> playerlist; public Dictionary<uint, CharInfo> attacklist; public Dictionary<uint, CharInfo> enemylist; public Dictionary<uint, CharInfo> deadlist; public CharInfo target = null; public List<uint> deletedenemies; public List<string> enemynames; public class Items { public uint id; public string name; public override string ToString() { return name; } } public class WatchedPlayers { public uint objid; public string name; public uint cp, maxcp; public uint hp, maxhp; public uint mp, maxmp; public override string ToString() { return name; } } public Dictionary<uint, WatchedPlayers> wlist; //network public TcpListener gsListen; public string gsIP; public int gsPort; //skills public Dictionary<uint, skillmap> skills; public string Targetter; public uint TargetterID = 0; //purg protection public uint PurgId = 0xffffffff; public uint LPid = 0xfffffff; public uint MimrId = 0xffffff; public bool autofollow = false; public bool autotalk = false; public Int32 talkdelay = 1; //leader public Client leader; public Thread targetselection; //command strings public List<string> commandlists; public int AttackDistance = 1200; public bool AssistLeader = false; public Dictionary<uint, Client.NPC> npclist; public Dictionary<uint, Client.NPC> moblist; public Dictionary<uint, Items> itemlist; public GameServer(string _gsIP, int _gsPort, string _lip) { IPAddress localip = IPAddress.Parse(_lip); // Console.WriteLine(localip.ToString()); gsListen = new TcpListener(System.Net.IPAddress.Any, 7777); gsIP = _gsIP; gsPort = _gsPort; commandlists = new List<string>(128); //initialize members clanlist = new Dictionary<uint, Clans>(); enemyclans = new Dictionary<uint, Clans>(); allplayerinfo = new Dictionary<uint, CharInfo>(); playerlist = new Dictionary<uint, CharInfo>(); attacklist = new Dictionary<uint, CharInfo>(); enemylist = new Dictionary<uint, CharInfo>(); deadlist = new Dictionary<uint, CharInfo>(); wlist = new Dictionary<uint, WatchedPlayers>(); deletedenemies = new List<uint>(); enemynames = new List<string>(); distanceupdates = true; targetselection = new Thread(this.selectTarget); target = null; npclist = new Dictionary<uint, Client.NPC>(); moblist = new Dictionary<uint, Client.NPC>(); shotlist = new List<shots>(); { StreamReader sReader = new StreamReader(new FileStream("shotid.txt", FileMode.Open, FileAccess.Read, FileShare.Read), Encoding.UTF8); while (true) { string line = sReader.ReadLine(); if (line == null) break; char[] sep = new char[4]; sep[0] = '='; sep[1] = '['; sep[2] = ']'; sep[3] = '\t'; string[] split = line.Split(sep, StringSplitOptions.RemoveEmptyEntries); //id = 2, name = 4 shots _s = new shots(); _s.id = Convert.ToUInt32(split[2]); _s.name = split[4]; shotlist.Add(_s); } } robeids = new List<uint>(); lightarmor = new List<uint>(); { StreamReader lReader = new StreamReader(new FileStream("armor.sql", FileMode.Open, FileAccess.Read, FileShare.Read), Encoding.UTF8); while (true) { string line = lReader.ReadLine(); if (line == null) break; if (line.Contains("--")) continue; if (line.Length < 6) continue; char[] sep = new char[4]; sep[0] = '('; sep[1] = ')'; sep[2] = ','; sep[3] = ';'; string[] splits = line.Split(sep, 6, StringSplitOptions.RemoveEmptyEntries); if (splits[4] == "\'magic\'") { robeids.Add(Convert.ToUInt32(splits[0])); } if (splits[4] == "\'light\'") { lightarmor.Add(Convert.ToUInt32(splits[0])); } } } Console.WriteLine("{0} in robe and {1} in light", robeids.Count, lightarmor.Count); itemlist = new Dictionary<uint, Items>(); { StreamReader lReader = new StreamReader(new FileStream("etcitem.sql", FileMode.Open, FileAccess.Read, FileShare.Read), Encoding.UTF8); while (true) { string line = lReader.ReadLine(); if (line == null) break; if (line.Contains("--")) continue; if (line.Length < 6) continue; char[] sep = new char[4]; sep[0] = '('; sep[1] = ')'; sep[2] = ','; sep[3] = ';'; string[] splits = line.Split(sep, 6, StringSplitOptions.RemoveEmptyEntries); try { Items i = new Items(); i.id = Convert.ToUInt32(splits[0]); i.name = splits[1]; itemlist.Add(i.id, i); } catch { } } } Console.WriteLine("Item count = {0}", itemlist.Count); skills = new Dictionary<uint, skillmap>(); { StreamReader lReader = new StreamReader(new FileStream("skill_trees.sql", FileMode.Open, FileAccess.Read, FileShare.Read), Encoding.UTF8); while (true) { string line = lReader.ReadLine(); if (line == null) break; if (line.Contains("--")) continue; if (line.Length < 6) continue; char[] sep = new char[5]; sep[0] = '('; sep[1] = ')'; sep[2] = ','; sep[3] = '\''; sep[4] = ';'; string[] splits = line.Split(sep, 6, StringSplitOptions.RemoveEmptyEntries); uint skillid = Convert.ToUInt32(splits[1]); skillmap s = new skillmap(); s.id = skillid; s.name = splits[3]; if (!skills.ContainsKey(skillid)) skills.Add(skillid, s); } } clist = new List<Client>(); leader = null; //start UI thread bwindow = new BotView(this); bwindow.Show(); } public bool flagfight = false; public bool kill2waywar = false; public List<uint> robeids; public List<uint> lightarmor; public void selectTarget() { while (true) { try { if (battack == false) { Thread.Sleep(50); continue; } CharInfo[] elist = null; target = null; do { try { elist = new CharInfo[enemylist.Count]; enemylist.Values.CopyTo(elist, 0); } catch { continue; } } while (false); //FIRST PASS - ROBE ARMORS foreach (CharInfo temp in elist) { if (temp == null) continue; if (flagfight == true) if (temp.rpvpflag == 0 && (temp.relation & 0x00002) != 0 && ((temp.relation & 0x080000) != 0)) continue; if (deadlist.ContainsKey(temp.ID)) { if (temp.isAlikeDead == 0) { deadlist.Remove(temp.ID); } else continue; } if (temp != null && temp.isAlikeDead == 1) { if (!deadlist.ContainsKey(temp.ID)) { deadlist.Add(temp.ID, temp); } continue; } if (!robeids.Contains(temp.Chest)) { //is not a robe user continue; } if (temp != null && temp.distance < AttackDistance && ((temp.AbnormalEffects & medusastate) == 0) && temp.isAlikeDead != 1 && temp.peace != 1) { if (target == null) { target = temp; } if (temp.distance < target.distance) { target = temp; } } } //2nd pass - light armors if (target == null) { foreach (CharInfo temp in elist) { if (temp == null) continue; if (flagfight == true && temp != null) if (temp.rpvpflag == 0 && (temp.relation & 0x00002) != 0 && ((temp.relation & 0x080000) != 0)) continue; if (deadlist.ContainsKey(temp.ID)) { if (temp.isAlikeDead == 0) { deadlist.Remove(temp.ID); } else continue; } if (temp != null && temp.isAlikeDead == 1) { if (!deadlist.ContainsKey(temp.ID)) { deadlist.Add(temp.ID, temp); } continue; } if (temp != null && !lightarmor.Contains(temp.Chest)) { //is not a robe user continue; } if (temp != null && temp.distance < AttackDistance && ((temp.AbnormalEffects & medusastate) == 0) && temp.isAlikeDead != 1 && temp.peace != 1) { if (target == null) { target = temp; } if (temp.distance < target.distance) { target = temp; } } } } //3rd pass closest if (target == null) { foreach (CharInfo temp in elist) { if (temp == null) continue; if (flagfight == true && temp != null) if ((temp.rpvpflag == 0 && (temp.relation & 0x00002) != 0 && ((temp.relation & 0x080000) != 0)) || temp.relation == 0) continue; if (deadlist.ContainsKey(temp.ID)) { if (temp.isAlikeDead == 0) { deadlist.Remove(temp.ID); } else continue; } if (temp != null && temp.isAlikeDead == 1) { if (!deadlist.ContainsKey(temp.ID)) { deadlist.Add(temp.ID, temp); } continue; } if (temp != null && temp.distance < AttackDistance && ((temp.AbnormalEffects & medusastate) == 0) && temp.isAlikeDead != 1 && temp.peace != 1) { if (target == null) { target = temp; } if (temp.distance < target.distance) { target = temp; } } } } if (target != null) { if (!attacklist.ContainsKey(target.ID)) { attacklist.Add(target.ID, target); enemylist.Remove(target.ID); } else enemylist.Remove(target.ID); } if (target == null) { foreach (CharInfo temp in elist) { if (temp != null && temp.peace == 1) { temp.peace = 0; continue; } } } if (target == null || enemylist.Count < 1) { Array.Clear(elist, 0, elist.Length); elist = new CharInfo[attacklist.Values.Count]; attacklist.Values.CopyTo(elist, 0); foreach (CharInfo i in elist) { if (i != null) { if (i.peace == 1) i.peace = 0; enemylist.Add(i.ID, i); attacklist.Remove(i.ID); } } } //if (target != null) //{ // if (robeids.Contains(target.Chest)) // Console.WriteLine("{0} is a robe user", target.Name); // else if (lightarmor.Contains(target.Chest)) // Console.WriteLine("{0} is a light user", target.Name); // else // Console.WriteLine("{0} is a heavy or no armor user", target.Name); //} for (int counter = 0; counter < 40; counter++) { Thread.Sleep(250); if(target != null) { if (target != null && target.distance < AttackDistance && ((target.AbnormalEffects & medusastate) == 0) && target.isAlikeDead != 1 && target.peace != 1) break; } else break; } } catch (ThreadInterruptedException e) { System.Console.WriteLine("Switching targets"); } catch(Exception e) { System.Console.WriteLine(e.ToString()); } } } public void startListen() { gsListen.Start(); while (true) { Socket newsocket = gsListen.AcceptSocket(); Client c = new Client(newsocket, this); clist.Add(c); } } public void deleteObject(uint id) { if (target == null) return; if (target.ID == id) { target.peace = 1; } } public void UpdateTarget(CharInfo cinfo) { if (target == null) return; if (cinfo.ID == target.ID) { target = cinfo; } } } }
// 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.IO; using System.Reflection; using System.Text; using Microsoft.NodejsTools.Jade; using Microsoft.VisualStudio.TestTools.UnitTesting; using TestUtilities; using TestUtilities.Nodejs; namespace NodejsTests { [TestClass] public class JadeTokenizerTest { private static bool _regenerateBaselineFiles = false; [ClassInitialize] public static void DoDeployment(TestContext context) { AssertListener.Initialize(); NodejsTestData.Deploy(); } [TestMethod, Priority(0)] public void JadeTokenizerTest_File01() { Tokenize("001.pug"); } [TestMethod, Priority(0)] public void JadeTokenizerTest_File02() { Tokenize("002.pug"); } [TestMethod, Priority(0)] public void JadeTokenizerTest_File03() { Tokenize("003.pug"); } [TestMethod, Priority(0)] public void JadeTokenizerTest_File04() { Tokenize("004.pug"); } [TestMethod, Priority(0)] public void JadeTokenizerTest_File05() { Tokenize("005.pug"); } [TestMethod, Priority(0)] public void JadeTokenizerTest_File06() { Tokenize("006.pug"); } [TestMethod, Priority(0)] public void JadeTokenizerTest_File07() { Tokenize("007.pug"); } [TestMethod, Priority(0)] public void JadeTokenizerTest_File08() { Tokenize("008.pug"); } [TestMethod, Priority(0)] public void JadeTokenizerTest_File09() { Tokenize("009.pug"); } [TestMethod, Priority(0)] public void JadeTokenizerTest_File10() { Tokenize("010.pug"); } [TestMethod, Priority(0)] public void JadeTokenizerTest_File11() { Tokenize("011.pug"); } [TestMethod, Priority(0)] public void JadeTokenizerTest_File12() { Tokenize("012.pug"); } [TestMethod, Priority(0)] public void JadeTokenizerTest_File13() { Tokenize("013.pug"); } [TestMethod, Priority(0)] public void JadeTokenizerTest_File14() { Tokenize("014.pug"); } [TestMethod, Priority(0)] public void JadeTokenizerTest_File15() { Tokenize("015.pug"); } [TestMethod, Priority(0)] public void JadeTokenizerTest_File16() { Tokenize("016.pug"); } [TestMethod, Priority(0)] public void JadeTokenizerTest_File17() { Tokenize("017.pug"); } [TestMethod, Priority(0)] public void JadeTokenizerTest_File18() { Tokenize("018.pug"); } [TestMethod, Priority(0)] public void JadeTokenizerTest_File19() { Tokenize("019.pug"); } [TestMethod, Priority(0)] public void JadeTokenizerTest_File20() { Tokenize("020.pug"); } [TestMethod, Priority(0)] public void JadeTokenizerTest_File21() { Tokenize("021.pug"); } [TestMethod, Priority(0)] public void JadeTokenizerTest_File22() { Tokenize("022.pug"); } [TestMethod, Priority(0)] public void JadeTokenizerTest_File23() { Tokenize("023.pug"); } private void Tokenize(string fileName) { string path = TestData.GetPath(Path.Combine("TestData", "Jade", fileName)); TokenizeFile<JadeToken, JadeTokenType>(path, new JadeTokenizer(null), _regenerateBaselineFiles); } static public string LoadFile(string language, string subfolder, string fileName) { var filePath = GetTestFilesPath(language, subfolder); return File.ReadAllText(filePath + "\\" + fileName); } static public string GetTestFilesPath(string language, string subfolder = null) { string thisAssembly = Assembly.GetExecutingAssembly().Location; string assemblyLoc = Path.GetDirectoryName(thisAssembly); string path = Path.Combine(assemblyLoc, @"Files\", language); if (subfolder != null) path = Path.Combine(path, subfolder); return path; } public static IList<string> GetFiles(string language, string folder, string extension) { string path = GetTestFilesPath(language, folder); var files = new List<string>(); IEnumerable<string> filesInFolder = Directory.EnumerateFiles(path); foreach (string name in filesInFolder) { if (name.EndsWith(extension)) files.Add(name); } return files; } private static void TokenizeFile<TokenClass, TokenType>(string fileName, ITokenizer<TokenClass> tokenizer, bool regenerateBaselineFiles) where TokenClass : IToken<TokenType> { string baselineFile = fileName + ".tokens"; string text = File.ReadAllText(fileName); var tokens = tokenizer.Tokenize(new TextStream(text), 0, text.Length); var actual = WriteTokens<TokenClass, TokenType>(tokens); BaselineCompare.CompareFiles(baselineFile, actual, regenerateBaselineFiles); } private static string WriteTokens<TokenClass, TokenType>(ReadOnlyTextRangeCollection<TokenClass> tokens) where TokenClass : IToken<TokenType> { var sb = new StringBuilder(); foreach (var token in tokens) { var tt = token.TokenType.ToString(); tt = tt.Substring(tt.LastIndexOf('.') + 1); var formattedToken = String.Format("{0} [{1}...{2}]\r\n", tt, token.Start, token.End); sb.Append(formattedToken); } return sb.ToString(); } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Dispatcher { using System.Runtime; enum ValueDataType : byte { None = 0, Boolean, Double, StackFrame, Sequence, String } // Value is like Variant. Since a Value is only temporary storage, we use memory to avoid typecasting type // casting, which in C# is expensive. Value contains storage for every possible XPath data type. // We avoid data copying by being smart about how we pass Value around - values are either accessed via // method calls, or the value object itself is passed by ref // // The filter engine never deals with a single value per se. We only work with Sets of Values. A single value // is a ValueSet of size 1 // internal struct Value { bool boolVal; double dblVal; StackFrame frame; NodeSequence sequence; string strVal; ValueDataType type; internal bool Boolean { get { return this.boolVal; } set { this.type = ValueDataType.Boolean; this.boolVal = value; } } internal double Double { get { return this.dblVal; } set { this.type = ValueDataType.Double; this.dblVal = value; } } internal StackFrame Frame { get { return this.frame; } #if NO set { this.type = ValueDataType.StackFrame; this.frame = value; } #endif } #if NO internal int FrameCount { get { return this.frame.Count; } } #endif internal int FrameEndPtr { #if NO get { return this.frame.endPtr; } #endif set { Fx.Assert(this.IsType(ValueDataType.StackFrame), ""); this.frame.EndPtr = value; } } #if NO internal int FrameBasePtr { get { return this.frame.basePtr; } } internal int StackPtr { get { return this.frame.basePtr - 1; } } #endif internal int NodeCount { get { return this.sequence.Count; } } internal NodeSequence Sequence { get { return this.sequence; } set { this.type = ValueDataType.Sequence; this.sequence = value; } } internal string String { get { return this.strVal; } set { this.type = ValueDataType.String; this.strVal = value; } } internal ValueDataType Type { get { return this.type; } } internal void Add(double val) { Fx.Assert(ValueDataType.Double == this.type, ""); this.dblVal += val; } #if NO internal void Clear() { this.type = ValueDataType.None; this.sequence = null; } #endif internal void Clear(ProcessingContext context) { if (ValueDataType.Sequence == this.type) { this.ReleaseSequence(context); } this.type = ValueDataType.None; } // Fully general compare internal bool CompareTo(ref Value val, RelationOperator op) { switch (this.type) { default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperCritical(new QueryProcessingException(QueryProcessingError.TypeMismatch)); case ValueDataType.Boolean: switch (val.type) { default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperCritical(new QueryProcessingException(QueryProcessingError.TypeMismatch)); case ValueDataType.Boolean: return QueryValueModel.Compare(this.boolVal, val.boolVal, op); case ValueDataType.Double: return QueryValueModel.Compare(this.boolVal, val.dblVal, op); case ValueDataType.Sequence: return QueryValueModel.Compare(this.boolVal, val.sequence, op); case ValueDataType.String: return QueryValueModel.Compare(this.boolVal, val.strVal, op); } case ValueDataType.Double: switch (val.type) { default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperCritical(new QueryProcessingException(QueryProcessingError.TypeMismatch)); case ValueDataType.Boolean: return QueryValueModel.Compare(this.dblVal, val.boolVal, op); case ValueDataType.Double: return QueryValueModel.Compare(this.dblVal, val.dblVal, op); case ValueDataType.Sequence: return QueryValueModel.Compare(this.dblVal, val.sequence, op); case ValueDataType.String: return QueryValueModel.Compare(this.dblVal, val.strVal, op); } case ValueDataType.Sequence: switch (val.type) { default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperCritical(new QueryProcessingException(QueryProcessingError.TypeMismatch)); case ValueDataType.Boolean: return QueryValueModel.Compare(this.sequence, val.boolVal, op); case ValueDataType.Double: return QueryValueModel.Compare(this.sequence, val.dblVal, op); case ValueDataType.Sequence: return QueryValueModel.Compare(this.sequence, val.sequence, op); case ValueDataType.String: return QueryValueModel.Compare(this.sequence, val.strVal, op); } case ValueDataType.String: switch (val.type) { default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperCritical(new QueryProcessingException(QueryProcessingError.TypeMismatch)); case ValueDataType.Boolean: return QueryValueModel.Compare(this.strVal, val.boolVal, op); case ValueDataType.Double: return QueryValueModel.Compare(this.strVal, val.dblVal, op); case ValueDataType.Sequence: return QueryValueModel.Compare(this.strVal, val.sequence, op); case ValueDataType.String: return QueryValueModel.Compare(this.strVal, val.strVal, op); } } } internal bool CompareTo(double val, RelationOperator op) { switch (this.type) { default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperCritical(new QueryProcessingException(QueryProcessingError.TypeMismatch)); case ValueDataType.Boolean: return QueryValueModel.Compare(this.boolVal, val, op); case ValueDataType.Double: return QueryValueModel.Compare(this.dblVal, val, op); case ValueDataType.Sequence: return QueryValueModel.Compare(this.sequence, val, op); case ValueDataType.String: return QueryValueModel.Compare(this.strVal, val, op); } } internal void ConvertTo(ProcessingContext context, ValueDataType newType) { Fx.Assert(null != context, ""); if (newType == this.type) { return; } switch (newType) { default: break; case ValueDataType.Boolean: this.boolVal = this.ToBoolean(); break; case ValueDataType.Double: this.dblVal = this.ToDouble(); break; case ValueDataType.String: this.strVal = this.ToString(); break; } if (ValueDataType.Sequence == this.type) { this.ReleaseSequence(context); } this.type = newType; } internal bool Equals(string val) { switch (this.type) { default: Fx.Assert("Invalid Type"); return false; case ValueDataType.Boolean: return QueryValueModel.Equals(this.boolVal, val); case ValueDataType.Double: return QueryValueModel.Equals(this.dblVal, val); case ValueDataType.Sequence: return QueryValueModel.Equals(this.sequence, val); case ValueDataType.String: return QueryValueModel.Equals(this.strVal, val); } } internal bool Equals(double val) { switch (this.type) { default: Fx.Assert("Invalid Type"); return false; case ValueDataType.Boolean: return QueryValueModel.Equals(this.boolVal, val); case ValueDataType.Double: return QueryValueModel.Equals(this.dblVal, val); case ValueDataType.Sequence: return QueryValueModel.Equals(this.sequence, val); case ValueDataType.String: return QueryValueModel.Equals(val, this.strVal); } } #if NO internal bool Equals(bool val) { switch (this.type) { default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new QueryProcessingException(QueryProcessingError.TypeMismatch), TraceEventType.Critical); case ValueDataType.Boolean: return QueryValueModel.Equals(this.boolVal, val); case ValueDataType.Double: return QueryValueModel.Equals(this.dblVal, val); case ValueDataType.Sequence: return QueryValueModel.Equals(this.sequence, val); case ValueDataType.String: return QueryValueModel.Equals(this.strVal, val); } } #endif internal bool GetBoolean() { if (ValueDataType.Boolean != this.type) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperCritical(new QueryProcessingException(QueryProcessingError.TypeMismatch)); } return this.boolVal; } internal double GetDouble() { if (ValueDataType.Double != this.type) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperCritical(new QueryProcessingException(QueryProcessingError.TypeMismatch)); } return this.dblVal; } internal NodeSequence GetSequence() { if (ValueDataType.Sequence != this.type) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperCritical(new QueryProcessingException(QueryProcessingError.TypeMismatch)); } return this.sequence; } internal string GetString() { if (ValueDataType.String != this.type) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperCritical(new QueryProcessingException(QueryProcessingError.TypeMismatch)); } return this.strVal; } internal bool IsType(ValueDataType type) { return (type == this.type); } internal void Multiply(double val) { Fx.Assert(ValueDataType.Double == this.type, ""); this.dblVal *= val; } internal void Negate() { Fx.Assert(this.type == ValueDataType.Double, ""); this.dblVal = -this.dblVal; } internal void Not() { Fx.Assert(this.type == ValueDataType.Boolean, ""); this.boolVal = !this.boolVal; } internal void ReleaseSequence(ProcessingContext context) { Fx.Assert(null != context && this.type == ValueDataType.Sequence && null != this.sequence, ""); context.ReleaseSequence(this.sequence); this.sequence = null; } internal void StartFrame(int start) { this.type = ValueDataType.StackFrame; this.frame.basePtr = start + 1; this.frame.endPtr = start; } #if NO internal void Subtract(double dblVal) { Fx.Assert(ValueDataType.Double == this.type, ""); this.dblVal -= dblVal; } #endif internal bool ToBoolean() { switch (this.type) { default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperCritical(new QueryProcessingException(QueryProcessingError.TypeMismatch)); case ValueDataType.Boolean: return this.boolVal; case ValueDataType.Double: return QueryValueModel.Boolean(this.dblVal); case ValueDataType.Sequence: return QueryValueModel.Boolean(this.sequence); case ValueDataType.String: return QueryValueModel.Boolean(this.strVal); } } internal double ToDouble() { switch (this.type) { default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperCritical(new QueryProcessingException(QueryProcessingError.TypeMismatch)); case ValueDataType.Boolean: return QueryValueModel.Double(this.boolVal); case ValueDataType.Double: return this.dblVal; case ValueDataType.Sequence: return QueryValueModel.Double(this.sequence); case ValueDataType.String: return QueryValueModel.Double(this.strVal); } } public override string ToString() { switch (this.type) { default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperCritical(new QueryProcessingException(QueryProcessingError.TypeMismatch)); case ValueDataType.Boolean: return QueryValueModel.String(this.boolVal); case ValueDataType.Double: return QueryValueModel.String(this.dblVal); case ValueDataType.Sequence: return QueryValueModel.String(this.sequence); case ValueDataType.String: return this.strVal; } } internal void Update(ProcessingContext context, bool val) { if (ValueDataType.Sequence == this.type) { context.ReleaseSequence(this.sequence); } this.Boolean = val; } internal void Update(ProcessingContext context, double val) { if (ValueDataType.Sequence == this.type) { context.ReleaseSequence(this.sequence); } this.Double = val; } internal void Update(ProcessingContext context, string val) { if (ValueDataType.Sequence == this.type) { context.ReleaseSequence(this.sequence); } this.String = val; } internal void Update(ProcessingContext context, NodeSequence val) { if (ValueDataType.Sequence == this.type) { context.ReleaseSequence(this.sequence); } this.Sequence = val; } } }
using Orleans; using Orleans.Runtime; using Orleans.Runtime.Configuration; using OrleansPSUtils; using System.Collections.Generic; using System.IO; using System.Management.Automation; using System.Management.Automation.Runspaces; using Xunit; using Xunit.Abstractions; using Orleans.TestingHost; using UnitTests.GrainInterfaces; using System; using TestExtensions; namespace PSUtils.Tests { using Orleans.Hosting; using System.Linq; public class PowershellHostFixture : BaseTestClusterFixture { public PowerShell Powershell { get; set; } public Runspace Runspace { get; set; } public ClientConfiguration ClientConfig { get; set; } protected override void ConfigureTestCluster(TestClusterBuilder builder) { builder.ConfigureLegacyConfiguration(legacy => { ClientConfig = legacy.ClientConfiguration; }); builder.AddSiloBuilderConfigurator<SiloConfigurator>(); } public class SiloConfigurator : ISiloBuilderConfigurator { public void Configure(ISiloHostBuilder hostBuilder) { hostBuilder.AddMemoryGrainStorageAsDefault() .AddMemoryGrainStorage("MemoryStore"); } } public PowershellHostFixture() { var initialSessionState = InitialSessionState.CreateDefault(); initialSessionState.Commands.Add(new SessionStateCmdletEntry("Start-GrainClient", typeof(StartGrainClient), null)); initialSessionState.Commands.Add(new SessionStateCmdletEntry("Stop-GrainClient", typeof(StopGrainClient), null)); initialSessionState.Commands.Add(new SessionStateCmdletEntry("Get-Grain", typeof(GetGrain), null)); Runspace = RunspaceFactory.CreateRunspace(initialSessionState); Runspace.Open(); Powershell = PowerShell.Create(); Powershell.Runspace = Runspace; } public override void Dispose() { try { var stopCommand = new Command("Stop-GrainClient"); Powershell.Commands.Clear(); Powershell.Commands.AddCommand(stopCommand); Powershell.Invoke(); } catch { } finally { Powershell.Dispose(); Runspace.Dispose(); base.Dispose(); } } } public class PSClientTests : OrleansTestingBase, IClassFixture<PowershellHostFixture> { private PowerShell _ps; private ClientConfiguration _clientConfig; private ITestOutputHelper output; public PSClientTests(ITestOutputHelper output, PowershellHostFixture fixture) { this.output = output; _clientConfig = fixture.ClientConfig; _ps = fixture.Powershell; _ps.Commands.Clear(); } [Fact, TestCategory("SlowBVT"), TestCategory("Tooling")] public void ScriptCallTest() { _ps.Commands.AddScript(File.ReadAllText(@".\PSClient\PSClientTests.ps1")); _ps.Commands.AddParameter("clientConfig", _clientConfig); var results = _ps.Invoke(); Assert.Equal(5, results.Count); // Stop-Client with no current/specified client should throw (outputting $didThrow = true). Assert.NotNull(results[0]); Assert.True((bool)results[0].BaseObject); // Client must true be initialized Assert.NotNull(results[1]); Assert.True((bool)results[1].BaseObject); // The grain reference must not be null and of type IManagementGrain Assert.NotNull(results[2]); Assert.True(results[2].BaseObject is IManagementGrain); var statuses = results[3].BaseObject as Dictionary<SiloAddress, SiloStatus>; Assert.NotNull(statuses); Assert.True(statuses.Count > 0); foreach (var pair in statuses) { output.WriteLine(" ######## Silo {0}, status: {1}", pair.Key, pair.Value); Assert.Equal( SiloStatus.Active, pair.Value); } // Client must be not initialized Assert.NotNull(results[4]); Assert.False((bool)results[4].BaseObject); } [Fact, TestCategory("SlowBVT"), TestCategory("Tooling")] public void GetGrainTest() { var startGrainClient = new Command("Start-GrainClient"); startGrainClient.Parameters.Add("Config", _clientConfig); _ps.Commands.AddCommand(startGrainClient); var client = _ps.Invoke().FirstOrDefault()?.BaseObject as IClusterClient; Assert.NotNull(client); Assert.True(client.IsInitialized); _ps.Commands.Clear(); var getGrainCommand = new Command("Get-Grain"); getGrainCommand.Parameters.Add("GrainType", typeof(IManagementGrain)); getGrainCommand.Parameters.Add("LongKey", (long)0); getGrainCommand.Parameters.Add("Client", client); _ps.Commands.AddCommand(getGrainCommand); var results = _ps.Invoke<IManagementGrain>(); //Must be exactly 1 but powershell APIs always return a list Assert.Single(results); _ps.Commands.Clear(); var mgmtGrain = results[0]; //From now on, it is just a regular grain call Dictionary<SiloAddress, SiloStatus> statuses = mgmtGrain.GetHosts(onlyActive: true).Result; foreach (var pair in statuses) { output.WriteLine(" ######## Silo {0}, status: {1}", pair.Key, pair.Value); Assert.Equal( SiloStatus.Active, pair.Value); } Assert.True(statuses.Count > 0); getGrainCommand.Parameters.Clear(); getGrainCommand.Parameters.Add("GrainType", typeof(IStringGrain)); getGrainCommand.Parameters.Add("StringKey", "myKey"); getGrainCommand.Parameters.Add("Client", client); _ps.Commands.AddCommand(getGrainCommand); var stringGrainsResults = _ps.Invoke<IStringGrain>(); //Must be exactly 1 but powershell APIs always return a list Assert.Single(stringGrainsResults); _ps.Commands.Clear(); var stringGrain = stringGrainsResults[0]; Assert.NotNull(stringGrain); getGrainCommand.Parameters.Clear(); getGrainCommand.Parameters.Add("GrainType", typeof(IGuidGrain)); getGrainCommand.Parameters.Add("GuidKey", Guid.NewGuid()); getGrainCommand.Parameters.Add("Client", client); _ps.Commands.AddCommand(getGrainCommand); var guidGrainsResults = _ps.Invoke<IGuidGrain>(); //Must be exactly 1 but powershell APIs always return a list Assert.Single(guidGrainsResults); _ps.Commands.Clear(); var guidGrain = guidGrainsResults[0]; Assert.NotNull(guidGrain); this.StopGrainClient(client); } private void StopGrainClient(IClusterClient client) { var stopGrainClient = new Command("Stop-GrainClient"); _ps.Commands.AddCommand(stopGrainClient).AddParameter("Client", client); _ps.Invoke(); _ps.Commands.Clear(); Assert.True(!client.IsInitialized); } } }
// // mTouch-PDFReader library // SettingsTableVC.cs // // Copyright (c) 2012-2014 AlexanderMac(amatsibarov@gmail.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // 'Software'), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Drawing; using MonoTouch.Foundation; using MonoTouch.UIKit; using mTouchPDFReader.Library.Managers; using mTouchPDFReader.Library.Data.Objects; using mTouchPDFReader.Library.Data.Enums; namespace mTouchPDFReader.Library.Views.Management { public class SettingsTableVC : UITableViewController { #region Constants & Fields private const int DefaultLabelLeft = 15; private const int DefaultLabelWidth = 200; private UITableViewCell _pageTransitionStyleCell; private UITableViewCell _pageNavigationOrientationCell; private UITableViewCell _autoScaleMode; private UITableViewCell _topToolbarVisibilityCell; private UITableViewCell _bottomToolbarVisibilityCell; private UITableViewCell _zoomScaleLevelsCell; private UITableViewCell _zoomByDoubleTouchCell; private UITableViewCell _libraryReleaseDateCell; private UITableViewCell _libraryVersionCell; #endregion #region Constructors public SettingsTableVC() : base(null, null) { } #endregion #region UIViewController members public override void ViewDidLoad() { base.ViewDidLoad(); View.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight; _pageTransitionStyleCell = createPageTransitionStyleCell(); _pageNavigationOrientationCell = createPageNavigationOrientationCell(); _autoScaleMode = createAutoScaleModeCell(); _topToolbarVisibilityCell = createTopToolbarVisibilityCell(); _bottomToolbarVisibilityCell = createBottomBarVisibilityCell(); _zoomScaleLevelsCell = createZoomScaleLevelsCell(); _zoomByDoubleTouchCell = createmZoomByDoubleTouchCell(); _libraryReleaseDateCell = createLibraryReleaseDateCell(); _libraryVersionCell = createLibraryVersionCell(); TableView = new UITableView(View.Bounds, UITableViewStyle.Grouped) { BackgroundView = null, AutoresizingMask = UIViewAutoresizing.All, Source = new DataSource(this) }; } #endregion #region Create controls helpers private UITableViewCell createCell(string id) { var cell = new UITableViewCell(UITableViewCellStyle.Default, id) { AutoresizingMask = UIViewAutoresizing.All, BackgroundColor = UIColor.White, SelectionStyle = UITableViewCellSelectionStyle.None }; return cell; } private UILabel createTitleLabelControl(string title) { var label = new UILabel(new RectangleF(DefaultLabelLeft, 15, DefaultLabelWidth, 20)) { AutoresizingMask = UIViewAutoresizing.All, BackgroundColor = UIColor.Clear, Text = title }; return label; } private UILabel createValueLabelControl(RectangleF cellRect, string title) { const int width = 150; var label = new UILabel(new RectangleF(cellRect.Width - DefaultLabelLeft - width, 15, width, 20)) { AutoresizingMask = UIViewAutoresizing.FlexibleLeftMargin, BackgroundColor = UIColor.Clear, TextAlignment = UITextAlignment.Right, Text = title }; return label; } private UISegmentedControl createSegmentControl(RectangleF cellRect, string[] values, int width) { var seg = new UISegmentedControl(new RectangleF(cellRect.Width - DefaultLabelLeft - width, 5, width, 30)) { AutoresizingMask = UIViewAutoresizing.FlexibleLeftMargin }; for (int i = 0; i < values.Length; i++) { seg.InsertSegment(values [i], i, false); } return seg; } private UISwitch createSwitchControl(RectangleF cellRect, string[] values) { const int width = 50; var ctrl = new UISwitch(new RectangleF(cellRect.Width - DefaultLabelLeft - width, 5, width, 30)) { AutoresizingMask = UIViewAutoresizing.FlexibleLeftMargin }; return ctrl; } private UISlider createSliderControl(RectangleF cellRect, int minValue, int maxValue) { const int width = 100; var slider = new UISlider(new RectangleF(cellRect.Width - DefaultLabelLeft - width, 5, width, 30)) { AutoresizingMask = UIViewAutoresizing.FlexibleLeftMargin, MinValue = minValue, MaxValue = maxValue }; return slider; } #endregion #region Create cells private UITableViewCell createPageTransitionStyleCell() { var cell = createCell("PageTransitionStyleCell"); var label = createTitleLabelControl("Transition style".t()); var seg = createSegmentControl(cell.Frame, new[] { "Curl".t(), "Scroll".t() }, 100); seg.SelectedSegment = (int)MgrAccessor.SettingsMgr.Settings.PageTransitionStyle; seg.ValueChanged += delegate { MgrAccessor.SettingsMgr.Settings.PageTransitionStyle = (UIPageViewControllerTransitionStyle)seg.SelectedSegment; MgrAccessor.SettingsMgr.Save(); }; cell.AddSubview(label); cell.AddSubview(seg); return cell; } private UITableViewCell createPageNavigationOrientationCell() { var cell = createCell("PageNavigationOrientationCell"); var label = createTitleLabelControl("Navigation orientation".t()); var seg = createSegmentControl(cell.Frame, new[] { "Horizontal".t(), "Vertical".t() }, 100); seg.SelectedSegment = (int)MgrAccessor.SettingsMgr.Settings.PageTransitionStyle; seg.ValueChanged += delegate { MgrAccessor.SettingsMgr.Settings.PageNavigationOrientation = (UIPageViewControllerNavigationOrientation)seg.SelectedSegment; MgrAccessor.SettingsMgr.Save(); }; cell.AddSubview(label); cell.AddSubview(seg); return cell; } private UITableViewCell createTopToolbarVisibilityCell() { var cell = createCell("TopToolbarVisibilityCell"); var label = createTitleLabelControl("Top Toolbar".t()); var switchCtrl = createSwitchControl(cell.Frame, new[] { "Yes".t(), "No".t() }); switchCtrl.SetState(MgrAccessor.SettingsMgr.Settings.TopToolbarVisible, false); switchCtrl.ValueChanged += delegate { MgrAccessor.SettingsMgr.Settings.TopToolbarVisible = switchCtrl.On; MgrAccessor.SettingsMgr.Save(); }; cell.AddSubview(label); cell.AddSubview(switchCtrl); return cell; } private UITableViewCell createBottomBarVisibilityCell() { var cell = createCell("BottomToolbarVisibilityCell"); var label = createTitleLabelControl("Bottom Toolbar".t()); var switchCtrl = createSwitchControl(cell.Frame, new[] { "Yes".t(), "No".t() }); switchCtrl.SetState(MgrAccessor.SettingsMgr.Settings.BottomToolbarVisible, false); switchCtrl.ValueChanged += delegate { MgrAccessor.SettingsMgr.Settings.BottomToolbarVisible = switchCtrl.On; MgrAccessor.SettingsMgr.Save(); }; cell.AddSubview(label); cell.AddSubview(switchCtrl); return cell; } private UITableViewCell createAutoScaleModeCell() { var cell = createCell("AutoScaleModelCell"); var label = createTitleLabelControl("Auto scale mode".t()); var seg = createSegmentControl(cell.Frame, new[] { "Auto width".t(), "Auto height".t() }, 150); seg.SelectedSegment = (int)MgrAccessor.SettingsMgr.Settings.AutoScaleMode; seg.ValueChanged += delegate { MgrAccessor.SettingsMgr.Settings.AutoScaleMode = (AutoScaleModes)seg.SelectedSegment; MgrAccessor.SettingsMgr.Save(); }; cell.AddSubview(label); cell.AddSubview(seg); return cell; } private UITableViewCell createZoomScaleLevelsCell() { var cell = createCell("ZoomScaleLevelsCell"); var label = createTitleLabelControl("Zoom scale levels".t()); var slider = createSliderControl(cell.Frame, Settings.MinZoomScaleLevels, Settings.MaxZoomScaleLevels); slider.SetValue(MgrAccessor.SettingsMgr.Settings.ZoomScaleLevels, false); slider.ValueChanged += delegate { MgrAccessor.SettingsMgr.Settings.ZoomScaleLevels = (int)slider.Value; MgrAccessor.SettingsMgr.Save(); }; cell.AddSubview(label); cell.AddSubview(slider); return cell; } private UITableViewCell createmZoomByDoubleTouchCell() { var cell = createCell("ZoomByDoubleTouchCell"); var label = createTitleLabelControl("Scale by double click".t()); var switchCtrl = createSwitchControl(cell.Frame, new[] { "Yes".t(), "No".t() }); switchCtrl.SetState(MgrAccessor.SettingsMgr.Settings.AllowZoomByDoubleTouch, false); switchCtrl.ValueChanged += delegate { MgrAccessor.SettingsMgr.Settings.AllowZoomByDoubleTouch = switchCtrl.On; MgrAccessor.SettingsMgr.Save(); }; cell.AddSubview(label); cell.AddSubview(switchCtrl); return cell; } private UITableViewCell createLibraryReleaseDateCell() { var cell = createCell("LibraryReleaseDateCell"); var label = createTitleLabelControl("Release date".t()); var labelInfo = createValueLabelControl(cell.Frame, MgrAccessor.SettingsMgr.Settings.LibraryReleaseDate.ToShortDateString()); cell.AddSubview(label); cell.AddSubview(labelInfo); return cell; } private UITableViewCell createLibraryVersionCell() { var cell = createCell("LibraryVersionCell"); var label = createTitleLabelControl("Version".t()); var labelInfo = createValueLabelControl(cell.Frame, MgrAccessor.SettingsMgr.Settings.LibraryVersion); cell.AddSubview(label); cell.AddSubview(labelInfo); return cell; } #endregion #region Table DataSource protected class DataSource : UITableViewSource { private const int SectionsCount = 4; private readonly int[] RowsInSections = new[] { 2, 2, 3, 2 }; private readonly string[] SectionTitles = new[] { "Transition style".t(), "Visibility".t(), "Scale".t(), "Library information".t() }; private readonly SettingsTableVC _vc; public DataSource(SettingsTableVC vc) { _vc = vc; } public override int NumberOfSections(UITableView tableView) { return SectionsCount; } public override int RowsInSection(UITableView tableview, int section) { return RowsInSections[section]; } public override string TitleForHeader(UITableView tableView, int section) { return SectionTitles[section]; } public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { switch (indexPath.Section) { case 0: switch (indexPath.Row) { case 0: return _vc._pageTransitionStyleCell; case 1: return _vc._pageNavigationOrientationCell; } break; case 1: switch (indexPath.Row) { case 0: return _vc._topToolbarVisibilityCell; case 1: return _vc._bottomToolbarVisibilityCell; } break; case 2: switch (indexPath.Row) { case 0: return _vc._autoScaleMode; case 1: return _vc._zoomScaleLevelsCell; case 2: return _vc._zoomByDoubleTouchCell; } break; case 3: switch (indexPath.Row) { case 0: return _vc._libraryReleaseDateCell; case 1: return _vc._libraryVersionCell; } break; } return null; } } #endregion } }
using Bridge; using System; using Bridge.Html5; using System; using System.Linq; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Redux { public static class Extensions { public static void Dispatch<T, U>(this Store<T> store, U action) { if (action == null) throw new ArgumentNullException(nameof(action)); if (typeof(U).FullName == "Object") throw new Exception("Action type cannot be 'Object' when dispatching a typed action where the full name of the action is needed, Consider using 'DispatchPlainObject'"); Script.Write("action = JSON.parse(JSON.stringify(action))"); action["type"] = typeof(U).FullName; Script.Write("store.dispatch(action)"); } public static TState Apply<TState, TAction>(this ReduxReducer<TState> reducer, TState state, TAction action) { if (action == null) throw new ArgumentNullException(nameof(action)); Script.Write("action = JSON.parse(JSON.stringify(action))"); action["type"] = typeof(TAction).FullName; return Script.Write<TState>("reducer(state, action)"); } public static TAction NormalizeActionForDispatch<TAction>(this TAction action) { Script.Write("action = JSON.parse(JSON.stringify(action))"); action["type"] = typeof(TAction).FullName; return action; } public static void DispatchPlainObject<T, U>(this Store<T> store, U action) { Script.Write("store.dispatch(action)"); } } } namespace Redux { [ObjectLiteral] public class ReduxLoggerOuput<T> { public T StateBefore { get; set; } public T StateAfter { get; set; } public object ActionDispatched { get; set; } } public class ReduxMiddleware { public static ReduxMiddleware From<TState>(Action<Store<TState>, dynamic, dynamic> func) { Func<Store<TState>, Func<dynamic, Action<dynamic>>> middleware = store => { return next => { return action => { func(store, next, action); }; }; }; return Script.Write<ReduxMiddleware>("middleware"); } public static readonly ReduxMiddleware Thunk = From<dynamic>((store, next, action) => { /*@ if (typeof action === 'function') { return action(store.dispatch, store.getState); } next(action); */ }); /// <summary> /// Logs current state, then the action being dispatched, then the state after reduction /// </summary> public static readonly ReduxMiddleware DefaultLogger = From<dynamic>((store, next, action) => { /*@ console.log(store.getState()); console.log(action); next(action) console.log(store.getState()); */ }); public static ReduxMiddleware Logger<T>(Action<ReduxLoggerOuput<T>> logHandler) { /*@ return Redux.ReduxMiddleware.from(Object, function (store, dipatchNext, action) { var stateBefore = store.getState(); dipatchNext(action); var stateAfter = store.getState(); var loggerOutput = { stateBefore: stateBefore, actionDispatched: action, stateAfter: stateAfter }; logHandler(loggerOutput); }); */ return Script.Write<ReduxMiddleware>(""); } } } namespace Redux { /// <summary> /// DSL to create redux reducers using pattern matching on the types of actions /// </summary> /// <typeparam name="TState">The type of the state tree object</typeparam> public class ReducerBuilder<TState> { private Dictionary<string, object> reducersDict; private string undefinedStateTypeName = "Redux.StateUndefined"; private string unknownActionTypeName = "Redux.ActionUndefined"; public ReducerBuilder() { reducersDict = new Dictionary<string, object>(); } public ReducerBuilder<TState> WhenActionHasType<TAction>(Func<TState, TAction, TState> reducer) { if (reducer == null) throw new ArgumentNullException(nameof(reducer)); if (typeof(TAction).FullName == "Object") throw new Exception("TAction cannot be 'Object' choose a proper type this action"); reducersDict.Add(typeof(TAction).FullName, reducer); return this; } public ReducerBuilder<TState> WhenStateIsUndefinedOrNull(Func<TState> reducer) { if (reducer == null) throw new ArgumentNullException(nameof(reducer)); Func<TState, object, TState> actualReducer = (state, action) => reducer(); if (!reducersDict.ContainsKey(undefinedStateTypeName)) { // it wasn't defined earlier, so add the reducer the dictionary! reducersDict.Add(undefinedStateTypeName, actualReducer); } else { // it has already been added, then overwrite it reducersDict[undefinedStateTypeName] = actualReducer; } return this; } public ReducerBuilder<TState> WhenActionHasType<TAction>(Func<TState, TState> reducer) { if (reducer == null) throw new ArgumentNullException(nameof(reducer)); if (typeof(TAction).FullName == "Object") throw new Exception("TAction cannot be 'Object' choose a proper type this action, "); Func<TState, TAction, TState> actualReducer = (state, action) => reducer(state); reducersDict.Add(typeof(TAction).FullName, actualReducer); return this; } public ReducerBuilder<TState> WhenActionIsUnknown(Func<TState, TState> reducer) { if (reducer == null) throw new ArgumentNullException(nameof(reducer)); // forget about the second argument Func<TState, object, TState> actualReducer = (state, action) => reducer(state); if (!reducersDict.ContainsKey(unknownActionTypeName)) { // it wasn't defined earlier, so add the reducer the dictionary! reducersDict.Add(unknownActionTypeName, actualReducer); } else { // it has already been added, then overwrite it reducersDict[unknownActionTypeName] = actualReducer; } return this; } public ReduxReducer<TState> Build() { Func<TState, object, TState> pureReducer = (state, action) => { if (reducersDict.ContainsKey(undefinedStateTypeName) && (!Script.IsDefined(state) || state == null)) { var func = (Func<TState, object, TState>)reducersDict[undefinedStateTypeName]; return func(state, action); } var typeName = Script.Write<string>("action.type"); if (reducersDict.ContainsKey(typeName)) { // then the type was known! var func = (Func<TState, object, TState>)reducersDict[typeName]; return func(state, action); } else if (!reducersDict.ContainsKey(typeName) && reducersDict.ContainsKey(unknownActionTypeName)) { var func = (Func<TState, object, TState>)reducersDict[unknownActionTypeName]; return func(state, action); } else { return state; } }; return Script.Write<ReduxReducer<TState>>("pureReducer"); } } } namespace Redux { [Name("Redux")] [External] public static class Redux { [Name("createStore")] public static extern Store<TState> CreateStore<TState>(ReduxReducer<TState> reducer); [Name("createStore")] public static extern Store<TState> CreateStore<TState>(ReduxReducer<TState> reducer, TState initialState); [Name("createStore")] public static extern Store<TState> CreateStore<TState>(ReduxReducer<TState> reducer, StoreMiddleware middleware); [Name("createStore")] public static extern Store<TState> CreateStore<TState>(ReduxReducer<TState> reducer, TState initialState, StoreMiddleware middleware); [Name("applyMiddleware")] public static extern StoreMiddleware ApplyMiddleware(params ReduxMiddleware[] middlewares); [Name("combineReducers")] public static extern ReduxReducer<TState> CombineReducers<TState>(TState state); } } namespace Redux { [External] public sealed class StoreMiddleware { } } namespace Redux { [IgnoreGeneric] public sealed class ReduxReducer<T> { private ReduxReducer() { } [IgnoreGeneric] public static implicit operator T(ReduxReducer<T> reducer) { return Script.Write<T>("reducer"); } } public static class BuildReducer { public static ReducerBuilder<TState> For<TState>() => new ReducerBuilder<TState>(); } } namespace Redux { [External] public class Store<TState> { [Name("getState")] public extern TState GetState(); [Name("subscribe")] public extern void Subscribe(Action action); [Name("dispatch")] public extern void ThunkDispatch(Action<Action<object>> dispatch); [Name("dispatch")] public extern void ThunkDispatch(Action<Action<object>, Func<TState>> dipatch); } }
using SteamKit2; using System.Collections.Generic; using SteamTrade; namespace SteamBot { public class SteamTradeDemoHandler : UserHandler { // NEW ------------------------------------------------------------------ private readonly GenericInventory mySteamInventory; private readonly GenericInventory OtherSteamInventory; private bool tested; // ---------------------------------------------------------------------- public SteamTradeDemoHandler(Bot bot, SteamID sid) : base(bot, sid) { mySteamInventory = new GenericInventory(SteamWeb); OtherSteamInventory = new GenericInventory(SteamWeb); } public override bool OnGroupAdd() { return false; } public override bool OnFriendAdd () { return true; } public override void OnLoginCompleted() {} public override void OnChatRoomMessage(SteamID chatID, SteamID sender, string message) { Log.Info(Bot.SteamFriends.GetFriendPersonaName(sender) + ": " + message); base.OnChatRoomMessage(chatID, sender, message); } public override void OnFriendRemove () {} public override void OnMessage (string message, EChatEntryType type) { SendChatMessage(Bot.ChatResponse); } public override bool OnTradeRequest() { return true; } public override void OnTradeError (string error) { SendChatMessage("Oh, there was an error: {0}.", error); Bot.log.Warn (error); } public override void OnTradeTimeout () { SendChatMessage("Sorry, but you were AFK and the trade was canceled."); Bot.log.Info ("User was kicked because he was AFK."); } public override void OnTradeInit() { // NEW ------------------------------------------------------------------------------- List<long> contextId = new List<long>(); tested = false; /************************************************************************************* * * SteamInventory AppId = 753 * * Context Id Description * 1 Gifts (Games), must be public on steam profile in order to work. * 6 Trading Cards, Emoticons & Backgrounds. * ************************************************************************************/ contextId.Add(1); contextId.Add(6); mySteamInventory.load(753, contextId, Bot.SteamClient.SteamID); OtherSteamInventory.load(753, contextId, OtherSID); if (!mySteamInventory.isLoaded | !OtherSteamInventory.isLoaded) { SendTradeMessage("Couldn't open an inventory, type 'errors' for more info."); } SendTradeMessage("Type 'test' to start."); // ----------------------------------------------------------------------------------- } public override void OnTradeAddItem (Schema.Item schemaItem, Inventory.Item inventoryItem) { // USELESS DEBUG MESSAGES ------------------------------------------------------------------------------- SendTradeMessage("Object AppID: {0}", inventoryItem.AppId); SendTradeMessage("Object ContextId: {0}", inventoryItem.ContextId); switch (inventoryItem.AppId) { case 440: SendTradeMessage("TF2 Item Added."); SendTradeMessage("Name: {0}", schemaItem.Name); SendTradeMessage("Quality: {0}", inventoryItem.Quality); SendTradeMessage("Level: {0}", inventoryItem.Level); SendTradeMessage("Craftable: {0}", (inventoryItem.IsNotCraftable ? "No" : "Yes")); break; case 753: GenericInventory.ItemDescription tmpDescription = OtherSteamInventory.getDescription(inventoryItem.Id); SendTradeMessage("Steam Inventory Item Added."); SendTradeMessage("Type: {0}", tmpDescription.type); SendTradeMessage("Marketable: {0}", (tmpDescription.marketable ? "Yes" : "No")); break; default: SendTradeMessage("Unknown item"); break; } // ------------------------------------------------------------------------------------------------------ } public override void OnTradeRemoveItem (Schema.Item schemaItem, Inventory.Item inventoryItem) {} public override void OnTradeMessage (string message) { switch (message.ToLower()) { case "errors": if (OtherSteamInventory.errors.Count > 0) { SendTradeMessage("User Errors:"); foreach (string error in OtherSteamInventory.errors) { SendTradeMessage(" * {0}", error); } } if (mySteamInventory.errors.Count > 0) { SendTradeMessage("Bot Errors:"); foreach (string error in mySteamInventory.errors) { SendTradeMessage(" * {0}", error); } } break; case "test": if (tested) { foreach (GenericInventory.Item item in mySteamInventory.items.Values) { Trade.RemoveItem(item); } } else { SendTradeMessage("Items on my bp: {0}", mySteamInventory.items.Count); foreach (GenericInventory.Item item in mySteamInventory.items.Values) { Trade.AddItem(item); } } tested = !tested; break; case "remove": foreach (var item in mySteamInventory.items) { Trade.RemoveItem(item.Value.assetid, item.Value.appid, item.Value.contextid); } break; } } public override void OnTradeReady (bool ready) { //Because SetReady must use its own version, it's important //we poll the trade to make sure everything is up-to-date. Trade.Poll(); if (!ready) { Trade.SetReady (false); } else { if(Validate () | IsAdmin) { Trade.SetReady (true); } } } public override void OnTradeSuccess() { // Trade completed successfully Log.Success("Trade Complete."); } public override void OnTradeAccept() { if (Validate() | IsAdmin) { //Even if it is successful, AcceptTrade can fail on //trades with a lot of items so we use a try-catch try { Trade.AcceptTrade(); } catch { Log.Warn ("The trade might have failed, but we can't be sure."); } Log.Success ("Trade Complete!"); } } public bool Validate () { List<string> errors = new List<string> (); errors.Add("This demo is meant to show you how to handle SteamInventory Items. Trade cannot be completed, unless you're an Admin."); // send the errors if (errors.Count != 0) SendTradeMessage("There were errors in your trade: "); foreach (string error in errors) { SendTradeMessage(error); } return errors.Count == 0; } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Net; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Connections; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.ClientObservers; using Orleans.Configuration; namespace Orleans.Runtime.Messaging { internal class Gateway : IConnectedClientCollection { private readonly GatewayClientCleanupAgent clientCleanupAgent; // clients is the main authorative collection of all connected clients. // Any client currently in the system appears in this collection. // In addition, we use clientConnections collection for fast retrival of ClientState. // Anything that appears in those 2 collections should also appear in the main clients collection. private readonly ConcurrentDictionary<ClientGrainId, ClientState> clients = new(); private readonly Dictionary<GatewayInboundConnection, ClientState> clientConnections = new(); private readonly SiloAddress gatewayAddress; private readonly GatewaySender sender; private readonly ClientsReplyRoutingCache clientsReplyRoutingCache; private readonly ILogger logger; private readonly ILoggerFactory loggerFactory; private readonly SiloMessagingOptions messagingOptions; private long clientsCollectionVersion = 0; public Gateway( MessageCenter msgCtr, ILocalSiloDetails siloDetails, MessageFactory messageFactory, ILoggerFactory loggerFactory, IOptions<SiloMessagingOptions> options) { this.messagingOptions = options.Value; this.loggerFactory = loggerFactory; this.logger = this.loggerFactory.CreateLogger<Gateway>(); clientCleanupAgent = new GatewayClientCleanupAgent(this, loggerFactory, messagingOptions.ClientDropTimeout); clientsReplyRoutingCache = new ClientsReplyRoutingCache(messagingOptions.ResponseTimeout); this.gatewayAddress = siloDetails.GatewayAddress; this.sender = new GatewaySender(this, msgCtr, messageFactory, loggerFactory.CreateLogger<GatewaySender>()); } public static GrainAddress GetClientActivationAddress(GrainId clientId, SiloAddress siloAddress) { // Need to pick a unique deterministic ActivationId for this client. // We store it in the grain directory and there for every GrainId we use ActivationId as a key // so every GW needs to behave as a different "activation" with a different ActivationId (its not enough that they have different SiloAddress) string stringToHash = clientId.ToString() + siloAddress.Endpoint + siloAddress.Generation.ToString(System.Globalization.CultureInfo.InvariantCulture); Guid hash = Utils.CalculateGuidHash(stringToHash); var activationId = ActivationId.GetActivationId(hash); return GrainAddress.GetAddress(siloAddress, clientId, activationId); } internal void Start() { clientCleanupAgent.Start(); } internal async Task SendStopSendMessages(IInternalGrainFactory grainFactory) { lock (clients) { foreach (var client in clients) { if (client.Value.IsConnected) { var observer = ClientGatewayObserver.GetObserver(grainFactory, client.Key); observer.StopSendingToGateway(this.gatewayAddress); } } } await Task.Delay(this.messagingOptions.ClientGatewayShutdownNotificationTimeout); } internal void Stop() { clientCleanupAgent.Stop(); } long IConnectedClientCollection.Version => Interlocked.Read(ref clientsCollectionVersion); List<GrainId> IConnectedClientCollection.GetConnectedClientIds() { var result = new List<GrainId>(); foreach (var pair in clients) { result.Add(pair.Key.GrainId); } return result; } internal void RecordOpenedConnection(GatewayInboundConnection connection, ClientGrainId clientId) { logger.LogInformation((int)ErrorCode.GatewayClientOpenedSocket, "Recorded opened connection from endpoint {EndPoint}, client ID {ClientId}.", connection.RemoteEndPoint, clientId); lock (clients) { if (clients.TryGetValue(clientId, out var clientState)) { var oldSocket = clientState.Connection; if (oldSocket != null) { // The old socket will be closed by itself later. clientConnections.Remove(oldSocket); } } else { clientState = new ClientState(clientId, messagingOptions.ClientDropTimeout); clients[clientId] = clientState; MessagingStatisticsGroup.ConnectedClientCount.Increment(); } clientState.RecordConnection(connection); clientConnections[connection] = clientState; clientsCollectionVersion++; } } internal void RecordClosedConnection(GatewayInboundConnection connection) { if (connection == null) return; ClientState clientState; lock (clients) { if (!clientConnections.Remove(connection, out clientState)) return; clientState.RecordDisconnection(); clientsCollectionVersion++; } logger.LogInformation( (int)ErrorCode.GatewayClientClosedSocket, "Recorded closed socket from endpoint {Endpoint}, client ID {clientId}.", connection.RemoteEndPoint?.ToString() ?? "null", clientState.Id); } internal SiloAddress TryToReroute(Message msg) { // ** Special routing rule for system target here ** // When a client make a request/response to/from a SystemTarget, the TargetSilo can be set to either // - the GatewayAddress of the target silo (for example, when the client want get the cluster typemap) // - the "internal" Silo-to-Silo address, if the client want to send a message to a specific SystemTarget // activation that is on a silo on which there is no gateway available (or if the client is not // connected to that gateway) // So, if the TargetGrain is a SystemTarget we always trust the value from Message.TargetSilo and forward // it to this address... // EXCEPT if the value is equal to the current GatewayAdress: in this case we will return // null and the local dispatcher will forward the Message to a local SystemTarget activation if (msg.TargetGrain.IsSystemTarget() && !IsTargetingLocalGateway(msg.TargetSilo)) return msg.TargetSilo; // for responses from ClientAddressableObject to ClientGrain try to use clientsReplyRoutingCache for sending replies directly back. if (!msg.SendingGrain.IsClient() || !msg.TargetGrain.IsClient()) return null; if (msg.Direction != Message.Directions.Response) return null; SiloAddress gateway; return clientsReplyRoutingCache.TryFindClientRoute(msg.TargetGrain, out gateway) ? gateway : null; } internal void DropExpiredRoutingCachedEntries() { lock (clients) { clientsReplyRoutingCache.DropExpiredEntries(); } } private bool IsTargetingLocalGateway(SiloAddress siloAddress) { // Special case if the address used by the client was loopback return this.gatewayAddress.Matches(siloAddress) || (IPAddress.IsLoopback(siloAddress.Endpoint.Address) && siloAddress.Endpoint.Port == this.gatewayAddress.Endpoint.Port && siloAddress.Generation == this.gatewayAddress.Generation); } // There is NO need to acquire individual ClientState lock, since we only close an older socket. internal void DropDisconnectedClients() { foreach (var kv in clients) { if (kv.Value.ReadyToDrop()) { lock (clients) { if (clients.TryGetValue(kv.Key, out var client) && client.ReadyToDrop()) { if (logger.IsEnabled(LogLevel.Information)) { logger.LogInformation( (int)ErrorCode.GatewayDroppingClient, "Dropping client {ClientId}, {IdleDuration} after disconnect with no reconnect", kv.Key, DateTime.UtcNow.Subtract(client.DisconnectedSince)); } clients.TryRemove(kv.Key, out _); clientsCollectionVersion++; MessagingStatisticsGroup.ConnectedClientCount.DecrementBy(1); } } } } } /// <summary> /// See if this message is intended for a grain we're proxying, and queue it for delivery if so. /// </summary> /// <param name="msg"></param> /// <returns>true if the message should be delivered to a proxied grain, false if not.</returns> internal bool TryDeliverToProxy(Message msg) { // See if it's a grain we're proxying. var targetGrain = msg.TargetGrain; if (!ClientGrainId.TryParse(targetGrain, out var clientId)) { return false; } if (!clients.TryGetValue(clientId, out var client)) { return false; } // when this Gateway receives a message from client X to client addressale object Y // it needs to record the original Gateway address through which this message came from (the address of the Gateway that X is connected to) // it will use this Gateway to re-route the REPLY from Y back to X. if (msg.SendingGrain.IsClient()) { clientsReplyRoutingCache.RecordClientRoute(msg.SendingGrain, msg.SendingSilo); } msg.TargetSilo = null; // Override the SendingSilo only if the sending grain is not // a system target if (!msg.SendingGrain.IsSystemTarget()) { msg.SendingSilo = gatewayAddress; } QueueRequest(client, msg); return true; } private void QueueRequest(ClientState clientState, Message msg) => this.sender.Send(clientState, msg); private class ClientState { private readonly TimeSpan clientDropTimeout; internal Queue<Message> PendingToSend { get; } = new(); internal GatewayInboundConnection Connection { get; private set; } internal DateTime DisconnectedSince { get; private set; } internal ClientGrainId Id { get; } public bool IsConnected => this.Connection != null; internal ClientState(ClientGrainId id, TimeSpan clientDropTimeout) { Id = id; this.clientDropTimeout = clientDropTimeout; } internal void RecordDisconnection() { if (Connection == null) return; DisconnectedSince = DateTime.UtcNow; Connection = null; } internal void RecordConnection(GatewayInboundConnection connection) { Connection = connection; DisconnectedSince = DateTime.MaxValue; } internal bool ReadyToDrop() { return !IsConnected && (DateTime.UtcNow.Subtract(DisconnectedSince) >= clientDropTimeout); } } private class GatewayClientCleanupAgent : TaskSchedulerAgent { private readonly Gateway gateway; private readonly TimeSpan clientDropTimeout; internal GatewayClientCleanupAgent(Gateway gateway, ILoggerFactory loggerFactory, TimeSpan clientDropTimeout) : base(loggerFactory) { this.gateway = gateway; this.clientDropTimeout = clientDropTimeout; } protected override async Task Run() { while (!Cts.IsCancellationRequested) { gateway.DropDisconnectedClients(); gateway.DropExpiredRoutingCachedEntries(); await Task.Delay(clientDropTimeout); } } } // this cache is used to record the addresses of Gateways from which clients connected to. // it is used to route replies to clients from client addressable objects // without this cache this Gateway will not know how to route the reply back to the client // (since clients are not registered in the directory and this Gateway may not be proxying for the client for whom the reply is destined). private class ClientsReplyRoutingCache { // for every client: the Gateway to use to route repies back to it plus the last time that client connected via this Gateway. private readonly ConcurrentDictionary<GrainId, Tuple<SiloAddress, DateTime>> clientRoutes = new(); private readonly TimeSpan TIME_BEFORE_ROUTE_CACHED_ENTRY_EXPIRES; internal ClientsReplyRoutingCache(TimeSpan responseTimeout) { TIME_BEFORE_ROUTE_CACHED_ENTRY_EXPIRES = responseTimeout.Multiply(5); } internal void RecordClientRoute(GrainId client, SiloAddress gateway) { clientRoutes[client] = new(gateway, DateTime.UtcNow); } internal bool TryFindClientRoute(GrainId client, out SiloAddress gateway) { if (clientRoutes.TryGetValue(client, out var tuple)) { gateway = tuple.Item1; return true; } gateway = null; return false; } internal void DropExpiredEntries() { var expiredTime = DateTime.UtcNow - TIME_BEFORE_ROUTE_CACHED_ENTRY_EXPIRES; foreach (var client in clientRoutes) { if (client.Value.Item2 < expiredTime) { clientRoutes.TryRemove(client.Key, out _); } } } } private sealed class GatewaySender { private readonly Gateway gateway; private readonly MessageCenter messageCenter; private readonly MessageFactory messageFactory; private readonly ILogger<GatewaySender> log; private readonly CounterStatistic gatewaySends; internal GatewaySender(Gateway gateway, MessageCenter messageCenter, MessageFactory messageFactory, ILogger<GatewaySender> log) { this.gateway = gateway; this.messageCenter = messageCenter; this.messageFactory = messageFactory; this.log = log; this.gatewaySends = CounterStatistic.FindOrCreate(StatisticNames.GATEWAY_SENT); } public void Send(ClientState clientState, Message msg) { // This should never happen -- but make sure to handle it reasonably, just in case if (clientState == null) { if (msg == null) return; this.log.Info(ErrorCode.GatewayTryingToSendToUnrecognizedClient, "Trying to send a message {0} to an unrecognized client {1}", msg.ToString(), msg.TargetGrain); MessagingStatisticsGroup.OnFailedSentMessage(msg); // Message for unrecognized client -- reject it if (msg.Direction == Message.Directions.Request) { MessagingStatisticsGroup.OnRejectedMessage(msg); Message error = this.messageFactory.CreateRejectionResponse( msg, Message.RejectionTypes.Unrecoverable, "Unknown client " + msg.TargetGrain); messageCenter.SendMessage(error); } else { MessagingStatisticsGroup.OnDroppedSentMessage(msg); } return; } lock (clientState.PendingToSend) { // if disconnected - queue for later. if (!clientState.IsConnected) { if (msg == null) return; if (this.log.IsEnabled(LogLevel.Trace)) this.log.Trace("Queued message {0} for client {1}", msg, msg.TargetGrain); clientState.PendingToSend.Enqueue(msg); return; } // if the queue is non empty - drain it first. if (clientState.PendingToSend.Count > 0) { if (msg != null) clientState.PendingToSend.Enqueue(msg); // For now, drain in-line, although in the future this should happen in yet another asynch agent Drain(clientState); return; } // the queue was empty AND we are connected. // If the request includes a message to send, send it (or enqueue it for later) if (msg == null) return; if (!Send(msg, clientState)) { if (this.log.IsEnabled(LogLevel.Trace)) this.log.Trace("Queued message {0} for client {1}", msg, msg.TargetGrain); clientState.PendingToSend.Enqueue(msg); } else { if (this.log.IsEnabled(LogLevel.Trace)) this.log.Trace("Sent message {0} to client {1}", msg, msg.TargetGrain); } } } private void Drain(ClientState clientState) { lock (clientState.PendingToSend) { while (clientState.PendingToSend.Count > 0) { var m = clientState.PendingToSend.Peek(); if (Send(m, clientState)) { if (this.log.IsEnabled(LogLevel.Trace)) this.log.Trace("Sent queued message {0} to client {1}", m, clientState.Id); clientState.PendingToSend.Dequeue(); } else { return; } } } } private bool Send(Message msg, ClientState client) { var connection = client.Connection; if (connection is null) return false; try { connection.Send(msg); gatewaySends.Increment(); return true; } catch (Exception exception) { gateway.RecordClosedConnection(connection); connection.CloseAsync(new ConnectionAbortedException("Exception posting a message to sender. See InnerException for details.", exception)).Ignore(); return false; } } } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Linq; using DotSpatial.Data; namespace DotSpatial.Symbology { /// <summary> /// DrawingFilter /// </summary> public class DrawingFilter : IDrawingFilter { #region Fields private IFeatureCategory _category; private int _chunk; private int _count; private bool _countIsValid; private bool _isInitialized; private IFeatureScheme _scheme; private bool _selected; private bool _useCategory; private bool _useChunks; private bool _useSelection; private bool _useVisibility; private bool _visible; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="DrawingFilter"/> class without using any chunks. /// The use chunks value will be false, and sub-categories will not be selected based on the chunk. /// </summary> /// <param name="features">The feature list containing the features that get filtered.</param> /// <param name="scheme">The scheme used getting the drawing characteristics from.</param> public DrawingFilter(IFeatureList features, IFeatureScheme scheme) { _useChunks = false; ChunkSize = -1; Configure(features, scheme); } /// <summary> /// Initializes a new instance of the <see cref="DrawingFilter"/> class, sub-dividing the features into chunks. /// Regardless of selection or category, chunks simply subdivide the filter into chunks of equal size. /// </summary> /// <param name="features">The feature list containing the features that get filtered.</param> /// <param name="scheme">The scheme used getting the drawing characteristics from.</param> /// <param name="chunkSize">Size of the chunks that should be used.</param> public DrawingFilter(IFeatureList features, IFeatureScheme scheme, int chunkSize) { _useChunks = true; ChunkSize = chunkSize; Configure(features, scheme); } #endregion #region Events /// <summary> /// Occurs after this filter has built its internal list of items. /// </summary> public event EventHandler Initialized; #endregion #region Properties /// <summary> /// Gets or sets the scheme category to use. /// </summary> public IFeatureCategory Category { get { return _category; } set { if (_category != value) _countIsValid = false; _category = value; } } /// <summary> /// Gets or sets the integer chunk that the filter should use. /// </summary> public int Chunk { get { return _chunk; } set { if (_chunk != value) _countIsValid = false; _chunk = value; } } /// <summary> /// Gets or sets the integer size of each chunk. Setting this to /// a new value will cycle through and update the chunk on all the features. /// </summary> public int ChunkSize { get; set; } /// <summary> /// Gets the count. If the drawing state for any features has changed, or else if the /// state of any members has changed, this will cycle through the filter members and cache /// a new count. If nothing has changed, then this will simply return the cached value. /// </summary> public int Count { get { if (_countIsValid) return _count; using (IEnumerator<IFeature> en = GetEnumerator()) { _count = 0; while (en.MoveNext()) { _count++; } _countIsValid = true; return _count; } } } /// <summary> /// Gets the default category for the scheme. /// </summary> public IFeatureCategory DefaultCategory => _scheme.GetCategories().First(); /// <summary> /// Gets the dictionary of drawn states that this drawing filter uses. /// </summary> public IDictionary<IFeature, IDrawnState> DrawnStates { get; private set; } /// <summary> /// Gets the underlying list of features that this drawing filter /// is ultimately based upon. /// </summary> public IFeatureList FeatureList { get; private set; } /// <summary> /// Gets the total count of chunks when chunks are used. /// Otherwise, this returns 1 as everything is effectively in one chunk. /// </summary> public int NumChunks { get { if (_useChunks) return Convert.ToInt32(Math.Ceiling(FeatureList.Count / (double)ChunkSize)); return 1; } } /// <summary> /// Gets or sets a value indicating whether values are selected. If UseSelection is true, this will get or set the boolean selection state /// that will be used to select values. /// </summary> public bool Selected { get { return _selected; } set { if (_selected != value) { _countIsValid = false; _selected = value; } } } /// <summary> /// Gets or sets a value indicating whether the filter should subdivide based on category. /// </summary> public bool UseCategory { get { return _useCategory; } set { if (_useCategory != value) { _countIsValid = false; } _useCategory = value; } } /// <summary> /// Gets or sets a value indicating whether we should use the chunk. /// </summary> public bool UseChunks { get { return _useChunks; } set { if (_useChunks != value) _countIsValid = false; _useChunks = value; } } /// <summary> /// Gets or sets a value indicating whether this filter should use the Selected. /// </summary> public bool UseSelection { get { return _useSelection; } set { if (_useSelection != value) _countIsValid = false; _useSelection = value; } } /// <summary> /// Gets or sets a value indicating whether or not this feature should be drawn. /// </summary> public bool UseVisibility { get { return _useVisibility; } set { if (_useVisibility != value) _countIsValid = false; _useVisibility = value; } } /// <summary> /// Gets or sets a value indicating whether to return visible, or hidden features if UseVisibility is true. /// </summary> public bool Visible { get { return _visible; } set { if (_visible != value) _countIsValid = false; _visible = value; } } #endregion #region Indexers /// <summary> /// This uses the feature as the key and attempts to find the specified drawn state /// that describes selection, chunk and category. /// </summary> /// <param name="key">The feature</param> /// <remarks>The strength is that if someone inserts a new member or re-orders /// the features in the featureset, we don't forget which ones are selected. /// The disadvantage is that duplicate features in the same featureset /// will cause an exception.</remarks> /// <returns>The drawn state of the given feature.</returns> public IDrawnState this[IFeature key] { get { if (!_isInitialized) DoInitialize(); return DrawnStates?[key]; } set { if (!_isInitialized) DoInitialize(); // this will cause an exception if _drawnStates is null, but that might be what is needed if (DrawnStates[key] != value) _countIsValid = false; DrawnStates[key] = value; } } /// <summary> /// This is less direct as it requires searching two indices rather than one, but /// allows access to the drawn state based on the feature ID. /// </summary> /// <param name="index">The integer index in the underlying featureSet.</param> /// <returns>The current IDrawnState for the current feature.</returns> public IDrawnState this[int index] { get { if (!_isInitialized) DoInitialize(); return DrawnStates[FeatureList[index]]; } set { if (!_isInitialized) DoInitialize(); if (DrawnStates[FeatureList[index]] != value) _countIsValid = false; DrawnStates[FeatureList[index]] = value; } } #endregion #region Methods /// <summary> /// This will use the filter expressions on the categories to change the categories for those members. /// This means that an item will be classified as the last filter that it qualifies for. /// </summary> /// <param name="scheme">The scheme of categories to apply to the drawing states</param> public void ApplyScheme(IFeatureScheme scheme) { _scheme = scheme; if (_isInitialized == false) DoInitialize(); var fc = _scheme.GetCategories().ToList(); // Short cut the rest of this (and prevent loading features) in the case where we know everything is in the default category if (fc.Count == 1 && string.IsNullOrEmpty(fc[0].FilterExpression)) { // Replace SchemeCategory in _drawnStates foreach (var drawnState in DrawnStates) { drawnState.Value.SchemeCategory = fc[0]; } return; } var tables = new List<IDataTable>(); // just in case there is more than one Table somehow var allRows = new Dictionary<IDataRow, int>(); var tempList = new List<IDataTable>(); var containsFid = fc.Any(category => category.FilterExpression != null && category.FilterExpression.Contains("[FID]")); var featureIndex = 0; foreach (var f in FeatureList) { if (f.DataRow == null) { f.ParentFeatureSet.FillAttributes(); } if (f.DataRow != null) { IDataTable t = f.DataRow.Table; if (tables.Contains(t) == false) { tables.Add(t); if (containsFid && t.Columns.Contains("FID") == false) { f.ParentFeatureSet.AddFid(); tempList.Add(t); } } allRows.Add(f.DataRow, featureIndex); } if (DrawnStates.ContainsKey(f)) DrawnStates[f].SchemeCategory = null; featureIndex++; } foreach (IFeatureCategory cat in fc) { foreach (IDataTable dt in tables) { // CGX TRY CATCH try { IDataRow[] rows = dt.Select(cat.FilterExpression); foreach (IDataRow dr in rows) { foreach (var key in allRows.Keys) { if (key.Equals(dr)) DrawnStates[FeatureList[allRows[key]]].SchemeCategory = cat; } /*int index; if (allRows.TryGetValue(dr, out index)) { DrawnStates[FeatureList[index]].SchemeCategory = cat; }*/ } } catch (Exception) { } } } foreach (IDataTable table in tempList) { table.Columns.Remove("FID"); } } /// <summary> /// Creates a shallow copy /// </summary> /// <returns>Returns a shallow copy of this object.</returns> public object Clone() { return MemberwiseClone(); } /// <summary> /// If UseChunks is true, this uses the index value combined with the chunk size /// to calculate the chunk, and also sets the category to the [0] category and the /// selection state to unselected. This can be overridden in sub-classes to come up /// with a different default state. /// </summary> /// <param name="index">The integer index to get the default state of</param> /// <returns>An IDrawnState</returns> public virtual IDrawnState GetDefaultState(int index) { if (_useChunks) { return new DrawnState(_scheme.GetCategories().First(), false, index / ChunkSize, true); } return new DrawnState(_scheme.GetCategories().First(), false, 0, true); } /// <summary> /// Gets an enumator for cycling through exclusively the features that satisfy all the listed criteria, /// including chunk index, selected state, and scheme category. /// </summary> /// <returns>An Enumerator for cycling through the values</returns> public IEnumerator<IFeature> GetEnumerator() { if (!_isInitialized) DoInitialize(); Func<IDrawnState, bool> alwaysTrue = drawnState => true; Func<IDrawnState, bool> visConstraint = alwaysTrue; // by default, don't test visibility Func<IDrawnState, bool> selConstraint = alwaysTrue; // by default, don't test selection Func<IDrawnState, bool> catConstraint = alwaysTrue; // by default, don't test category Func<IDrawnState, bool> chunkConstraint = alwaysTrue; // by default, don't test chunk if (_useVisibility) { visConstraint = drawnState => drawnState.IsVisible == _visible; } if (_useChunks) { chunkConstraint = drawnState => drawnState.Chunk == _chunk; } if (_useSelection) { selConstraint = drawnState => drawnState.IsSelected == _selected; } if (_useCategory) { catConstraint = drawnState => drawnState.SchemeCategory == _category; } Func<IDrawnState, bool> constraint = drawnState => selConstraint(drawnState) && chunkConstraint(drawnState) && catConstraint(drawnState) && visConstraint(drawnState); var query = from kvp in DrawnStates where constraint(kvp.Value) select kvp.Key; return query.GetEnumerator(); } /// <summary> /// Invalidates this drawing filter, effectively eliminating all the original /// categories, selection statuses, and only keeps the basic chunk size. /// </summary> public void Invalidate() { _isInitialized = false; } /// <summary> /// Gets the enumerstor. /// </summary> /// <returns>The enumerator</returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Fires the Initialized Event /// </summary> protected virtual void OnInitialize() { _isInitialized = true; Initialized?.Invoke(this, EventArgs.Empty); } private void Configure(IFeatureList features, IFeatureScheme scheme) { FeatureList = features; _scheme = scheme; // features.FeatureAdded += new EventHandler<FeatureEventArgs>(features_FeatureAdded); // features.FeatureRemoved += new EventHandler<FeatureEventArgs>(features_FeatureRemoved); } /// <summary> /// This block of code actually cycles through the source features, and assigns a default /// drawing state to each feature. I thought duplicate features would be less of a problem /// then people re-ordering an indexed list at some point, so for now we are using /// features to index the values. /// </summary> private void DoInitialize() { DrawnStates = new Dictionary<IFeature, IDrawnState>(); for (int i = 0; i < FeatureList.Count; i++) { DrawnStates.Add(new KeyValuePair<IFeature, IDrawnState>(FeatureList[i], GetDefaultState(i))); } OnInitialize(); } #endregion } }
#region Copyright & License // // Copyright 2001-2005 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System.Collections; using log4net.Core; using log4net.Repository.Hierarchy; using log4net.Tests.Appender; using NUnit.Framework; namespace log4net.Tests.Hierarchy { /// <summary> /// Used for internal unit testing the <see cref="Logger"/> class. /// </summary> /// <remarks> /// Internal unit test. Uses the NUnit test harness. /// </remarks> [TestFixture] public class LoggerTest { Logger log; // A short message. static string MSG = "M"; /// <summary> /// Any initialization that happens before each test can /// go here /// </summary> [SetUp] public void SetUp() { } /// <summary> /// Any steps that happen after each test go here /// </summary> [TearDown] public void TearDown() { // Regular users should not use the clear method lightly! LogManager.GetRepository().ResetConfiguration(); LogManager.GetRepository().Shutdown(); ((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Clear(); } /// <summary> /// Add an appender and see if it can be retrieved. /// </summary> [Test] public void TestAppender1() { log = LogManager.GetLogger("test").Logger as Logger; CountingAppender a1 = new CountingAppender(); a1.Name = "testAppender1"; log.AddAppender(a1); IEnumerator enumAppenders = ((IEnumerable)log.Appenders).GetEnumerator(); Assert.IsTrue( enumAppenders.MoveNext() ); CountingAppender aHat = (CountingAppender) enumAppenders.Current; Assert.AreEqual(a1, aHat); } /// <summary> /// Add an appender X, Y, remove X and check if Y is the only /// remaining appender. /// </summary> [Test] public void TestAppender2() { CountingAppender a1 = new CountingAppender(); a1.Name = "testAppender2.1"; CountingAppender a2 = new CountingAppender(); a2.Name = "testAppender2.2"; log = LogManager.GetLogger("test").Logger as Logger; log.AddAppender(a1); log.AddAppender(a2); CountingAppender aHat = (CountingAppender)log.GetAppender(a1.Name); Assert.AreEqual(a1, aHat); aHat = (CountingAppender)log.GetAppender(a2.Name); Assert.AreEqual(a2, aHat); log.RemoveAppender("testAppender2.1"); IEnumerator enumAppenders = ((IEnumerable)log.Appenders).GetEnumerator(); Assert.IsTrue( enumAppenders.MoveNext() ); aHat = (CountingAppender) enumAppenders.Current; Assert.AreEqual(a2, aHat); Assert.IsTrue(!enumAppenders.MoveNext()); aHat = (CountingAppender)log.GetAppender(a2.Name); Assert.AreEqual(a2, aHat); } /// <summary> /// Test if logger a.b inherits its appender from a. /// </summary> [Test] public void TestAdditivity1() { Logger a = LogManager.GetLogger("a").Logger as Logger; Logger ab = LogManager.GetLogger("a.b").Logger as Logger; CountingAppender ca = new CountingAppender(); a.AddAppender(ca); a.Repository.Configured = true; Assert.AreEqual(ca.Counter, 0); ab.Log(Level.Debug, MSG, null); Assert.AreEqual(ca.Counter, 1); ab.Log(Level.Info, MSG, null); Assert.AreEqual(ca.Counter, 2); ab.Log(Level.Warn, MSG, null); Assert.AreEqual(ca.Counter, 3); ab.Log(Level.Error, MSG, null); Assert.AreEqual(ca.Counter, 4); } /// <summary> /// Test multiple additivity. /// </summary> [Test] public void TestAdditivity2() { Logger a = LogManager.GetLogger("a").Logger as Logger; Logger ab = LogManager.GetLogger("a.b").Logger as Logger; Logger abc = LogManager.GetLogger("a.b.c").Logger as Logger; Logger x = LogManager.GetLogger("x").Logger as Logger; CountingAppender ca1 = new CountingAppender(); CountingAppender ca2 = new CountingAppender(); a.AddAppender(ca1); abc.AddAppender(ca2); a.Repository.Configured = true; Assert.AreEqual(ca1.Counter, 0); Assert.AreEqual(ca2.Counter, 0); ab.Log(Level.Debug, MSG, null); Assert.AreEqual(ca1.Counter, 1); Assert.AreEqual(ca2.Counter, 0); abc.Log(Level.Debug, MSG, null); Assert.AreEqual(ca1.Counter, 2); Assert.AreEqual(ca2.Counter, 1); x.Log(Level.Debug, MSG, null); Assert.AreEqual(ca1.Counter, 2); Assert.AreEqual(ca2.Counter, 1); } /// <summary> /// Test additivity flag. /// </summary> [Test] public void TestAdditivity3() { Logger root = ((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root; Logger a = LogManager.GetLogger("a").Logger as Logger; Logger ab = LogManager.GetLogger("a.b").Logger as Logger; Logger abc = LogManager.GetLogger("a.b.c").Logger as Logger; CountingAppender caRoot = new CountingAppender(); CountingAppender caA = new CountingAppender(); CountingAppender caABC = new CountingAppender(); root.AddAppender(caRoot); a.AddAppender(caA); abc.AddAppender(caABC); a.Repository.Configured = true; Assert.AreEqual(caRoot.Counter, 0); Assert.AreEqual(caA.Counter, 0); Assert.AreEqual(caABC.Counter, 0); ab.Additivity = false; a.Log(Level.Debug, MSG, null); Assert.AreEqual(caRoot.Counter, 1); Assert.AreEqual(caA.Counter, 1); Assert.AreEqual(caABC.Counter, 0); ab.Log(Level.Debug, MSG, null); Assert.AreEqual(caRoot.Counter, 1); Assert.AreEqual(caA.Counter, 1); Assert.AreEqual(caABC.Counter, 0); abc.Log(Level.Debug, MSG, null); Assert.AreEqual(caRoot.Counter, 1); Assert.AreEqual(caA.Counter, 1); Assert.AreEqual(caABC.Counter, 1); } /// <summary> /// Test the ability to disable a level of message /// </summary> [Test] public void TestDisable1() { CountingAppender caRoot = new CountingAppender(); Logger root = ((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root; root.AddAppender(caRoot); log4net.Repository.Hierarchy.Hierarchy h = ((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()); h.Threshold = Level.Info; h.Configured = true; Assert.AreEqual(caRoot.Counter, 0); root.Log(Level.Debug, MSG, null); Assert.AreEqual(caRoot.Counter, 0); root.Log(Level.Info, MSG, null); Assert.AreEqual(caRoot.Counter, 1); root.Log(Level.Warn, MSG, null); Assert.AreEqual(caRoot.Counter, 2); root.Log(Level.Warn, MSG, null); Assert.AreEqual(caRoot.Counter, 3); h.Threshold = Level.Warn; root.Log(Level.Debug, MSG, null); Assert.AreEqual(caRoot.Counter, 3); root.Log(Level.Info, MSG, null); Assert.AreEqual(caRoot.Counter, 3); root.Log(Level.Warn, MSG, null); Assert.AreEqual(caRoot.Counter, 4); root.Log(Level.Error, MSG, null); Assert.AreEqual(caRoot.Counter, 5); root.Log(Level.Error, MSG, null); Assert.AreEqual(caRoot.Counter, 6); h.Threshold = Level.Off; root.Log(Level.Debug, MSG, null); Assert.AreEqual(caRoot.Counter, 6); root.Log(Level.Info, MSG, null); Assert.AreEqual(caRoot.Counter, 6); root.Log(Level.Warn, MSG, null); Assert.AreEqual(caRoot.Counter, 6); root.Log(Level.Error, MSG, null); Assert.AreEqual(caRoot.Counter, 6); root.Log(Level.Fatal, MSG, null); Assert.AreEqual(caRoot.Counter, 6); root.Log(Level.Fatal, MSG, null); Assert.AreEqual(caRoot.Counter, 6); } /// <summary> /// Tests the Exists method of the Logger class /// </summary> [Test] public void TestExists() { object a = LogManager.GetLogger("a"); object a_b = LogManager.GetLogger("a.b"); object a_b_c = LogManager.GetLogger("a.b.c"); object t; t = LogManager.Exists("xx"); Assert.IsNull(t); t = LogManager.Exists("a"); Assert.AreSame(a, t); t = LogManager.Exists("a.b"); Assert.AreSame(a_b, t); t = LogManager.Exists("a.b.c"); Assert.AreSame(a_b_c, t); } /// <summary> /// Tests the chained level for a hierarchy /// </summary> [Test] public void TestHierarchy1() { log4net.Repository.Hierarchy.Hierarchy h = new log4net.Repository.Hierarchy.Hierarchy(); h.Root.Level = Level.Error; Logger a0 = h.GetLogger("a") as Logger; Assert.AreEqual("a", a0.Name); Assert.IsNull(a0.Level); Assert.AreSame(Level.Error, a0.EffectiveLevel); Logger a1 = h.GetLogger("a") as Logger; Assert.AreSame(a0, a1); } } }
#region License Agreement - READ THIS FIRST!!! /* ********************************************************************************** * Copyright (c) 2008, Kristian Trenskow * * All rights reserved. * ********************************************************************************** * This code is subject to terms of the BSD License. A copy of this license is * * included with this software distribution in the file COPYING. If you do not * * have a copy of, you can contain a copy by visiting this URL: * * * * http://www.opensource.org/licenses/bsd-license.php * * * * Replace <OWNER>, <ORGANISATION> and <YEAR> with the info in the above * * copyright notice. * * * ********************************************************************************** */ #endregion using System; using System.IO; namespace ircsharp { /// <summary> /// An enum with info on what to do when accepting a file that already exist. /// </summary> public enum DCCTransferFileExist { /// <summary> /// Overwrite local file. /// </summary> Overwrite = 0, /// <summary> /// Resume file from local filesize. /// </summary> Resume, /// <summary> /// Ignore file transfer. /// </summary> Ignore } internal enum DCCTransferDirection { Send = 0, Receive } /// <summary> /// Used with the TransferBegun, TransferFailed and TransferComplete events. /// </summary> public delegate void DCCTransferEventHandler(DCCTransfer sender, EventArgs e); /// <summary> /// Used with the TransferProgress event. /// </summary> public delegate void DCCTransferProgressEventHandler(DCCTransfer sender, DCCTransferProgressEventArgs e); /// <summary> /// Class represents a DCC transfer. /// </summary> public class DCCTransfer : DCCBase { private long lngSize = 0; private string strLocalFile = ""; private string strRemoteFile = ""; private long lngBytesTransfered = 0; private DCCTransferDirection direction; public event DCCTransferEventHandler TransferBegun; public event DCCTransferEventHandler TransferFailed; public event DCCTransferProgressEventHandler TransferProgress; public event DCCTransferEventHandler TransferComplete; internal DCCTransfer(ServerConnection creatorsServerConnection, long RemoteHost, int Port, string Nickname, string Filename, long Size, DCCTransferContainer parent):base(creatorsServerConnection, RemoteHost, Port, Nickname, parent) { lngSize = Size; strRemoteFile = Filename; direction = DCCTransferDirection.Receive; } internal DCCTransfer(ServerConnection creatorsServerConnection, string Nickname, int Port, string Filename, string RemoteFilename, DCCTransferContainer parent):base(creatorsServerConnection, Nickname, Port, parent) { direction = DCCTransferDirection.Send; strLocalFile = Filename; strRemoteFile = RemoteFilename; FileInfo fileInfo = new FileInfo(Filename); lngSize = fileInfo.Length; } /// <summary> /// Gets the filename of the local file. /// </summary> /// <remarks>If a file is recieved, this is the file name where the incoming file is saved. If file is sent, this is the file name of the file being sent.</remarks> public string LocalFile { get { return strLocalFile; } } /// <summary> /// Gets the filename of the remote file. /// </summary> /// <remarks>This is the filename used between the client. It's equal to LocalFile just that it's without path, and space is replaced by _.</remarks> public string RemoteFile { get { return strRemoteFile; } } /// <summary> /// Gets the number of bytes transfered. /// </summary> public long BytesTransfered { get { return lngBytesTransfered; } } /// <summary> /// Gets the total number of bytes to be transfered. /// </summary> public long BytesTotal { get { return lngSize; } } /// <summary> /// Accept the incoming DCC file request. /// </summary> /// <param name="Filename">The path and file name where the incoming file is to be saved.</param> public void Accept(string Filename) { Accept(Filename, DCCTransferFileExist.Overwrite); } /// <summary> /// Accept the incoming DCC file request. /// </summary> /// <param name="Filename">The path and file name where the incoming file is to be saved.</param> /// <param name="Action">What to do in case the file already exist.</param> public void Accept(string Filename, DCCTransferFileExist Action) { strLocalFile = Filename; if (File.Exists(Filename)) { switch (Action) { case DCCTransferFileExist.Resume: FileInfo fileInfo = new FileInfo(Filename); base.CurrentConnection.SendData("PRIVMSG " + base.Nick + " :\x01" + "DCC RESUME " + strRemoteFile + " " + base.Identifier.ToString() + " " + fileInfo.Length.ToString() + "\x01"); return; case DCCTransferFileExist.Ignore: return; case DCCTransferFileExist.Overwrite: File.Delete(Filename); break; } } base.EtablishConnection(); } internal void ResumeAccepted(long lngPosition) { lngBytesTransfered = lngPosition; base.EtablishConnection(); } internal void ResumeRequested(long lngPosition) { if (lngPosition<=lngSize) { lngBytesTransfered = lngPosition; base.CurrentConnection.SendData("PRIVMSG " + base.strNickname + " :\x01" + "DCC ACCEPT " + strRemoteFile + " " + base.Identifier.ToString() + " " + lngPosition.ToString() + "\x01"); } } protected override void Connected() { if (TransferBegun!=null) TransferBegun(this, new EventArgs()); if (direction==DCCTransferDirection.Send) SendNextChunk(); } protected override void Disconnected() { if (lngBytesTransfered!=lngSize&&TransferFailed!=null) TransferFailed(this, new EventArgs()); } protected override void OnData(byte[] buffer, int Length) { if (direction==DCCTransferDirection.Send) { long lngCBR = OctetToLong(buffer, Length); if (lngCBR!=lngBytesTransfered) { if (TransferFailed!=null) TransferFailed(this, new EventArgs()); CloseSocket(); } else { if (TransferProgress!=null) TransferProgress(this, new DCCTransferProgressEventArgs(lngBytesTransfered, lngSize)); if (lngBytesTransfered==lngSize&&TransferComplete!=null) { TransferComplete(this, new EventArgs()); CloseSocket(); } else SendNextChunk(); } } else { FileStream file = File.OpenWrite(strLocalFile); file.Seek(lngBytesTransfered, SeekOrigin.Begin); file.Write(buffer, 0, Length); lngBytesTransfered += Length; file.Close(); SendData(LongToOctet(lngBytesTransfered), lngBytesTransfered==lngSize); if (TransferProgress!=null) TransferProgress(this, new DCCTransferProgressEventArgs(lngBytesTransfered, lngSize)); } } /// <summary> /// Cancels the transfer. /// </summary> public void CancelTransfer() { CloseSocket(); } private void SendNextChunk() { int intLength = 1024; FileStream file = File.OpenRead(strLocalFile); if (file.Length-lngBytesTransfered<intLength) intLength = Convert.ToInt32(file.Length - lngBytesTransfered); file.Seek(lngBytesTransfered, SeekOrigin.Begin); byte[] toSend = new byte[intLength]; int intRead = file.Read(toSend, 0, intLength); file.Close(); lngBytesTransfered += intRead; SendData(toSend); } private long OctetToLong(byte[] octets, int Length) { long ret = 0; long currentPos = 16777216; for (int x=0;x<4;x++) { ret += (long) (octets[x] * currentPos); currentPos /= 256; } return ret; } private byte[] LongToOctet(long Value) { byte[] ret = new byte[4]; long currentByte = 16777216; for (int x=0;x<4;x++) { ret[x] = Convert.ToByte(Math.Floor((double)Value / (double)currentByte)); Value = Value - (ret[x] * currentByte); currentByte /= 256; } return ret; } } }
// 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.Reflection.Internal; using System.Reflection.Metadata.Ecma335; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System.Reflection.Metadata { [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] public unsafe struct BlobReader { /// <summary>An array containing the '\0' character.</summary> private static readonly char[] s_nullCharArray = new char[1] { '\0' }; internal const int InvalidCompressedInteger = Int32.MaxValue; private readonly MemoryBlock _block; // Points right behind the last byte of the block. private readonly byte* _endPointer; private byte* _currentPointer; /// <summary> /// Creates a reader of the specified memory block. /// </summary> /// <param name="buffer">Pointer to the start of the memory block.</param> /// <param name="length">Length in bytes of the memory block.</param> /// <exception cref="ArgumentNullException"><paramref name="buffer"/> is null and <paramref name="length"/> is greater than zero.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="length"/> is negative.</exception> /// <exception cref="PlatformNotSupportedException">The current platform is not little-endian.</exception> public BlobReader(byte* buffer, int length) : this(MemoryBlock.CreateChecked(buffer, length)) { } internal BlobReader(MemoryBlock block) { Debug.Assert(BitConverter.IsLittleEndian && block.Length >= 0 && (block.Pointer != null || block.Length == 0)); _block = block; _currentPointer = block.Pointer; _endPointer = block.Pointer + block.Length; } internal string GetDebuggerDisplay() { if (_block.Pointer == null) { return "<null>"; } int displayedBytes; string display = _block.GetDebuggerDisplay(out displayedBytes); if (this.Offset < displayedBytes) { display = display.Insert(this.Offset * 3, "*"); } else if (displayedBytes == _block.Length) { display += "*"; } else { display += "*..."; } return display; } #region Offset, Skipping, Marking, Alignment, Bounds Checking /// <summary> /// Pointer to the byte at the start of the underlying memory block. /// </summary> public byte* StartPointer => _block.Pointer; /// <summary> /// Pointer to the byte at the current position of the reader. /// </summary> public byte* CurrentPointer => _currentPointer; /// <summary> /// The total length of the underlying memory block. /// </summary> public int Length => _block.Length; /// <summary> /// Offset from start of underlying memory block to current position. /// </summary> public int Offset => (int)(_currentPointer - _block.Pointer); /// <summary> /// Bytes remaining from current position to end of underlying memory block. /// </summary> public int RemainingBytes => (int)(_endPointer - _currentPointer); /// <summary> /// Repositions the reader to the start of the underluing memory block. /// </summary> public void Reset() { _currentPointer = _block.Pointer; } /// <summary> /// Repositions the reader to the given offset from the start of the underlying memory block. /// </summary> /// <exception cref="BadImageFormatException">Offset is outside the bounds of underlying reader.</exception> public void SeekOffset(int offset) { if (!TrySeekOffset(offset)) { Throw.OutOfBounds(); } } internal bool TrySeekOffset(int offset) { if (unchecked((uint)offset) >= (uint)_block.Length) { return false; } _currentPointer = _block.Pointer + offset; return true; } /// <summary> /// Repositions the reader forward by the given number of bytes. /// </summary> public void SkipBytes(int count) { GetCurrentPointerAndAdvance(count); } /// <summary> /// Repositions the reader forward by the number of bytes required to satisfy the given alignment. /// </summary> public void Align(byte alignment) { if (!TryAlign(alignment)) { Throw.OutOfBounds(); } } internal bool TryAlign(byte alignment) { int remainder = this.Offset & (alignment - 1); Debug.Assert((alignment & (alignment - 1)) == 0, "Alignment must be a power of two."); Debug.Assert(remainder >= 0 && remainder < alignment); if (remainder != 0) { int bytesToSkip = alignment - remainder; if (bytesToSkip > RemainingBytes) { return false; } _currentPointer += bytesToSkip; } return true; } internal MemoryBlock GetMemoryBlockAt(int offset, int length) { CheckBounds(offset, length); return new MemoryBlock(_currentPointer + offset, length); } #endregion #region Bounds Checking [MethodImpl(MethodImplOptions.AggressiveInlining)] private void CheckBounds(int offset, int byteCount) { if (unchecked((ulong)(uint)offset + (uint)byteCount) > (ulong)(_endPointer - _currentPointer)) { Throw.OutOfBounds(); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void CheckBounds(int byteCount) { if (unchecked((uint)byteCount) > (_endPointer - _currentPointer)) { Throw.OutOfBounds(); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private byte* GetCurrentPointerAndAdvance(int length) { byte* p = _currentPointer; if (unchecked((uint)length) > (uint)(_endPointer - p)) { Throw.OutOfBounds(); } _currentPointer = p + length; return p; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private byte* GetCurrentPointerAndAdvance1() { byte* p = _currentPointer; if (p == _endPointer) { Throw.OutOfBounds(); } _currentPointer = p + 1; return p; } #endregion #region Read Methods public bool ReadBoolean() { // It's not clear from the ECMA spec what exactly is the encoding of Boolean. // Some metadata writers encode "true" as 0xff, others as 1. So we treat all non-zero values as "true". // // We propose to clarify and relax the current wording in the spec as follows: // // Chapter II.16.2 "Field init metadata" // ... bool '(' true | false ')' Boolean value stored in a single byte, 0 represents false, any non-zero value represents true ... // // Chapter 23.3 "Custom attributes" // ... A bool is a single byte with value 0 representing false and any non-zero value representing true ... return ReadByte() != 0; } public sbyte ReadSByte() { return *(sbyte*)GetCurrentPointerAndAdvance1(); } public byte ReadByte() { return *(byte*)GetCurrentPointerAndAdvance1(); } public char ReadChar() { return *(char*)GetCurrentPointerAndAdvance(sizeof(char)); } public short ReadInt16() { return *(short*)GetCurrentPointerAndAdvance(sizeof(short)); } public ushort ReadUInt16() { return *(ushort*)GetCurrentPointerAndAdvance(sizeof(ushort)); } public int ReadInt32() { return *(int*)GetCurrentPointerAndAdvance(sizeof(int)); } public uint ReadUInt32() { return *(uint*)GetCurrentPointerAndAdvance(sizeof(uint)); } public long ReadInt64() { return *(long*)GetCurrentPointerAndAdvance(sizeof(long)); } public ulong ReadUInt64() { return *(ulong*)GetCurrentPointerAndAdvance(sizeof(ulong)); } public float ReadSingle() { int val = ReadInt32(); return *(float*)&val; } public double ReadDouble() { long val = ReadInt64(); return *(double*)&val; } public Guid ReadGuid() { const int size = 16; return *(Guid*)GetCurrentPointerAndAdvance(size); } /// <summary> /// Reads <see cref="decimal"/> number. /// </summary> /// <remarks> /// Decimal number is encoded in 13 bytes as follows: /// - byte 0: highest bit indicates sign (1 for negative, 0 for non-negative); the remaining 7 bits encode scale /// - bytes 1..12: 96-bit unsigned integer in little endian encoding. /// </remarks> /// <exception cref="BadImageFormatException">The data at the current position was not a valid <see cref="decimal"/> number.</exception> public decimal ReadDecimal() { byte* ptr = GetCurrentPointerAndAdvance(13); byte scale = (byte)(*ptr & 0x7f); if (scale > 28) { throw new BadImageFormatException(SR.ValueTooLarge); } return new decimal( *(int*)(ptr + 1), *(int*)(ptr + 5), *(int*)(ptr + 9), isNegative: (*ptr & 0x80) != 0, scale: scale); } public DateTime ReadDateTime() { return new DateTime(ReadInt64()); } public SignatureHeader ReadSignatureHeader() { return new SignatureHeader(ReadByte()); } /// <summary> /// Reads UTF8 encoded string starting at the current position. /// </summary> /// <param name="byteCount">The number of bytes to read.</param> /// <returns>The string.</returns> /// <exception cref="BadImageFormatException"><paramref name="byteCount"/> bytes not available.</exception> public string ReadUTF8(int byteCount) { string s = _block.PeekUtf8(this.Offset, byteCount); _currentPointer += byteCount; return s; } /// <summary> /// Reads UTF16 (little-endian) encoded string starting at the current position. /// </summary> /// <param name="byteCount">The number of bytes to read.</param> /// <returns>The string.</returns> /// <exception cref="BadImageFormatException"><paramref name="byteCount"/> bytes not available.</exception> public string ReadUTF16(int byteCount) { string s = _block.PeekUtf16(this.Offset, byteCount); _currentPointer += byteCount; return s; } /// <summary> /// Reads bytes starting at the current position. /// </summary> /// <param name="byteCount">The number of bytes to read.</param> /// <returns>The byte array.</returns> /// <exception cref="BadImageFormatException"><paramref name="byteCount"/> bytes not available.</exception> public byte[] ReadBytes(int byteCount) { byte[] bytes = _block.PeekBytes(this.Offset, byteCount); _currentPointer += byteCount; return bytes; } /// <summary> /// Reads bytes starting at the current position in to the given buffer at the given offset; /// </summary> /// <param name="byteCount">The number of bytes to read.</param> /// <param name="buffer">The destination buffer the bytes read will be written.</param> /// <param name="bufferOffset">The offset in the destination buffer where the bytes read will be written.</param> /// <exception cref="BadImageFormatException"><paramref name="byteCount"/> bytes not available.</exception> public void ReadBytes(int byteCount, byte[] buffer, int bufferOffset) { Marshal.Copy((IntPtr)GetCurrentPointerAndAdvance(byteCount), buffer, bufferOffset, byteCount); } internal string ReadUtf8NullTerminated() { int bytesRead; string value = _block.PeekUtf8NullTerminated(this.Offset, null, MetadataStringDecoder.DefaultUTF8, out bytesRead, '\0'); _currentPointer += bytesRead; return value; } private int ReadCompressedIntegerOrInvalid() { int bytesRead; int value = _block.PeekCompressedInteger(this.Offset, out bytesRead); _currentPointer += bytesRead; return value; } /// <summary> /// Reads an unsigned compressed integer value. /// See Metadata Specification section II.23.2: Blobs and signatures. /// </summary> /// <param name="value">The value of the compressed integer that was read.</param> /// <returns>true if the value was read successfully. false if the data at the current position was not a valid compressed integer.</returns> public bool TryReadCompressedInteger(out int value) { value = ReadCompressedIntegerOrInvalid(); return value != InvalidCompressedInteger; } /// <summary> /// Reads an unsigned compressed integer value. /// See Metadata Specification section II.23.2: Blobs and signatures. /// </summary> /// <returns>The value of the compressed integer that was read.</returns> /// <exception cref="BadImageFormatException">The data at the current position was not a valid compressed integer.</exception> public int ReadCompressedInteger() { int value; if (!TryReadCompressedInteger(out value)) { Throw.InvalidCompressedInteger(); } return value; } /// <summary> /// Reads a signed compressed integer value. /// See Metadata Specification section II.23.2: Blobs and signatures. /// </summary> /// <param name="value">The value of the compressed integer that was read.</param> /// <returns>true if the value was read successfully. false if the data at the current position was not a valid compressed integer.</returns> public bool TryReadCompressedSignedInteger(out int value) { int bytesRead; value = _block.PeekCompressedInteger(this.Offset, out bytesRead); if (value == InvalidCompressedInteger) { return false; } bool signExtend = (value & 0x1) != 0; value >>= 1; if (signExtend) { switch (bytesRead) { case 1: value |= unchecked((int)0xffffffc0); break; case 2: value |= unchecked((int)0xffffe000); break; default: Debug.Assert(bytesRead == 4); value |= unchecked((int)0xf0000000); break; } } _currentPointer += bytesRead; return true; } /// <summary> /// Reads a signed compressed integer value. /// See Metadata Specification section II.23.2: Blobs and signatures. /// </summary> /// <returns>The value of the compressed integer that was read.</returns> /// <exception cref="BadImageFormatException">The data at the current position was not a valid compressed integer.</exception> public int ReadCompressedSignedInteger() { int value; if (!TryReadCompressedSignedInteger(out value)) { Throw.InvalidCompressedInteger(); } return value; } /// <summary> /// Reads type code encoded in a serialized custom attribute value. /// </summary> /// <returns><see cref="SerializationTypeCode.Invalid"/> if the encoding is invalid.</returns> public SerializationTypeCode ReadSerializationTypeCode() { int value = ReadCompressedIntegerOrInvalid(); if (value > byte.MaxValue) { return SerializationTypeCode.Invalid; } return unchecked((SerializationTypeCode)value); } /// <summary> /// Reads type code encoded in a signature. /// </summary> /// <returns><see cref="SignatureTypeCode.Invalid"/> if the encoding is invalid.</returns> public SignatureTypeCode ReadSignatureTypeCode() { int value = ReadCompressedIntegerOrInvalid(); switch (value) { case (int)CorElementType.ELEMENT_TYPE_CLASS: case (int)CorElementType.ELEMENT_TYPE_VALUETYPE: return SignatureTypeCode.TypeHandle; default: if (value > byte.MaxValue) { return SignatureTypeCode.Invalid; } return unchecked((SignatureTypeCode)value); } } /// <summary> /// Reads a string encoded as a compressed integer containing its length followed by /// its contents in UTF8. Null strings are encoded as a single 0xFF byte. /// </summary> /// <remarks>Defined as a 'SerString' in the ECMA CLI specification.</remarks> /// <returns>String value or null.</returns> /// <exception cref="BadImageFormatException">If the encoding is invalid.</exception> public string ReadSerializedString() { int length; if (TryReadCompressedInteger(out length)) { // Removal of trailing '\0' is a departure from the spec, but required // for compatibility with legacy compilers. return ReadUTF8(length).TrimEnd(s_nullCharArray); } if (ReadByte() != 0xFF) { Throw.InvalidSerializedString(); } return null; } /// <summary> /// Reads a type handle encoded in a signature as TypeDefOrRefOrSpecEncoded (see ECMA-335 II.23.2.8). /// </summary> /// <returns>The handle or nil if the encoding is invalid.</returns> public EntityHandle ReadTypeHandle() { uint value = (uint)ReadCompressedIntegerOrInvalid(); uint tokenType = s_corEncodeTokenArray[value & 0x3]; if (value == InvalidCompressedInteger || tokenType == 0) { return default(EntityHandle); } return new EntityHandle(tokenType | (value >> 2)); } private static readonly uint[] s_corEncodeTokenArray = new uint[] { TokenTypeIds.TypeDef, TokenTypeIds.TypeRef, TokenTypeIds.TypeSpec, 0 }; /// <summary> /// Reads a #Blob heap handle encoded as a compressed integer. /// </summary> /// <remarks> /// Blobs that contain references to other blobs are used in Portable PDB format, for example <see cref="Document.Name"/>. /// </remarks> public BlobHandle ReadBlobHandle() { return BlobHandle.FromOffset(ReadCompressedInteger()); } /// <summary> /// Reads a constant value (see ECMA-335 Partition II section 22.9) from the current position. /// </summary> /// <exception cref="BadImageFormatException">Error while reading from the blob.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="typeCode"/> is not a valid <see cref="ConstantTypeCode"/>.</exception> /// <returns> /// Boxed constant value. To avoid allocating the object use Read* methods directly. /// Constants of type <see cref="ConstantTypeCode.String"/> are encoded as UTF16 strings, use <see cref="ReadUTF16(int)"/> to read them. /// </returns> public object ReadConstant(ConstantTypeCode typeCode) { // Partition II section 22.9: // // Type shall be exactly one of: ELEMENT_TYPE_BOOLEAN, ELEMENT_TYPE_CHAR, ELEMENT_TYPE_I1, // ELEMENT_TYPE_U1, ELEMENT_TYPE_I2, ELEMENT_TYPE_U2, ELEMENT_TYPE_I4, ELEMENT_TYPE_U4, // ELEMENT_TYPE_I8, ELEMENT_TYPE_U8, ELEMENT_TYPE_R4, ELEMENT_TYPE_R8, or ELEMENT_TYPE_STRING; // or ELEMENT_TYPE_CLASS with a Value of zero (23.1.16) switch (typeCode) { case ConstantTypeCode.Boolean: return ReadBoolean(); case ConstantTypeCode.Char: return ReadChar(); case ConstantTypeCode.SByte: return ReadSByte(); case ConstantTypeCode.Int16: return ReadInt16(); case ConstantTypeCode.Int32: return ReadInt32(); case ConstantTypeCode.Int64: return ReadInt64(); case ConstantTypeCode.Byte: return ReadByte(); case ConstantTypeCode.UInt16: return ReadUInt16(); case ConstantTypeCode.UInt32: return ReadUInt32(); case ConstantTypeCode.UInt64: return ReadUInt64(); case ConstantTypeCode.Single: return ReadSingle(); case ConstantTypeCode.Double: return ReadDouble(); case ConstantTypeCode.String: return ReadUTF16(RemainingBytes); case ConstantTypeCode.NullReference: // Partition II section 22.9: // The encoding of Type for the nullref value is ELEMENT_TYPE_CLASS with a Value of a 4-byte zero. // Unlike uses of ELEMENT_TYPE_CLASS in signatures, this one is not followed by a type token. if (ReadUInt32() != 0) { throw new BadImageFormatException(SR.InvalidConstantValue); } return null; default: throw new ArgumentOutOfRangeException(nameof(typeCode)); } } #endregion } }
/* Copyright (c) 2006 - 2008 The Open Toolkit library. 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; namespace OpenTK { /// <summary> /// 4-component Vector of the Half type. Occupies 8 Byte total. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct Vector4h : IEquatable<Vector4h> { /// <summary>The X component of the Half4.</summary> public Half X; /// <summary>The Y component of the Half4.</summary> public Half Y; /// <summary>The Z component of the Half4.</summary> public Half Z; /// <summary>The W component of the Half4.</summary> public Half W; /// <summary> /// Constructs a new instance. /// </summary> /// <param name="value">The value that will initialize this instance.</param> public Vector4h(Half value) { X = value; Y = value; Z = value; W = value; } /// <summary> /// Constructs a new instance. /// </summary> /// <param name="value">The value that will initialize this instance.</param> public Vector4h(Single value) { X = new Half(value); Y = new Half(value); Z = new Half(value); W = new Half(value); } /// <summary> /// The new Half4 instance will avoid conversion and copy directly from the Half parameters. /// </summary> /// <param name="x">An Half instance of a 16-bit half-precision floating-point number.</param> /// <param name="y">An Half instance of a 16-bit half-precision floating-point number.</param> /// <param name="z">An Half instance of a 16-bit half-precision floating-point number.</param> /// <param name="w">An Half instance of a 16-bit half-precision floating-point number.</param> public Vector4h(Half x, Half y, Half z, Half w) { this.X = x; this.Y = y; this.Z = z; this.W = w; } /// <summary> /// The new Half4 instance will convert the 4 parameters into 16-bit half-precision floating-point. /// </summary> /// <param name="x">32-bit single-precision floating-point number.</param> /// <param name="y">32-bit single-precision floating-point number.</param> /// <param name="z">32-bit single-precision floating-point number.</param> /// <param name="w">32-bit single-precision floating-point number.</param> public Vector4h(Single x, Single y, Single z, Single w) { X = new Half(x); Y = new Half(y); Z = new Half(z); W = new Half(w); } /// <summary> /// The new Half4 instance will convert the 4 parameters into 16-bit half-precision floating-point. /// </summary> /// <param name="x">32-bit single-precision floating-point number.</param> /// <param name="y">32-bit single-precision floating-point number.</param> /// <param name="z">32-bit single-precision floating-point number.</param> /// <param name="w">32-bit single-precision floating-point number.</param> /// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param> public Vector4h(Single x, Single y, Single z, Single w, bool throwOnError) { X = new Half(x, throwOnError); Y = new Half(y, throwOnError); Z = new Half(z, throwOnError); W = new Half(w, throwOnError); } /// <summary> /// The new Half4 instance will convert the Vector4 into 16-bit half-precision floating-point. /// </summary> /// <param name="v">OpenTK.Vector4</param> [CLSCompliant(false)] public Vector4h(Vector4 v) { X = new Half(v.X); Y = new Half(v.Y); Z = new Half(v.Z); W = new Half(v.W); } /// <summary> /// The new Half4 instance will convert the Vector4 into 16-bit half-precision floating-point. /// </summary> /// <param name="v">OpenTK.Vector4</param> /// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param> [CLSCompliant(false)] public Vector4h(Vector4 v, bool throwOnError) { X = new Half(v.X, throwOnError); Y = new Half(v.Y, throwOnError); Z = new Half(v.Z, throwOnError); W = new Half(v.W, throwOnError); } /// <summary> /// The new Half4 instance will convert the Vector4 into 16-bit half-precision floating-point. /// This is the fastest constructor. /// </summary> /// <param name="v">OpenTK.Vector4</param> public Vector4h(ref Vector4 v) { X = new Half(v.X); Y = new Half(v.Y); Z = new Half(v.Z); W = new Half(v.W); } /// <summary> /// The new Half4 instance will convert the Vector4 into 16-bit half-precision floating-point. /// </summary> /// <param name="v">OpenTK.Vector4</param> /// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param> public Vector4h(ref Vector4 v, bool throwOnError) { X = new Half(v.X, throwOnError); Y = new Half(v.Y, throwOnError); Z = new Half(v.Z, throwOnError); W = new Half(v.W, throwOnError); } /// <summary> /// The new Half4 instance will convert the Vector4d into 16-bit half-precision floating-point. /// </summary> /// <param name="v">OpenTK.Vector4d</param> [CLSCompliant(false)] public Vector4h(Vector4d v) { X = new Half(v.X); Y = new Half(v.Y); Z = new Half(v.Z); W = new Half(v.W); } /// <summary> /// The new Half4 instance will convert the Vector4d into 16-bit half-precision floating-point. /// </summary> /// <param name="v">OpenTK.Vector4d</param> /// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param> [CLSCompliant(false)] public Vector4h(Vector4d v, bool throwOnError) { X = new Half(v.X, throwOnError); Y = new Half(v.Y, throwOnError); Z = new Half(v.Z, throwOnError); W = new Half(v.W, throwOnError); } /// <summary> /// The new Half4 instance will convert the Vector4d into 16-bit half-precision floating-point. /// This is the faster constructor. /// </summary> /// <param name="v">OpenTK.Vector4d</param> [CLSCompliant(false)] public Vector4h(ref Vector4d v) { X = new Half(v.X); Y = new Half(v.Y); Z = new Half(v.Z); W = new Half(v.W); } /// <summary> /// The new Half4 instance will convert the Vector4d into 16-bit half-precision floating-point. /// </summary> /// <param name="v">OpenTK.Vector4d</param> /// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param> [CLSCompliant(false)] public Vector4h(ref Vector4d v, bool throwOnError) { X = new Half(v.X, throwOnError); Y = new Half(v.Y, throwOnError); Z = new Half(v.Z, throwOnError); W = new Half(v.W, throwOnError); } /// <summary> /// Gets or sets an OpenTK.Vector2h with the X and Y components of this instance. /// </summary> [XmlIgnore] public Vector2h Xy { get { return new Vector2h(X, Y); } set { X = value.X; Y = value.Y; } } /// <summary> /// Gets or sets an OpenTK.Vector2h with the X and Z components of this instance. /// </summary> [XmlIgnore] public Vector2h Xz { get { return new Vector2h(X, Z); } set { X = value.X; Z = value.Y; } } /// <summary> /// Gets or sets an OpenTK.Vector2h with the X and W components of this instance. /// </summary> [XmlIgnore] public Vector2h Xw { get { return new Vector2h(X, W); } set { X = value.X; W = value.Y; } } /// <summary> /// Gets or sets an OpenTK.Vector2h with the Y and X components of this instance. /// </summary> [XmlIgnore] public Vector2h Yx { get { return new Vector2h(Y, X); } set { Y = value.X; X = value.Y; } } /// <summary> /// Gets or sets an OpenTK.Vector2h with the Y and Z components of this instance. /// </summary> [XmlIgnore] public Vector2h Yz { get { return new Vector2h(Y, Z); } set { Y = value.X; Z = value.Y; } } /// <summary> /// Gets or sets an OpenTK.Vector2h with the Y and W components of this instance. /// </summary> [XmlIgnore] public Vector2h Yw { get { return new Vector2h(Y, W); } set { Y = value.X; W = value.Y; } } /// <summary> /// Gets or sets an OpenTK.Vector2h with the Z and X components of this instance. /// </summary> [XmlIgnore] public Vector2h Zx { get { return new Vector2h(Z, X); } set { Z = value.X; X = value.Y; } } /// <summary> /// Gets or sets an OpenTK.Vector2h with the Z and Y components of this instance. /// </summary> [XmlIgnore] public Vector2h Zy { get { return new Vector2h(Z, Y); } set { Z = value.X; Y = value.Y; } } /// <summary> /// Gets an OpenTK.Vector2h with the Z and W components of this instance. /// </summary> [XmlIgnore] public Vector2h Zw { get { return new Vector2h(Z, W); } set { Z = value.X; W = value.Y; } } /// <summary> /// Gets or sets an OpenTK.Vector2h with the W and X components of this instance. /// </summary> [XmlIgnore] public Vector2h Wx { get { return new Vector2h(W, X); } set { W = value.X; X = value.Y; } } /// <summary> /// Gets or sets an OpenTK.Vector2h with the W and Y components of this instance. /// </summary> [XmlIgnore] public Vector2h Wy { get { return new Vector2h(W, Y); } set { W = value.X; Y = value.Y; } } /// <summary> /// Gets or sets an OpenTK.Vector2h with the W and Z components of this instance. /// </summary> [XmlIgnore] public Vector2h Wz { get { return new Vector2h(W, Z); } set { W = value.X; Z = value.Y; } } /// <summary> /// Gets or sets an OpenTK.Vector3h with the X, Y, and Z components of this instance. /// </summary> [XmlIgnore] public Vector3h Xyz { get { return new Vector3h(X, Y, Z); } set { X = value.X; Y = value.Y; Z = value.Z; } } /// <summary> /// Gets or sets an OpenTK.Vector3h with the X, Y, and Z components of this instance. /// </summary> [XmlIgnore] public Vector3h Xyw { get { return new Vector3h(X, Y, W); } set { X = value.X; Y = value.Y; W = value.Z; } } /// <summary> /// Gets or sets an OpenTK.Vector3h with the X, Z, and Y components of this instance. /// </summary> [XmlIgnore] public Vector3h Xzy { get { return new Vector3h(X, Z, Y); } set { X = value.X; Z = value.Y; Y = value.Z; } } /// <summary> /// Gets or sets an OpenTK.Vector3h with the X, Z, and W components of this instance. /// </summary> [XmlIgnore] public Vector3h Xzw { get { return new Vector3h(X, Z, W); } set { X = value.X; Z = value.Y; W = value.Z; } } /// <summary> /// Gets or sets an OpenTK.Vector3h with the X, W, and Y components of this instance. /// </summary> [XmlIgnore] public Vector3h Xwy { get { return new Vector3h(X, W, Y); } set { X = value.X; W = value.Y; Y = value.Z; } } /// <summary> /// Gets or sets an OpenTK.Vector3h with the X, W, and Z components of this instance. /// </summary> [XmlIgnore] public Vector3h Xwz { get { return new Vector3h(X, W, Z); } set { X = value.X; W = value.Y; Z = value.Z; } } /// <summary> /// Gets or sets an OpenTK.Vector3h with the Y, X, and Z components of this instance. /// </summary> [XmlIgnore] public Vector3h Yxz { get { return new Vector3h(Y, X, Z); } set { Y = value.X; X = value.Y; Z = value.Z; } } /// <summary> /// Gets or sets an OpenTK.Vector3h with the Y, X, and W components of this instance. /// </summary> [XmlIgnore] public Vector3h Yxw { get { return new Vector3h(Y, X, W); } set { Y = value.X; X = value.Y; W = value.Z; } } /// <summary> /// Gets or sets an OpenTK.Vector3h with the Y, Z, and X components of this instance. /// </summary> [XmlIgnore] public Vector3h Yzx { get { return new Vector3h(Y, Z, X); } set { Y = value.X; Z = value.Y; X = value.Z; } } /// <summary> /// Gets or sets an OpenTK.Vector3h with the Y, Z, and W components of this instance. /// </summary> [XmlIgnore] public Vector3h Yzw { get { return new Vector3h(Y, Z, W); } set { Y = value.X; Z = value.Y; W = value.Z; } } /// <summary> /// Gets or sets an OpenTK.Vector3h with the Y, W, and X components of this instance. /// </summary> [XmlIgnore] public Vector3h Ywx { get { return new Vector3h(Y, W, X); } set { Y = value.X; W = value.Y; X = value.Z; } } /// <summary> /// Gets an OpenTK.Vector3h with the Y, W, and Z components of this instance. /// </summary> [XmlIgnore] public Vector3h Ywz { get { return new Vector3h(Y, W, Z); } set { Y = value.X; W = value.Y; Z = value.Z; } } /// <summary> /// Gets or sets an OpenTK.Vector3h with the Z, X, and Y components of this instance. /// </summary> [XmlIgnore] public Vector3h Zxy { get { return new Vector3h(Z, X, Y); } set { Z = value.X; X = value.Y; Y = value.Z; } } /// <summary> /// Gets or sets an OpenTK.Vector3h with the Z, X, and W components of this instance. /// </summary> [XmlIgnore] public Vector3h Zxw { get { return new Vector3h(Z, X, W); } set { Z = value.X; X = value.Y; W = value.Z; } } /// <summary> /// Gets or sets an OpenTK.Vector3h with the Z, Y, and X components of this instance. /// </summary> [XmlIgnore] public Vector3h Zyx { get { return new Vector3h(Z, Y, X); } set { Z = value.X; Y = value.Y; X = value.Z; } } /// <summary> /// Gets or sets an OpenTK.Vector3h with the Z, Y, and W components of this instance. /// </summary> [XmlIgnore] public Vector3h Zyw { get { return new Vector3h(Z, Y, W); } set { Z = value.X; Y = value.Y; W = value.Z; } } /// <summary> /// Gets or sets an OpenTK.Vector3h with the Z, W, and X components of this instance. /// </summary> [XmlIgnore] public Vector3h Zwx { get { return new Vector3h(Z, W, X); } set { Z = value.X; W = value.Y; X = value.Z; } } /// <summary> /// Gets or sets an OpenTK.Vector3h with the Z, W, and Y components of this instance. /// </summary> [XmlIgnore] public Vector3h Zwy { get { return new Vector3h(Z, W, Y); } set { Z = value.X; W = value.Y; Y = value.Z; } } /// <summary> /// Gets or sets an OpenTK.Vector3h with the W, X, and Y components of this instance. /// </summary> [XmlIgnore] public Vector3h Wxy { get { return new Vector3h(W, X, Y); } set { W = value.X; X = value.Y; Y = value.Z; } } /// <summary> /// Gets or sets an OpenTK.Vector3h with the W, X, and Z components of this instance. /// </summary> [XmlIgnore] public Vector3h Wxz { get { return new Vector3h(W, X, Z); } set { W = value.X; X = value.Y; Z = value.Z; } } /// <summary> /// Gets or sets an OpenTK.Vector3h with the W, Y, and X components of this instance. /// </summary> [XmlIgnore] public Vector3h Wyx { get { return new Vector3h(W, Y, X); } set { W = value.X; Y = value.Y; X = value.Z; } } /// <summary> /// Gets or sets an OpenTK.Vector3h with the W, Y, and Z components of this instance. /// </summary> [XmlIgnore] public Vector3h Wyz { get { return new Vector3h(W, Y, Z); } set { W = value.X; Y = value.Y; Z = value.Z; } } /// <summary> /// Gets or sets an OpenTK.Vector3h with the W, Z, and X components of this instance. /// </summary> [XmlIgnore] public Vector3h Wzx { get { return new Vector3h(W, Z, X); } set { W = value.X; Z = value.Y; X = value.Z; } } /// <summary> /// Gets or sets an OpenTK.Vector3h with the W, Z, and Y components of this instance. /// </summary> [XmlIgnore] public Vector3h Wzy { get { return new Vector3h(W, Z, Y); } set { W = value.X; Z = value.Y; Y = value.Z; } } /// <summary> /// Gets or sets an OpenTK.Vector4h with the X, Y, W, and Z components of this instance. /// </summary> [XmlIgnore] public Vector4h Xywz { get { return new Vector4h(X, Y, W, Z); } set { X = value.X; Y = value.Y; W = value.Z; Z = value.W; } } /// <summary> /// Gets or sets an OpenTK.Vector4h with the X, Z, Y, and W components of this instance. /// </summary> [XmlIgnore] public Vector4h Xzyw { get { return new Vector4h(X, Z, Y, W); } set { X = value.X; Z = value.Y; Y = value.Z; W = value.W; } } /// <summary> /// Gets or sets an OpenTK.Vector4h with the X, Z, W, and Y components of this instance. /// </summary> [XmlIgnore] public Vector4h Xzwy { get { return new Vector4h(X, Z, W, Y); } set { X = value.X; Z = value.Y; W = value.Z; Y = value.W; } } /// <summary> /// Gets or sets an OpenTK.Vector4h with the X, W, Y, and Z components of this instance. /// </summary> [XmlIgnore] public Vector4h Xwyz { get { return new Vector4h(X, W, Y, Z); } set { X = value.X; W = value.Y; Y = value.Z; Z = value.W; } } /// <summary> /// Gets or sets an OpenTK.Vector4h with the X, W, Z, and Y components of this instance. /// </summary> [XmlIgnore] public Vector4h Xwzy { get { return new Vector4h(X, W, Z, Y); } set { X = value.X; W = value.Y; Z = value.Z; Y = value.W; } } /// <summary> /// Gets or sets an OpenTK.Vector4h with the Y, X, Z, and W components of this instance. /// </summary> [XmlIgnore] public Vector4h Yxzw { get { return new Vector4h(Y, X, Z, W); } set { Y = value.X; X = value.Y; Z = value.Z; W = value.W; } } /// <summary> /// Gets or sets an OpenTK.Vector4h with the Y, X, W, and Z components of this instance. /// </summary> [XmlIgnore] public Vector4h Yxwz { get { return new Vector4h(Y, X, W, Z); } set { Y = value.X; X = value.Y; W = value.Z; Z = value.W; } } /// <summary> /// Gets an OpenTK.Vector4h with the Y, Y, Z, and W components of this instance. /// </summary> [XmlIgnore] public Vector4h Yyzw { get { return new Vector4h(Y, Y, Z, W); } set { X = value.X; Y = value.Y; Z = value.Z; W = value.W; } } /// <summary> /// Gets an OpenTK.Vector4h with the Y, Y, W, and Z components of this instance. /// </summary> [XmlIgnore] public Vector4h Yywz { get { return new Vector4h(Y, Y, W, Z); } set { X = value.X; Y = value.Y; W = value.Z; Z = value.W; } } /// <summary> /// Gets or sets an OpenTK.Vector4h with the Y, Z, X, and W components of this instance. /// </summary> [XmlIgnore] public Vector4h Yzxw { get { return new Vector4h(Y, Z, X, W); } set { Y = value.X; Z = value.Y; X = value.Z; W = value.W; } } /// <summary> /// Gets or sets an OpenTK.Vector4h with the Y, Z, W, and X components of this instance. /// </summary> [XmlIgnore] public Vector4h Yzwx { get { return new Vector4h(Y, Z, W, X); } set { Y = value.X; Z = value.Y; W = value.Z; X = value.W; } } /// <summary> /// Gets or sets an OpenTK.Vector4h with the Y, W, X, and Z components of this instance. /// </summary> [XmlIgnore] public Vector4h Ywxz { get { return new Vector4h(Y, W, X, Z); } set { Y = value.X; W = value.Y; X = value.Z; Z = value.W; } } /// <summary> /// Gets or sets an OpenTK.Vector4h with the Y, W, Z, and X components of this instance. /// </summary> [XmlIgnore] public Vector4h Ywzx { get { return new Vector4h(Y, W, Z, X); } set { Y = value.X; W = value.Y; Z = value.Z; X = value.W; } } /// <summary> /// Gets or sets an OpenTK.Vector4h with the Z, X, Y, and Z components of this instance. /// </summary> [XmlIgnore] public Vector4h Zxyw { get { return new Vector4h(Z, X, Y, W); } set { Z = value.X; X = value.Y; Y = value.Z; W = value.W; } } /// <summary> /// Gets or sets an OpenTK.Vector4h with the Z, X, W, and Y components of this instance. /// </summary> [XmlIgnore] public Vector4h Zxwy { get { return new Vector4h(Z, X, W, Y); } set { Z = value.X; X = value.Y; W = value.Z; Y = value.W; } } /// <summary> /// Gets or sets an OpenTK.Vector4h with the Z, Y, X, and W components of this instance. /// </summary> [XmlIgnore] public Vector4h Zyxw { get { return new Vector4h(Z, Y, X, W); } set { Z = value.X; Y = value.Y; X = value.Z; W = value.W; } } /// <summary> /// Gets or sets an OpenTK.Vector4h with the Z, Y, W, and X components of this instance. /// </summary> [XmlIgnore] public Vector4h Zywx { get { return new Vector4h(Z, Y, W, X); } set { Z = value.X; Y = value.Y; W = value.Z; X = value.W; } } /// <summary> /// Gets or sets an OpenTK.Vector4h with the Z, W, X, and Y components of this instance. /// </summary> [XmlIgnore] public Vector4h Zwxy { get { return new Vector4h(Z, W, X, Y); } set { Z = value.X; W = value.Y; X = value.Z; Y = value.W; } } /// <summary> /// Gets or sets an OpenTK.Vector4h with the Z, W, Y, and X components of this instance. /// </summary> [XmlIgnore] public Vector4h Zwyx { get { return new Vector4h(Z, W, Y, X); } set { Z = value.X; W = value.Y; Y = value.Z; X = value.W; } } /// <summary> /// Gets an OpenTK.Vector4h with the Z, W, Z, and Y components of this instance. /// </summary> [XmlIgnore] public Vector4h Zwzy { get { return new Vector4h(Z, W, Z, Y); } set { X = value.X; W = value.Y; Z = value.Z; Y = value.W; } } /// <summary> /// Gets or sets an OpenTK.Vector4h with the W, X, Y, and Z components of this instance. /// </summary> [XmlIgnore] public Vector4h Wxyz { get { return new Vector4h(W, X, Y, Z); } set { W = value.X; X = value.Y; Y = value.Z; Z = value.W; } } /// <summary> /// Gets or sets an OpenTK.Vector4h with the W, X, Z, and Y components of this instance. /// </summary> [XmlIgnore] public Vector4h Wxzy { get { return new Vector4h(W, X, Z, Y); } set { W = value.X; X = value.Y; Z = value.Z; Y = value.W; } } /// <summary> /// Gets or sets an OpenTK.Vector4h with the W, Y, X, and Z components of this instance. /// </summary> [XmlIgnore] public Vector4h Wyxz { get { return new Vector4h(W, Y, X, Z); } set { W = value.X; Y = value.Y; X = value.Z; Z = value.W; } } /// <summary> /// Gets or sets an OpenTK.Vector4h with the W, Y, Z, and X components of this instance. /// </summary> [XmlIgnore] public Vector4h Wyzx { get { return new Vector4h(W, Y, Z, X); } set { W = value.X; Y = value.Y; Z = value.Z; X = value.W; } } /// <summary> /// Gets or sets an OpenTK.Vector4h with the W, Z, X, and Y components of this instance. /// </summary> [XmlIgnore] public Vector4h Wzxy { get { return new Vector4h(W, Z, X, Y); } set { W = value.X; Z = value.Y; X = value.Z; Y = value.W; } } /// <summary> /// Gets or sets an OpenTK.Vector4h with the W, Z, Y, and X components of this instance. /// </summary> [XmlIgnore] public Vector4h Wzyx { get { return new Vector4h(W, Z, Y, X); } set { W = value.X; Z = value.Y; Y = value.Z; X = value.W; } } /// <summary> /// Gets an OpenTK.Vector4h with the W, Z, Y, and W components of this instance. /// </summary> [XmlIgnore] public Vector4h Wzyw { get { return new Vector4h(W, Z, Y, W); } set { X = value.X; Z = value.Y; Y = value.Z; W = value.W; } } /// <summary> /// Returns this Half4 instance's contents as Vector4. /// </summary> /// <returns>OpenTK.Vector4</returns> public Vector4 ToVector4() { return new Vector4(X, Y, Z, W); } /// <summary> /// Returns this Half4 instance's contents as Vector4d. /// </summary> public Vector4d ToVector4d() { return new Vector4d(X, Y, Z, W); } /// <summary>Converts OpenTK.Vector4 to OpenTK.Half4.</summary> /// <param name="v4f">The Vector4 to convert.</param> /// <returns>The resulting Half vector.</returns> public static explicit operator Vector4h(Vector4 v4f) { return new Vector4h(v4f); } /// <summary>Converts OpenTK.Vector4d to OpenTK.Half4.</summary> /// <param name="v4d">The Vector4d to convert.</param> /// <returns>The resulting Half vector.</returns> public static explicit operator Vector4h(Vector4d v4d) { return new Vector4h(v4d); } /// <summary>Converts OpenTK.Half4 to OpenTK.Vector4.</summary> /// <param name="h4">The Half4 to convert.</param> /// <returns>The resulting Vector4.</returns> public static explicit operator Vector4(Vector4h h4) { return new Vector4( h4.X.ToSingle(), h4.Y.ToSingle(), h4.Z.ToSingle(), h4.W.ToSingle()); } /// <summary>Converts OpenTK.Half4 to OpenTK.Vector4d.</summary> /// <param name="h4">The Half4 to convert.</param> /// <returns>The resulting Vector4d.</returns> public static explicit operator Vector4d(Vector4h h4) { return new Vector4d( h4.X.ToSingle(), h4.Y.ToSingle(), h4.Z.ToSingle(), h4.W.ToSingle()); } /// <summary>The size in bytes for an instance of the Half4 struct is 8.</summary> public static readonly int SizeInBytes = 8; ///// <summary>Constructor used by ISerializable to deserialize the object.</summary> ///// <param name="info"></param> ///// <param name="context"></param> //public Vector4h(SerializationInfo info, StreamingContext context) //{ // this.X = (Half)info.GetValue("X", typeof(Half)); // this.Y = (Half)info.GetValue("Y", typeof(Half)); // this.Z = (Half)info.GetValue("Z", typeof(Half)); // this.W = (Half)info.GetValue("W", typeof(Half)); //} ///// <summary>Used by ISerialize to serialize the object.</summary> ///// <param name="info"></param> ///// <param name="context"></param> //public void GetObjectData(SerializationInfo info, StreamingContext context) //{ // info.AddValue("X", this.X); // info.AddValue("Y", this.Y); // info.AddValue("Z", this.Z); // info.AddValue("W", this.W); //} /// <summary>Updates the X,Y,Z and W components of this instance by reading from a Stream.</summary> /// <param name="bin">A BinaryReader instance associated with an open Stream.</param> public void FromBinaryStream(BinaryReader bin) { X.FromBinaryStream(bin); Y.FromBinaryStream(bin); Z.FromBinaryStream(bin); W.FromBinaryStream(bin); } /// <summary>Writes the X,Y,Z and W components of this instance into a Stream.</summary> /// <param name="bin">A BinaryWriter instance associated with an open Stream.</param> public void ToBinaryStream(BinaryWriter bin) { X.ToBinaryStream(bin); Y.ToBinaryStream(bin); Z.ToBinaryStream(bin); W.ToBinaryStream(bin); } /// <summary>Returns a value indicating whether this instance is equal to a specified OpenTK.Half4 vector.</summary> /// <param name="other">OpenTK.Half4 to compare to this instance..</param> /// <returns>True, if other is equal to this instance; false otherwise.</returns> public bool Equals(Vector4h other) { return (this.X.Equals(other.X) && this.Y.Equals(other.Y) && this.Z.Equals(other.Z) && this.W.Equals(other.W)); } private static string listSeparator = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator; /// <summary>Returns a string that contains this Half4's numbers in human-legible form.</summary> public override string ToString() { return String.Format("({0}{4} {1}{4} {2}{4} {3})", X.ToString(), Y.ToString(), Z.ToString(), W.ToString(), listSeparator); } /// <summary>Returns the Half4 as an array of bytes.</summary> /// <param name="h">The Half4 to convert.</param> /// <returns>The input as byte array.</returns> public static byte[] GetBytes(Vector4h h) { byte[] result = new byte[SizeInBytes]; byte[] temp = Half.GetBytes(h.X); result[0] = temp[0]; result[1] = temp[1]; temp = Half.GetBytes(h.Y); result[2] = temp[0]; result[3] = temp[1]; temp = Half.GetBytes(h.Z); result[4] = temp[0]; result[5] = temp[1]; temp = Half.GetBytes(h.W); result[6] = temp[0]; result[7] = temp[1]; return result; } /// <summary>Converts an array of bytes into Half4.</summary> /// <param name="value">A Half4 in it's byte[] representation.</param> /// <param name="startIndex">The starting position within value.</param> /// <returns>A new Half4 instance.</returns> public static Vector4h FromBytes(byte[] value, int startIndex) { return new Vector4h( Half.FromBytes(value, startIndex), Half.FromBytes(value, startIndex + 2), Half.FromBytes(value, startIndex + 4), Half.FromBytes(value, startIndex + 6)); } } }
namespace KojtoCAD.Plotter { partial class PlotterForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PlotterForm)); this.buttonExit = new System.Windows.Forms.Button(); this.buttonPlot = new System.Windows.Forms.Button(); this.folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog(); this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); this.checkBoxDWG = new System.Windows.Forms.CheckBox(); this.cmbPlotStyleTables = new System.Windows.Forms.ComboBox(); this.checkBoxDXF = new System.Windows.Forms.CheckBox(); this.cmbPaperSizePrint = new System.Windows.Forms.ComboBox(); this.label2 = new System.Windows.Forms.Label(); this.labelInputType = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.buttonSourcePath = new System.Windows.Forms.Button(); this.LabelSource = new System.Windows.Forms.Label(); this.textBoxSourcePath = new System.Windows.Forms.TextBox(); this.checkBoxCenterPlot = new System.Windows.Forms.CheckBox(); this.checkBoxPlotAllDWGs = new System.Windows.Forms.CheckBox(); this.cmbPlotDevicePrinter = new System.Windows.Forms.ComboBox(); this.labelOutputType = new System.Windows.Forms.Label(); this.checkBoxIgnoreModelSpace = new System.Windows.Forms.CheckBox(); this.checkBoxPDF = new System.Windows.Forms.CheckBox(); this.checkBoxDWF = new System.Windows.Forms.CheckBox(); this.checkBoxMultiSheet = new System.Windows.Forms.CheckBox(); this.checkBoxPrint = new System.Windows.Forms.CheckBox(); this.cmbPlotDevicePDF = new System.Windows.Forms.ComboBox(); this.cmbPlotDeviceDWF = new System.Windows.Forms.ComboBox(); this.cmbPaperSizePDF = new System.Windows.Forms.ComboBox(); this.label1 = new System.Windows.Forms.Label(); this.buttonSavePath = new System.Windows.Forms.Button(); this.cmbPaperSizeDWF = new System.Windows.Forms.ComboBox(); this.label_savePath_PDF = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.textBoxSavePath = new System.Windows.Forms.TextBox(); this.textBoxDynamicBlockFrameName = new System.Windows.Forms.TextBox(); this.labelFrameName = new System.Windows.Forms.Label(); this.labelFrameLayout = new System.Windows.Forms.Label(); this.textBoxFrameLayout = new System.Windows.Forms.TextBox(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.checkBoxPlotTransparency = new System.Windows.Forms.CheckBox(); this.checkBoxTurnOnViewPorts = new System.Windows.Forms.CheckBox(); this.label12 = new System.Windows.Forms.Label(); this.label11 = new System.Windows.Forms.Label(); this.label10 = new System.Windows.Forms.Label(); this.label9 = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.labelPrinterPlotter = new System.Windows.Forms.Label(); this.labelMessageToTheUser = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.buttonSelect_UnselectFiles = new System.Windows.Forms.Button(); this.LayoutNameList = new System.Windows.Forms.CheckedListBox(); this.DwgNameList = new System.Windows.Forms.CheckedListBox(); this.labelDrawings = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.BoxDwgLayout = new System.Windows.Forms.GroupBox(); this.buttonSelect_UnselectLayouts = new System.Windows.Forms.Button(); this.groupBox2.SuspendLayout(); this.BoxDwgLayout.SuspendLayout(); this.SuspendLayout(); // // buttonExit // this.buttonExit.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonExit.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.buttonExit.Image = ((System.Drawing.Image)(resources.GetObject("buttonExit.Image"))); this.buttonExit.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.buttonExit.Location = new System.Drawing.Point(418, 630); this.buttonExit.Name = "buttonExit"; this.buttonExit.Size = new System.Drawing.Size(85, 22); this.buttonExit.TabIndex = 26; this.buttonExit.Text = "Cancel"; this.buttonExit.UseVisualStyleBackColor = true; this.buttonExit.Click += new System.EventHandler(this.buttonExit_Click); // // buttonPlot // this.buttonPlot.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.buttonPlot.Image = ((System.Drawing.Image)(resources.GetObject("buttonPlot.Image"))); this.buttonPlot.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.buttonPlot.Location = new System.Drawing.Point(771, 630); this.buttonPlot.Name = "buttonPlot"; this.buttonPlot.Size = new System.Drawing.Size(85, 22); this.buttonPlot.TabIndex = 25; this.buttonPlot.Text = "Plot"; this.buttonPlot.UseVisualStyleBackColor = true; this.buttonPlot.Click += new System.EventHandler(this.buttonPlot_Click); // // checkBoxDWG // this.checkBoxDWG.AutoSize = true; this.checkBoxDWG.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.checkBoxDWG.Location = new System.Drawing.Point(124, 57); this.checkBoxDWG.Name = "checkBoxDWG"; this.checkBoxDWG.Size = new System.Drawing.Size(56, 17); this.checkBoxDWG.TabIndex = 0; this.checkBoxDWG.Text = "DWG"; this.checkBoxDWG.UseVisualStyleBackColor = true; this.checkBoxDWG.CheckedChanged += new System.EventHandler(this.checkBoxDWG_CheckedChanged); // // cmbPlotStyleTables // this.cmbPlotStyleTables.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbPlotStyleTables.FormattingEnabled = true; this.cmbPlotStyleTables.Location = new System.Drawing.Point(123, 132); this.cmbPlotStyleTables.Name = "cmbPlotStyleTables"; this.cmbPlotStyleTables.Size = new System.Drawing.Size(261, 21); this.cmbPlotStyleTables.TabIndex = 19; this.cmbPlotStyleTables.SelectedIndexChanged += new System.EventHandler(this.cmbPlotStyleTables_SelectedIndexChanged); // // checkBoxDXF // this.checkBoxDXF.AutoSize = true; this.checkBoxDXF.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.checkBoxDXF.Location = new System.Drawing.Point(220, 58); this.checkBoxDXF.Name = "checkBoxDXF"; this.checkBoxDXF.Size = new System.Drawing.Size(50, 17); this.checkBoxDXF.TabIndex = 2; this.checkBoxDXF.Text = "DXF"; this.checkBoxDXF.UseVisualStyleBackColor = true; this.checkBoxDXF.CheckedChanged += new System.EventHandler(this.checkBoxDXF_CheckedChanged); // // cmbPaperSizePrint // this.cmbPaperSizePrint.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbPaperSizePrint.FormattingEnabled = true; this.cmbPaperSizePrint.Location = new System.Drawing.Point(123, 436); this.cmbPaperSizePrint.Name = "cmbPaperSizePrint"; this.cmbPaperSizePrint.Size = new System.Drawing.Size(261, 21); this.cmbPaperSizePrint.TabIndex = 23; this.cmbPaperSizePrint.SelectedIndexChanged += new System.EventHandler(this.cmbPaperSize_SelectedIndexChanged); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(4, 135); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(91, 13); this.label2.TabIndex = 18; this.label2.Text = "Source Plot Style:"; // // labelInputType // this.labelInputType.AutoSize = true; this.labelInputType.Location = new System.Drawing.Point(4, 58); this.labelInputType.Name = "labelInputType"; this.labelInputType.Size = new System.Drawing.Size(93, 13); this.labelInputType.TabIndex = 3; this.labelInputType.Text = "Source File Type :"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(3, 442); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(59, 13); this.label4.TabIndex = 22; this.label4.Text = "Paper size:"; // // buttonSourcePath // this.buttonSourcePath.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.buttonSourcePath.Location = new System.Drawing.Point(351, 82); this.buttonSourcePath.Name = "buttonSourcePath"; this.buttonSourcePath.Size = new System.Drawing.Size(33, 20); this.buttonSourcePath.TabIndex = 28; this.buttonSourcePath.Text = "..."; this.buttonSourcePath.UseVisualStyleBackColor = true; this.buttonSourcePath.Click += new System.EventHandler(this.buttonSourcePath_Click); // // LabelSource // this.LabelSource.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.LabelSource.Location = new System.Drawing.Point(4, 88); this.LabelSource.Name = "LabelSource"; this.LabelSource.Size = new System.Drawing.Size(91, 13); this.LabelSource.TabIndex = 29; this.LabelSource.Text = "Source Folder:"; // // textBoxSourcePath // this.textBoxSourcePath.AllowDrop = true; this.textBoxSourcePath.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBoxSourcePath.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBoxSourcePath.Location = new System.Drawing.Point(123, 82); this.textBoxSourcePath.Name = "textBoxSourcePath"; this.textBoxSourcePath.Size = new System.Drawing.Size(219, 20); this.textBoxSourcePath.TabIndex = 27; this.textBoxSourcePath.TextChanged += new System.EventHandler(this.textBoxSourcePath_TextChanged); // // checkBoxCenterPlot // this.checkBoxCenterPlot.AutoSize = true; this.checkBoxCenterPlot.Location = new System.Drawing.Point(123, 463); this.checkBoxCenterPlot.Name = "checkBoxCenterPlot"; this.checkBoxCenterPlot.Size = new System.Drawing.Size(95, 17); this.checkBoxCenterPlot.TabIndex = 0; this.checkBoxCenterPlot.Text = "Center the plot"; this.checkBoxCenterPlot.UseVisualStyleBackColor = true; // // checkBoxPlotAllDWGs // this.checkBoxPlotAllDWGs.AutoSize = true; this.checkBoxPlotAllDWGs.Location = new System.Drawing.Point(123, 108); this.checkBoxPlotAllDWGs.Name = "checkBoxPlotAllDWGs"; this.checkBoxPlotAllDWGs.Size = new System.Drawing.Size(267, 17); this.checkBoxPlotAllDWGs.TabIndex = 42; this.checkBoxPlotAllDWGs.Text = "Search subdirectories for DWGs in source directory"; this.checkBoxPlotAllDWGs.UseVisualStyleBackColor = true; // // cmbPlotDevicePrinter // this.cmbPlotDevicePrinter.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbPlotDevicePrinter.FormattingEnabled = true; this.cmbPlotDevicePrinter.Location = new System.Drawing.Point(123, 407); this.cmbPlotDevicePrinter.Name = "cmbPlotDevicePrinter"; this.cmbPlotDevicePrinter.Size = new System.Drawing.Size(261, 21); this.cmbPlotDevicePrinter.TabIndex = 45; this.cmbPlotDevicePrinter.SelectedIndexChanged += new System.EventHandler(this.cmbPlotDevice_SelectedIndexChanged); // // labelOutputType // this.labelOutputType.AutoSize = true; this.labelOutputType.Location = new System.Drawing.Point(4, 211); this.labelOutputType.Name = "labelOutputType"; this.labelOutputType.Size = new System.Drawing.Size(88, 13); this.labelOutputType.TabIndex = 41; this.labelOutputType.Text = "Make PDF Files :"; // // checkBoxIgnoreModelSpace // this.checkBoxIgnoreModelSpace.AutoSize = true; this.checkBoxIgnoreModelSpace.Location = new System.Drawing.Point(242, 463); this.checkBoxIgnoreModelSpace.Name = "checkBoxIgnoreModelSpace"; this.checkBoxIgnoreModelSpace.Size = new System.Drawing.Size(152, 17); this.checkBoxIgnoreModelSpace.TabIndex = 10; this.checkBoxIgnoreModelSpace.Text = "Ignore modelspace layouts"; this.checkBoxIgnoreModelSpace.UseVisualStyleBackColor = true; // // checkBoxPDF // this.checkBoxPDF.AutoSize = true; this.checkBoxPDF.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.checkBoxPDF.Location = new System.Drawing.Point(124, 210); this.checkBoxPDF.Name = "checkBoxPDF"; this.checkBoxPDF.Size = new System.Drawing.Size(50, 17); this.checkBoxPDF.TabIndex = 2; this.checkBoxPDF.Text = "PDF"; this.checkBoxPDF.UseVisualStyleBackColor = true; // // checkBoxDWF // this.checkBoxDWF.AutoSize = true; this.checkBoxDWF.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.checkBoxDWF.Location = new System.Drawing.Point(124, 291); this.checkBoxDWF.Name = "checkBoxDWF"; this.checkBoxDWF.Size = new System.Drawing.Size(54, 17); this.checkBoxDWF.TabIndex = 0; this.checkBoxDWF.Text = "DWF"; this.checkBoxDWF.UseVisualStyleBackColor = true; // // checkBoxMultiSheet // this.checkBoxMultiSheet.AutoSize = true; this.checkBoxMultiSheet.Location = new System.Drawing.Point(123, 509); this.checkBoxMultiSheet.Name = "checkBoxMultiSheet"; this.checkBoxMultiSheet.Size = new System.Drawing.Size(157, 17); this.checkBoxMultiSheet.TabIndex = 11; this.checkBoxMultiSheet.Text = "Make multisheet PDF/DWF"; this.checkBoxMultiSheet.UseVisualStyleBackColor = true; // // checkBoxPrint // this.checkBoxPrint.AutoSize = true; this.checkBoxPrint.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.checkBoxPrint.Location = new System.Drawing.Point(123, 380); this.checkBoxPrint.Name = "checkBoxPrint"; this.checkBoxPrint.Size = new System.Drawing.Size(64, 17); this.checkBoxPrint.TabIndex = 46; this.checkBoxPrint.Text = "PRINT"; this.checkBoxPrint.UseVisualStyleBackColor = true; // // cmbPlotDevicePDF // this.cmbPlotDevicePDF.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbPlotDevicePDF.FormattingEnabled = true; this.cmbPlotDevicePDF.Location = new System.Drawing.Point(124, 231); this.cmbPlotDevicePDF.Name = "cmbPlotDevicePDF"; this.cmbPlotDevicePDF.Size = new System.Drawing.Size(260, 21); this.cmbPlotDevicePDF.TabIndex = 43; this.cmbPlotDevicePDF.SelectedIndexChanged += new System.EventHandler(this.cmbPlotDevicePDF_SelectedIndexChanged); // // cmbPlotDeviceDWF // this.cmbPlotDeviceDWF.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbPlotDeviceDWF.FormattingEnabled = true; this.cmbPlotDeviceDWF.Location = new System.Drawing.Point(123, 315); this.cmbPlotDeviceDWF.Name = "cmbPlotDeviceDWF"; this.cmbPlotDeviceDWF.Size = new System.Drawing.Size(261, 21); this.cmbPlotDeviceDWF.TabIndex = 45; this.cmbPlotDeviceDWF.SelectedIndexChanged += new System.EventHandler(this.cmbPlotDeviceDWF_SelectedIndexChanged); // // cmbPaperSizePDF // this.cmbPaperSizePDF.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbPaperSizePDF.FormattingEnabled = true; this.cmbPaperSizePDF.Location = new System.Drawing.Point(124, 260); this.cmbPaperSizePDF.Name = "cmbPaperSizePDF"; this.cmbPaperSizePDF.Size = new System.Drawing.Size(260, 21); this.cmbPaperSizePDF.TabIndex = 48; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(4, 263); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(59, 13); this.label1.TabIndex = 47; this.label1.Text = "Paper size:"; // // buttonSavePath // this.buttonSavePath.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.buttonSavePath.Location = new System.Drawing.Point(351, 181); this.buttonSavePath.Name = "buttonSavePath"; this.buttonSavePath.Size = new System.Drawing.Size(33, 20); this.buttonSavePath.TabIndex = 15; this.buttonSavePath.Text = "..."; this.buttonSavePath.UseVisualStyleBackColor = true; this.buttonSavePath.Click += new System.EventHandler(this.buttonSavePath_Click); // // cmbPaperSizeDWF // this.cmbPaperSizeDWF.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbPaperSizeDWF.FormattingEnabled = true; this.cmbPaperSizeDWF.Location = new System.Drawing.Point(123, 348); this.cmbPaperSizeDWF.Name = "cmbPaperSizeDWF"; this.cmbPaperSizeDWF.Size = new System.Drawing.Size(261, 21); this.cmbPaperSizeDWF.TabIndex = 50; // // label_savePath_PDF // this.label_savePath_PDF.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label_savePath_PDF.Location = new System.Drawing.Point(4, 184); this.label_savePath_PDF.Name = "label_savePath_PDF"; this.label_savePath_PDF.Size = new System.Drawing.Size(104, 22); this.label_savePath_PDF.TabIndex = 16; this.label_savePath_PDF.Text = "Destination Folder:"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(6, 349); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(59, 13); this.label3.TabIndex = 49; this.label3.Text = "Paper size:"; // // textBoxSavePath // this.textBoxSavePath.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBoxSavePath.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBoxSavePath.Location = new System.Drawing.Point(124, 181); this.textBoxSavePath.Name = "textBoxSavePath"; this.textBoxSavePath.Size = new System.Drawing.Size(219, 20); this.textBoxSavePath.TabIndex = 14; // // textBoxDynamicBlockFrameName // this.textBoxDynamicBlockFrameName.Location = new System.Drawing.Point(126, 544); this.textBoxDynamicBlockFrameName.Name = "textBoxDynamicBlockFrameName"; this.textBoxDynamicBlockFrameName.Size = new System.Drawing.Size(258, 20); this.textBoxDynamicBlockFrameName.TabIndex = 36; // // labelFrameName // this.labelFrameName.AutoSize = true; this.labelFrameName.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.labelFrameName.Location = new System.Drawing.Point(3, 547); this.labelFrameName.Name = "labelFrameName"; this.labelFrameName.Size = new System.Drawing.Size(117, 13); this.labelFrameName.TabIndex = 37; this.labelFrameName.Text = "Drawing Frame Names:"; // // labelFrameLayout // this.labelFrameLayout.AutoSize = true; this.labelFrameLayout.Location = new System.Drawing.Point(3, 601); this.labelFrameLayout.Name = "labelFrameLayout"; this.labelFrameLayout.Size = new System.Drawing.Size(118, 13); this.labelFrameLayout.TabIndex = 51; this.labelFrameLayout.Text = "Name of Polyline Layer:"; // // textBoxFrameLayout // this.textBoxFrameLayout.Location = new System.Drawing.Point(127, 598); this.textBoxFrameLayout.Name = "textBoxFrameLayout"; this.textBoxFrameLayout.Size = new System.Drawing.Size(257, 20); this.textBoxFrameLayout.TabIndex = 52; // // groupBox2 // this.groupBox2.Controls.Add(this.checkBoxPlotTransparency); this.groupBox2.Controls.Add(this.checkBoxTurnOnViewPorts); this.groupBox2.Controls.Add(this.label12); this.groupBox2.Controls.Add(this.label11); this.groupBox2.Controls.Add(this.label10); this.groupBox2.Controls.Add(this.label9); this.groupBox2.Controls.Add(this.label8); this.groupBox2.Controls.Add(this.label7); this.groupBox2.Controls.Add(this.labelPrinterPlotter); this.groupBox2.Controls.Add(this.labelMessageToTheUser); this.groupBox2.Controls.Add(this.label5); this.groupBox2.Controls.Add(this.textBoxFrameLayout); this.groupBox2.Controls.Add(this.labelFrameLayout); this.groupBox2.Controls.Add(this.labelFrameName); this.groupBox2.Controls.Add(this.textBoxDynamicBlockFrameName); this.groupBox2.Controls.Add(this.textBoxSavePath); this.groupBox2.Controls.Add(this.label3); this.groupBox2.Controls.Add(this.label_savePath_PDF); this.groupBox2.Controls.Add(this.cmbPaperSizeDWF); this.groupBox2.Controls.Add(this.buttonSavePath); this.groupBox2.Controls.Add(this.label1); this.groupBox2.Controls.Add(this.cmbPaperSizePDF); this.groupBox2.Controls.Add(this.cmbPlotDeviceDWF); this.groupBox2.Controls.Add(this.cmbPlotDevicePDF); this.groupBox2.Controls.Add(this.checkBoxPrint); this.groupBox2.Controls.Add(this.checkBoxMultiSheet); this.groupBox2.Controls.Add(this.checkBoxDWF); this.groupBox2.Controls.Add(this.checkBoxPDF); this.groupBox2.Controls.Add(this.checkBoxIgnoreModelSpace); this.groupBox2.Controls.Add(this.labelOutputType); this.groupBox2.Controls.Add(this.cmbPlotDevicePrinter); this.groupBox2.Controls.Add(this.checkBoxPlotAllDWGs); this.groupBox2.Controls.Add(this.checkBoxCenterPlot); this.groupBox2.Controls.Add(this.textBoxSourcePath); this.groupBox2.Controls.Add(this.LabelSource); this.groupBox2.Controls.Add(this.buttonSourcePath); this.groupBox2.Controls.Add(this.label4); this.groupBox2.Controls.Add(this.labelInputType); this.groupBox2.Controls.Add(this.label2); this.groupBox2.Controls.Add(this.cmbPaperSizePrint); this.groupBox2.Controls.Add(this.checkBoxDXF); this.groupBox2.Controls.Add(this.cmbPlotStyleTables); this.groupBox2.Controls.Add(this.checkBoxDWG); this.groupBox2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.groupBox2.Location = new System.Drawing.Point(8, 12); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(400, 638); this.groupBox2.TabIndex = 42; this.groupBox2.TabStop = false; this.groupBox2.Text = "General Options"; // // checkBoxPlotTransparency // this.checkBoxPlotTransparency.AutoSize = true; this.checkBoxPlotTransparency.Location = new System.Drawing.Point(286, 487); this.checkBoxPlotTransparency.Name = "checkBoxPlotTransparency"; this.checkBoxPlotTransparency.Size = new System.Drawing.Size(112, 17); this.checkBoxPlotTransparency.TabIndex = 64; this.checkBoxPlotTransparency.Text = "Plot Transparency"; this.checkBoxPlotTransparency.UseVisualStyleBackColor = true; // // checkBoxTurnOnViewPorts // this.checkBoxTurnOnViewPorts.AutoSize = true; this.checkBoxTurnOnViewPorts.Location = new System.Drawing.Point(123, 486); this.checkBoxTurnOnViewPorts.Name = "checkBoxTurnOnViewPorts"; this.checkBoxTurnOnViewPorts.Size = new System.Drawing.Size(156, 17); this.checkBoxTurnOnViewPorts.TabIndex = 63; this.checkBoxTurnOnViewPorts.Text = "Turn On disabled Viewports"; this.checkBoxTurnOnViewPorts.UseVisualStyleBackColor = true; // // label12 // this.label12.AutoSize = true; this.label12.Font = new System.Drawing.Font("Georgia", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label12.ForeColor = System.Drawing.SystemColors.GrayText; this.label12.Location = new System.Drawing.Point(6, 618); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(342, 15); this.label12.TabIndex = 62; this.label12.Text = "Example:PLOTTI;FrameLayerName1;Layer245;Defpoints"; // // label11 // this.label11.AutoSize = true; this.label11.Font = new System.Drawing.Font("Georgia", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label11.ForeColor = System.Drawing.SystemColors.GrayText; this.label11.Location = new System.Drawing.Point(7, 572); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(363, 15); this.label11.TabIndex = 61; this.label11.Text = "Example: DrawingFrame1;DrawingFrame2;DrawingFrame3"; // // label10 // this.label10.AutoSize = true; this.label10.Location = new System.Drawing.Point(4, 412); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(75, 13); this.label10.TabIndex = 60; this.label10.Text = "Plotter/Printer:"; // // label9 // this.label9.AutoSize = true; this.label9.Location = new System.Drawing.Point(4, 381); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(81, 13); this.label9.TabIndex = 59; this.label9.Text = "Print/Plot Files :"; // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(4, 319); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(75, 13); this.label8.TabIndex = 58; this.label8.Text = "Plotter/Printer:"; // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(4, 291); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(92, 13); this.label7.TabIndex = 57; this.label7.Text = "Make DWF Files :"; // // labelPrinterPlotter // this.labelPrinterPlotter.AutoSize = true; this.labelPrinterPlotter.Location = new System.Drawing.Point(4, 238); this.labelPrinterPlotter.Name = "labelPrinterPlotter"; this.labelPrinterPlotter.Size = new System.Drawing.Size(75, 13); this.labelPrinterPlotter.TabIndex = 56; this.labelPrinterPlotter.Text = "Plotter/Printer:"; // // labelMessageToTheUser // this.labelMessageToTheUser.AutoSize = true; this.labelMessageToTheUser.Font = new System.Drawing.Font("Georgia", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelMessageToTheUser.ForeColor = System.Drawing.SystemColors.MenuHighlight; this.labelMessageToTheUser.Location = new System.Drawing.Point(68, 25); this.labelMessageToTheUser.Name = "labelMessageToTheUser"; this.labelMessageToTheUser.Size = new System.Drawing.Size(254, 14); this.labelMessageToTheUser.TabIndex = 54; this.labelMessageToTheUser.Text = "Please Fill The Follwing Form Correctly"; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(184, 59); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(16, 13); this.label5.TabIndex = 53; this.label5.Text = "or"; // // buttonSelect_UnselectFiles // this.buttonSelect_UnselectFiles.Location = new System.Drawing.Point(14, 582); this.buttonSelect_UnselectFiles.Name = "buttonSelect_UnselectFiles"; this.buttonSelect_UnselectFiles.Size = new System.Drawing.Size(186, 24); this.buttonSelect_UnselectFiles.TabIndex = 14; this.buttonSelect_UnselectFiles.Text = "Select/Unselect all files"; this.buttonSelect_UnselectFiles.UseVisualStyleBackColor = true; this.buttonSelect_UnselectFiles.Click += new System.EventHandler(this.buttonSelect_Unselect_Click); // // LayoutNameList // this.LayoutNameList.FormattingEnabled = true; this.LayoutNameList.HorizontalScrollbar = true; this.LayoutNameList.Location = new System.Drawing.Point(226, 44); this.LayoutNameList.Name = "LayoutNameList"; this.LayoutNameList.Size = new System.Drawing.Size(200, 529); this.LayoutNameList.Sorted = true; this.LayoutNameList.TabIndex = 13; this.LayoutNameList.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler(this.LayoutNames_ItemCheck); this.LayoutNameList.MouseDown += new System.Windows.Forms.MouseEventHandler(this.LayoutNameList_MouseDown); // // DwgNameList // this.DwgNameList.FormattingEnabled = true; this.DwgNameList.HorizontalScrollbar = true; this.DwgNameList.Location = new System.Drawing.Point(11, 44); this.DwgNameList.Name = "DwgNameList"; this.DwgNameList.Size = new System.Drawing.Size(200, 529); this.DwgNameList.Sorted = true; this.DwgNameList.TabIndex = 12; this.DwgNameList.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler(this.DwgNameList_ItemCheck); this.DwgNameList.SelectedIndexChanged += new System.EventHandler(this.DwgNameList_SelectedIndexChanged); this.DwgNameList.MouseDown += new System.Windows.Forms.MouseEventHandler(this.DwgNameList_MouseDown); // // labelDrawings // this.labelDrawings.AutoSize = true; this.labelDrawings.Font = new System.Drawing.Font("Georgia", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelDrawings.ForeColor = System.Drawing.SystemColors.MenuHighlight; this.labelDrawings.Location = new System.Drawing.Point(11, 25); this.labelDrawings.Name = "labelDrawings"; this.labelDrawings.Size = new System.Drawing.Size(135, 14); this.labelDrawings.TabIndex = 14; this.labelDrawings.Text = "Drawings Name List"; // // label6 // this.label6.AutoSize = true; this.label6.Font = new System.Drawing.Font("Georgia", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label6.ForeColor = System.Drawing.SystemColors.MenuHighlight; this.label6.Location = new System.Drawing.Point(227, 25); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(126, 14); this.label6.TabIndex = 15; this.label6.Text = "Layouts Name List"; // // BoxDwgLayout // this.BoxDwgLayout.Anchor = System.Windows.Forms.AnchorStyles.Top; this.BoxDwgLayout.Controls.Add(this.buttonSelect_UnselectLayouts); this.BoxDwgLayout.Controls.Add(this.buttonSelect_UnselectFiles); this.BoxDwgLayout.Controls.Add(this.label6); this.BoxDwgLayout.Controls.Add(this.labelDrawings); this.BoxDwgLayout.Controls.Add(this.DwgNameList); this.BoxDwgLayout.Controls.Add(this.LayoutNameList); this.BoxDwgLayout.Location = new System.Drawing.Point(418, 12); this.BoxDwgLayout.Name = "BoxDwgLayout"; this.BoxDwgLayout.Size = new System.Drawing.Size(438, 612); this.BoxDwgLayout.TabIndex = 43; this.BoxDwgLayout.TabStop = false; this.BoxDwgLayout.Text = "Drawings Options"; // // buttonSelect_UnselectLayouts // this.buttonSelect_UnselectLayouts.Location = new System.Drawing.Point(230, 582); this.buttonSelect_UnselectLayouts.Name = "buttonSelect_UnselectLayouts"; this.buttonSelect_UnselectLayouts.Size = new System.Drawing.Size(186, 24); this.buttonSelect_UnselectLayouts.TabIndex = 16; this.buttonSelect_UnselectLayouts.Text = "Select/Unselect All layouts"; this.buttonSelect_UnselectLayouts.UseVisualStyleBackColor = true; this.buttonSelect_UnselectLayouts.Click += new System.EventHandler(this.buttonSelect_UnselectLayouts_Click); // // PlotterForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(866, 662); this.Controls.Add(this.BoxDwgLayout); this.Controls.Add(this.groupBox2); this.Controls.Add(this.buttonExit); this.Controls.Add(this.buttonPlot); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.KeyPreview = true; this.MaximizeBox = false; this.MaximumSize = new System.Drawing.Size(1200, 900); this.MinimizeBox = false; this.MinimumSize = new System.Drawing.Size(872, 39); this.Name = "PlotterForm"; this.Text = "KojtoCAD Plotter"; this.Load += new System.EventHandler(this.PlotterForm_Load); this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.PlotterForm_KeyPress); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.BoxDwgLayout.ResumeLayout(false); this.BoxDwgLayout.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button buttonExit; private System.Windows.Forms.Button buttonPlot; private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog; private System.Windows.Forms.OpenFileDialog openFileDialog; private System.Windows.Forms.CheckBox checkBoxDWG; private System.Windows.Forms.ComboBox cmbPlotStyleTables; private System.Windows.Forms.CheckBox checkBoxDXF; private System.Windows.Forms.ComboBox cmbPaperSizePrint; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label labelInputType; private System.Windows.Forms.Label label4; private System.Windows.Forms.Button buttonSourcePath; private System.Windows.Forms.Label LabelSource; private System.Windows.Forms.TextBox textBoxSourcePath; private System.Windows.Forms.CheckBox checkBoxCenterPlot; private System.Windows.Forms.CheckBox checkBoxPlotAllDWGs; private System.Windows.Forms.ComboBox cmbPlotDevicePrinter; private System.Windows.Forms.Label labelOutputType; private System.Windows.Forms.CheckBox checkBoxIgnoreModelSpace; private System.Windows.Forms.CheckBox checkBoxPDF; private System.Windows.Forms.CheckBox checkBoxDWF; private System.Windows.Forms.CheckBox checkBoxMultiSheet; private System.Windows.Forms.CheckBox checkBoxPrint; private System.Windows.Forms.ComboBox cmbPlotDevicePDF; private System.Windows.Forms.ComboBox cmbPlotDeviceDWF; private System.Windows.Forms.ComboBox cmbPaperSizePDF; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button buttonSavePath; private System.Windows.Forms.ComboBox cmbPaperSizeDWF; private System.Windows.Forms.Label label_savePath_PDF; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox textBoxSavePath; private System.Windows.Forms.TextBox textBoxDynamicBlockFrameName; private System.Windows.Forms.Label labelFrameName; private System.Windows.Forms.Label labelFrameLayout; private System.Windows.Forms.TextBox textBoxFrameLayout; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label labelMessageToTheUser; private System.Windows.Forms.Label labelPrinterPlotter; private System.Windows.Forms.Label label9; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label10; private System.Windows.Forms.Label label11; private System.Windows.Forms.Label label12; private System.Windows.Forms.Button buttonSelect_UnselectFiles; private System.Windows.Forms.CheckedListBox LayoutNameList; private System.Windows.Forms.CheckedListBox DwgNameList; private System.Windows.Forms.Label labelDrawings; private System.Windows.Forms.Label label6; private System.Windows.Forms.GroupBox BoxDwgLayout; private System.Windows.Forms.Button buttonSelect_UnselectLayouts; private System.Windows.Forms.CheckBox checkBoxTurnOnViewPorts; private System.Windows.Forms.CheckBox checkBoxPlotTransparency; } }
// 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.Composition.Runtime.Util; using System.Linq; namespace System.Composition.Hosting.Core { /// <summary> /// The link between exports and imports. /// </summary> public sealed class CompositionContract { private readonly Type _contractType; private readonly string _contractName; private readonly IDictionary<string, object> _metadataConstraints; /// <summary> /// Construct a <see cref="CompositionContract"/>. /// </summary> /// <param name="contractType">The type shared between the exporter and importer.</param> public CompositionContract(Type contractType) : this(contractType, null) { } /// <summary> /// Construct a <see cref="CompositionContract"/>. /// </summary> /// <param name="contractType">The type shared between the exporter and importer.</param> /// <param name="contractName">Optionally, a name that discriminates this contract from others with the same type.</param> public CompositionContract(Type contractType, string contractName) : this(contractType, contractName, null) { } /// <summary> /// Construct a <see cref="CompositionContract"/>. /// </summary> /// <param name="contractType">The type shared between the exporter and importer.</param> /// <param name="contractName">Optionally, a name that discriminates this contract from others with the same type.</param> /// <param name="metadataConstraints">Optionally, a non-empty collection of named constraints that apply to the contract.</param> public CompositionContract(Type contractType, string contractName, IDictionary<string, object> metadataConstraints) { if (contractType == null) throw new ArgumentNullException(nameof(contractType)); if (metadataConstraints != null && metadataConstraints.Count == 0) throw new ArgumentOutOfRangeException(nameof(metadataConstraints)); _contractType = contractType; _contractName = contractName; _metadataConstraints = metadataConstraints; } /// <summary> /// The type shared between the exporter and importer. /// </summary> public Type ContractType { get { return _contractType; } } /// <summary> /// A name that discriminates this contract from others with the same type. /// </summary> public string ContractName { get { return _contractName; } } /// <summary> /// Constraints applied to the contract. Instead of using this collection /// directly it is advisable to use the <see cref="TryUnwrapMetadataConstraint"/> method. /// </summary> public IEnumerable<KeyValuePair<string, object>> MetadataConstraints { get { return _metadataConstraints; } } /// <summary> /// Determines equality between two contracts. /// </summary> /// <param name="obj">The contract to test.</param> /// <returns>True if the contracts are equivalent; otherwise, false.</returns> public override bool Equals(object obj) { var contract = obj as CompositionContract; return contract != null && contract._contractType.Equals(_contractType) && (_contractName == null ? contract._contractName == null : _contractName.Equals(contract._contractName)) && ConstraintEqual(_metadataConstraints, contract._metadataConstraints); } /// <summary> /// Gets a hash code for the contract. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { var hc = _contractType.GetHashCode(); if (_contractName != null) hc = hc ^ _contractName.GetHashCode(); if (_metadataConstraints != null) hc = hc ^ ConstraintHashCode(_metadataConstraints); return hc; } /// <summary> /// Creates a string representation of the contract. /// </summary> /// <returns>A string representation of the contract.</returns> public override string ToString() { var result = Formatters.Format(_contractType); if (_contractName != null) result += " " + Formatters.Format(_contractName); if (_metadataConstraints != null) result += string.Format(" {{ {0} }}", string.Join(Properties.Resources.Formatter_ListSeparatorWithSpace, _metadataConstraints.Select(kv => string.Format("{0} = {1}", kv.Key, Formatters.Format(kv.Value))))); return result; } /// <summary> /// Transform the contract into a matching contract with a /// new contract type (with the same contract name and constraints). /// </summary> /// <param name="newContractType">The contract type for the new contract.</param> /// <returns>A matching contract with a /// new contract type.</returns> public CompositionContract ChangeType(Type newContractType) { if (newContractType == null) throw new ArgumentNullException(nameof(newContractType)); return new CompositionContract(newContractType, _contractName, _metadataConstraints); } /// <summary> /// Check the contract for a constraint with a particular name and value, and, if it exists, /// retrieve both the value and the remainder of the contract with the constraint /// removed. /// </summary> /// <typeparam name="T">The type of the constraint value.</typeparam> /// <param name="constraintName">The name of the constraint.</param> /// <param name="constraintValue">The value if it is present and of the correct type, otherwise null.</param> /// <param name="remainingContract">The contract with the constraint removed if present, otherwise null.</param> /// <returns>True if the constraint is present and of the correct type, otherwise false.</returns> public bool TryUnwrapMetadataConstraint<T>(string constraintName, out T constraintValue, out CompositionContract remainingContract) { if (constraintName == null) throw new ArgumentNullException(nameof(constraintName)); constraintValue = default(T); remainingContract = null; if (_metadataConstraints == null) return false; object value; if (!_metadataConstraints.TryGetValue(constraintName, out value)) return false; if (!(value is T)) return false; constraintValue = (T)value; if (_metadataConstraints.Count == 1) { remainingContract = new CompositionContract(_contractType, _contractName); } else { var remainingConstraints = new Dictionary<string, object>(_metadataConstraints); remainingConstraints.Remove(constraintName); remainingContract = new CompositionContract(_contractType, _contractName, remainingConstraints); } return true; } internal static bool ConstraintEqual(IDictionary<string, object> first, IDictionary<string, object> second) { if (first == second) return true; if (first == null || second == null) return false; if (first.Count != second.Count) return false; foreach (var firstItem in first) { object secondValue; if (!second.TryGetValue(firstItem.Key, out secondValue)) return false; if (firstItem.Value == null && secondValue != null || secondValue == null && firstItem.Value != null) { return false; } else { var firstEnumerable = firstItem.Value as IEnumerable; if (firstEnumerable != null && !(firstEnumerable is string)) { var secondEnumerable = secondValue as IEnumerable; if (secondEnumerable == null || !Enumerable.SequenceEqual(firstEnumerable.Cast<object>(), secondEnumerable.Cast<object>())) return false; } else if (!firstItem.Value.Equals(secondValue)) { return false; } } } return true; } private static int ConstraintHashCode(IDictionary<string, object> metadata) { var result = -1; foreach (var kv in metadata) { result ^= kv.Key.GetHashCode(); if (kv.Value != null) { var sval = kv.Value as string; if (sval != null) { result ^= sval.GetHashCode(); } else { var enumerableValue = kv.Value as IEnumerable; if (enumerableValue != null) { foreach (var ev in enumerableValue) if (ev != null) result ^= ev.GetHashCode(); } else { result ^= kv.Value.GetHashCode(); } } } } return result; } } }
//Copyright (c) Microsoft Corporation. All rights reserved. using System; using System.Collections.Generic; using System.Text; using System.ServiceModel; using System.ServiceModel.Channels; using System.Data.SqlClient; using System.Data; namespace Microsoft.Samples.SsbTransportChannel { delegate Message ReceiveDelegate(TimeSpan timeout); delegate void CloseDelegate(TimeSpan timeout); delegate void OpenDelegate(TimeSpan timeout); public static class SsbHelper { internal static SqlConnection GetConnection(String connectionString) { SqlConnection con = new System.Data.SqlClient.SqlConnection(connectionString); SqlConnectionLifetimeTracker.TrackSqlConnectionLifetime(con); return con; } internal static bool IsValidSsbAddress(Uri uri) { // valid format is net.ssb://hostname/servicename if (uri.Scheme == SsbConstants.Scheme && uri.Port == -1 && !String.IsNullOrEmpty(uri.PathAndQuery) && uri.PathAndQuery != "/") { return true; } else { return false; } } internal static string GetServiceName(Uri uri) { return new SsbUri(uri).Service; } internal static ServiceInfo GetServiceInfo(string serviceName, TimeSpan timeout, string connstr) { using (SqlConnection con = SsbHelper.GetConnection(connstr)) { con.Open(); return GetServiceInfo(serviceName, timeout, con); } } internal static ServiceInfo GetServiceInfo(string serviceName, TimeSpan timeout, SqlConnection con) { TimeoutHelper helper=new TimeoutHelper(timeout); ServiceInfo info = null; string SQL = @" select s.name As ServiceName , s.service_id As ServiceId , q.name As QueueName , q.object_id As QueueId from sys.services s inner join sys.service_queues q on s.service_queue_id=q.object_id where s.name=@ServiceName"; SqlCommand cmd = new SqlCommand(SQL, con); cmd.Parameters.Add("@ServiceName", SqlDbType.VarChar).Value = serviceName; cmd.CommandTimeout = helper.RemainingTimeInMillisecondsOrZero(); try { using (SqlDataReader rdr = cmd.ExecuteReader()) { if (!rdr.Read()) { throw new CommunicationException(string.Format("Service {0} not found", serviceName)); } info = new ServiceInfo(); info.ServiceName = rdr.GetString(0); info.ServiceId = rdr.GetInt32(1); info.QueueName = rdr.GetString(2); info.QueueId = rdr.GetInt32(3); rdr.Close(); } } catch (SqlException ex) { if (!helper.IsTimeRemaining) { throw new TimeoutException(String.Format("Timed out while getting service information. Timeout value was {0} seconds",timeout.TotalSeconds),ex); } else { throw new CommunicationException("An exception occurred while getting service information", ex); } } return info; } static string forbiddenCharacters = "[]'\"\r\n\t"; static char[] arrForbiddenCharacters = forbiddenCharacters.ToCharArray(); /// <summary> /// A quick check for SQL escape characters and delimiters. Identifiers should /// follow the rules for SQL Server Regular Identifiers. In case they don't /// the binding will automatically apply the delimiters. Delimiters embedded in the /// identifier should be avoided as they are confusing and a security risk. Eg configure /// the binding to use contract "My Contract", instead of "[My Contract]". /// </summary> /// <param name="identifier"></param> internal static string ValidateIdentifier(string identifier) { if (identifier.IndexOfAny(arrForbiddenCharacters) != -1) { throw new ArgumentException("Identifer contains an illegal character ([]'\"\r\n\t). "); } return identifier; } internal static void SetConversationTimer(Guid conversationHandle, TimeSpan timerTimeout, string connstr) { using (SqlConnection con = SsbHelper.GetConnection(connstr)) { con.Open(); SetConversationTimer(conversationHandle, timerTimeout, con); } } internal static void SetConversationTimer(Guid conversationHandle, TimeSpan timerTimeout, SqlConnection con) { double totalSeconds = Math.Round(timerTimeout.TotalSeconds, MidpointRounding.AwayFromZero); int timeoutSeconds; if (totalSeconds > 2147483646d) { timeoutSeconds = 2147483646; } else if (totalSeconds < 1) { timeoutSeconds = 1; } else { timeoutSeconds = (int)totalSeconds; } string sql = @"BEGIN CONVERSATION TIMER ( @conversation_handle ) TIMEOUT = @timeout "; SqlCommand cmd = new SqlCommand(sql, con); cmd.Parameters.Add("@conversation_handle", SqlDbType.UniqueIdentifier).Value = conversationHandle; cmd.Parameters.Add("@timeout", SqlDbType.Int).Value = timeoutSeconds; cmd.ExecuteNonQuery(); } internal static ConversationInfo GetConversationInfo(Guid conversationHandle, string constr) { using (SqlConnection con = SsbHelper.GetConnection(constr)) { con.Open(); return GetConversationInfo(conversationHandle, con); } } internal static ConversationInfo GetConversationInfo(Guid conversationHandle, SqlConnection con) { #region Build SqlCommand cmd string SQL = @" select @ConversationGroupId = ce.conversation_group_id, @ConversationId = ce.conversation_id, @ServiceName = s.name, @TargetServiceName = ce.far_service, @QueueName = q.name, @State = ce.state from sys.conversation_endpoints ce join sys.services s on ce.service_id = s.service_id join sys.service_queue_usages u on u.service_id = s.service_id join sys.service_queues q on q.object_id = u.service_queue_id where ce.conversation_handle = @ConversationHandle; if @@rowcount = 0 begin --raiserror('No Service Broker conversation found with handle: %s',16,1,@ConversationHandle); raiserror('Service Broker conversation not found.',16,1); end "; SqlCommand cmd = new SqlCommand(SQL, con); SqlParameter pConversationId = cmd.Parameters.Add("@ConversationId", SqlDbType.UniqueIdentifier); pConversationId.Direction = ParameterDirection.Output; SqlParameter pConversationGroupId = cmd.Parameters.Add("@ConversationGroupId", SqlDbType.UniqueIdentifier); pConversationGroupId.Direction = ParameterDirection.Output; SqlParameter pServiceName = cmd.Parameters.Add("@ServiceName", SqlDbType.VarChar); pServiceName.Size = 30; pServiceName.Direction = ParameterDirection.Output; SqlParameter pTargetServiceName = cmd.Parameters.Add("@TargetServiceName", SqlDbType.VarChar); pTargetServiceName.Size = 30; pTargetServiceName.Direction = ParameterDirection.Output; SqlParameter pQueueName = cmd.Parameters.Add("@QueueName", SqlDbType.VarChar); pQueueName.Size = 30; pQueueName.Direction = ParameterDirection.Output; SqlParameter pState = cmd.Parameters.Add("@State", SqlDbType.Char); pState.Size = 2; pState.Direction = ParameterDirection.Output; SqlParameter pConversationHandle = cmd.Parameters.Add("@ConversationHandle", SqlDbType.UniqueIdentifier); pConversationHandle.Value = conversationHandle; #endregion try { cmd.ExecuteNonQuery(); } catch (SqlException ex) { throw new CommunicationException("An exception occurred while getting service information", ex); } string state = (string)pState.Value; if (state != "CO" && state != "SO") { throw new InvalidOperationException("Cannot open conversation in state " + ConversationInfo.GetTransmissionStateDescription(state)); } string serviceName = (string)pServiceName.Value; string targetServiceName = (string)pTargetServiceName.Value; string queueName = (string)pQueueName.Value; Guid conversationId = (Guid)pConversationId.Value; Guid conversationGroupId = (Guid)pConversationGroupId.Value; ConversationInfo ci = new ConversationInfo(serviceName, queueName, targetServiceName, conversationId, conversationHandle, conversationGroupId, state); return ci; } public static int EndAllConversationsWithCleanup(string connstr) { using (SqlConnection con = SsbHelper.GetConnection(connstr)) { con.Open(); return EndAllConversationsWithCleanup(con); } } internal static int EndAllConversationsWithCleanup(SqlConnection con) { string SQL = @" declare conversations cursor local for select conversation_handle from sys.conversation_endpoints where not (state='CD' and is_initiator=0) declare @ConversationHandle uniqueidentifier declare @count int set @count = 0 open conversations fetch next from conversations into @ConversationHandle while @@fetch_status = 0 begin set @count = @count + 1 end conversation @ConversationHandle with cleanup; fetch next from conversations into @ConversationHandle end select @count conversations_ended "; using (SqlCommand cmd = new SqlCommand(SQL, con)) { return (int)cmd.ExecuteScalar(); } } public static void EndConversationWithCleanup(string connstr, Guid conversationHandle) { using (SqlConnection con = SsbHelper.GetConnection(connstr)) { con.Open(); EndConversationWithCleanup(con, conversationHandle); } } internal static void EndConversationWithCleanup(SqlConnection con, Guid conversationHandle) { string SQL = @"END CONVERSATION @Conversation WITH CLEANUP"; using (SqlCommand cmd = new SqlCommand(SQL, con)) { SqlParameter pConversation = cmd.Parameters.Add("@Conversation", SqlDbType.UniqueIdentifier); pConversation.Value = conversationHandle; cmd.ExecuteNonQuery(); } } internal static string CheckConversationForErrorMessage(string connstr, Guid conversationHandle) { using (SqlConnection con = SsbHelper.GetConnection(connstr)) { con.Open(); return CheckConversationForErrorMessage(con, conversationHandle); } } internal static string CheckConversationForErrorMessage(SqlConnection con, Guid conversationHandle) { #region Build SqlCommand cmd string SQL = @" declare @queueName varchar(200) set @queueName = ( select sq.name queue_name from sys.conversation_endpoints ce join sys.services s on s.service_id = ce.service_id join sys.service_queue_usages squ on s.service_id = squ.service_id join sys.service_queues sq on squ.service_queue_id = sq.object_id where conversation_handle = @Conversation ) declare @sql nvarchar(max) declare @msg xml set @sql = N'select @m=cast(message_body as xml) from [' + @queueName + '] with (nolock) where message_type_id = 1 and conversation_handle = @ch' --print @sql exec sp_executesql @sql, N'@ch uniqueidentifier, @m xml output',@ch=@Conversation, @m=@msg out if @msg is not null begin ;with xmlnamespaces ('http://schemas.microsoft.com/SQL/ServiceBroker/Error' as e) select @ErrorMessage = E.Error.value('(e:Code)[1]','nvarchar(max)') + ': ' + E.Error.value('(e:Description)[1]','nvarchar(max)') from @msg.nodes('/e:Error') as E(Error) end "; #endregion using (SqlCommand cmd = new SqlCommand(SQL, con)) { SqlParameter pConversation = cmd.Parameters.Add("@Conversation", SqlDbType.UniqueIdentifier); pConversation.Value = conversationHandle; SqlParameter pErrorMessage = cmd.Parameters.Add("@ErrorMessage", SqlDbType.NVarChar, 500); pErrorMessage.Direction = ParameterDirection.Output; cmd.ExecuteNonQuery(); string errorMessage = pErrorMessage.Value as string; return errorMessage; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Text.Utf8; using Newtonsoft.Json; using JsonReader = System.Text.Json.JsonReader; using JsonWriter = System.Text.Json.JsonWriter; using JsonParser = System.Text.Json.JsonParser; using System.Text.Formatting; using System.Text; using System.IO; using Newtonsoft.Json.Linq; namespace Json.Net.Tests { internal class JsonNetComparison { private const int NumberOfIterations = 10; private const int NumberOfSamples = 10; private const bool OutputResults = true; private const bool OutputJsonData = false; private static readonly Stopwatch Timer = new Stopwatch(); private static readonly List<long> TimingResultsJsonNet = new List<long>(); private static readonly List<long> TimingResultsJsonReader = new List<long>(); private static void Main() { RunParserTest(); RunWriterTest(); RunReaderTest(); //Console.Read(); } private static void RunReaderTest() { Output("====== TEST Read ======"); // Do not test first iteration ReaderTestJsonNet(TestJson.Json3KB, false); ReaderTestJsonNet(TestJson.Json30KB, false); ReaderTestJsonNet(TestJson.Json300KB, false); ReaderTestJsonNet(TestJson.Json3MB, false); Output("Json.NET Timing Results"); for (int i = 0; i < NumberOfSamples; i++) { ReaderTestJsonNet(TestJson.Json3KB, OutputResults); ReaderTestJsonNet(TestJson.Json30KB, OutputResults); ReaderTestJsonNet(TestJson.Json300KB, OutputResults); ReaderTestJsonNet(TestJson.Json3MB, OutputResults); } // Do not test first iteration ReaderTestSystemTextJson(TestJson.Json3KB, false); ReaderTestSystemTextJson(TestJson.Json30KB, false); ReaderTestSystemTextJson(TestJson.Json300KB, false); ReaderTestSystemTextJson(TestJson.Json3MB, false); Output("System.Text.Json Timing Results"); for (int i = 0; i < NumberOfSamples; i++) { ReaderTestSystemTextJson(TestJson.Json3KB, OutputResults); ReaderTestSystemTextJson(TestJson.Json30KB, OutputResults); ReaderTestSystemTextJson(TestJson.Json300KB, OutputResults); ReaderTestSystemTextJson(TestJson.Json3MB, OutputResults); } } private static void ReaderTestJsonNet(string str, bool output) { Timer.Restart(); for (var i = 0; i < NumberOfIterations; i++) { JsonNetReaderHelper(new StringReader(str), OutputJsonData); } if (output) Console.WriteLine(Timer.ElapsedTicks); } private static void JsonNetReaderHelper(TextReader str, bool output) { var reader = new JsonTextReader(str); while (reader.Read()) { if (reader.Value != null) { // ReSharper disable once UnusedVariable var x = reader.TokenType; // ReSharper disable once UnusedVariable var y = reader.Value; if (output) Console.WriteLine(y); } else { // ReSharper disable once UnusedVariable var z = reader.TokenType; if (output) Console.WriteLine(z); } } } private static void ReaderTestSystemTextJson(string str, bool output) { var utf8Str = new Utf8Span(str); Timer.Restart(); for (var i = 0; i < NumberOfIterations; i++) { JsonReaderHelper(utf8Str, OutputJsonData); } if (output) Console.WriteLine(Timer.ElapsedTicks); } private static void JsonReaderHelper(Utf8Span str, bool output) { var reader = new JsonReader(str); while (reader.Read()) { var tokenType = reader.TokenType; switch (tokenType) { case JsonReader.JsonTokenType.ObjectStart: case JsonReader.JsonTokenType.ObjectEnd: case JsonReader.JsonTokenType.ArrayStart: case JsonReader.JsonTokenType.ArrayEnd: if (output) Console.WriteLine(tokenType); break; case JsonReader.JsonTokenType.Property: var name = reader.GetName(); if (output) Console.WriteLine(name); var value = reader.GetValue(); if (output) Console.WriteLine(value); break; case JsonReader.JsonTokenType.Value: value = reader.GetValue(); if (output) Console.WriteLine(value); break; default: throw new ArgumentOutOfRangeException(); } } } private static void RunParserTest() { Output("====== TEST Parse ======"); // Do not test first iteration ParserTestJsonNet(TestJson.Json3KB, false); ParserTestJsonNet(TestJson.Json30KB, false); ParserTestJsonNet(TestJson.Json300KB, false); ParserTestJsonNet(TestJson.Json3MB, false); Output("Json.NET Timing Results"); for (int i = 0; i < NumberOfSamples; i++) { ParserTestJsonNet(TestJson.Json3KB, OutputResults); ParserTestJsonNet(TestJson.Json30KB, OutputResults); ParserTestJsonNet(TestJson.Json300KB, OutputResults); ParserTestJsonNet(TestJson.Json3MB, OutputResults); } // Do not test first iteration ParserTestSystemTextJson(TestJson.Json3KB, 3, false); ParserTestSystemTextJson(TestJson.Json30KB, 30, false); ParserTestSystemTextJson(TestJson.Json300KB, 300, false); ParserTestSystemTextJson(TestJson.Json3MB, 3000, false); Output("System.Text.Json Timing Results"); for (int i = 0; i < NumberOfSamples; i++) { ParserTestSystemTextJson(TestJson.Json3KB, 3, OutputResults); ParserTestSystemTextJson(TestJson.Json30KB, 30, OutputResults); ParserTestSystemTextJson(TestJson.Json300KB, 300, OutputResults); ParserTestSystemTextJson(TestJson.Json3MB, 3000, OutputResults); } } private static void ParserTestSystemTextJson(string str, int numElements, bool timeResults) { int strLength = str.Length; int byteLength = strLength * 2; var buffer = new byte[byteLength]; for (var j = 0; j < strLength; j++) { buffer[j] = (byte)str[j]; } SystemTextParserHelper(buffer, strLength, numElements, timeResults); } private static void SystemTextParserHelper(byte[] buffer, int strLength, int numElements, bool timeResults) { if (timeResults) Timer.Restart(); var json = new JsonParser(buffer, strLength); var parseObject = json.Parse(); if (timeResults) Console.WriteLine("Parse: " + Timer.ElapsedTicks); if (timeResults) Timer.Restart(); for (int i = 0; i < numElements; i++) { var xElement = parseObject[i]; var id = (Utf8Span)xElement["_id"]; var index = (int)xElement["index"]; var guid = (Utf8Span)xElement["guid"]; var isActive = (bool)xElement["isActive"]; var balance = (Utf8Span)xElement["balance"]; var picture = (Utf8Span)xElement["picture"]; var age = (int)xElement["age"]; var eyeColor = (Utf8Span)xElement["eyeColor"]; var name = (Utf8Span)xElement["name"]; var gender = (Utf8Span)xElement["gender"]; var company = (Utf8Span)xElement["company"]; var email = (Utf8Span)xElement["email"]; var phone = (Utf8Span)xElement["phone"]; var address = (Utf8Span)xElement["address"]; var about = (Utf8Span)xElement["about"]; var registered = (Utf8Span)xElement["registered"]; var latitude = (double)xElement["latitude"]; var longitude = (double)xElement["longitude"]; var tags = xElement["tags"]; var tags1 = (Utf8Span)tags[0]; var tags2 = (Utf8Span)tags[1]; var tags3 = (Utf8Span)tags[2]; var tags4 = (Utf8Span)tags[3]; var tags5 = (Utf8Span)tags[4]; var tags6 = (Utf8Span)tags[5]; var tags7 = (Utf8Span)tags[6]; var friends = xElement["friends"]; var friend1 = friends[0]; var friend2 = friends[1]; var friend3 = friends[2]; var id1 = (int)friend1["id"]; var friendName1 = (Utf8Span)friend1["name"]; var id2 = (int)friend2["id"]; var friendName2 = (Utf8Span)friend2["name"]; var id3 = (int)friend3["id"]; var friendName3 = (Utf8Span)friend3["name"]; var greeting = (Utf8Span)xElement["greeting"]; var favoriteFruit = (Utf8Span)xElement["favoriteFruit"]; } if (timeResults) Console.WriteLine("Access: " + Timer.ElapsedTicks); } private static void ParserTestJsonNet(string str, bool timeResults) { if (timeResults) Timer.Restart(); JArray parseObject = JArray.Parse(str); if (timeResults) Console.WriteLine("Parse: " + Timer.ElapsedTicks); if (timeResults) Timer.Restart(); for (int i = 0; i < parseObject.Count; i++) { var xElement = parseObject[i]; var id = (string)xElement["_id"]; var index = (int)xElement["index"]; var guid = (string)xElement["guid"]; var isActive = (bool)xElement["isActive"]; var balance = (string)xElement["balance"]; var picture = (string)xElement["picture"]; var age = (int)xElement["age"]; var eyeColor = (string)xElement["eyeColor"]; var name = (string)xElement["name"]; var gender = (string)xElement["gender"]; var company = (string)xElement["company"]; var email = (string)xElement["email"]; var phone = (string)xElement["phone"]; var address = (string)xElement["address"]; var about = (string)xElement["about"]; var registered = (string)xElement["registered"]; var latitude = (double)xElement["latitude"]; var longitude = (double)xElement["longitude"]; var tags = xElement["tags"]; var tags1 = (string)tags[0]; var tags2 = (string)tags[1]; var tags3 = (string)tags[2]; var tags4 = (string)tags[3]; var tags5 = (string)tags[4]; var tags6 = (string)tags[5]; var tags7 = (string)tags[6]; var friends = xElement["friends"]; var friend1 = friends[0]; var friend2 = friends[1]; var friend3 = friends[2]; var id1 = (int)friend1["id"]; var friendName1 = (string)friend1["name"]; var id2 = (int)friend2["id"]; var friendName2 = (string)friend2["name"]; var id3 = (int)friend3["id"]; var friendName3 = (string)friend3["name"]; var greeting = (string)xElement["greeting"]; var favoriteFruit = (string)xElement["favoriteFruit"]; } if (timeResults) Console.WriteLine("Access: " + Timer.ElapsedTicks); } private static void ParsingAccess3MBBreakdown(string str, bool timeResults) { int strLength = str.Length; int byteLength = strLength * 2; var buffer = new byte[byteLength]; for (var j = 0; j < strLength; j++) { buffer[j] = (byte)str[j]; } int iter = 10; var json = new JsonParser(buffer, strLength); var parseObject = json.Parse(); var xElement = parseObject[1500]; if (timeResults) Timer.Restart(); for (int i = 0; i < iter; i++) { xElement = parseObject[1500]; } if (timeResults) Console.WriteLine(Timer.ElapsedTicks); if (timeResults) Timer.Restart(); var email = xElement["email"]; if (timeResults) Timer.Restart(); for (int i = 0; i < iter; i++) { email = xElement["email"]; } if (timeResults) Console.WriteLine(Timer.ElapsedTicks); if (timeResults) Timer.Restart(); var emailString = (Utf8Span)email; if (timeResults) Timer.Restart(); for (int i = 0; i < iter; i++) { emailString = (Utf8Span)email; } if (timeResults) Console.WriteLine(Timer.ElapsedTicks); if (timeResults) Timer.Restart(); var about = xElement["about"]; if (timeResults) Timer.Restart(); for (int i = 0; i < iter; i++) { about = xElement["about"]; } if (timeResults) Console.WriteLine(Timer.ElapsedTicks); if (timeResults) Timer.Restart(); var aboutString = (Utf8Span)about; if (timeResults) Timer.Restart(); for (int i = 0; i < iter; i++) { aboutString = (Utf8Span)about; } if (timeResults) Console.WriteLine(Timer.ElapsedTicks); if (timeResults) Timer.Restart(); var age = xElement["age"]; if (timeResults) Timer.Restart(); for (int i = 0; i < iter; i++) { age = xElement["age"]; } if (timeResults) Console.WriteLine(Timer.ElapsedTicks); if (timeResults) Timer.Restart(); var ageInt = (int)age; if (timeResults) Timer.Restart(); for (int i = 0; i < iter; i++) { ageInt = (int)age; } if (timeResults) Console.WriteLine(Timer.ElapsedTicks); if (timeResults) Timer.Restart(); var latitude = xElement["latitude"]; if (timeResults) Timer.Restart(); for (int i = 0; i < iter; i++) { latitude = xElement["latitude"]; } if (timeResults) Console.WriteLine(Timer.ElapsedTicks); if (timeResults) Timer.Restart(); var latitudeDouble = (double)latitude; if (timeResults) Timer.Restart(); for (int i = 0; i < iter; i++) { latitudeDouble = (double)latitude; } if (timeResults) Console.WriteLine(Timer.ElapsedTicks); if (timeResults) Timer.Restart(); var isActive = xElement["isActive"]; if (timeResults) Timer.Restart(); for (int i = 0; i < iter; i++) { isActive = xElement["isActive"]; } if (timeResults) Console.WriteLine(Timer.ElapsedTicks); if (timeResults) Timer.Restart(); var isActiveBool = (bool)isActive; if (timeResults) Timer.Restart(); for (int i = 0; i < iter; i++) { isActiveBool = (bool)isActive; } if (timeResults) Console.WriteLine(Timer.ElapsedTicks); } private static void RunWriterTest() { Output("====== TEST Write ======"); for (var i = 0; i < NumberOfSamples; i++) { JsonNetWriterHelper(OutputJsonData); // Do not test first iteration RunWriterTestJsonNet(); JsonWriterHelper(OutputJsonData); // Do not test first iteration RunWriterTestJson(); } Output("Json.NET Timing Results"); foreach (var res in TimingResultsJsonNet) { Output(res.ToString()); } Output("System.Text.Json Timing Results"); foreach (var res in TimingResultsJsonReader) { Output(res.ToString()); } TimingResultsJsonNet.Clear(); TimingResultsJsonReader.Clear(); } private static void RunWriterTestJsonNet() { Timer.Restart(); for (var i = 0; i < NumberOfIterations*NumberOfIterations; i++) { JsonNetWriterHelper(OutputJsonData); } TimingResultsJsonNet.Add(Timer.ElapsedMilliseconds); } private static void JsonNetWriterHelper(bool output) { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); var writer = new JsonTextWriter(sw); writer.Formatting = Formatting.Indented; writer.WriteStartObject(); writer.WritePropertyName("CPU"); writer.WriteValue("Intel"); writer.WritePropertyName("PSU"); writer.WriteValue("500W"); writer.WritePropertyName("Drives"); writer.WriteStartArray(); writer.WriteValue("DVD read/writer"); writer.WriteValue("500 gigabyte hard drive"); writer.WriteValue("200 gigabype hard drive"); writer.WriteEnd(); writer.WriteEndObject(); if (output) Console.WriteLine(sw.ToString()); } private static void RunWriterTestJson() { Timer.Restart(); for (var i = 0; i < NumberOfIterations*NumberOfIterations; i++) { JsonWriterHelper(OutputJsonData); } TimingResultsJsonReader.Add(Timer.ElapsedMilliseconds); } private static void JsonWriterHelper(bool output) { var buffer = new byte[1024]; var stream = new MemoryStream(buffer); var writer = new JsonWriter(stream, TextEncoder.Encoding.Utf8, prettyPrint: true); writer.WriteObjectStart(); writer.WriteAttribute("CPU", "Intel"); writer.WriteAttribute("PSU", "500W"); writer.WriteMember("Drives"); writer.WriteArrayStart(); writer.WriteString("DVD read/writer"); writer.WriteString("500 gigabyte hard drive"); writer.WriteString("200 gigabype hard drive"); writer.WriteArrayEnd(); writer.WriteObjectEnd(); if (output) Console.WriteLine(Encoding.UTF8.GetString(buffer, 0, (int)stream.Position)); } private static void Output(string str) { if (!OutputResults) return; Console.WriteLine(str); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using Microsoft.Research.CodeAnalysis; using Microsoft.Research.DataStructures; using Microsoft.Research.AbstractDomains.Expressions; using System.Diagnostics.Contracts; namespace Microsoft.Research.AbstractDomains.Numerical { public static class IntervalInference { /// <summary> /// left \lt k /// </summary> static public bool TryRefine_LeftLessThanK<Variable, Expression, IType>( bool isSigned, Variable left, IType k, ISetOfNumbersAbstraction<Variable, Expression, Rational, IType> iquery, out IType refinedIntv) where IType : IntervalBase<IType, Rational> { var result = new List<Pair<Variable, IType>>(); if (k.IsNormal) { var upperBound = k.UpperBound.IsInteger ? k.UpperBound - 1 : k.UpperBound; var LessEquanThanK = iquery.IntervalLeftOpen(upperBound); IType oldValueForLeft; if (iquery.TryGetValue(left, isSigned, out oldValueForLeft)) { refinedIntv = oldValueForLeft.Meet(LessEquanThanK); } else { refinedIntv = LessEquanThanK; } return true; } refinedIntv = default(IType); return false; } static public bool TryRefine_KLessThanRight<Variable, Expression, IType>( bool isSigned, IType k, Variable right, Rational succ, ISetOfNumbersAbstraction<Variable, Expression, Rational, IType> iquery, out IType refinedIntv) where IType : IntervalBase<IType, Rational> { if (k.IsNormal) { var lowerBound = k.LowerBound.IsInteger ? k.LowerBound.NextInt32 + succ : k.LowerBound; var GreaterThanK = iquery.IntervalRightOpen(lowerBound); IType oldValueForRight; if (iquery.TryGetValue(right, isSigned, out oldValueForRight)) { refinedIntv = oldValueForRight.Meet(GreaterThanK); } else { refinedIntv = GreaterThanK; } return true; } refinedIntv = default(IType); return false; } static public bool TryRefine_KLessEqualThanRight<Variable, Expression, NType, IType>( bool isSigned, IType k, Variable right, ISetOfNumbersAbstraction<Variable, Expression, NType, IType> iquery, out IType refinedIntv) where IType : IntervalBase<IType, NType> { if (k.IsNormal) { var GreaterThanK = iquery.IntervalRightOpen(k.LowerBound); IType oldValueForRight; if (iquery.TryGetValue(right, isSigned, out oldValueForRight)) { refinedIntv = oldValueForRight.Meet(GreaterThanK); } else { refinedIntv = GreaterThanK; } return true; } refinedIntv = default(IType); return false; } static public bool TryRefine_LeftLessEqualThanK<Variable, Expression, NType, IType>( bool isSigned, Variable left, IType k, ISetOfNumbersAbstraction<Variable, Expression, NType, IType> iquery, out IType refinedIntv) where IType : IntervalBase<IType, NType> { if (k.IsNormal) { var LessEquanThanK = iquery.IntervalLeftOpen(k.UpperBound); IType oldValueForLeft; if (iquery.TryGetValue(left, isSigned, out oldValueForLeft)) { refinedIntv = oldValueForLeft.Meet(LessEquanThanK); } else { refinedIntv = LessEquanThanK; } return true; } refinedIntv = default(IType); return false; } /// <summary> /// Infer exp \in [0, +oo], and if exp is a compound expression also some other constraints /// </summary> static public List<Pair<Variable, IType>> InferConstraints_GeqZero<Variable, Expression, IType>( Expression exp, IExpressionDecoder<Variable, Expression> decoder, ISetOfNumbersAbstraction<Variable, Expression, Rational, IType> iquery) where IType : IntervalBase<IType, Rational> { Contract.Requires(decoder != null); Contract.Requires(iquery != null); Contract.Ensures(Contract.Result<List<Pair<Variable, IType>>>() != null); var result = new List<Pair<Variable, IType>>(); var expVar = decoder.UnderlyingVariable(exp); result.Add(expVar, iquery.Eval(exp).Meet(iquery.Interval_Positive)); if (!decoder.IsVariable(exp)) { Polynomial<Variable, Expression> zero; // = 0 if (!Polynomial<Variable, Expression>.TryToPolynomialForm(new Monomial<Variable>[] { new Monomial<Variable>(0) }, out zero)) { throw new AbstractInterpretationException("It can never be the case that the conversion of a list of monomials into a polynomial fails"); } Polynomial<Variable, Expression> expAsPolynomial, newPolynomial; if (Polynomial<Variable, Expression>.TryToPolynomialForm(exp, decoder, out expAsPolynomial) && Polynomial<Variable, Expression>.TryToPolynomialForm(ExpressionOperator.LessEqualThan, zero, expAsPolynomial, out newPolynomial)) // 0 <= exp { if (newPolynomial.IsIntervalForm) { // if it is in the form of k1 * x <= k2 var k1 = newPolynomial.Left[0].K; var x = newPolynomial.Left[0].VariableAt(0); var k2 = newPolynomial.Right[0].K; Rational bound; if (Rational.TryDiv(k2, k1, out bound)) //var bound = k2 / k1; { if (k1 > 0) { var intv = iquery.Eval(x).Meet(iquery.IntervalLeftOpen(bound)); result.Add(x, intv); } else if (k1 < 0) { var intv = iquery.Eval(x).Meet(iquery.IntervalRightOpen(bound)); result.Add(x, intv); } else { throw new AbstractInterpretationException("Impossible case"); } } } } } return result; } static public List<Pair<Variable, IType>> InferConstraints_Leq<Variable, Expression, IType>( bool isSignedComparison, Expression left, Expression right, IExpressionDecoder<Variable, Expression> decoder, ISetOfNumbersAbstraction<Variable, Expression, Rational, IType> iquery, out bool isBottom) where IType : IntervalBase<IType, Rational> { Contract.Requires(iquery != null); Contract.Ensures(Contract.Result<List<Pair<Variable, IType>>>() != null); isBottom = false; // false, unless someine proves the contrary var result = new List<Pair<Variable, IType>>(); if (IsFloat(left, decoder) || IsFloat(right, decoder)) { return result; } var kLeft = iquery.Eval(left); var kRight = iquery.Eval(right); // We have to take into account the polymorphism of constants if (!isSignedComparison) { kLeft = kLeft.ToUnsigned(); kRight = kRight.ToUnsigned(); } //AssumeKLessEqualThanRight(kLeft, this.Decoder.UnderlyingVariable(right)) IType refinedIntv; var rightVar = decoder.UnderlyingVariable(right); if (IntervalInference.TryRefine_KLessEqualThanRight(isSignedComparison, kLeft, rightVar, iquery, out refinedIntv)) { // If it is an unsigned comparison, and it is a constant, then we should avoid generating the constraint // Example: left <={un} right, with right == -1 then we do not want to generate the constraint right == 2^{32}-1 which is wrong! // unsigned ==> right is not a constant if (isSignedComparison || !kRight.IsSingleton) { result.Add(rightVar, refinedIntv); } } //AssumeLeftLessEqualThanK(this.Decoder.UnderlyingVariable(left), kRight); var leftVar = decoder.UnderlyingVariable(left); if (IntervalInference.TryRefine_LeftLessEqualThanK(isSignedComparison, leftVar, kRight, iquery, out refinedIntv)) { // unsigned ==> left is not a constant if (isSignedComparison || !kLeft.IsSingleton) { result.Add(leftVar, refinedIntv); } } if (isSignedComparison) { Polynomial<Variable, Expression> guardInCanonicalForm; if (Polynomial<Variable, Expression>.TryToPolynomialForm(ExpressionOperator.LessEqualThan, left, right, decoder, out guardInCanonicalForm) && guardInCanonicalForm.IsLinear) { // We consider only the case when there is at MOST one variable on the left, i.e. a * x \leq b, or TWO, i.e. a*x +b*y <= c if (guardInCanonicalForm.Left.Length == 1) { return HelperFortestTrueLessEqualThan_AxLeqK(guardInCanonicalForm, iquery, result, out isBottom); } else if (guardInCanonicalForm.Left.Length == 2) { return HelperFortestTrueLessEqualThan_AxByLtK(guardInCanonicalForm, iquery, result, out isBottom); } } } return result; } static public List<Pair<Variable, IType>> InferConstraints_LT<Variable, Expression, IType>( bool isSignedComparison, Expression left, Expression right, IExpressionDecoder<Variable, Expression> decoder, ISetOfNumbersAbstraction<Variable, Expression, Rational, IType> iquery, out bool isBottom) where IType : IntervalBase<IType, Rational> { Contract.Ensures(Contract.Result<List<Pair<Variable, IType>>>() != null); isBottom = false; // False untils someone proves the contrary var result = new List<Pair<Variable, IType>>(); var kLeft = iquery.Eval(left); var kRight = iquery.Eval(right); if (!isSignedComparison && !IsFloat(left, decoder) && !IsFloat(right, decoder)) { kLeft = kLeft.ToUnsigned(); kRight = kRight.ToUnsigned(); } IType refinedIntv; var rightVar = decoder.UnderlyingVariable(right); var succ = IsFloat(left, decoder) || IsFloat(right, decoder) ? Rational.For(0) : Rational.For(1); if (TryRefine_KLessThanRight(isSignedComparison, kLeft, rightVar, succ, iquery, out refinedIntv)) { // If it is an unsigned comparison, and it is a constant, then we should avoid generating the constraint // Example: left <{un} right, with right == -1 then we do not want to generate the constraint right == 2^{32}-1 which is wrong! // unsigned ==> right is not a constant if (isSignedComparison || !kRight.IsSingleton) { result.Add(rightVar, refinedIntv); } } if (IsFloat(left, decoder) || IsFloat(right, decoder)) { return result; } var leftVar = decoder.UnderlyingVariable(left); if (TryRefine_LeftLessThanK(isSignedComparison, leftVar, kRight, iquery, out refinedIntv)) { // As above // unsigned ==> right is not a constant if (isSignedComparison || !kLeft.IsSingleton) { result.Add(leftVar, refinedIntv); } } if (isSignedComparison) { // Try to infer some more fact Polynomial<Variable, Expression> guardInCanonicalForm; if (Polynomial<Variable, Expression>.TryToPolynomialForm(ExpressionOperator.LessThan, left, right, decoder, out guardInCanonicalForm) && guardInCanonicalForm.IsLinear) { // First, we consider only the case when there is at MOST one variable on the left, i.e. a * x < b { if (guardInCanonicalForm.Left.Length == 1) { result = HelperFortestTrueLessThan_AxLtK(guardInCanonicalForm, iquery, result, out isBottom); } // Then, we consider the case when it is in the form a*x + b*y < k else if (guardInCanonicalForm.Left.Length == 2) { return HelperFortestTrueLessThan_AxByLtK(guardInCanonicalForm, iquery, result, out isBottom); } } } else { #region Try to infer something else... switch (decoder.OperatorFor(left)) { case ExpressionOperator.And: // case "(leftLeft && leftRight) < right var leftRight = decoder.RightExpressionFor(left); Int32 valueLeft; if (decoder.IsConstantInt(leftRight, out valueLeft)) { if (IsPowerOfTwoMinusOne(valueLeft)) { // add the constraint " 0 <= right < valueLeft " var oldVal = iquery.Eval(right); var evalVal = iquery.Eval(left); var newVal = iquery.For(Rational.For(0), Rational.For(valueLeft - 1)); // [0, valueLeft-1], "-1" as we know it is an integer result.Add(rightVar, oldVal.Meet(newVal).Meet(evalVal)); } } break; default: // do nothing... break; } #endregion } } return result; } static public void InferConstraints_NotEq<Variable, Expression, IType>( Expression left, Expression right, IExpressionDecoder<Variable, Expression> decoder, ISetOfNumbersAbstraction<Variable, Expression, Rational, IType> iquery, out List<Pair<Variable, IType>> resultLeft, out List<Pair<Variable, IType>> resultRight, out bool isBottomLeft, out bool isBottomRight) where IType : IntervalBase<IType, Rational> { isBottomLeft = false; // False untils someone proves the contrary isBottomRight = false; resultLeft = new List<Pair<Variable, IType>>(); resultRight = new List<Pair<Variable, IType>>(); var kLeft = iquery.Eval(left); var kRight = iquery.Eval(right); var rightVar = decoder.UnderlyingVariable(right); var leftVar = decoder.UnderlyingVariable(left); var succ = IsFloat(left, decoder) || IsFloat(right, decoder) ? Rational.For(0) : Rational.For(1); NewMethod<Variable, Expression, IType>(succ, iquery, kLeft, kRight, rightVar, leftVar, resultLeft); NewMethod<Variable, Expression, IType>(succ, iquery, kRight, kLeft, leftVar, rightVar, resultRight); // Try to infer some more fact Polynomial<Variable, Expression> tmpLeftPoly, tmpRightPoly; if (Polynomial<Variable, Expression>.TryToPolynomialForm(left, decoder, out tmpLeftPoly) && Polynomial<Variable, Expression>.TryToPolynomialForm(right, decoder, out tmpRightPoly)) { NewMethod2<Variable, Expression, IType>(tmpLeftPoly, tmpRightPoly, iquery, ref isBottomLeft, resultLeft); NewMethod2<Variable, Expression, IType>(tmpRightPoly, tmpLeftPoly, iquery, ref isBottomRight, resultRight); } } private static void NewMethod2<Variable, Expression, IType>( Polynomial<Variable, Expression> tmpLeftPoly, Polynomial<Variable, Expression> tmpRightPoly, ISetOfNumbersAbstraction<Variable, Expression, Rational, IType> iquery, ref bool isBottom, List<Pair<Variable, IType>> resultLeft) where IType : IntervalBase<IType, Rational> { Polynomial<Variable, Expression> guardInCanonicalForm; if (Polynomial<Variable, Expression>.TryToPolynomialForm(ExpressionOperator.LessThan, tmpLeftPoly, tmpRightPoly, out guardInCanonicalForm)) { // First, we consider only the case when there is at MOST one variable on the left, i.e. a * x < b if (guardInCanonicalForm.IsLinear) { if (guardInCanonicalForm.Left.Length == 1) { resultLeft = HelperFortestTrueLessThan_AxLtK(guardInCanonicalForm, iquery, resultLeft, out isBottom); } // Then, we consider the case when it is in the form a*x + b*y < k else if (guardInCanonicalForm.Left.Length == 2) { resultLeft = HelperFortestTrueLessThan_AxByLtK(guardInCanonicalForm, iquery, resultLeft, out isBottom); } } } } private static void NewMethod<Variable, Expression, IType>( Rational succ, ISetOfNumbersAbstraction<Variable, Expression, Rational, IType> iquery, IType kLeft, IType kRight, Variable rightVar, Variable leftVar, List<Pair<Variable, IType>> result) where IType : IntervalBase<IType, Rational> { IType refinedIntv; if (TryRefine_KLessThanRight(true, kLeft, rightVar, succ, iquery, out refinedIntv)) { result.Add(rightVar, refinedIntv); } if (TryRefine_LeftLessThanK(true, leftVar, kRight, iquery, out refinedIntv)) { result.Add(leftVar, refinedIntv); } } #region Private helpers static private List<Pair<Variable, IType>> HelperFortestTrueLessEqualThan_AxLeqK<Variable, Expression, IType>( Polynomial<Variable, Expression> guardInCanonicalForm, ISetOfNumbersAbstraction<Variable, Expression, Rational, IType> iquery, List<Pair<Variable, IType>> result, out bool isBottom) where IType : IntervalBase<IType, Rational> { Contract.Requires(!object.ReferenceEquals(guardInCanonicalForm, null)); Contract.Requires(result != null); Contract.Requires(guardInCanonicalForm.Right.Length == 1); Contract.Ensures(Contract.Result<List<Pair<Variable, IType>>>() != null); var MonomialForX = guardInCanonicalForm.Left[0]; var MonomilaForB = guardInCanonicalForm.Right[0]; Contract.Assert(MonomilaForB.IsConstant); isBottom = false; // 1. We have a case a <= b if (MonomialForX.IsConstant) { var a = MonomialForX.K; var b = MonomilaForB.K; if (a > b) { isBottom = true; } } else // 2. We have the case a * x \leq b { var x = MonomialForX.VariableAt(0); Rational k; if ( MonomialForX.K.IsInteger && Rational.TryDiv(MonomilaForB.K, MonomialForX.K, out k)) { var oldValueForX = iquery.Eval(x); IType newValueForX; if (MonomialForX.K.Sign == 1) { // The constraint is x \leq k newValueForX = oldValueForX.Meet(iquery.IntervalLeftOpen(k)); } else { // The constraint is x \geq k newValueForX = oldValueForX.Meet(iquery.IntervalRightOpen(k)); } if (newValueForX.IsBottom) { isBottom = true; } else { Contract.Assert(isBottom == false); result.Add(x, newValueForX); } } } return result; } /// <summary> /// Handles the case when the guard is in the form of "A*x + B*y &lt;= k" /// </summary> static private List<Pair<Variable, IType>> HelperFortestTrueLessEqualThan_AxByLtK<Variable, Expression, IType>( Polynomial<Variable, Expression> guardInCanonicalForm, ISetOfNumbersAbstraction<Variable, Expression, Rational, IType> iquery, List<Pair<Variable, IType>> result, out bool isBottom) where IType : IntervalBase<IType, Rational> { Contract.Requires(!object.ReferenceEquals(guardInCanonicalForm, null)); Contract.Requires(iquery != null); Contract.Requires(result != null); Contract.Requires(guardInCanonicalForm.Right.Length == 1); Contract.Requires(guardInCanonicalForm.Left.Length == 2); Contract.Ensures(Contract.Result<List<Pair<Variable, IType>>>() != null); isBottom = false; // false, unless someone proves not var monomialForX = guardInCanonicalForm.Left[0]; var monomialForY = guardInCanonicalForm.Left[1]; var X = monomialForX.VariableAt(0); var Y = monomialForY.VariableAt(0); var K = guardInCanonicalForm.Right[0].K; var A = monomialForX.K; var B = monomialForY.K; var intervalForA = iquery.For(A); var intervalForB = iquery.For(B); var intervalForK = iquery.For(K); var intervalForX = iquery.Eval(X); var intervalForY = iquery.Eval(Y); // 1. Handle the case for x // evalForX =(k - b * y) / a var evalForX = iquery.Interval_Div(iquery.Interval_Sub(intervalForK, (iquery.Interval_Mul(intervalForB, intervalForY))), intervalForA); if (A > 0) { // x <= (k - b * y) / a var upperBound = evalForX.UpperBound; var geq = iquery.IntervalLeftOpen(upperBound); var newIntv = intervalForX.Meet(geq); if (newIntv.IsBottom) { isBottom = true; return result; } result.Add(X, newIntv); } else if (A < 0) { // x >= (k - b * y) / a var lowerBound = evalForX.LowerBound; var leq = iquery.IntervalRightOpen(lowerBound); var newIntv = intervalForX.Meet(leq); if (newIntv.IsBottom) { isBottom = true; return result; } result.Add(X, newIntv); } else { Contract.Assert(false, "Cannot have a == 0"); } // 2. Handle the case for y // evalForY =(k - a * x) / b //var evalForY = (intervalForK - (intervalForA * intervalForX)) / (intervalForB); var evalForY = iquery.Interval_Div(iquery.Interval_Sub(intervalForK, (iquery.Interval_Mul(intervalForA, intervalForX))), intervalForB); if (B > 0) { // y <= (k - a * x) / b var upperBound = evalForY.UpperBound; var geq = iquery.IntervalLeftOpen(upperBound); var newIntv = intervalForY.Meet(geq); if (newIntv.IsBottom) { isBottom = true; return result; } result.Add(Y, newIntv); } else if (B < 0) { // x >= (k - a * x) / b var lowerBound = evalForY.LowerBound; var leq = iquery.IntervalRightOpen(lowerBound); var newIntv = intervalForY.Meet(leq); if (newIntv.IsBottom) { isBottom = true; return result; } result.Add(Y, newIntv); } else { Contract.Assert(false, "Cannot have b == 0"); } return result; } /// <summary> /// Handles the case when the guard is in the form of "A*x &lt; k" /// </summary> /// <param name="guardInCanonicalForm">A polynomial that must have been already put into canonical form</param> static private List<Pair<Variable, IType>> HelperFortestTrueLessThan_AxLtK<Variable, Expression, IType>( Polynomial<Variable, Expression> guardInCanonicalForm, ISetOfNumbersAbstraction<Variable, Expression, Rational, IType> iquery, List<Pair<Variable, IType>> result, out bool isBottom) where IType : IntervalBase<IType, Rational> { Contract.Requires(!object.ReferenceEquals(guardInCanonicalForm, null)); Contract.Requires(guardInCanonicalForm.Right.Length == 1); Contract.Requires(iquery != null); Contract.Requires(result != null); Contract.Ensures(Contract.Result<List<Pair<Variable, IType>>>() != null); isBottom = false; var MonomialForX = guardInCanonicalForm.Left[0]; var MonomilaForB = guardInCanonicalForm.Right[0]; Contract.Assert(MonomilaForB.IsConstant); // 1. We have a case a < b if (MonomialForX.IsConstant) { var a = MonomialForX.K; var b = MonomilaForB.K; if (a >= b) { isBottom = true; } } else // 2. We have the case a * x < b { var x = MonomialForX.VariableAt(0); Rational k; if (!Rational.TryDiv(MonomilaForB.K, MonomialForX.K, out k)) //var k = MonomilaForB.K / MonomialForX.K; { return result; } var oldValueForX = iquery.Eval(x); IType newConstraint; if (MonomialForX.K.Sign == 1) { // The constraint is x < k, but if k is a rational, we approximate it with x \leq k if (k.IsInteger) { newConstraint = iquery.IntervalLeftOpen(k - 1); } else { newConstraint = iquery.IntervalLeftOpen(k.PreviousInt32); } } else { // The constraint is x > k, but if k is a rational, we approximate it with k \leq x if (k.IsInteger) { newConstraint = iquery.IntervalRightOpen(k + 1); } else { newConstraint = iquery.IntervalRightOpen(k.NextInt32); } } var newValueForX = oldValueForX.Meet(newConstraint); if (newValueForX.IsBottom) { isBottom = true; } else { result.Add(x, newValueForX); } } return result; } /// <summary> /// Handles the case when the guard is in the form of "A*x + B*y &lt; k" /// </summary> /// <param name="guardInCanonicalForm">A polynomial that must have been already put into canonical form</param> static private List<Pair<Variable, IType>> HelperFortestTrueLessThan_AxByLtK<Variable, Expression, IType>( Polynomial<Variable, Expression> guardInCanonicalForm, ISetOfNumbersAbstraction<Variable, Expression, Rational, IType> iquery, List<Pair<Variable, IType>> result, out bool isBottom) where IType : IntervalBase<IType, Rational> { Contract.Requires(!object.ReferenceEquals(guardInCanonicalForm, null)); Contract.Requires(iquery != null); Contract.Requires(result != null); Contract.Requires(guardInCanonicalForm.Left.Length == 2); Contract.Requires(guardInCanonicalForm.Right.Length == 1); Contract.Ensures(Contract.Result<List<Pair<Variable, IType>>>() != null); isBottom = false; // False, unless another proof var monomialForX = guardInCanonicalForm.Left[0]; var monomialForY = guardInCanonicalForm.Left[1]; var X = monomialForX.VariableAt(0); var Y = monomialForY.VariableAt(0); var K = guardInCanonicalForm.Right[0].K; var A = monomialForX.K; var B = monomialForY.K; var intervalForA = iquery.For(A); var intervalForB = iquery.For(B); var intervalForK = iquery.For(K); var intervalForX = iquery.Eval(X); var intervalForY = iquery.Eval(Y); // 1. Handle the case for x // evalForX =(k - b * y) / a var evalForX = iquery.Interval_Div((iquery.Interval_Sub(intervalForK, (iquery.Interval_Mul(intervalForB, intervalForY)))), intervalForA); if (A > 0) { // x < (k - b * y) / a var upperBound = evalForX.UpperBound; IType gt; if (upperBound.IsInteger) { gt = iquery.IntervalLeftOpen(upperBound - 1); } else { gt = iquery.IntervalLeftOpen(upperBound.PreviousInt32); } var intv = intervalForX.Meet(gt); if (intv.IsBottom) { isBottom = true; return result; } result.Add(X, intv); } else if (A < 0) { // x > (k - b * y) / a var lowerBound = evalForX.LowerBound; IType lt; if (lowerBound.IsInteger) { lt = iquery.IntervalRightOpen(lowerBound + 1); } else { lt = iquery.IntervalRightOpen(lowerBound.NextInt32); } var intv = intervalForX.Meet(lt); if (intv.IsBottom) { isBottom = true; return result; } result.Add(X, intv); } else { Contract.Assert(false, "Cannot have a == 0"); } // 2. Handle the case for y // evalForY =(k - a * x) / b var evalForY = iquery.Interval_Div((iquery.Interval_Sub(intervalForK, (iquery.Interval_Mul(intervalForA, intervalForX)))), intervalForB); if (B > 0) { // y < (k - a * x) / b var upperBound = evalForY.UpperBound; IType gt; if (upperBound.IsInteger) { gt = iquery.IntervalLeftOpen(upperBound - 1); } else { gt = iquery.IntervalLeftOpen(upperBound.PreviousInt32); } var intv = intervalForY.Meet(gt); if (intv.IsBottom) { isBottom = true; return result; } result.Add(Y, intv); } else if (B < 0) { // x > (k - a * x) / b var lowerBound = evalForY.LowerBound; IType lt; if (lowerBound.IsInteger) { lt = iquery.IntervalRightOpen(lowerBound + 1); } else { lt = iquery.IntervalRightOpen(lowerBound.NextInt32); } var intv = intervalForY.Meet(lt); if (intv.IsBottom) { isBottom = true; return result; } result.Add(Y, intv); } else { Contract.Assert(false, "Cannot have b == 0"); } return result; } private static bool IsPowerOfTwoMinusOne(int r) { return r == 15 || r == 31 || r == 63 || r == 127 || r == 255 || r == 511 || r == 1023 || r == 2047 || r == 4095 || r == 8191 || r == 16385 || r == 32767 || r == 65535 || r == 131071 || r == 262143 || r == 524287 || r == 1048575 || r == 2097151 || r == 4194303 || r == 8388607 || r == 16777215; } private static bool IsFloat<Variable, Expression>(Expression exp, IExpressionDecoder<Variable, Expression> decoder) { if (decoder == null) { return false; } var type = decoder.TypeOf(exp); return type == ExpressionType.Float32 || type == ExpressionType.Float64; } #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.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.NetCore.Extensions; namespace System.Tests { public class EnvironmentTests : RemoteExecutorTestBase { [Fact] public void CurrentDirectory_Null_Path_Throws_ArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("value", () => Environment.CurrentDirectory = null); } [Fact] public void CurrentDirectory_Empty_Path_Throws_ArgumentException() { AssertExtensions.Throws<ArgumentException>("value", null, () => Environment.CurrentDirectory = string.Empty); } [Fact] public void CurrentDirectory_SetToNonExistentDirectory_ThrowsDirectoryNotFoundException() { Assert.Throws<DirectoryNotFoundException>(() => Environment.CurrentDirectory = GetTestFilePath()); } [Fact] public void CurrentDirectory_SetToValidOtherDirectory() { RemoteInvoke(() => { Environment.CurrentDirectory = TestDirectory; Assert.Equal(Directory.GetCurrentDirectory(), Environment.CurrentDirectory); if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { // On OSX, the temp directory /tmp/ is a symlink to /private/tmp, so setting the current // directory to a symlinked path will result in GetCurrentDirectory returning the absolute // path that followed the symlink. Assert.Equal(TestDirectory, Directory.GetCurrentDirectory()); } return SuccessExitCode; }).Dispose(); } [Fact] public void CurrentManagedThreadId_Idempotent() { Assert.Equal(Environment.CurrentManagedThreadId, Environment.CurrentManagedThreadId); } [Fact] public void CurrentManagedThreadId_DifferentForActiveThreads() { var ids = new HashSet<int>(); Barrier b = new Barrier(10); Task.WaitAll((from i in Enumerable.Range(0, b.ParticipantCount) select Task.Factory.StartNew(() => { b.SignalAndWait(); lock (ids) ids.Add(Environment.CurrentManagedThreadId); b.SignalAndWait(); }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)).ToArray()); Assert.Equal(b.ParticipantCount, ids.Count); } [Fact] public void HasShutdownStarted_FalseWhileExecuting() { Assert.False(Environment.HasShutdownStarted); } [Fact] public void Is64BitProcess_MatchesIntPtrSize() { Assert.Equal(IntPtr.Size == 8, Environment.Is64BitProcess); } [Fact] public void Is64BitOperatingSystem_TrueIf64BitProcess() { if (Environment.Is64BitProcess) { Assert.True(Environment.Is64BitOperatingSystem); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests OS-specific environment public void Is64BitOperatingSystem_Unix_TrueIff64BitProcess() { Assert.Equal(Environment.Is64BitProcess, Environment.Is64BitOperatingSystem); } [Fact] public void OSVersion_Idempotent() { Assert.Same(Environment.OSVersion, Environment.OSVersion); } [Fact] public void OSVersion_MatchesPlatform() { PlatformID id = Environment.OSVersion.Platform; Assert.Equal( RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? PlatformID.Win32NT : PlatformID.Unix, id); } [Fact] public void OSVersion_ValidVersion() { Version version = Environment.OSVersion.Version; string versionString = Environment.OSVersion.VersionString; Assert.False(string.IsNullOrWhiteSpace(versionString), "Expected non-empty version string"); Assert.True(version.Major > 0); Assert.Contains(version.ToString(2), versionString); Assert.Contains(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "Windows" : "Unix", versionString); } [Fact] public void SystemPageSize_Valid() { int pageSize = Environment.SystemPageSize; Assert.Equal(pageSize, Environment.SystemPageSize); Assert.True(pageSize > 0, "Expected positive page size"); Assert.True((pageSize & (pageSize - 1)) == 0, "Expected power-of-2 page size"); } [Fact] public void UserInteractive_True() { Assert.True(Environment.UserInteractive); } [Fact] public void UserName_Valid() { Assert.False(string.IsNullOrWhiteSpace(Environment.UserName)); } [Fact] public void UserDomainName_Valid() { Assert.False(string.IsNullOrWhiteSpace(Environment.UserDomainName)); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests OS-specific environment public void UserDomainName_Unix_MatchesMachineName() { Assert.Equal(Environment.MachineName, Environment.UserDomainName); } [Fact] public void Version_MatchesFixedVersion() { Assert.Equal(new Version(4, 0, 30319, 42000), Environment.Version); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap)] // Throws InvalidOperationException in Uap as NtQuerySystemInformation Pinvoke is not available public void WorkingSet_Valid() { Assert.True(Environment.WorkingSet > 0, "Expected positive WorkingSet value"); } [Fact] [SkipOnTargetFramework(~TargetFrameworkMonikers.Uap)] public void WorkingSet_Valid_Uap() { Assert.Throws<PlatformNotSupportedException>(() => Environment.WorkingSet); } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // fail fast crashes the process [OuterLoop] [Fact] [ActiveIssue("https://github.com/dotnet/corefx/issues/21404", TargetFrameworkMonikers.Uap)] public void FailFast_ExpectFailureExitCode() { using (Process p = RemoteInvoke(() => { Environment.FailFast("message"); return SuccessExitCode; }).Process) { p.WaitForExit(); Assert.NotEqual(SuccessExitCode, p.ExitCode); } using (Process p = RemoteInvoke(() => { Environment.FailFast("message", new Exception("uh oh")); return SuccessExitCode; }).Process) { p.WaitForExit(); Assert.NotEqual(SuccessExitCode, p.ExitCode); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests OS-specific environment public void GetFolderPath_Unix_PersonalIsHomeAndUserProfile() { Assert.Equal(Environment.GetEnvironmentVariable("HOME"), Environment.GetFolderPath(Environment.SpecialFolder.Personal)); Assert.Equal(Environment.GetEnvironmentVariable("HOME"), Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)); Assert.Equal(Environment.GetEnvironmentVariable("HOME"), Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)); } [Fact] public void GetSystemDirectory() { if (PlatformDetection.IsWindowsNanoServer) { // https://github.com/dotnet/corefx/issues/19110 // On Windows Nano, ShGetKnownFolderPath currently doesn't give // the correct result for SystemDirectory. // Assert that it's wrong, so that if it's fixed, we don't forget to // enable this test for Nano. Assert.NotEqual(Environment.GetFolderPath(Environment.SpecialFolder.System), Environment.SystemDirectory); return; } Assert.Equal(Environment.GetFolderPath(Environment.SpecialFolder.System), Environment.SystemDirectory); } [Theory] [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests OS-specific environment [InlineData(Environment.SpecialFolder.UserProfile, Environment.SpecialFolderOption.None)] [InlineData(Environment.SpecialFolder.Personal, Environment.SpecialFolderOption.None)] [InlineData(Environment.SpecialFolder.MyDocuments, Environment.SpecialFolderOption.None)] [InlineData(Environment.SpecialFolder.CommonApplicationData, Environment.SpecialFolderOption.None)] [InlineData(Environment.SpecialFolder.CommonTemplates, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.ApplicationData, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.Desktop, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.DesktopDirectory, Environment.SpecialFolderOption.DoNotVerify)] // Not set on Unix (amongst others) //[InlineData(Environment.SpecialFolder.System, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.Templates, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.MyVideos, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.MyMusic, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.MyPictures, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.Fonts, Environment.SpecialFolderOption.DoNotVerify)] public void GetFolderPath_Unix_NonEmptyFolderPaths(Environment.SpecialFolder folder, Environment.SpecialFolderOption option) { Assert.NotEmpty(Environment.GetFolderPath(folder, option)); if (option == Environment.SpecialFolderOption.None) { Assert.NotEmpty(Environment.GetFolderPath(folder)); } } [Theory] [PlatformSpecific(TestPlatforms.OSX)] // Tests OS-specific environment [InlineData(Environment.SpecialFolder.Favorites, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.InternetCache, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.ProgramFiles, Environment.SpecialFolderOption.None)] [InlineData(Environment.SpecialFolder.System, Environment.SpecialFolderOption.None)] public void GetFolderPath_OSX_NonEmptyFolderPaths(Environment.SpecialFolder folder, Environment.SpecialFolderOption option) { Assert.NotEmpty(Environment.GetFolderPath(folder, option)); if (option == Environment.SpecialFolderOption.None) { Assert.NotEmpty(Environment.GetFolderPath(folder)); } } // Requires recent RS3 builds [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsWindows10Version16251OrGreater))] [SkipOnTargetFramework(~(TargetFrameworkMonikers.Uap | TargetFrameworkMonikers.UapAot))] [InlineData(Environment.SpecialFolder.LocalApplicationData)] [InlineData(Environment.SpecialFolder.Cookies)] [InlineData(Environment.SpecialFolder.History)] [InlineData(Environment.SpecialFolder.InternetCache)] [InlineData(Environment.SpecialFolder.System)] [InlineData(Environment.SpecialFolder.SystemX86)] [InlineData(Environment.SpecialFolder.Windows)] public void GetFolderPath_UapExistAndAccessible(Environment.SpecialFolder folder) { string knownFolder = Environment.GetFolderPath(folder); Assert.NotEmpty(knownFolder); AssertDirectoryExists(knownFolder); } // Requires recent RS3 builds [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsWindows10Version16251OrGreater))] [SkipOnTargetFramework(~(TargetFrameworkMonikers.Uap | TargetFrameworkMonikers.UapAot))] [InlineData(Environment.SpecialFolder.ApplicationData)] [InlineData(Environment.SpecialFolder.MyMusic)] [InlineData(Environment.SpecialFolder.MyPictures)] [InlineData(Environment.SpecialFolder.MyVideos)] [InlineData(Environment.SpecialFolder.Recent)] [InlineData(Environment.SpecialFolder.Templates)] [InlineData(Environment.SpecialFolder.DesktopDirectory)] [InlineData(Environment.SpecialFolder.Personal)] [InlineData(Environment.SpecialFolder.UserProfile)] [InlineData(Environment.SpecialFolder.CommonDocuments)] [InlineData(Environment.SpecialFolder.CommonMusic)] [InlineData(Environment.SpecialFolder.CommonPictures)] [InlineData(Environment.SpecialFolder.CommonDesktopDirectory)] [InlineData(Environment.SpecialFolder.CommonVideos)] // These are in the package folder [InlineData(Environment.SpecialFolder.CommonApplicationData)] [InlineData(Environment.SpecialFolder.Desktop)] [InlineData(Environment.SpecialFolder.Favorites)] public void GetFolderPath_UapNotEmpty(Environment.SpecialFolder folder) { // The majority of the paths here cannot be accessed from an appcontainer string knownFolder = Environment.GetFolderPath(folder); Assert.NotEmpty(knownFolder); } private void AssertDirectoryExists(string path) { // Directory.Exists won't tell us if access was denied, etc. Invoking directly // to get diagnosable test results. FileAttributes attributes = GetFileAttributesW(path); if (attributes == (FileAttributes)(-1)) { int error = Marshal.GetLastWin32Error(); Assert.False(true, $"error {error} getting attributes for {path}"); } Assert.True((attributes & FileAttributes.Directory) == FileAttributes.Directory, $"not a directory: {path}"); } // The commented out folders aren't set on all systems. [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))] // https://github.com/dotnet/corefx/issues/19110 [InlineData(Environment.SpecialFolder.ApplicationData)] [InlineData(Environment.SpecialFolder.CommonApplicationData)] [InlineData(Environment.SpecialFolder.LocalApplicationData)] [InlineData(Environment.SpecialFolder.Cookies)] [InlineData(Environment.SpecialFolder.Desktop)] [InlineData(Environment.SpecialFolder.Favorites)] [InlineData(Environment.SpecialFolder.History)] [InlineData(Environment.SpecialFolder.InternetCache)] [InlineData(Environment.SpecialFolder.Programs)] // [InlineData(Environment.SpecialFolder.MyComputer)] [InlineData(Environment.SpecialFolder.MyMusic)] [InlineData(Environment.SpecialFolder.MyPictures)] [InlineData(Environment.SpecialFolder.MyVideos)] [InlineData(Environment.SpecialFolder.Recent)] [InlineData(Environment.SpecialFolder.SendTo)] [InlineData(Environment.SpecialFolder.StartMenu)] [InlineData(Environment.SpecialFolder.Startup)] [InlineData(Environment.SpecialFolder.System)] [InlineData(Environment.SpecialFolder.Templates)] [InlineData(Environment.SpecialFolder.DesktopDirectory)] [InlineData(Environment.SpecialFolder.Personal)] [InlineData(Environment.SpecialFolder.ProgramFiles)] [InlineData(Environment.SpecialFolder.CommonProgramFiles)] [InlineData(Environment.SpecialFolder.AdminTools)] [InlineData(Environment.SpecialFolder.CDBurning)] [InlineData(Environment.SpecialFolder.CommonAdminTools)] [InlineData(Environment.SpecialFolder.CommonDocuments)] [InlineData(Environment.SpecialFolder.CommonMusic)] // [InlineData(Environment.SpecialFolder.CommonOemLinks)] [InlineData(Environment.SpecialFolder.CommonPictures)] [InlineData(Environment.SpecialFolder.CommonStartMenu)] [InlineData(Environment.SpecialFolder.CommonPrograms)] [InlineData(Environment.SpecialFolder.CommonStartup)] [InlineData(Environment.SpecialFolder.CommonDesktopDirectory)] [InlineData(Environment.SpecialFolder.CommonTemplates)] [InlineData(Environment.SpecialFolder.CommonVideos)] [InlineData(Environment.SpecialFolder.Fonts)] [InlineData(Environment.SpecialFolder.NetworkShortcuts)] // [InlineData(Environment.SpecialFolder.PrinterShortcuts)] [InlineData(Environment.SpecialFolder.UserProfile)] [InlineData(Environment.SpecialFolder.CommonProgramFilesX86)] [InlineData(Environment.SpecialFolder.ProgramFilesX86)] [InlineData(Environment.SpecialFolder.Resources)] // [InlineData(Environment.SpecialFolder.LocalizedResources)] [InlineData(Environment.SpecialFolder.SystemX86)] [InlineData(Environment.SpecialFolder.Windows)] [PlatformSpecific(TestPlatforms.Windows)] // Tests OS-specific environment [SkipOnTargetFramework(TargetFrameworkMonikers.Uap | TargetFrameworkMonikers.UapAot)] // Don't run on UAP public unsafe void GetFolderPath_Windows(Environment.SpecialFolder folder) { string knownFolder = Environment.GetFolderPath(folder); Assert.NotEmpty(knownFolder); // Call the older folder API to compare our results. char* buffer = stackalloc char[260]; SHGetFolderPathW(IntPtr.Zero, (int)folder, IntPtr.Zero, 0, buffer); string folderPath = new string(buffer); Assert.Equal(folderPath, knownFolder); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Uses P/Invokes public void GetLogicalDrives_Unix_AtLeastOneIsRoot() { string[] drives = Environment.GetLogicalDrives(); Assert.NotNull(drives); Assert.True(drives.Length > 0, "Expected at least one drive"); Assert.All(drives, d => Assert.NotNull(d)); Assert.Contains(drives, d => d == "/"); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes public void GetLogicalDrives_Windows_MatchesExpectedLetters() { string[] drives = Environment.GetLogicalDrives(); uint mask = (uint)GetLogicalDrives(); var bits = new BitArray(new[] { (int)mask }); Assert.Equal(bits.Cast<bool>().Count(b => b), drives.Length); for (int bit = 0, d = 0; bit < bits.Length; bit++) { if (bits[bit]) { Assert.Contains((char)('A' + bit), drives[d++]); } } } [DllImport("kernel32.dll", SetLastError = true)] internal static extern int GetLogicalDrives(); [DllImport("shell32.dll", SetLastError = false, BestFitMapping = false, ExactSpelling = true)] internal static extern unsafe int SHGetFolderPathW( IntPtr hwndOwner, int nFolder, IntPtr hToken, uint dwFlags, char* pszPath); [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true)] internal static extern FileAttributes GetFileAttributesW(string lpFileName); public static IEnumerable<object[]> EnvironmentVariableTargets { get { yield return new object[] { EnvironmentVariableTarget.Process }; yield return new object[] { EnvironmentVariableTarget.User }; yield return new object[] { EnvironmentVariableTarget.Machine }; } } } }
/* * Copyright (c) 2006-2008, openmetaverse.org * 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. * - Neither the name of the openmetaverse.org nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Threading; using System.Collections; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Globalization; using System.IO; using OpenMetaverse.Packets; using OpenMetaverse.StructuredData; namespace OpenMetaverse { /// <summary> /// This exception is thrown whenever a network operation is attempted /// without a network connection. /// </summary> public class NotConnectedException : ApplicationException { } /// <summary> /// NetworkManager is responsible for managing the network layer of /// OpenMetaverse. It tracks all the server connections, serializes /// outgoing traffic and deserializes incoming traffic, and provides /// instances of delegates for network-related events. /// </summary> public partial class NetworkManager : INetworkManager { #region Enums /// <summary> /// Explains why a simulator or the grid disconnected from us /// </summary> public enum DisconnectType { /// <summary>The client requested the logout or simulator disconnect</summary> ClientInitiated, /// <summary>The server notified us that it is disconnecting</summary> ServerInitiated, /// <summary>Either a socket was closed or network traffic timed out</summary> NetworkTimeout, /// <summary>The last active simulator shut down</summary> SimShutdown } #endregion Enums #region Structs /// <summary> /// Holds a simulator reference and a decoded packet, these structs are put in /// the packet inbox for event handling /// </summary> public struct IncomingPacket { /// <summary>Reference to the simulator that this packet came from</summary> public Simulator Simulator; /// <summary>Packet that needs to be processed</summary> public Packet Packet; public IncomingPacket(Simulator simulator, Packet packet) { Simulator = simulator; Packet = packet; } } /// <summary> /// Holds a simulator reference and an encoded packet, these structs are put in /// the packet outbox for sending /// </summary> public struct OutgoingPacket { /// <summary>Reference to the simulator this packet is destined for</summary> public Simulator Simulator; /// <summary>Packet that needs to be processed</summary> public Packet Packet; /// <summary>True if the sequence number needs to be set, otherwise false</summary> public bool SetSequence; /// <summary>Number of times this packet has been resent</summary> public int ResendCount; /// <summary>Environment.TickCount when this packet was last sent over the wire</summary> public int TickCount; public OutgoingPacket(Simulator simulator, Packet packet, bool setSequence) { Simulator = simulator; Packet = packet; SetSequence = setSequence; ResendCount = 0; TickCount = 0; } public void IncrementResendCount() { ++ResendCount; } public void SetTickCount() { TickCount = Environment.TickCount; } public void ZeroTickCount() { TickCount = 0; } } #endregion Structs #region Delegates /// <summary> /// Coupled with RegisterCallback(), this is triggered whenever a packet /// of a registered type is received /// </summary> /// <param name="packet"></param> /// <param name="simulator"></param> public delegate void PacketCallback(Packet packet, Simulator simulator); /// <summary> /// Assigned by the OnConnected event. Raised when login was a success /// </summary> /// <param name="sender">Reference to the GridClient object that called the event</param> public delegate void ConnectedCallback(object sender); /// <summary> /// Assigned by the OnLogoutReply callback. Raised upone receipt of a LogoutReply packet during logout process. /// </summary> /// <param name="inventoryItems"></param> public delegate void LogoutCallback(List<UUID> inventoryItems); /// <summary> /// Triggered before a new connection to a simulator is established /// </summary> /// <remarks>The connection to the new simulator won't be established /// until this callback returns</remarks> /// <param name="simulator">The simulator that is being connected to</param> /// <returns>Whether to continue connecting to the simulator or abort /// the connection</returns> public delegate bool SimConnectingCallback(Simulator simulator); /// <summary> /// Triggered when a new connection to a simulator is established /// </summary> /// <param name="simulator">The simulator that is being connected to</param> public delegate void SimConnectedCallback(Simulator simulator); /// <summary> /// Triggered when a simulator other than the simulator that is currently /// being occupied disconnects for whatever reason /// </summary> /// <param name="simulator">The simulator that disconnected, which will become a null /// reference after the callback is finished</param> /// <param name="reason">Enumeration explaining the reason for the disconnect</param> public delegate void SimDisconnectedCallback(Simulator simulator, DisconnectType reason); /// <summary> /// Triggered when we are logged out of the grid due to a simulator request, /// client request, network timeout, or any other cause /// </summary> /// <param name="reason">Enumeration explaining the reason for the disconnect</param> /// <param name="message">If we were logged out by the simulator, this /// is a message explaining why</param> public delegate void DisconnectedCallback(DisconnectType reason, string message); /// <summary> /// Triggered when CurrentSim changes /// </summary> /// <param name="PreviousSimulator">A reference to the old value of CurrentSim</param> public delegate void CurrentSimChangedCallback(Simulator PreviousSimulator); /// <summary> /// Triggered when an event queue makes the initial connection /// </summary> /// <param name="simulator">Simulator this event queue is tied to</param> public delegate void EventQueueRunningCallback(Simulator simulator); #endregion Delegates #region Events /// <summary> /// Event raised when the client was able to connected successfully. /// </summary> /// <remarks>Uses the ConnectedCallback delegate.</remarks> public event ConnectedCallback OnConnected; /// <summary> /// Event raised when a logout is confirmed by the simulator /// </summary> public event LogoutCallback OnLogoutReply; /// <summary> /// Event raised when a before a connection to a simulator is /// initialized /// </summary> public event SimConnectingCallback OnSimConnecting; /// <summary> /// Event raised when a connection to a simulator is established /// </summary> public event SimConnectedCallback OnSimConnected; /// <summary> /// An event for the connection to a simulator other than the currently /// occupied one disconnecting /// </summary> /// <remarks>The Simulators list is locked when this event is /// triggered, do not attempt to modify the collection or acquire a /// lock on it when this callback is fired</remarks> public event SimDisconnectedCallback OnSimDisconnected; /// <summary> /// An event for being logged out either through client request, server /// forced, or network error /// </summary> public event DisconnectedCallback OnDisconnected; /// <summary> /// An event for when CurrentSim changes /// </summary> public event CurrentSimChangedCallback OnCurrentSimChanged; /// <summary> /// Triggered when an event queue makes the initial connection /// </summary> public event EventQueueRunningCallback OnEventQueueRunning; #endregion Events #region Properties /// <summary>Unique identifier associated with our connections to /// simulators</summary> public uint CircuitCode { get { return _CircuitCode; } set { _CircuitCode = value; } } /// <summary>The simulator that the logged in avatar is currently /// occupying</summary> public Simulator CurrentSim { get { return _CurrentSim; } set { _CurrentSim = value; } } /// <summary>Shows whether the network layer is logged in to the /// grid or not</summary> public bool Connected { get { return connected; } } /// <summary>Number of packets in the incoming queue</summary> public int InboxCount { get { return PacketInbox.Count; } } /// <summary>Number of packets in the outgoing queue</summary> public int OutboxCount { get { return PacketOutbox.Count; } } #endregion Properties /// <summary>All of the simulators we are currently connected to</summary> public List<Simulator> Simulators = new List<Simulator>(); /// <summary>Handlers for incoming capability events</summary> internal CapsEventDictionary CapsEvents; /// <summary>Handlers for incoming packets</summary> internal PacketEventDictionary PacketEvents; /// <summary>Incoming packets that are awaiting handling</summary> internal BlockingQueue<IncomingPacket> PacketInbox = new BlockingQueue<IncomingPacket>(Settings.PACKET_INBOX_SIZE); /// <summary>Outgoing packets that are awaiting handling</summary> internal BlockingQueue<OutgoingPacket> PacketOutbox = new BlockingQueue<OutgoingPacket>(Settings.PACKET_INBOX_SIZE); private GridClient Client; private Timer DisconnectTimer; private uint _CircuitCode; private Simulator _CurrentSim = null; private bool connected = false; /// <summary> /// Default constructor /// </summary> /// <param name="client">Reference to the GridClient object</param> public NetworkManager(GridClient client) { Client = client; PacketEvents = new PacketEventDictionary(client); CapsEvents = new CapsEventDictionary(client); // Register internal CAPS callbacks RegisterEventCallback("EnableSimulator", new Caps.EventQueueCallback(EnableSimulatorHandler)); // Register the internal callbacks RegisterCallback(PacketType.RegionHandshake, new PacketCallback(RegionHandshakeHandler)); RegisterCallback(PacketType.StartPingCheck, new PacketCallback(StartPingCheckHandler)); RegisterCallback(PacketType.DisableSimulator, new PacketCallback(DisableSimulatorHandler)); RegisterCallback(PacketType.KickUser, new PacketCallback(KickUserHandler)); RegisterCallback(PacketType.LogoutReply, new PacketCallback(LogoutReplyHandler)); RegisterCallback(PacketType.CompletePingCheck, new PacketCallback(PongHandler)); RegisterCallback(PacketType.SimStats, new PacketCallback(SimStatsHandler)); // GLOBAL SETTING: Don't force Expect-100: Continue headers on HTTP POST calls ServicePointManager.Expect100Continue = false; } /// <summary> /// Register an event handler for a packet. This is a low level event /// interface and should only be used if you are doing something not /// supported in the library /// </summary> /// <param name="type">Packet type to trigger events for</param> /// <param name="callback">Callback to fire when a packet of this type /// is received</param> public void RegisterCallback(PacketType type, PacketCallback callback) { PacketEvents.RegisterEvent(type, callback); } /// <summary> /// Unregister an event handler for a packet. This is a low level event /// interface and should only be used if you are doing something not /// supported in the library /// </summary> /// <param name="type">Packet type this callback is registered with</param> /// <param name="callback">Callback to stop firing events for</param> public void UnregisterCallback(PacketType type, PacketCallback callback) { PacketEvents.UnregisterEvent(type, callback); } /// <summary> /// Register a CAPS event handler. This is a low level event interface /// and should only be used if you are doing something not supported in /// the library /// </summary> /// <param name="capsEvent">Name of the CAPS event to register a handler for</param> /// <param name="callback">Callback to fire when a CAPS event is received</param> public void RegisterEventCallback(string capsEvent, Caps.EventQueueCallback callback) { CapsEvents.RegisterEvent(capsEvent, callback); } /// <summary> /// Unregister a CAPS event handler. This is a low level event interface /// and should only be used if you are doing something not supported in /// the library /// </summary> /// <param name="capsEvent">Name of the CAPS event this callback is /// registered with</param> /// <param name="callback">Callback to stop firing events for</param> public void UnregisterEventCallback(string capsEvent, Caps.EventQueueCallback callback) { CapsEvents.UnregisterEvent(capsEvent, callback); } /// <summary> /// Send a packet to the simulator the avatar is currently occupying /// </summary> /// <param name="packet">Packet to send</param> public void SendPacket(Packet packet) { if (CurrentSim != null && CurrentSim.Connected) CurrentSim.SendPacket(packet, true); } /// <summary> /// Send a packet to a specified simulator /// </summary> /// <param name="packet">Packet to send</param> /// <param name="simulator">Simulator to send the packet to</param> public void SendPacket(Packet packet, Simulator simulator) { if (simulator != null) simulator.SendPacket(packet, true); } /// <summary> /// Connect to a simulator /// </summary> /// <param name="ip">IP address to connect to</param> /// <param name="port">Port to connect to</param> /// <param name="handle">Handle for this simulator, to identify its /// location in the grid</param> /// <param name="setDefault">Whether to set CurrentSim to this new /// connection, use this if the avatar is moving in to this simulator</param> /// <param name="seedcaps">URL of the capabilities server to use for /// this sim connection</param> /// <returns>A Simulator object on success, otherwise null</returns> public Simulator Connect(IPAddress ip, ushort port, ulong handle, bool setDefault, string seedcaps) { IPEndPoint endPoint = new IPEndPoint(ip, (int)port); return Connect(endPoint, handle, setDefault, seedcaps); } /// <summary> /// Connect to a simulator /// </summary> /// <param name="endPoint">IP address and port to connect to</param> /// <param name="handle">Handle for this simulator, to identify its /// location in the grid</param> /// <param name="setDefault">Whether to set CurrentSim to this new /// connection, use this if the avatar is moving in to this simulator</param> /// <param name="seedcaps">URL of the capabilities server to use for /// this sim connection</param> /// <returns>A Simulator object on success, otherwise null</returns> public Simulator Connect(IPEndPoint endPoint, ulong handle, bool setDefault, string seedcaps) { Simulator simulator = FindSimulator(endPoint); if (simulator == null) { // We're not tracking this sim, create a new Simulator object simulator = new Simulator(Client, endPoint, handle); // Immediately add this simulator to the list of current sims. It will be removed if the // connection fails lock (Simulators) Simulators.Add(simulator); } if (!simulator.Connected) { if (!connected) { // Mark that we are connecting/connected to the grid connected = true; // Open the queues in case this is a reconnect and they were shut down PacketInbox.Open(); PacketOutbox.Open(); // Start the packet decoding thread Thread decodeThread = new Thread(new ThreadStart(IncomingPacketHandler)); decodeThread.Start(); // Start the packet sending thread Thread sendThread = new Thread(new ThreadStart(OutgoingPacketHandler)); sendThread.Start(); } // Fire the OnSimConnecting event if (OnSimConnecting != null) { try { if (!OnSimConnecting(simulator)) { // Callback is requesting that we abort this connection lock (Simulators) Simulators.Remove(simulator); return null; } } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); } } // Attempt to establish a connection to the simulator if (simulator.Connect(setDefault)) { if (DisconnectTimer == null) { // Start a timer that checks if we've been disconnected DisconnectTimer = new Timer(new TimerCallback(DisconnectTimer_Elapsed), null, Client.Settings.SIMULATOR_TIMEOUT, Client.Settings.SIMULATOR_TIMEOUT); } if (setDefault) SetCurrentSim(simulator, seedcaps); // Fire the simulator connection callback if one is registered if (OnSimConnected != null) { try { OnSimConnected(simulator); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); } } // If enabled, send an AgentThrottle packet to the server to increase our bandwidth if (Client.Settings.SEND_AGENT_THROTTLE) Client.Throttle.Set(simulator); return simulator; } else { // Connection failed, remove this simulator from our list and destroy it lock (Simulators) Simulators.Remove(simulator); return null; } } else if (setDefault) { // We're already connected to this server, but need to set it to the default SetCurrentSim(simulator, seedcaps); // Move in to this simulator Client.Self.CompleteAgentMovement(simulator); // Send an initial AgentUpdate to complete our movement in to the sim if (Client.Settings.SEND_AGENT_UPDATES) Client.Self.Movement.SendUpdate(true, simulator); return simulator; } else { // Already connected to this simulator and wasn't asked to set it as the default, // just return a reference to the existing object return simulator; } } /// <summary> /// Initiate a blocking logout request. This will return when the logout /// handshake has completed or when <code>Settings.LOGOUT_TIMEOUT</code> /// has expired and the network layer is manually shut down /// </summary> public void Logout() { AutoResetEvent logoutEvent = new AutoResetEvent(false); LogoutCallback callback = delegate(List<UUID> inventoryItems) { logoutEvent.Set(); }; OnLogoutReply += callback; // Send the packet requesting a clean logout RequestLogout(); // Wait for a logout response. If the response is received, shutdown // will be fired in the callback. Otherwise we fire it manually with // a NetworkTimeout type if (!logoutEvent.WaitOne(Client.Settings.LOGOUT_TIMEOUT, false)) Shutdown(DisconnectType.NetworkTimeout); OnLogoutReply -= callback; } /// <summary> /// Initiate the logout process. Check if logout succeeded with the /// <code>OnLogoutReply</code> event, and if this does not fire the /// <code>Shutdown()</code> function needs to be manually called /// </summary> public void RequestLogout() { // No need to run the disconnect timer any more if (DisconnectTimer != null) DisconnectTimer.Dispose(); // This will catch a Logout when the client is not logged in if (CurrentSim == null || !connected) { Logger.Log("Ignoring RequestLogout(), client is already logged out", Helpers.LogLevel.Warning, Client); return; } Logger.Log("Logging out", Helpers.LogLevel.Info, Client); // Send a logout request to the current sim LogoutRequestPacket logout = new LogoutRequestPacket(); logout.AgentData.AgentID = Client.Self.AgentID; logout.AgentData.SessionID = Client.Self.SessionID; CurrentSim.SendPacket(logout, true); } /// <summary> /// /// </summary> /// <param name="sim"></param> /// <param name="sendCloseCircuit"></param> public void DisconnectSim(Simulator sim, bool sendCloseCircuit) { if (sim != null) { sim.Disconnect(sendCloseCircuit); // Fire the SimDisconnected event if a handler is registered if (OnSimDisconnected != null) { try { OnSimDisconnected(sim, DisconnectType.NetworkTimeout); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); } } lock (Simulators) Simulators.Remove(sim); if (Simulators.Count == 0) Shutdown(DisconnectType.SimShutdown); } else { Logger.Log("DisconnectSim() called with a null Simulator reference", Helpers.LogLevel.Warning, Client); } } /// <summary> /// Shutdown will disconnect all the sims except for the current sim /// first, and then kill the connection to CurrentSim. This should only /// be called if the logout process times out on <code>RequestLogout</code> /// </summary> public void Shutdown(DisconnectType type) { Logger.Log("NetworkManager shutdown initiated", Helpers.LogLevel.Info, Client); // Send a CloseCircuit packet to simulators if we are initiating the disconnect bool sendCloseCircuit = (type == DisconnectType.ClientInitiated || type == DisconnectType.NetworkTimeout); lock (Simulators) { // Disconnect all simulators except the current one for (int i = 0; i < Simulators.Count; i++) { if (Simulators[i] != null && Simulators[i] != CurrentSim) { Simulators[i].Disconnect(sendCloseCircuit); // Fire the SimDisconnected event if a handler is registered if (OnSimDisconnected != null) { try { OnSimDisconnected(Simulators[i], type); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); } } } } Simulators.Clear(); } if (CurrentSim != null) { // Kill the connection to the curent simulator CurrentSim.Disconnect(sendCloseCircuit); // Fire the SimDisconnected event if a handler is registered if (OnSimDisconnected != null) { try { OnSimDisconnected(CurrentSim, type); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); } } } // Clear out all of the packets that never had time to process PacketInbox.Close(); PacketOutbox.Close(); connected = false; // Fire the disconnected callback if (OnDisconnected != null) { try { OnDisconnected(DisconnectType.ClientInitiated, String.Empty); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); } } } /// <summary> /// Searches through the list of currently connected simulators to find /// one attached to the given IPEndPoint /// </summary> /// <param name="endPoint">IPEndPoint of the Simulator to search for</param> /// <returns>A Simulator reference on success, otherwise null</returns> public Simulator FindSimulator(IPEndPoint endPoint) { lock (Simulators) { for (int i = 0; i < Simulators.Count; i++) { if (Simulators[i].IPEndPoint.Equals(endPoint)) return Simulators[i]; } } return null; } /// <summary> /// Fire an event when an event queue connects for capabilities /// </summary> /// <param name="simulator">Simulator the event queue is attached to</param> internal void RaiseConnectedEvent(Simulator simulator) { if (OnEventQueueRunning != null) { try { OnEventQueueRunning(simulator); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); } } } private void OutgoingPacketHandler() { OutgoingPacket outgoingPacket = new OutgoingPacket(); Simulator simulator = null; Packet packet = null; int now; int lastPacketTime = Environment.TickCount; while (connected) { if (PacketOutbox.Dequeue(100, ref outgoingPacket)) { simulator = outgoingPacket.Simulator; packet = outgoingPacket.Packet; // Very primitive rate limiting, keeps a fixed buffer of time between each packet now = Environment.TickCount; int ms = now - lastPacketTime; if (ms < 75) { //Logger.DebugLog(String.Format("Rate limiting, last packet was {0}ms ago", ms)); Thread.Sleep(75 - ms); } lastPacketTime = now; simulator.SendPacketUnqueued(packet, outgoingPacket.SetSequence); } } } private void IncomingPacketHandler() { IncomingPacket incomingPacket = new IncomingPacket(); Packet packet = null; Simulator simulator = null; while (connected) { // Reset packet to null for the check below packet = null; if (PacketInbox.Dequeue(100, ref incomingPacket)) { packet = incomingPacket.Packet; simulator = incomingPacket.Simulator; if (packet != null) { // Skip the ACK handling on packets synthesized from CAPS messages if (packet.Header.Sequence != 0) { #region ACK accounting // TODO: Replace PacketArchive Queue<> with something more efficient // Check the archives to see whether we already received this packet lock (simulator.PacketArchive) { if (simulator.PacketArchive.Contains(packet.Header.Sequence)) { if (packet.Header.Resent) { Logger.DebugLog("Received resent packet #" + packet.Header.Sequence, Client); } else { Logger.Log(String.Format("Received a duplicate of packet #{0}, current type: {1}", packet.Header.Sequence, packet.Type), Helpers.LogLevel.Warning, Client); } // Avoid firing a callback twice for the same packet continue; } else { // Keep the PacketArchive size within a certain capacity while (simulator.PacketArchive.Count >= Settings.PACKET_ARCHIVE_SIZE) { simulator.PacketArchive.Dequeue(); simulator.PacketArchive.Dequeue(); simulator.PacketArchive.Dequeue(); simulator.PacketArchive.Dequeue(); } simulator.PacketArchive.Enqueue(packet.Header.Sequence); } } #endregion ACK accounting #region ACK handling // Handle appended ACKs if (packet.Header.AppendedAcks) { lock (simulator.NeedAck) { for (int i = 0; i < packet.Header.AckList.Length; i++) simulator.NeedAck.Remove(packet.Header.AckList[i]); } } // Handle PacketAck packets if (packet.Type == PacketType.PacketAck) { PacketAckPacket ackPacket = (PacketAckPacket)packet; lock (simulator.NeedAck) { for (int i = 0; i < ackPacket.Packets.Length; i++) simulator.NeedAck.Remove(ackPacket.Packets[i].ID); } } #endregion ACK handling } #region Fire callbacks if (Client.Settings.SYNC_PACKETCALLBACKS) PacketEvents.RaiseEvent(packet.Type, packet, simulator); else PacketEvents.BeginRaiseEvent(packet.Type, packet, simulator); #endregion Fire callbacks } } } } private void SetCurrentSim(Simulator simulator, string seedcaps) { if (simulator != CurrentSim) { Simulator oldSim = CurrentSim; lock (Simulators) CurrentSim = simulator; // CurrentSim is synchronized against Simulators simulator.SetSeedCaps(seedcaps); // If the current simulator changed fire the callback if (OnCurrentSimChanged != null && simulator != oldSim) { try { OnCurrentSimChanged(oldSim); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); } } } } #region Timers private void DisconnectTimer_Elapsed(object obj) { if (!connected || CurrentSim == null) { if (DisconnectTimer != null) DisconnectTimer.Dispose(); connected = false; } else if (CurrentSim.DisconnectCandidate) { // The currently occupied simulator hasn't sent us any traffic in a while, shutdown Logger.Log("Network timeout for the current simulator (" + CurrentSim.ToString() + "), logging out", Helpers.LogLevel.Warning, Client); if (DisconnectTimer != null) DisconnectTimer.Dispose(); connected = false; // Shutdown the network layer Shutdown(DisconnectType.NetworkTimeout); } else { #region Check for timed out simulators // Figure out which sims need to be disconnected, then fire // all of the events to avoid calling DisconnectSim() inside // the Simulators lock List<Simulator> disconnectedSims = null; // Check all of the connected sims for disconnects lock (Simulators) { for (int i = 0; i < Simulators.Count; i++) { if (Simulators[i].DisconnectCandidate) { // Avoid initializing a new List<> every time the timer // fires with this piece of code if (disconnectedSims == null) disconnectedSims = new List<Simulator>(); disconnectedSims.Add(Simulators[i]); } else { Simulators[i].DisconnectCandidate = true; } } } // Actually disconnect each sim we detected as disconnected if (disconnectedSims != null) { for (int i = 0; i < disconnectedSims.Count; i++) { if (disconnectedSims[i] != null) { // This sim hasn't received any network traffic since the // timer last elapsed, consider it disconnected Logger.Log("Network timeout for simulator " + disconnectedSims[i].ToString() + ", disconnecting", Helpers.LogLevel.Warning, Client); DisconnectSim(disconnectedSims[i], true); } } } #endregion Check for timed out simulators } } #endregion Timers #region Packet Callbacks /// <summary> /// Called to deal with LogoutReply packet and fires off callback /// </summary> /// <param name="packet">Full packet of type LogoutReplyPacket</param> /// <param name="simulator"></param> private void LogoutReplyHandler(Packet packet, Simulator simulator) { LogoutReplyPacket logout = (LogoutReplyPacket)packet; if ((logout.AgentData.SessionID == Client.Self.SessionID) && (logout.AgentData.AgentID == Client.Self.AgentID)) { Logger.DebugLog("Logout reply received", Client); // Deal with callbacks, if any if (OnLogoutReply != null) { List<UUID> itemIDs = new List<UUID>(); foreach (LogoutReplyPacket.InventoryDataBlock InventoryData in logout.InventoryData) { itemIDs.Add(InventoryData.ItemID); } try { OnLogoutReply(itemIDs); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); } } // If we are receiving a LogoutReply packet assume this is a client initiated shutdown Shutdown(DisconnectType.ClientInitiated); } else { Logger.Log("Invalid Session or Agent ID received in Logout Reply... ignoring", Helpers.LogLevel.Warning, Client); } } private void StartPingCheckHandler(Packet packet, Simulator simulator) { StartPingCheckPacket incomingPing = (StartPingCheckPacket)packet; CompletePingCheckPacket ping = new CompletePingCheckPacket(); ping.PingID.PingID = incomingPing.PingID.PingID; ping.Header.Reliable = false; // TODO: We can use OldestUnacked to correct transmission errors // I don't think that's right. As far as I can tell, the Viewer // only uses this to prune its duplicate-checking buffer. -bushing SendPacket(ping, simulator); } private void PongHandler(Packet packet, Simulator simulator) { CompletePingCheckPacket pong = (CompletePingCheckPacket)packet; String retval = "Pong2: " + (Environment.TickCount - simulator.Stats.LastPingSent); if ((pong.PingID.PingID - simulator.Stats.LastPingID + 1) != 0) retval += " (gap of " + (pong.PingID.PingID - simulator.Stats.LastPingID + 1) + ")"; simulator.Stats.LastLag = Environment.TickCount - simulator.Stats.LastPingSent; simulator.Stats.ReceivedPongs++; // Client.Log(retval, Helpers.LogLevel.Info); } private void SimStatsHandler(Packet packet, Simulator simulator) { if ( ! Client.Settings.ENABLE_SIMSTATS ) { return; } SimStatsPacket stats = (SimStatsPacket)packet; for ( int i = 0 ; i < stats.Stat.Length ; i++ ) { SimStatsPacket.StatBlock s = stats.Stat[i]; switch (s.StatID ) { case 0: simulator.Stats.Dilation = s.StatValue; break; case 1: simulator.Stats.FPS = Convert.ToInt32(s.StatValue); break; case 2: simulator.Stats.PhysicsFPS = s.StatValue; break; case 3: simulator.Stats.AgentUpdates = s.StatValue; break; case 4: simulator.Stats.FrameTime = s.StatValue; break; case 5: simulator.Stats.NetTime = s.StatValue; break; case 6: simulator.Stats.OtherTime = s.StatValue; break; case 7: simulator.Stats.PhysicsTime = s.StatValue; break; case 8: simulator.Stats.AgentTime = s.StatValue; break; case 9: simulator.Stats.ImageTime = s.StatValue; break; case 10: simulator.Stats.ScriptTime = s.StatValue; break; case 11: simulator.Stats.Objects = Convert.ToInt32(s.StatValue); break; case 12: simulator.Stats.ScriptedObjects = Convert.ToInt32(s.StatValue); break; case 13: simulator.Stats.Agents = Convert.ToInt32(s.StatValue); break; case 14: simulator.Stats.ChildAgents = Convert.ToInt32(s.StatValue); break; case 15: simulator.Stats.ActiveScripts = Convert.ToInt32(s.StatValue); break; case 16: simulator.Stats.LSLIPS = Convert.ToInt32(s.StatValue); break; case 17: simulator.Stats.INPPS = Convert.ToInt32(s.StatValue); break; case 18: simulator.Stats.OUTPPS = Convert.ToInt32(s.StatValue); break; case 19: simulator.Stats.PendingDownloads = Convert.ToInt32(s.StatValue); break; case 20: simulator.Stats.PendingUploads = Convert.ToInt32(s.StatValue); break; case 21: simulator.Stats.VirtualSize = Convert.ToInt32(s.StatValue); break; case 22: simulator.Stats.ResidentSize = Convert.ToInt32(s.StatValue); break; case 23: simulator.Stats.PendingLocalUploads = Convert.ToInt32(s.StatValue); break; case 24: simulator.Stats.UnackedBytes = Convert.ToInt32(s.StatValue); break; } } } private void RegionHandshakeHandler(Packet packet, Simulator simulator) { RegionHandshakePacket handshake = (RegionHandshakePacket)packet; simulator.ID = handshake.RegionInfo.CacheID; simulator.IsEstateManager = handshake.RegionInfo.IsEstateManager; simulator.Name = Utils.BytesToString(handshake.RegionInfo.SimName); simulator.SimOwner = handshake.RegionInfo.SimOwner; simulator.TerrainBase0 = handshake.RegionInfo.TerrainBase0; simulator.TerrainBase1 = handshake.RegionInfo.TerrainBase1; simulator.TerrainBase2 = handshake.RegionInfo.TerrainBase2; simulator.TerrainBase3 = handshake.RegionInfo.TerrainBase3; simulator.TerrainDetail0 = handshake.RegionInfo.TerrainDetail0; simulator.TerrainDetail1 = handshake.RegionInfo.TerrainDetail1; simulator.TerrainDetail2 = handshake.RegionInfo.TerrainDetail2; simulator.TerrainDetail3 = handshake.RegionInfo.TerrainDetail3; simulator.TerrainHeightRange00 = handshake.RegionInfo.TerrainHeightRange00; simulator.TerrainHeightRange01 = handshake.RegionInfo.TerrainHeightRange01; simulator.TerrainHeightRange10 = handshake.RegionInfo.TerrainHeightRange10; simulator.TerrainHeightRange11 = handshake.RegionInfo.TerrainHeightRange11; simulator.TerrainStartHeight00 = handshake.RegionInfo.TerrainStartHeight00; simulator.TerrainStartHeight01 = handshake.RegionInfo.TerrainStartHeight01; simulator.TerrainStartHeight10 = handshake.RegionInfo.TerrainStartHeight10; simulator.TerrainStartHeight11 = handshake.RegionInfo.TerrainStartHeight11; simulator.WaterHeight = handshake.RegionInfo.WaterHeight; simulator.Flags = (RegionFlags)handshake.RegionInfo.RegionFlags; simulator.BillableFactor = handshake.RegionInfo.BillableFactor; simulator.Access = (SimAccess)handshake.RegionInfo.SimAccess; Logger.Log("Received a region handshake for " + simulator.ToString(), Helpers.LogLevel.Info, Client); // Send a RegionHandshakeReply RegionHandshakeReplyPacket reply = new RegionHandshakeReplyPacket(); reply.AgentData.AgentID = Client.Self.AgentID; reply.AgentData.SessionID = Client.Self.SessionID; reply.RegionInfo.Flags = 0; SendPacket(reply, simulator); // We're officially connected to this sim simulator.connected = true; simulator.ConnectedEvent.Set(); } /// <summary> /// Handler for EnableSimulator packet /// </summary> /// <param name="capsKey">the Capabilities Key, "EnableSimulator"</param> /// <param name="llsd">the LLSD Encoded packet</param> /// <param name="simulator">The simulator the packet was sent from</param> private void EnableSimulatorHandler(string capsKey, LLSD llsd, Simulator simulator) { if (!Client.Settings.MULTIPLE_SIMS) return; LLSDMap map = (LLSDMap)llsd; LLSDArray connectInfo = (LLSDArray)map["SimulatorInfo"]; for(int i = 0; i < connectInfo.Count; i++) { LLSDMap data = (LLSDMap)connectInfo[i]; IPAddress ip = new IPAddress(data["IP"].AsBinary()); ushort port = (ushort)data["Port"].AsInteger(); byte[] bytes = data["Handle"].AsBinary(); if (BitConverter.IsLittleEndian) Array.Reverse(bytes); ulong rh = Utils.BytesToUInt64(bytes); IPEndPoint endPoint = new IPEndPoint(ip, port); // don't reconnect if we're already connected or attempting to connect if (FindSimulator(endPoint) != null) return; if (Connect(ip, port, rh, false, LoginSeedCapability) == null) { Logger.Log("Unabled to connect to new sim " + ip + ":" + port, Helpers.LogLevel.Error, Client); } } } private void DisableSimulatorHandler(Packet packet, Simulator simulator) { Logger.DebugLog("Received a DisableSimulator packet from " + simulator + ", shutting it down", Client); DisconnectSim(simulator, false); } private void KickUserHandler(Packet packet, Simulator simulator) { string message = Utils.BytesToString(((KickUserPacket)packet).UserInfo.Reason); // Fire the callback to let client apps know we are shutting down if (OnDisconnected != null) { try { OnDisconnected(DisconnectType.ServerInitiated, message); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); } } // Shutdown the network layer Shutdown(DisconnectType.ServerInitiated); } #endregion Packet Callbacks } }
using System; using System.Threading.Tasks; using System.Web; using System.Net; using System.Text; using System.IO; using System.Threading; using System.Collections.Generic; using System.Security.Cryptography; using System.ComponentModel; using SteamBot.SteamGroups; using SteamKit2; using SteamTrade; using SteamKit2.Internal; using SteamTrade.TradeOffer; using System.Globalization; using System.Text.RegularExpressions; namespace SteamBot { public class Bot : IDisposable { #region Bot delegates public delegate UserHandler UserHandlerCreator(Bot bot, SteamID id); #endregion #region Private readonly variables private readonly SteamUser.LogOnDetails logOnDetails; private readonly string schemaLang; private readonly string logFile; private readonly Dictionary<SteamID, UserHandler> userHandlers; private readonly Log.LogLevel consoleLogLevel; private readonly Log.LogLevel fileLogLevel; private readonly UserHandlerCreator createHandler; private readonly bool isProccess; private readonly BackgroundWorker botThread; private readonly CallbackManager steamCallbackManager; #endregion #region Private variables private Task<Inventory> myInventoryTask; private TradeManager tradeManager; private TradeOfferManager tradeOfferManager; private int tradePollingInterval; private int tradeOfferPollingIntervalSecs; private string myUserNonce; private string myUniqueId; private bool cookiesAreInvalid = true; private List<SteamID> friends; private bool disposed = false; private string consoleInput; private Thread tradeOfferThread; #endregion #region Public readonly variables /// <summary> /// Userhandler class bot is running. /// </summary> public readonly string BotControlClass; /// <summary> /// The display name of bot to steam. /// </summary> public readonly string DisplayName; /// <summary> /// The chat response from the config file. /// </summary> public readonly string ChatResponse; /// <summary> /// An array of admins for bot. /// </summary> public readonly IEnumerable<SteamID> Admins; public readonly SteamClient SteamClient; public readonly SteamUser SteamUser; public readonly SteamFriends SteamFriends; public readonly SteamTrading SteamTrade; public readonly SteamGameCoordinator SteamGameCoordinator; public readonly SteamNotifications SteamNotifications; /// <summary> /// The amount of time the bot will trade for. /// </summary> public readonly int MaximumTradeTime; /// <summary> /// The amount of time the bot will wait between user interactions with trade. /// </summary> public readonly int MaximumActionGap; /// <summary> /// The api key of bot. /// </summary> public readonly string ApiKey; public readonly SteamWeb SteamWeb; /// <summary> /// The prefix shown before bot's display name. /// </summary> public readonly string DisplayNamePrefix; /// <summary> /// The instance of the Logger for the bot. /// </summary> public readonly Log Log; #endregion #region Public variables public string AuthCode; public bool IsRunning; /// <summary> /// Is bot fully Logged in. /// Set only when bot did successfully Log in. /// </summary> public bool IsLoggedIn { get; private set; } /// <summary> /// The current trade the bot is in. /// </summary> public Trade CurrentTrade { get; private set; } /// <summary> /// The current game bot is in. /// Default: 0 = No game. /// </summary> public int CurrentGame { get; private set; } public SteamAuth.SteamGuardAccount SteamGuardAccount; #endregion public IEnumerable<SteamID> FriendsList { get { CreateFriendsListIfNecessary(); return friends; } } public Inventory MyInventory { get { myInventoryTask.Wait(); return myInventoryTask.Result; } } public CallbackManager SteamCallbackManager { get { return steamCallbackManager; } } /// <summary> /// Compatibility sanity. /// </summary> [Obsolete("Refactored to be Log instead of log")] public Log log { get { return Log; } } public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false, bool process = false, bool useTwoFactorByDefault = false) { userHandlers = new Dictionary<SteamID, UserHandler>(); logOnDetails = new SteamUser.LogOnDetails { Username = config.Username, Password = config.Password }; DisplayName = config.DisplayName; ChatResponse = config.ChatResponse; MaximumTradeTime = config.MaximumTradeTime; MaximumActionGap = config.MaximumActionGap; DisplayNamePrefix = config.DisplayNamePrefix; tradePollingInterval = config.TradePollingInterval <= 100 ? 800 : config.TradePollingInterval; tradeOfferPollingIntervalSecs = (config.TradeOfferPollingIntervalSecs == 0 ? 30 : config.TradeOfferPollingIntervalSecs); schemaLang = config.SchemaLang != null && config.SchemaLang.Length == 2 ? config.SchemaLang.ToLower() : "en"; Admins = config.Admins; ApiKey = !String.IsNullOrEmpty(config.ApiKey) ? config.ApiKey : apiKey; isProccess = process; try { if( config.LogLevel != null ) { consoleLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.LogLevel, true); Console.WriteLine(@"(Console) LogLevel configuration parameter used in bot {0} is depreciated and may be removed in future versions. Please use ConsoleLogLevel instead.", DisplayName); } else consoleLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.ConsoleLogLevel, true); } catch (ArgumentException) { Console.WriteLine(@"(Console) ConsoleLogLevel invalid or unspecified for bot {0}. Defaulting to ""Info""", DisplayName); consoleLogLevel = Log.LogLevel.Info; } try { fileLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.FileLogLevel, true); } catch (ArgumentException) { Console.WriteLine(@"(Console) FileLogLevel invalid or unspecified for bot {0}. Defaulting to ""Info""", DisplayName); fileLogLevel = Log.LogLevel.Info; } logFile = config.LogFile; Log = new Log(logFile, DisplayName, consoleLogLevel, fileLogLevel); if (useTwoFactorByDefault) { var mobileAuthCode = GetMobileAuthCode(); if (string.IsNullOrEmpty(mobileAuthCode)) { Log.Error("Failed to generate 2FA code. Make sure you have linked the authenticator via SteamBot."); } else { logOnDetails.TwoFactorCode = mobileAuthCode; Log.Success("Generated 2FA code."); } } createHandler = handlerCreator; BotControlClass = config.BotControlClass; SteamWeb = new SteamWeb(); // Hacking around https ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate; Log.Debug ("Initializing Steam Bot..."); SteamClient = new SteamClient(); SteamClient.AddHandler(new SteamNotifications()); steamCallbackManager = new CallbackManager(SteamClient); SubscribeSteamCallbacks(); SteamTrade = SteamClient.GetHandler<SteamTrading>(); SteamUser = SteamClient.GetHandler<SteamUser>(); SteamFriends = SteamClient.GetHandler<SteamFriends>(); SteamGameCoordinator = SteamClient.GetHandler<SteamGameCoordinator>(); SteamNotifications = SteamClient.GetHandler<SteamNotifications>(); botThread = new BackgroundWorker { WorkerSupportsCancellation = true }; botThread.DoWork += BackgroundWorkerOnDoWork; botThread.RunWorkerCompleted += BackgroundWorkerOnRunWorkerCompleted; } ~Bot() { Dispose(false); } private void CreateFriendsListIfNecessary() { if (friends != null) return; friends = new List<SteamID>(); for (int i = 0; i < SteamFriends.GetFriendCount(); i++) friends.Add(SteamFriends.GetFriendByIndex(i)); } /// <summary> /// Occurs when the bot needs the SteamGuard authentication code. /// </summary> /// <remarks> /// Return the code in <see cref="SteamGuardRequiredEventArgs.SteamGuard"/> /// </remarks> public event EventHandler<SteamGuardRequiredEventArgs> OnSteamGuardRequired; /// <summary> /// Starts the callback thread and connects to Steam via SteamKit2. /// </summary> /// <remarks> /// THIS NEVER RETURNS. /// </remarks> /// <returns><c>true</c>. See remarks</returns> public bool StartBot() { IsRunning = true; Log.Info("Connecting..."); if (!botThread.IsBusy) botThread.RunWorkerAsync(); SteamClient.Connect(); Log.Success("Done Loading Bot!"); return true; // never get here } /// <summary> /// Disconnect from the Steam network and stop the callback /// thread. /// </summary> public void StopBot() { IsRunning = false; Log.Debug("Trying to shut down bot thread."); SteamClient.Disconnect(); botThread.CancelAsync(); while (botThread.IsBusy) Thread.Yield(); userHandlers.Clear(); } /// <summary> /// Creates a new trade with the given partner. /// </summary> /// <returns> /// <c>true</c>, if trade was opened, /// <c>false</c> if there is another trade that must be closed first. /// </returns> public bool OpenTrade (SteamID other) { if (CurrentTrade != null || CheckCookies() == false) return false; SteamTrade.Trade(other); return true; } /// <summary> /// Closes the current active trade. /// </summary> public void CloseTrade() { if (CurrentTrade == null) return; UnsubscribeTrade (GetUserHandler (CurrentTrade.OtherSID), CurrentTrade); tradeManager.StopTrade (); CurrentTrade = null; } void OnTradeTimeout(object sender, EventArgs args) { // ignore event params and just null out the trade. GetUserHandler(CurrentTrade.OtherSID).OnTradeTimeout(); } /// <summary> /// Create a new trade offer with the specified partner /// </summary> /// <param name="other">SteamId of the partner</param> /// <returns></returns> public TradeOffer NewTradeOffer(SteamID other) { return tradeOfferManager.NewOffer(other); } /// <summary> /// Try to get a specific trade offer using the offerid /// </summary> /// <param name="offerId"></param> /// <param name="tradeOffer"></param> /// <returns></returns> public bool TryGetTradeOffer(string offerId, out TradeOffer tradeOffer) { return tradeOfferManager.TryGetOffer(offerId, out tradeOffer); } public void HandleBotCommand(string command) { try { if (command == "linkauth") { LinkMobileAuth(); } else if (command == "getauth") { try { Log.Success("Generated Steam Guard code: " + SteamGuardAccount.GenerateSteamGuardCode()); } catch (NullReferenceException) { Log.Error("Unable to generate Steam Guard code."); } } else if (command == "unlinkauth") { if (SteamGuardAccount == null) { Log.Error("Mobile authenticator is not active on this bot."); } else if (SteamGuardAccount.DeactivateAuthenticator()) { Log.Success("Deactivated authenticator on this account."); } else { Log.Error("Failed to deactivate authenticator on this account."); } } else { GetUserHandler(SteamClient.SteamID).OnBotCommand(command); } } catch (ObjectDisposedException e) { // Writing to console because odds are the error was caused by a disposed Log. Console.WriteLine(string.Format("Exception caught in BotCommand Thread: {0}", e)); if (!this.IsRunning) { Console.WriteLine("The Bot is no longer running and could not write to the Log. Try Starting this bot first."); } } catch (Exception e) { Console.WriteLine(string.Format("Exception caught in BotCommand Thread: {0}", e)); } } protected void SpawnTradeOfferPollingThread() { if (tradeOfferThread == null) { tradeOfferThread = new Thread(TradeOfferPollingFunction); tradeOfferThread.Start(); } } protected void CancelTradeOfferPollingThread() { tradeOfferThread = null; } protected void TradeOfferPollingFunction() { while (tradeOfferThread == Thread.CurrentThread) { try { tradeOfferManager.EnqueueUpdatedOffers(); } catch (Exception e) { Log.Error("Error while polling trade offers: " + e); } Thread.Sleep(tradeOfferPollingIntervalSecs*1000); } } public void HandleInput(string input) { consoleInput = input; } public string WaitForInput() { consoleInput = null; while (true) { if (consoleInput != null) { return consoleInput; } Thread.Sleep(5); } } bool HandleTradeSessionStart (SteamID other) { if (CurrentTrade != null) return false; try { tradeManager.InitializeTrade(SteamUser.SteamID, other); CurrentTrade = tradeManager.CreateTrade(SteamUser.SteamID, other); CurrentTrade.OnClose += CloseTrade; SubscribeTrade(CurrentTrade, GetUserHandler(other)); tradeManager.StartTradeThread(CurrentTrade); return true; } catch (SteamTrade.Exceptions.InventoryFetchException) { // we shouldn't get here because the inv checks are also // done in the TradeProposedCallback handler. /*string response = String.Empty; if (ie.FailingSteamId.ConvertToUInt64() == other.ConvertToUInt64()) { response = "Trade failed. Could not correctly fetch your backpack. Either the inventory is inaccessible or your backpack is private."; } else { response = "Trade failed. Could not correctly fetch my backpack."; } SteamFriends.SendChatMessage(other, EChatEntryType.ChatMsg, response); Log.Info ("Bot sent other: {0}", response); CurrentTrade = null;*/ return false; } } public void SetGamePlaying(int id) { var gamePlaying = new SteamKit2.ClientMsgProtobuf<CMsgClientGamesPlayed>(EMsg.ClientGamesPlayed); if (id != 0) gamePlaying.Body.games_played.Add(new CMsgClientGamesPlayed.GamePlayed { game_id = new GameID(id), }); SteamClient.Send(gamePlaying); CurrentGame = id; } string GetMobileAuthCode() { var authFile = Path.Combine("authfiles", String.Format("{0}.auth", logOnDetails.Username)); if (File.Exists(authFile)) { SteamGuardAccount = Newtonsoft.Json.JsonConvert.DeserializeObject<SteamAuth.SteamGuardAccount>(File.ReadAllText(authFile)); return SteamGuardAccount.GenerateSteamGuardCode(); } return string.Empty; } /// <summary> /// Link a mobile authenticator to bot account, using SteamTradeOffersBot as the authenticator. /// Called from bot manager console. Usage: "exec [index] linkauth" /// If successful, 2FA will be required upon the next login. /// Use "exec [index] getauth" if you need to get a Steam Guard code for the account. /// To deactivate the authenticator, use "exec [index] unlinkauth". /// </summary> void LinkMobileAuth() { new Thread(() => { var login = new SteamAuth.UserLogin(logOnDetails.Username, logOnDetails.Password); var loginResult = login.DoLogin(); if (loginResult == SteamAuth.LoginResult.NeedEmail) { while (loginResult == SteamAuth.LoginResult.NeedEmail) { Log.Interface("Enter Steam Guard code from email (type \"input [index] [code]\"):"); var emailCode = WaitForInput(); login.EmailCode = emailCode; loginResult = login.DoLogin(); } } if (loginResult == SteamAuth.LoginResult.LoginOkay) { Log.Info("Linking mobile authenticator..."); var authLinker = new SteamAuth.AuthenticatorLinker(login.Session); var addAuthResult = authLinker.AddAuthenticator(); if (addAuthResult == SteamAuth.AuthenticatorLinker.LinkResult.MustProvidePhoneNumber) { while (addAuthResult == SteamAuth.AuthenticatorLinker.LinkResult.MustProvidePhoneNumber) { Log.Interface("Enter phone number with country code, e.g. +1XXXXXXXXXXX (type \"input [index] [number]\"):"); var phoneNumber = WaitForInput(); authLinker.PhoneNumber = phoneNumber; addAuthResult = authLinker.AddAuthenticator(); } } if (addAuthResult == SteamAuth.AuthenticatorLinker.LinkResult.AwaitingFinalization) { SteamGuardAccount = authLinker.LinkedAccount; try { var authFile = Path.Combine("authfiles", String.Format("{0}.auth", logOnDetails.Username)); Directory.CreateDirectory(Path.Combine(System.Windows.Forms.Application.StartupPath, "authfiles")); File.WriteAllText(authFile, Newtonsoft.Json.JsonConvert.SerializeObject(SteamGuardAccount)); Log.Interface("Enter SMS code (type \"input [index] [code]\"):"); var smsCode = WaitForInput(); var authResult = authLinker.FinalizeAddAuthenticator(smsCode); if (authResult == SteamAuth.AuthenticatorLinker.FinalizeResult.Success) { Log.Success("Linked authenticator."); } else { Log.Error("Error linking authenticator: " + authResult); } } catch (IOException) { Log.Error("Failed to save auth file. Aborting authentication."); } } else { Log.Error("Error adding authenticator: " + addAuthResult); } } else { if (loginResult == SteamAuth.LoginResult.Need2FA) { Log.Error("Mobile authenticator has already been linked!"); } else { Log.Error("Error performing mobile login: " + loginResult); } } }).Start(); } void UserLogOn() { // get sentry file which has the machine hw info saved // from when a steam guard code was entered Directory.CreateDirectory(System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "sentryfiles")); FileInfo fi = new FileInfo(System.IO.Path.Combine("sentryfiles",String.Format("{0}.sentryfile", logOnDetails.Username))); if (fi.Exists && fi.Length > 0) logOnDetails.SentryFileHash = SHAHash(File.ReadAllBytes(fi.FullName)); else logOnDetails.SentryFileHash = null; SteamUser.LogOn(logOnDetails); } void UserWebLogOn() { do { IsLoggedIn = SteamWeb.Authenticate(myUniqueId, SteamClient, myUserNonce); if(!IsLoggedIn) { Log.Warn("Authentication failed, retrying in 2s..."); Thread.Sleep(2000); } } while(!IsLoggedIn); Log.Success("User Authenticated!"); tradeManager = new TradeManager(ApiKey, SteamWeb); tradeManager.SetTradeTimeLimits(MaximumTradeTime, MaximumActionGap, tradePollingInterval); tradeManager.OnTimeout += OnTradeTimeout; tradeOfferManager = new TradeOfferManager(ApiKey, SteamWeb); SubscribeTradeOffer(tradeOfferManager); cookiesAreInvalid = false; // Success, check trade offers which we have received while we were offline SpawnTradeOfferPollingThread(); } /// <summary> /// Checks if sessionId and token cookies are still valid. /// Sets cookie flag if they are invalid. /// </summary> /// <returns>true if cookies are valid; otherwise false</returns> bool CheckCookies() { // We still haven't re-authenticated if (cookiesAreInvalid) return false; try { if (!SteamWeb.VerifyCookies()) { // Cookies are no longer valid Log.Warn("Cookies are invalid. Need to re-authenticate."); cookiesAreInvalid = true; SteamUser.RequestWebAPIUserNonce(); return false; } } catch { // Even if exception is caught, we should still continue. Log.Warn("Cookie check failed. http://steamcommunity.com is possibly down."); } return true; } public UserHandler GetUserHandler(SteamID sid) { if (!userHandlers.ContainsKey(sid)) userHandlers[sid] = createHandler(this, sid); return userHandlers[sid]; } void RemoveUserHandler(SteamID sid) { if (userHandlers.ContainsKey(sid)) userHandlers.Remove(sid); } static byte [] SHAHash (byte[] input) { SHA1Managed sha = new SHA1Managed(); byte[] output = sha.ComputeHash( input ); sha.Clear(); return output; } void OnUpdateMachineAuthCallback(SteamUser.UpdateMachineAuthCallback machineAuth) { byte[] hash = SHAHash (machineAuth.Data); Directory.CreateDirectory(System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "sentryfiles")); File.WriteAllBytes (System.IO.Path.Combine("sentryfiles", String.Format("{0}.sentryfile", logOnDetails.Username)), machineAuth.Data); var authResponse = new SteamUser.MachineAuthDetails { BytesWritten = machineAuth.BytesToWrite, FileName = machineAuth.FileName, FileSize = machineAuth.BytesToWrite, Offset = machineAuth.Offset, SentryFileHash = hash, // should be the sha1 hash of the sentry file we just wrote OneTimePassword = machineAuth.OneTimePassword, // not sure on this one yet, since we've had no examples of steam using OTPs LastError = 0, // result from win32 GetLastError Result = EResult.OK, // if everything went okay, otherwise ~who knows~ JobID = machineAuth.JobID, // so we respond to the correct server job }; // send off our response SteamUser.SendMachineAuthResponse (authResponse); } /// <summary> /// Gets the bot's inventory and stores it in MyInventory. /// </summary> /// <example> This sample shows how to find items in the bot's inventory from a user handler. /// <code> /// Bot.GetInventory(); // Get the inventory first /// foreach (var item in Bot.MyInventory.Items) /// { /// if (item.Defindex == 5021) /// { /// // Bot has a key in its inventory /// } /// } /// </code> /// </example> public void GetInventory() { myInventoryTask = Task.Factory.StartNew((Func<Inventory>) FetchBotsInventory); } public void TradeOfferRouter(TradeOffer offer) { GetUserHandler(offer.PartnerSteamId).OnTradeOfferUpdated(offer); } public void SubscribeTradeOffer(TradeOfferManager tradeOfferManager) { tradeOfferManager.OnTradeOfferUpdated += TradeOfferRouter; } //todo: should unsubscribe eventually... public void UnsubscribeTradeOffer(TradeOfferManager tradeOfferManager) { tradeOfferManager.OnTradeOfferUpdated -= TradeOfferRouter; } /// <summary> /// Subscribes all listeners of this to the trade. /// </summary> public void SubscribeTrade (Trade trade, UserHandler handler) { trade.OnAwaitingConfirmation += handler._OnTradeAwaitingConfirmation; trade.OnClose += handler.OnTradeClose; trade.OnError += handler.OnTradeError; trade.OnStatusError += handler.OnStatusError; //trade.OnTimeout += OnTradeTimeout; trade.OnAfterInit += handler.OnTradeInit; trade.OnUserAddItem += handler.OnTradeAddItem; trade.OnUserRemoveItem += handler.OnTradeRemoveItem; trade.OnMessage += handler.OnTradeMessageHandler; trade.OnUserSetReady += handler.OnTradeReadyHandler; trade.OnUserAccept += handler.OnTradeAcceptHandler; } /// <summary> /// Unsubscribes all listeners of this from the current trade. /// </summary> public void UnsubscribeTrade (UserHandler handler, Trade trade) { trade.OnAwaitingConfirmation -= handler._OnTradeAwaitingConfirmation; trade.OnClose -= handler.OnTradeClose; trade.OnError -= handler.OnTradeError; trade.OnStatusError -= handler.OnStatusError; //Trade.OnTimeout -= OnTradeTimeout; trade.OnAfterInit -= handler.OnTradeInit; trade.OnUserAddItem -= handler.OnTradeAddItem; trade.OnUserRemoveItem -= handler.OnTradeRemoveItem; trade.OnMessage -= handler.OnTradeMessageHandler; trade.OnUserSetReady -= handler.OnTradeReadyHandler; trade.OnUserAccept -= handler.OnTradeAcceptHandler; } /// <summary> /// Fetch the Bot's inventory and log a warning if it's private /// </summary> private Inventory FetchBotsInventory() { var inventory = Inventory.FetchInventory(SteamUser.SteamID, ApiKey, SteamWeb); if(inventory.IsPrivate) { Log.Warn("The bot's backpack is private! If your bot adds any items it will fail! Your bot's backpack should be Public."); } return inventory; } public void AcceptAllMobileTradeConfirmations() { if (SteamGuardAccount == null) { Log.Warn("Bot account does not have 2FA enabled."); } else { SteamGuardAccount.Session.SteamLogin = SteamWeb.Token; SteamGuardAccount.Session.SteamLoginSecure = SteamWeb.TokenSecure; try { foreach (var confirmation in SteamGuardAccount.FetchConfirmations()) { if (SteamGuardAccount.AcceptConfirmation(confirmation)) { Log.Success("Confirmed {0}. (Confirmation ID #{1})", confirmation.Description, confirmation.ID); } } } catch (SteamAuth.SteamGuardAccount.WGTokenInvalidException) { Log.Error("Invalid session when trying to fetch trade confirmations."); } } } /// <summary> /// Get duration of escrow in days. Call this before sending a trade offer. /// Credit to: https://www.reddit.com/r/SteamBot/comments/3w8j7c/code_getescrowduration_for_c/ /// </summary> /// <param name="steamId">Steam ID of user you want to send a trade offer to</param> /// <param name="token">User's trade token. Can be an empty string if user is on bot's friends list.</param> /// <exception cref="NullReferenceException">Thrown when Steam returns an empty response.</exception> /// <exception cref="TradeOfferEscrowDurationParseException">Thrown when the user is unavailable for trade or Steam returns invalid data.</exception> /// <returns>TradeOfferEscrowDuration</returns> public TradeOfferEscrowDuration GetEscrowDuration(SteamID steamId, string token) { var url = "https://steamcommunity.com/tradeoffer/new/"; var data = new System.Collections.Specialized.NameValueCollection(); data.Add("partner", steamId.AccountID.ToString()); if (!string.IsNullOrEmpty(token)) { data.Add("token", token); } var resp = SteamWeb.Fetch(url, "GET", data, false); if (string.IsNullOrWhiteSpace(resp)) { throw new NullReferenceException("Empty response from Steam when trying to retrieve escrow duration."); } return ParseEscrowResponse(resp); } /// <summary> /// Get duration of escrow in days. Call this after receiving a trade offer. /// </summary> /// <param name="tradeOfferId">The ID of the trade offer</param> /// <exception cref="NullReferenceException">Thrown when Steam returns an empty response.</exception> /// <exception cref="TradeOfferEscrowDurationParseException">Thrown when the user is unavailable for trade or Steam returns invalid data.</exception> /// <returns>TradeOfferEscrowDuration</returns> public TradeOfferEscrowDuration GetEscrowDuration(string tradeOfferId) { var url = "http://steamcommunity.com/tradeoffer/" + tradeOfferId; var resp = SteamWeb.Fetch(url, "GET", null, false); if (string.IsNullOrWhiteSpace(resp)) { throw new NullReferenceException("Empty response from Steam when trying to retrieve escrow duration."); } return ParseEscrowResponse(resp); } private TradeOfferEscrowDuration ParseEscrowResponse(string resp) { var myM = Regex.Match(resp, @"g_daysMyEscrow(?:[\s=]+)(?<days>[\d]+);", RegexOptions.IgnoreCase); var theirM = Regex.Match(resp, @"g_daysTheirEscrow(?:[\s=]+)(?<days>[\d]+);", RegexOptions.IgnoreCase); if (!myM.Groups["days"].Success || !theirM.Groups["days"].Success) { var steamErrorM = Regex.Match(resp, @"<div id=""error_msg"">([^>]+)<\/div>", RegexOptions.IgnoreCase); if (steamErrorM.Groups.Count > 1) { var steamError = Regex.Replace(steamErrorM.Groups[1].Value.Trim(), @"\t|\n|\r", ""); ; throw new TradeOfferEscrowDurationParseException(steamError); } else { throw new TradeOfferEscrowDurationParseException(string.Empty); } } return new TradeOfferEscrowDuration() { DaysMyEscrow = int.Parse(myM.Groups["days"].Value), DaysTheirEscrow = int.Parse(theirM.Groups["days"].Value) }; } public class TradeOfferEscrowDuration { public int DaysMyEscrow { get; set; } public int DaysTheirEscrow { get; set; } } public class TradeOfferEscrowDurationParseException : Exception { public TradeOfferEscrowDurationParseException() : base() { } public TradeOfferEscrowDurationParseException(string message) : base(message) { } } #region Background Worker Methods private void BackgroundWorkerOnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs runWorkerCompletedEventArgs) { if (runWorkerCompletedEventArgs.Error != null) { Exception ex = runWorkerCompletedEventArgs.Error; Log.Error("Unhandled exceptions in bot {0} callback thread: {1} {2}", DisplayName, Environment.NewLine, ex); Log.Info("This bot died. Stopping it.."); //backgroundWorker.RunWorkerAsync(); //Thread.Sleep(10000); StopBot(); //StartBot(); } } private void BackgroundWorkerOnDoWork(object sender, DoWorkEventArgs doWorkEventArgs) { while (!botThread.CancellationPending) { try { SteamCallbackManager.RunCallbacks(); if(tradeOfferManager != null) { tradeOfferManager.HandleNextPendingTradeOfferUpdate(); } Thread.Sleep(1); } catch (WebException e) { Log.Error("URI: {0} >> {1}", (e.Response != null && e.Response.ResponseUri != null ? e.Response.ResponseUri.ToString() : "unknown"), e.ToString()); System.Threading.Thread.Sleep(45000);//Steam is down, retry in 45 seconds. } catch (Exception e) { Log.Error("Unhandled exception occurred in bot: " + e); } } } #endregion Background Worker Methods private void FireOnSteamGuardRequired(SteamGuardRequiredEventArgs e) { // Set to null in case this is another attempt this.AuthCode = null; EventHandler<SteamGuardRequiredEventArgs> handler = OnSteamGuardRequired; if (handler != null) handler(this, e); else { while (true) { if (this.AuthCode != null) { e.SteamGuard = this.AuthCode; break; } Thread.Sleep(5); } } } #region Group Methods /// <summary> /// Accepts the invite to a Steam Group /// </summary> /// <param name="group">SteamID of the group to accept the invite from.</param> private void AcceptGroupInvite(SteamID group) { var AcceptInvite = new ClientMsg<CMsgGroupInviteAction>((int)EMsg.ClientAcknowledgeClanInvite); AcceptInvite.Body.GroupID = group.ConvertToUInt64(); AcceptInvite.Body.AcceptInvite = true; this.SteamClient.Send(AcceptInvite); } /// <summary> /// Declines the invite to a Steam Group /// </summary> /// <param name="group">SteamID of the group to decline the invite from.</param> private void DeclineGroupInvite(SteamID group) { var DeclineInvite = new ClientMsg<CMsgGroupInviteAction>((int)EMsg.ClientAcknowledgeClanInvite); DeclineInvite.Body.GroupID = group.ConvertToUInt64(); DeclineInvite.Body.AcceptInvite = false; this.SteamClient.Send(DeclineInvite); } /// <summary> /// Invites a use to the specified Steam Group /// </summary> /// <param name="user">SteamID of the user to invite.</param> /// <param name="groupId">SteamID of the group to invite the user to.</param> public void InviteUserToGroup(SteamID user, SteamID groupId) { var InviteUser = new ClientMsg<CMsgInviteUserToGroup>((int)EMsg.ClientInviteUserToClan); InviteUser.Body.GroupID = groupId.ConvertToUInt64(); InviteUser.Body.Invitee = user.ConvertToUInt64(); InviteUser.Body.UnknownInfo = true; this.SteamClient.Send(InviteUser); } #endregion public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (disposed) return; StopBot(); if (disposing) Log.Dispose(); disposed = true; } private void SubscribeSteamCallbacks() { #region Login steamCallbackManager.Subscribe<SteamClient.ConnectedCallback>(callback => { Log.Debug("Connection Callback: {0}", callback.Result); if (callback.Result == EResult.OK) { UserLogOn(); } else { Log.Error("Failed to connect to Steam Community, trying again..."); SteamClient.Connect(); } }); steamCallbackManager.Subscribe<SteamUser.LoggedOnCallback>(callback => { Log.Debug("Logged On Callback: {0}", callback.Result); if (callback.Result == EResult.OK) { myUserNonce = callback.WebAPIUserNonce; } else { Log.Error("Login Error: {0}", callback.Result); } if (callback.Result == EResult.AccountLoginDeniedNeedTwoFactor) { var mobileAuthCode = GetMobileAuthCode(); if (string.IsNullOrEmpty(mobileAuthCode)) { Log.Error("Failed to generate 2FA code. Make sure you have linked the authenticator via SteamBot."); } else { logOnDetails.TwoFactorCode = mobileAuthCode; Log.Success("Generated 2FA code."); } } else if (callback.Result == EResult.TwoFactorCodeMismatch) { SteamAuth.TimeAligner.AlignTime(); logOnDetails.TwoFactorCode = SteamGuardAccount.GenerateSteamGuardCode(); Log.Success("Regenerated 2FA code."); } else if (callback.Result == EResult.AccountLogonDenied) { Log.Interface("This account is SteamGuard enabled. Enter the code via the `auth' command."); // try to get the steamguard auth code from the event callback var eva = new SteamGuardRequiredEventArgs(); FireOnSteamGuardRequired(eva); if (!String.IsNullOrEmpty(eva.SteamGuard)) logOnDetails.AuthCode = eva.SteamGuard; else logOnDetails.AuthCode = Console.ReadLine(); } else if (callback.Result == EResult.InvalidLoginAuthCode) { Log.Interface("The given SteamGuard code was invalid. Try again using the `auth' command."); logOnDetails.AuthCode = Console.ReadLine(); } }); steamCallbackManager.Subscribe<SteamUser.LoginKeyCallback>(callback => { myUniqueId = callback.UniqueID.ToString(); UserWebLogOn(); if (Trade.CurrentSchema == null) { Log.Info("Downloading Schema..."); Trade.CurrentSchema = Schema.FetchSchema(ApiKey, schemaLang); Log.Success("Schema Downloaded!"); } SteamFriends.SetPersonaName(DisplayNamePrefix + DisplayName); SteamFriends.SetPersonaState(EPersonaState.Online); Log.Success("Steam Bot Logged In Completely!"); GetUserHandler(SteamClient.SteamID).OnLoginCompleted(); }); steamCallbackManager.Subscribe<SteamUser.WebAPIUserNonceCallback>(webCallback => { Log.Debug("Received new WebAPIUserNonce."); if (webCallback.Result == EResult.OK) { myUserNonce = webCallback.Nonce; UserWebLogOn(); } else { Log.Error("WebAPIUserNonce Error: " + webCallback.Result); } }); steamCallbackManager.Subscribe<SteamUser.UpdateMachineAuthCallback>( authCallback => OnUpdateMachineAuthCallback(authCallback) ); #endregion #region Friends steamCallbackManager.Subscribe<SteamFriends.FriendsListCallback>(callback => { foreach (SteamFriends.FriendsListCallback.Friend friend in callback.FriendList) { switch (friend.SteamID.AccountType) { case EAccountType.Clan: if (friend.Relationship == EFriendRelationship.RequestRecipient) { if (GetUserHandler(friend.SteamID).OnGroupAdd()) { AcceptGroupInvite(friend.SteamID); } else { DeclineGroupInvite(friend.SteamID); } } break; default: CreateFriendsListIfNecessary(); if (friend.Relationship == EFriendRelationship.None) { friends.Remove(friend.SteamID); GetUserHandler(friend.SteamID).OnFriendRemove(); RemoveUserHandler(friend.SteamID); } else if (friend.Relationship == EFriendRelationship.RequestRecipient) { if (GetUserHandler(friend.SteamID).OnFriendAdd()) { if (!friends.Contains(friend.SteamID)) { friends.Add(friend.SteamID); } SteamFriends.AddFriend(friend.SteamID); } else { if (friends.Contains(friend.SteamID)) { friends.Remove(friend.SteamID); } SteamFriends.RemoveFriend(friend.SteamID); RemoveUserHandler(friend.SteamID); } } break; } } }); steamCallbackManager.Subscribe<SteamFriends.FriendMsgCallback>(callback => { EChatEntryType type = callback.EntryType; if (callback.EntryType == EChatEntryType.ChatMsg) { Log.Info("Chat Message from {0}: {1}", SteamFriends.GetFriendPersonaName(callback.Sender), callback.Message ); GetUserHandler(callback.Sender).OnMessageHandler(callback.Message, type); } }); #endregion #region Group Chat steamCallbackManager.Subscribe<SteamFriends.ChatMsgCallback>(callback => { GetUserHandler(callback.ChatterID).OnChatRoomMessage(callback.ChatRoomID, callback.ChatterID, callback.Message); }); #endregion #region Trading steamCallbackManager.Subscribe<SteamTrading.SessionStartCallback>(callback => { bool started = HandleTradeSessionStart(callback.OtherClient); if (!started) Log.Error("Could not start the trade session."); else Log.Debug("SteamTrading.SessionStartCallback handled successfully. Trade Opened."); }); steamCallbackManager.Subscribe<SteamTrading.TradeProposedCallback>(callback => { if (CheckCookies() == false) { SteamTrade.RespondToTrade(callback.TradeID, false); return; } try { tradeManager.InitializeTrade(SteamUser.SteamID, callback.OtherClient); } catch (WebException we) { SteamFriends.SendChatMessage(callback.OtherClient, EChatEntryType.ChatMsg, "Trade error: " + we.Message); SteamTrade.RespondToTrade(callback.TradeID, false); return; } catch (Exception) { SteamFriends.SendChatMessage(callback.OtherClient, EChatEntryType.ChatMsg, "Trade declined. Could not correctly fetch your backpack."); SteamTrade.RespondToTrade(callback.TradeID, false); return; } //if (tradeManager.OtherInventory.IsPrivate) //{ // SteamFriends.SendChatMessage(callback.OtherClient, // EChatEntryType.ChatMsg, // "Trade declined. Your backpack cannot be private."); // SteamTrade.RespondToTrade (callback.TradeID, false); // return; //} if (CurrentTrade == null && GetUserHandler(callback.OtherClient).OnTradeRequest()) SteamTrade.RespondToTrade(callback.TradeID, true); else SteamTrade.RespondToTrade(callback.TradeID, false); }); steamCallbackManager.Subscribe<SteamTrading.TradeResultCallback>(callback => { if (callback.Response == EEconTradeResponse.Accepted) { Log.Debug("Trade Status: {0}", callback.Response); Log.Info("Trade Accepted!"); GetUserHandler(callback.OtherClient).OnTradeRequestReply(true, callback.Response.ToString()); } else { Log.Warn("Trade failed: {0}", callback.Response); CloseTrade(); GetUserHandler(callback.OtherClient).OnTradeRequestReply(false, callback.Response.ToString()); } }); #endregion #region Disconnect steamCallbackManager.Subscribe<SteamUser.LoggedOffCallback>(callback => { IsLoggedIn = false; Log.Warn("Logged off Steam. Reason: {0}", callback.Result); CancelTradeOfferPollingThread(); }); steamCallbackManager.Subscribe<SteamClient.DisconnectedCallback>(callback => { if (IsLoggedIn) { IsLoggedIn = false; CloseTrade(); Log.Warn("Disconnected from Steam Network!"); CancelTradeOfferPollingThread(); } SteamClient.Connect(); }); #endregion #region Notifications steamCallbackManager.Subscribe<SteamBot.SteamNotifications.CommentNotificationCallback>(callback => { //various types of comment notifications on profile/activity feed etc //Log.Info("received CommentNotificationCallback"); //Log.Info("New Commments " + callback.CommentNotifications.CountNewComments); //Log.Info("New Commments Owners " + callback.CommentNotifications.CountNewCommentsOwner); //Log.Info("New Commments Subscriptions" + callback.CommentNotifications.CountNewCommentsSubscriptions); }); #endregion } } }