context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
// Copyright (C) 2014 dot42
//
// Original filename: Java.Awt.Font.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma warning disable 1717
namespace Java.Awt.Font
{
/// <summary>
/// <para>The TextAttribute class defines attribute keys and attribute values for text rendering. Each TextAttributes should have the following information: <ul><li><para>key name; </para></li><li><para>valid values; </para></li><li><para>relevant constants; </para></li><li><para>default action if the attribute is absent; </para></li><li><para>default action's description. </para></li></ul></para>
/// </summary>
/// <java-name>
/// java/awt/font/TextAttribute
/// </java-name>
[Dot42.DexImport("java/awt/font/TextAttribute", AccessFlags = 49)]
public sealed partial class TextAttribute : global::Java.Text.IAttributedCharacterIterator_Attribute
/* scope: __dot42__ */
{
/// <summary>
/// <para>The BACKGROUND text attribute. </para>
/// </summary>
/// <java-name>
/// BACKGROUND
/// </java-name>
[Dot42.DexImport("BACKGROUND", "Ljava/awt/font/TextAttribute;", AccessFlags = 25)]
public static readonly global::Java.Awt.Font.TextAttribute BACKGROUND;
/// <summary>
/// <para>The BIDI_EMBEDDING text attribute key. </para>
/// </summary>
/// <java-name>
/// BIDI_EMBEDDING
/// </java-name>
[Dot42.DexImport("BIDI_EMBEDDING", "Ljava/awt/font/TextAttribute;", AccessFlags = 25)]
public static readonly global::Java.Awt.Font.TextAttribute BIDI_EMBEDDING;
/// <summary>
/// <para>The CHAR_REPLACEMENT text attribute key. </para>
/// </summary>
/// <java-name>
/// CHAR_REPLACEMENT
/// </java-name>
[Dot42.DexImport("CHAR_REPLACEMENT", "Ljava/awt/font/TextAttribute;", AccessFlags = 25)]
public static readonly global::Java.Awt.Font.TextAttribute CHAR_REPLACEMENT;
/// <summary>
/// <para>The FAMILY text attribute key. </para>
/// </summary>
/// <java-name>
/// FAMILY
/// </java-name>
[Dot42.DexImport("FAMILY", "Ljava/awt/font/TextAttribute;", AccessFlags = 25)]
public static readonly global::Java.Awt.Font.TextAttribute FAMILY;
/// <summary>
/// <para>The FONT text attribute key. </para>
/// </summary>
/// <java-name>
/// FONT
/// </java-name>
[Dot42.DexImport("FONT", "Ljava/awt/font/TextAttribute;", AccessFlags = 25)]
public static readonly global::Java.Awt.Font.TextAttribute FONT;
/// <summary>
/// <para>The FOREGROUND text attribute key. </para>
/// </summary>
/// <java-name>
/// FOREGROUND
/// </java-name>
[Dot42.DexImport("FOREGROUND", "Ljava/awt/font/TextAttribute;", AccessFlags = 25)]
public static readonly global::Java.Awt.Font.TextAttribute FOREGROUND;
/// <summary>
/// <para>The INPUT_METHOD_HIGHLIGHT text attribute key. </para>
/// </summary>
/// <java-name>
/// INPUT_METHOD_HIGHLIGHT
/// </java-name>
[Dot42.DexImport("INPUT_METHOD_HIGHLIGHT", "Ljava/awt/font/TextAttribute;", AccessFlags = 25)]
public static readonly global::Java.Awt.Font.TextAttribute INPUT_METHOD_HIGHLIGHT;
/// <summary>
/// <para>The INPUT_METHOD_UNDERLINE text attribute key. </para>
/// </summary>
/// <java-name>
/// INPUT_METHOD_UNDERLINE
/// </java-name>
[Dot42.DexImport("INPUT_METHOD_UNDERLINE", "Ljava/awt/font/TextAttribute;", AccessFlags = 25)]
public static readonly global::Java.Awt.Font.TextAttribute INPUT_METHOD_UNDERLINE;
/// <summary>
/// <para>The JUSTIFICATION text attribute key. </para>
/// </summary>
/// <java-name>
/// JUSTIFICATION
/// </java-name>
[Dot42.DexImport("JUSTIFICATION", "Ljava/awt/font/TextAttribute;", AccessFlags = 25)]
public static readonly global::Java.Awt.Font.TextAttribute JUSTIFICATION;
/// <summary>
/// <para>The Constant JUSTIFICATION_indicates the full requested width. </para>
/// </summary>
/// <java-name>
/// JUSTIFICATION_FULL
/// </java-name>
[Dot42.DexImport("JUSTIFICATION_FULL", "Ljava/lang/Float;", AccessFlags = 25)]
public static readonly float? JUSTIFICATION_FULL;
/// <summary>
/// <para>The Constant JUSTIFICATION_NONE indicates that line is not allowed for justification. </para>
/// </summary>
/// <java-name>
/// JUSTIFICATION_NONE
/// </java-name>
[Dot42.DexImport("JUSTIFICATION_NONE", "Ljava/lang/Float;", AccessFlags = 25)]
public static readonly float? JUSTIFICATION_NONE;
/// <summary>
/// <para>The KERNING text attribute key.</para><para><para>1.6 </para></para>
/// </summary>
/// <java-name>
/// KERNING
/// </java-name>
[Dot42.DexImport("KERNING", "Ljava/awt/font/TextAttribute;", AccessFlags = 25)]
public static readonly global::Java.Awt.Font.TextAttribute KERNING;
/// <summary>
/// <para><para>1.6 </para></para>
/// </summary>
/// <java-name>
/// KERNING_ON
/// </java-name>
[Dot42.DexImport("KERNING_ON", "Ljava/lang/Integer;", AccessFlags = 25)]
public static readonly int? KERNING_ON;
/// <summary>
/// <para>The LIGATURES text attribute key.</para><para><para>1.6 </para></para>
/// </summary>
/// <java-name>
/// LIGATURES
/// </java-name>
[Dot42.DexImport("LIGATURES", "Ljava/awt/font/TextAttribute;", AccessFlags = 25)]
public static readonly global::Java.Awt.Font.TextAttribute LIGATURES;
/// <summary>
/// <para><para>1.6 </para></para>
/// </summary>
/// <java-name>
/// LIGATURES_ON
/// </java-name>
[Dot42.DexImport("LIGATURES_ON", "Ljava/lang/Integer;", AccessFlags = 25)]
public static readonly int? LIGATURES_ON;
/// <summary>
/// <para>The NUMERIC_SHAPING text attribute. </para>
/// </summary>
/// <java-name>
/// NUMERIC_SHAPING
/// </java-name>
[Dot42.DexImport("NUMERIC_SHAPING", "Ljava/awt/font/TextAttribute;", AccessFlags = 25)]
public static readonly global::Java.Awt.Font.TextAttribute NUMERIC_SHAPING;
/// <summary>
/// <para>The POSTURE text attribute. </para>
/// </summary>
/// <java-name>
/// POSTURE
/// </java-name>
[Dot42.DexImport("POSTURE", "Ljava/awt/font/TextAttribute;", AccessFlags = 25)]
public static readonly global::Java.Awt.Font.TextAttribute POSTURE;
/// <summary>
/// <para>The Constant POSTURE_REGULAR indicates regular posture. </para>
/// </summary>
/// <java-name>
/// POSTURE_REGULAR
/// </java-name>
[Dot42.DexImport("POSTURE_REGULAR", "Ljava/lang/Float;", AccessFlags = 25)]
public static readonly float? POSTURE_REGULAR;
/// <summary>
/// <para>The Constant POSTURE_OBLIQUE indicates italic posture. </para>
/// </summary>
/// <java-name>
/// POSTURE_OBLIQUE
/// </java-name>
[Dot42.DexImport("POSTURE_OBLIQUE", "Ljava/lang/Float;", AccessFlags = 25)]
public static readonly float? POSTURE_OBLIQUE;
/// <summary>
/// <para>The RUN_DIRECTION text attribute. </para>
/// </summary>
/// <java-name>
/// RUN_DIRECTION
/// </java-name>
[Dot42.DexImport("RUN_DIRECTION", "Ljava/awt/font/TextAttribute;", AccessFlags = 25)]
public static readonly global::Java.Awt.Font.TextAttribute RUN_DIRECTION;
/// <summary>
/// <para>The Constant RUN_DIRECTION_LTR indicates left-to-right run direction. </para>
/// </summary>
/// <java-name>
/// RUN_DIRECTION_LTR
/// </java-name>
[Dot42.DexImport("RUN_DIRECTION_LTR", "Ljava/lang/Boolean;", AccessFlags = 25)]
public static readonly bool? RUN_DIRECTION_LTR;
/// <summary>
/// <para>The Constant RUN_DIRECTION_RTL indicates right-to-left run direction. </para>
/// </summary>
/// <java-name>
/// RUN_DIRECTION_RTL
/// </java-name>
[Dot42.DexImport("RUN_DIRECTION_RTL", "Ljava/lang/Boolean;", AccessFlags = 25)]
public static readonly bool? RUN_DIRECTION_RTL;
/// <summary>
/// <para>The SIZE text attribute. </para>
/// </summary>
/// <java-name>
/// SIZE
/// </java-name>
[Dot42.DexImport("SIZE", "Ljava/awt/font/TextAttribute;", AccessFlags = 25)]
public static readonly global::Java.Awt.Font.TextAttribute SIZE;
/// <summary>
/// <para>The STRIKETHROUGH text attribute. </para>
/// </summary>
/// <java-name>
/// STRIKETHROUGH
/// </java-name>
[Dot42.DexImport("STRIKETHROUGH", "Ljava/awt/font/TextAttribute;", AccessFlags = 25)]
public static readonly global::Java.Awt.Font.TextAttribute STRIKETHROUGH;
/// <summary>
/// <para>The Constant STRIKETHROUGH_ON indicates a single strikethrough. </para>
/// </summary>
/// <java-name>
/// STRIKETHROUGH_ON
/// </java-name>
[Dot42.DexImport("STRIKETHROUGH_ON", "Ljava/lang/Boolean;", AccessFlags = 25)]
public static readonly bool? STRIKETHROUGH_ON;
/// <summary>
/// <para>The SUPERSCRIPT text attribute. </para>
/// </summary>
/// <java-name>
/// SUPERSCRIPT
/// </java-name>
[Dot42.DexImport("SUPERSCRIPT", "Ljava/awt/font/TextAttribute;", AccessFlags = 25)]
public static readonly global::Java.Awt.Font.TextAttribute SUPERSCRIPT;
/// <summary>
/// <para>The Constant SUPERSCRIPT_SUB indicates a standard subscript. </para>
/// </summary>
/// <java-name>
/// SUPERSCRIPT_SUB
/// </java-name>
[Dot42.DexImport("SUPERSCRIPT_SUB", "Ljava/lang/Integer;", AccessFlags = 25)]
public static readonly int? SUPERSCRIPT_SUB;
/// <summary>
/// <para>The Constant SUPERSCRIPT_SUPER indicates a standard superscript. </para>
/// </summary>
/// <java-name>
/// SUPERSCRIPT_SUPER
/// </java-name>
[Dot42.DexImport("SUPERSCRIPT_SUPER", "Ljava/lang/Integer;", AccessFlags = 25)]
public static readonly int? SUPERSCRIPT_SUPER;
/// <summary>
/// <para>The SWAP_COLORS text attribute. </para>
/// </summary>
/// <java-name>
/// SWAP_COLORS
/// </java-name>
[Dot42.DexImport("SWAP_COLORS", "Ljava/awt/font/TextAttribute;", AccessFlags = 25)]
public static readonly global::Java.Awt.Font.TextAttribute SWAP_COLORS;
/// <summary>
/// <para>The Constant SWAP_COLORS_ON indicates a swap of foreground and background. </para>
/// </summary>
/// <java-name>
/// SWAP_COLORS_ON
/// </java-name>
[Dot42.DexImport("SWAP_COLORS_ON", "Ljava/lang/Boolean;", AccessFlags = 25)]
public static readonly bool? SWAP_COLORS_ON;
/// <summary>
/// <para>The TRACKING text attribute key.</para><para><para>1.6 </para></para>
/// </summary>
/// <java-name>
/// TRACKING
/// </java-name>
[Dot42.DexImport("TRACKING", "Ljava/awt/font/TextAttribute;", AccessFlags = 25)]
public static readonly global::Java.Awt.Font.TextAttribute TRACKING;
/// <summary>
/// <para><para>1.6 </para></para>
/// </summary>
/// <java-name>
/// TRACKING_LOOSE
/// </java-name>
[Dot42.DexImport("TRACKING_LOOSE", "Ljava/lang/Float;", AccessFlags = 25)]
public static readonly float? TRACKING_LOOSE;
/// <summary>
/// <para><para>1.6 </para></para>
/// </summary>
/// <java-name>
/// TRACKING_TIGHT
/// </java-name>
[Dot42.DexImport("TRACKING_TIGHT", "Ljava/lang/Float;", AccessFlags = 25)]
public static readonly float? TRACKING_TIGHT;
/// <summary>
/// <para>The TRANSFORM text attribute. </para>
/// </summary>
/// <java-name>
/// TRANSFORM
/// </java-name>
[Dot42.DexImport("TRANSFORM", "Ljava/awt/font/TextAttribute;", AccessFlags = 25)]
public static readonly global::Java.Awt.Font.TextAttribute TRANSFORM;
/// <summary>
/// <para>The Constant UNDERLINE text attribute. </para>
/// </summary>
/// <java-name>
/// UNDERLINE
/// </java-name>
[Dot42.DexImport("UNDERLINE", "Ljava/awt/font/TextAttribute;", AccessFlags = 25)]
public static readonly global::Java.Awt.Font.TextAttribute UNDERLINE;
/// <summary>
/// <para>The Constant UNDERLINE_ON indicates a standard underline at the roman baseline for roman text. </para>
/// </summary>
/// <java-name>
/// UNDERLINE_ON
/// </java-name>
[Dot42.DexImport("UNDERLINE_ON", "Ljava/lang/Integer;", AccessFlags = 25)]
public static readonly int? UNDERLINE_ON;
/// <summary>
/// <para>The Constant UNDERLINE_LOW_ONE_PIXEL indicates a single pixel solid low underline. </para>
/// </summary>
/// <java-name>
/// UNDERLINE_LOW_ONE_PIXEL
/// </java-name>
[Dot42.DexImport("UNDERLINE_LOW_ONE_PIXEL", "Ljava/lang/Integer;", AccessFlags = 25)]
public static readonly int? UNDERLINE_LOW_ONE_PIXEL;
/// <summary>
/// <para>The Constant UNDERLINE_LOW_TWO_PIXEL indicates a double pixel solid low underline. </para>
/// </summary>
/// <java-name>
/// UNDERLINE_LOW_TWO_PIXEL
/// </java-name>
[Dot42.DexImport("UNDERLINE_LOW_TWO_PIXEL", "Ljava/lang/Integer;", AccessFlags = 25)]
public static readonly int? UNDERLINE_LOW_TWO_PIXEL;
/// <summary>
/// <para>The Constant UNDERLINE_LOW_DOTTED indicates a single pixel dotted low underline. </para>
/// </summary>
/// <java-name>
/// UNDERLINE_LOW_DOTTED
/// </java-name>
[Dot42.DexImport("UNDERLINE_LOW_DOTTED", "Ljava/lang/Integer;", AccessFlags = 25)]
public static readonly int? UNDERLINE_LOW_DOTTED;
/// <summary>
/// <para>The Constant UNDERLINE_LOW_GRAY indicates double pixel gray low underline. </para>
/// </summary>
/// <java-name>
/// UNDERLINE_LOW_GRAY
/// </java-name>
[Dot42.DexImport("UNDERLINE_LOW_GRAY", "Ljava/lang/Integer;", AccessFlags = 25)]
public static readonly int? UNDERLINE_LOW_GRAY;
/// <summary>
/// <para>The Constant UNDERLINE_LOW_DASHED indicates single pixel dashed low underline. </para>
/// </summary>
/// <java-name>
/// UNDERLINE_LOW_DASHED
/// </java-name>
[Dot42.DexImport("UNDERLINE_LOW_DASHED", "Ljava/lang/Integer;", AccessFlags = 25)]
public static readonly int? UNDERLINE_LOW_DASHED;
/// <summary>
/// <para>The WEIGHT text attribute. </para>
/// </summary>
/// <java-name>
/// WEIGHT
/// </java-name>
[Dot42.DexImport("WEIGHT", "Ljava/awt/font/TextAttribute;", AccessFlags = 25)]
public static readonly global::Java.Awt.Font.TextAttribute WEIGHT;
/// <summary>
/// <para>The Constant WEIGHT_EXTRA_LIGHT indicates the lightest predefined weight. </para>
/// </summary>
/// <java-name>
/// WEIGHT_EXTRA_LIGHT
/// </java-name>
[Dot42.DexImport("WEIGHT_EXTRA_LIGHT", "Ljava/lang/Float;", AccessFlags = 25)]
public static readonly float? WEIGHT_EXTRA_LIGHT;
/// <summary>
/// <para>The Constant WEIGHT_LIGHT indicates the standard light weight. </para>
/// </summary>
/// <java-name>
/// WEIGHT_LIGHT
/// </java-name>
[Dot42.DexImport("WEIGHT_LIGHT", "Ljava/lang/Float;", AccessFlags = 25)]
public static readonly float? WEIGHT_LIGHT;
/// <summary>
/// <para>The Constant WEIGHT_DEMILIGHT indicates an intermediate weight between LIGHT and STANDARD. </para>
/// </summary>
/// <java-name>
/// WEIGHT_DEMILIGHT
/// </java-name>
[Dot42.DexImport("WEIGHT_DEMILIGHT", "Ljava/lang/Float;", AccessFlags = 25)]
public static readonly float? WEIGHT_DEMILIGHT;
/// <summary>
/// <para>The Constant WEIGHT_REGULAR indicates the standart weight. </para>
/// </summary>
/// <java-name>
/// WEIGHT_REGULAR
/// </java-name>
[Dot42.DexImport("WEIGHT_REGULAR", "Ljava/lang/Float;", AccessFlags = 25)]
public static readonly float? WEIGHT_REGULAR;
/// <summary>
/// <para>The Constant WEIGHT_SEMIBOLD indicates a semi weight of REGULAR. </para>
/// </summary>
/// <java-name>
/// WEIGHT_SEMIBOLD
/// </java-name>
[Dot42.DexImport("WEIGHT_SEMIBOLD", "Ljava/lang/Float;", AccessFlags = 25)]
public static readonly float? WEIGHT_SEMIBOLD;
/// <summary>
/// <para>The Constant WEIGHT_MEDIUM indicates average weight between the REGULAR and BOLD. </para>
/// </summary>
/// <java-name>
/// WEIGHT_MEDIUM
/// </java-name>
[Dot42.DexImport("WEIGHT_MEDIUM", "Ljava/lang/Float;", AccessFlags = 25)]
public static readonly float? WEIGHT_MEDIUM;
/// <summary>
/// <para>The Constant WEIGHT_DEMIBOLD indicates a lighter weight than BOLD. </para>
/// </summary>
/// <java-name>
/// WEIGHT_DEMIBOLD
/// </java-name>
[Dot42.DexImport("WEIGHT_DEMIBOLD", "Ljava/lang/Float;", AccessFlags = 25)]
public static readonly float? WEIGHT_DEMIBOLD;
/// <summary>
/// <para>The Constant WEIGHT_BOLD indicates the standard bold weight. </para>
/// </summary>
/// <java-name>
/// WEIGHT_BOLD
/// </java-name>
[Dot42.DexImport("WEIGHT_BOLD", "Ljava/lang/Float;", AccessFlags = 25)]
public static readonly float? WEIGHT_BOLD;
/// <summary>
/// <para>The Constant WEIGHT_HEAVY indicates a heavier weight than BOLD. </para>
/// </summary>
/// <java-name>
/// WEIGHT_HEAVY
/// </java-name>
[Dot42.DexImport("WEIGHT_HEAVY", "Ljava/lang/Float;", AccessFlags = 25)]
public static readonly float? WEIGHT_HEAVY;
/// <summary>
/// <para>The Constant WEIGHT_EXTRABOLD indicates an extra heavy weight. </para>
/// </summary>
/// <java-name>
/// WEIGHT_EXTRABOLD
/// </java-name>
[Dot42.DexImport("WEIGHT_EXTRABOLD", "Ljava/lang/Float;", AccessFlags = 25)]
public static readonly float? WEIGHT_EXTRABOLD;
/// <summary>
/// <para>The Constant WEIGHT_ULTRABOLD indicates the heaviest predefined weight. </para>
/// </summary>
/// <java-name>
/// WEIGHT_ULTRABOLD
/// </java-name>
[Dot42.DexImport("WEIGHT_ULTRABOLD", "Ljava/lang/Float;", AccessFlags = 25)]
public static readonly float? WEIGHT_ULTRABOLD;
/// <summary>
/// <para>The WIDTH text attribute. </para>
/// </summary>
/// <java-name>
/// WIDTH
/// </java-name>
[Dot42.DexImport("WIDTH", "Ljava/awt/font/TextAttribute;", AccessFlags = 25)]
public static readonly global::Java.Awt.Font.TextAttribute WIDTH;
/// <summary>
/// <para>The Constant WIDTH_CONDENSED indicates the most condensed predefined width. </para>
/// </summary>
/// <java-name>
/// WIDTH_CONDENSED
/// </java-name>
[Dot42.DexImport("WIDTH_CONDENSED", "Ljava/lang/Float;", AccessFlags = 25)]
public static readonly float? WIDTH_CONDENSED;
/// <summary>
/// <para>The Constant WIDTH_SEMI_CONDENSED indicates a semi condensed width. </para>
/// </summary>
/// <java-name>
/// WIDTH_SEMI_CONDENSED
/// </java-name>
[Dot42.DexImport("WIDTH_SEMI_CONDENSED", "Ljava/lang/Float;", AccessFlags = 25)]
public static readonly float? WIDTH_SEMI_CONDENSED;
/// <summary>
/// <para>The Constant WIDTH_REGULAR indicates the standard width. </para>
/// </summary>
/// <java-name>
/// WIDTH_REGULAR
/// </java-name>
[Dot42.DexImport("WIDTH_REGULAR", "Ljava/lang/Float;", AccessFlags = 25)]
public static readonly float? WIDTH_REGULAR;
/// <summary>
/// <para>The Constant WIDTH_SEMI_EXTENDED indicates semi extended width. </para>
/// </summary>
/// <java-name>
/// WIDTH_SEMI_EXTENDED
/// </java-name>
[Dot42.DexImport("WIDTH_SEMI_EXTENDED", "Ljava/lang/Float;", AccessFlags = 25)]
public static readonly float? WIDTH_SEMI_EXTENDED;
/// <summary>
/// <para>The Constant WIDTH_EXTENDED indicates extended width. </para>
/// </summary>
/// <java-name>
/// WIDTH_EXTENDED
/// </java-name>
[Dot42.DexImport("WIDTH_EXTENDED", "Ljava/lang/Float;", AccessFlags = 25)]
public static readonly float? WIDTH_EXTENDED;
/// <summary>
/// <para>Instantiates a new TextAttribute with the specified name.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 4)]
internal TextAttribute(string name) /* MethodBuilder.Create */
{
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal TextAttribute() /* TypeBuilder.AddDefaultConstructor */
{
}
}
/// <summary>
/// <para>The Class NumericShaper provides methods to convert latin character codes to unicode character codes. For tables of the character codes used, see . </para>
/// </summary>
/// <java-name>
/// java/awt/font/NumericShaper
/// </java-name>
[Dot42.DexImport("java/awt/font/NumericShaper", AccessFlags = 49)]
public sealed partial class NumericShaper : global::Java.Io.ISerializable
/* scope: __dot42__ */
{
/// <summary>
/// <para>The Constant EUROPEAN indicates the latin and extended range, and latin decimal base. </para>
/// </summary>
/// <java-name>
/// EUROPEAN
/// </java-name>
[Dot42.DexImport("EUROPEAN", "I", AccessFlags = 25)]
public const int EUROPEAN = 1;
/// <summary>
/// <para>The Constant ARABIC indicates the ARABIC range and decimal base. </para>
/// </summary>
/// <java-name>
/// ARABIC
/// </java-name>
[Dot42.DexImport("ARABIC", "I", AccessFlags = 25)]
public const int ARABIC = 2;
/// <summary>
/// <para>The Constant EASTERN_ARABIC indicates the ARABIC range and ARABIC_EXTENDED decimal base. </para>
/// </summary>
/// <java-name>
/// EASTERN_ARABIC
/// </java-name>
[Dot42.DexImport("EASTERN_ARABIC", "I", AccessFlags = 25)]
public const int EASTERN_ARABIC = 4;
/// <summary>
/// <para>The Constant DEVANAGARI indicates the DEVANAGARI range and decimal base. </para>
/// </summary>
/// <java-name>
/// DEVANAGARI
/// </java-name>
[Dot42.DexImport("DEVANAGARI", "I", AccessFlags = 25)]
public const int DEVANAGARI = 8;
/// <summary>
/// <para>The Constant BENGALI indicates the BENGALI range and decimal base. </para>
/// </summary>
/// <java-name>
/// BENGALI
/// </java-name>
[Dot42.DexImport("BENGALI", "I", AccessFlags = 25)]
public const int BENGALI = 16;
/// <summary>
/// <para>The Constant GURMUKHI indicates the GURMUKHI range and decimal base. </para>
/// </summary>
/// <java-name>
/// GURMUKHI
/// </java-name>
[Dot42.DexImport("GURMUKHI", "I", AccessFlags = 25)]
public const int GURMUKHI = 32;
/// <summary>
/// <para>The Constant GUJARATI indicates the GUJARATI range and decimal base. </para>
/// </summary>
/// <java-name>
/// GUJARATI
/// </java-name>
[Dot42.DexImport("GUJARATI", "I", AccessFlags = 25)]
public const int GUJARATI = 64;
/// <summary>
/// <para>The Constant ORIYA indicates the ORIYA range and decimal base. </para>
/// </summary>
/// <java-name>
/// ORIYA
/// </java-name>
[Dot42.DexImport("ORIYA", "I", AccessFlags = 25)]
public const int ORIYA = 128;
/// <summary>
/// <para>The Constant TAMIL indicates the TAMIL range and decimal base. </para>
/// </summary>
/// <java-name>
/// TAMIL
/// </java-name>
[Dot42.DexImport("TAMIL", "I", AccessFlags = 25)]
public const int TAMIL = 256;
/// <summary>
/// <para>The Constant TELUGU indicates the TELUGU range and decimal base. </para>
/// </summary>
/// <java-name>
/// TELUGU
/// </java-name>
[Dot42.DexImport("TELUGU", "I", AccessFlags = 25)]
public const int TELUGU = 512;
/// <summary>
/// <para>The Constant KANNADA indicates the KANNADA range and decimal base. </para>
/// </summary>
/// <java-name>
/// KANNADA
/// </java-name>
[Dot42.DexImport("KANNADA", "I", AccessFlags = 25)]
public const int KANNADA = 1024;
/// <summary>
/// <para>The Constant MALAYALAM indicates the MALAYALAM range and decimal base. </para>
/// </summary>
/// <java-name>
/// MALAYALAM
/// </java-name>
[Dot42.DexImport("MALAYALAM", "I", AccessFlags = 25)]
public const int MALAYALAM = 2048;
/// <summary>
/// <para>The Constant THAI indicates the THAI range and decimal base. </para>
/// </summary>
/// <java-name>
/// THAI
/// </java-name>
[Dot42.DexImport("THAI", "I", AccessFlags = 25)]
public const int THAI = 4096;
/// <summary>
/// <para>The Constant LAO indicates the LAO range and decimal base. </para>
/// </summary>
/// <java-name>
/// LAO
/// </java-name>
[Dot42.DexImport("LAO", "I", AccessFlags = 25)]
public const int LAO = 8192;
/// <summary>
/// <para>The Constant TIBETAN indicates the TIBETAN range and decimal base. </para>
/// </summary>
/// <java-name>
/// TIBETAN
/// </java-name>
[Dot42.DexImport("TIBETAN", "I", AccessFlags = 25)]
public const int TIBETAN = 16384;
/// <summary>
/// <para>The Constant MYANMAR indicates the MYANMAR range and decimal base. </para>
/// </summary>
/// <java-name>
/// MYANMAR
/// </java-name>
[Dot42.DexImport("MYANMAR", "I", AccessFlags = 25)]
public const int MYANMAR = 32768;
/// <summary>
/// <para>The Constant ETHIOPIC indicates the ETHIOPIC range and decimal base. </para>
/// </summary>
/// <java-name>
/// ETHIOPIC
/// </java-name>
[Dot42.DexImport("ETHIOPIC", "I", AccessFlags = 25)]
public const int ETHIOPIC = 65536;
/// <summary>
/// <para>The Constant KHMER indicates the KHMER range and decimal base. </para>
/// </summary>
/// <java-name>
/// KHMER
/// </java-name>
[Dot42.DexImport("KHMER", "I", AccessFlags = 25)]
public const int KHMER = 131072;
/// <summary>
/// <para>The Constant MONGOLIAN indicates the MONGOLIAN range and decimal base. </para>
/// </summary>
/// <java-name>
/// MONGOLIAN
/// </java-name>
[Dot42.DexImport("MONGOLIAN", "I", AccessFlags = 25)]
public const int MONGOLIAN = 262144;
/// <summary>
/// <para>The Constant ALL_RANGES indicates all ranges. </para>
/// </summary>
/// <java-name>
/// ALL_RANGES
/// </java-name>
[Dot42.DexImport("ALL_RANGES", "I", AccessFlags = 25)]
public const int ALL_RANGES = 524287;
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal NumericShaper() /* MethodBuilder.Create */
{
}
/// <java-name>
/// hashCode
/// </java-name>
[Dot42.DexImport("hashCode", "()I", AccessFlags = 1)]
public override int GetHashCode() /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// equals
/// </java-name>
[Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 1)]
public override bool Equals(object obj) /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Gets the NumericShaper for the specified unicode ranges and default unicode range. The defaultContext parameter is used as the starting context (which indicates the language/script being used). The OR logical operation should be used for multiple ranges: NumericShaper.DEVANAGARI | NumericShaper.BENGALI. The NumericShaper returned by this method is contextual in that it supports multiple character ranges, depending on the context.</para><para></para>
/// </summary>
/// <returns>
/// <para>the NumericShaper for the specified ranges. </para>
/// </returns>
/// <java-name>
/// getContextualShaper
/// </java-name>
[Dot42.DexImport("getContextualShaper", "(II)Ljava/awt/font/NumericShaper;", AccessFlags = 9)]
public static global::Java.Awt.Font.NumericShaper GetContextualShaper(int ranges, int defaultContext) /* MethodBuilder.Create */
{
return default(global::Java.Awt.Font.NumericShaper);
}
/// <summary>
/// <para>Gets the NumericShaper for the specified unicode ranges. The OR logical operation should be used for multiple ranges: NumericShaper.DEVANAGARI | NumericShaper.BENGALI. The NumericShaper returned by this method is contextual in that it supports multiple character ranges, depending on the context.</para><para></para>
/// </summary>
/// <returns>
/// <para>the NumericShaper for the specified ranges. </para>
/// </returns>
/// <java-name>
/// getContextualShaper
/// </java-name>
[Dot42.DexImport("getContextualShaper", "(I)Ljava/awt/font/NumericShaper;", AccessFlags = 9)]
public static global::Java.Awt.Font.NumericShaper GetContextualShaper(int ranges) /* MethodBuilder.Create */
{
return default(global::Java.Awt.Font.NumericShaper);
}
/// <summary>
/// <para>Gets the masks for all of the ranges supported by this NumericShaper, packed into an int value using the logical OR logical operation for multiple ranges: NumericShaper.DEVANAGARI | NumericShaper.BENGALI.</para><para></para>
/// </summary>
/// <returns>
/// <para>all ranges of this NumericShaper. </para>
/// </returns>
/// <java-name>
/// getRanges
/// </java-name>
[Dot42.DexImport("getRanges", "()I", AccessFlags = 1)]
public int GetRanges() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Gets a NumericShaper for the specified unicode range. The NumericShaper supports only a single range and hence is not contextual.</para><para></para>
/// </summary>
/// <returns>
/// <para>the NumericShaper for the specified unicode range. </para>
/// </returns>
/// <java-name>
/// getShaper
/// </java-name>
[Dot42.DexImport("getShaper", "(I)Ljava/awt/font/NumericShaper;", AccessFlags = 9)]
public static global::Java.Awt.Font.NumericShaper GetShaper(int singleRange) /* MethodBuilder.Create */
{
return default(global::Java.Awt.Font.NumericShaper);
}
/// <summary>
/// <para>Checks if this NumericShaper is contextual (supporting multiple script ranges) or not.</para><para></para>
/// </summary>
/// <returns>
/// <para>true, if this NumericShaper is contextual, false otherwise. </para>
/// </returns>
/// <java-name>
/// isContextual
/// </java-name>
[Dot42.DexImport("isContextual", "()Z", AccessFlags = 1)]
public bool IsContextual() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Transforms the encoding of the text, starting from the character at index start and transforming count characters, using the specified context.</para><para></para>
/// </summary>
/// <java-name>
/// shape
/// </java-name>
[Dot42.DexImport("shape", "([CIII)V", AccessFlags = 1)]
public void Shape(char[] text, int start, int count, int context) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Transforms the encoding of the text, starting from the character at index start and transforming count characters.</para><para></para>
/// </summary>
/// <java-name>
/// shape
/// </java-name>
[Dot42.DexImport("shape", "([CII)V", AccessFlags = 1)]
public void Shape(char[] text, int start, int count) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Gets the masks for all of the ranges supported by this NumericShaper, packed into an int value using the logical OR logical operation for multiple ranges: NumericShaper.DEVANAGARI | NumericShaper.BENGALI.</para><para></para>
/// </summary>
/// <returns>
/// <para>all ranges of this NumericShaper. </para>
/// </returns>
/// <java-name>
/// getRanges
/// </java-name>
public int Ranges
{
[Dot42.DexImport("getRanges", "()I", AccessFlags = 1)]
get{ return GetRanges(); }
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Junit.Framework.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma warning disable 1717
namespace Junit.Framework
{
/// <summary>
/// <para>A set of assert methods. Messages are only displayed when an assert fails. </para>
/// </summary>
/// <java-name>
/// junit/framework/Assert
/// </java-name>
[Dot42.DexImport("junit/framework/Assert", AccessFlags = 33)]
public partial class Assert
/* scope: __dot42__ */
{
/// <summary>
/// <para>Protect constructor since it is a static only class </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 4)]
protected internal Assert() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that a condition is true. If it isn't it throws an AssertionFailedError with the given message. </para>
/// </summary>
/// <java-name>
/// assertTrue
/// </java-name>
[Dot42.DexImport("assertTrue", "(Ljava/lang/String;Z)V", AccessFlags = 9)]
public static void AssertTrue(string message, bool condition) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that a condition is true. If it isn't it throws an AssertionFailedError. </para>
/// </summary>
/// <java-name>
/// assertTrue
/// </java-name>
[Dot42.DexImport("assertTrue", "(Z)V", AccessFlags = 9)]
public static void AssertTrue(bool condition) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that a condition is false. If it isn't it throws an AssertionFailedError with the given message. </para>
/// </summary>
/// <java-name>
/// assertFalse
/// </java-name>
[Dot42.DexImport("assertFalse", "(Ljava/lang/String;Z)V", AccessFlags = 9)]
public static void AssertFalse(string message, bool condition) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that a condition is false. If it isn't it throws an AssertionFailedError. </para>
/// </summary>
/// <java-name>
/// assertFalse
/// </java-name>
[Dot42.DexImport("assertFalse", "(Z)V", AccessFlags = 9)]
public static void AssertFalse(bool condition) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Fails a test with the given message. </para>
/// </summary>
/// <java-name>
/// fail
/// </java-name>
[Dot42.DexImport("fail", "(Ljava/lang/String;)V", AccessFlags = 9)]
public static void Fail(string message) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Fails a test with no message. </para>
/// </summary>
/// <java-name>
/// fail
/// </java-name>
[Dot42.DexImport("fail", "()V", AccessFlags = 9)]
public static void Fail() /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 9)]
public static void AssertEquals(string @string, object @object, object object1) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two ints are equal. </para>
/// </summary>
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 9)]
public static void AssertEquals(object expected, object actual) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 9)]
public static void AssertEquals(string @string, string string1, string string2) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two ints are equal. </para>
/// </summary>
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 9)]
public static void AssertEquals(string expected, string actual) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;DDD)V", AccessFlags = 9)]
public static void AssertEquals(string @string, double @double, double double1, double double2) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(DDD)V", AccessFlags = 9)]
public static void AssertEquals(double @double, double double1, double double2) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;FFF)V", AccessFlags = 9)]
public static void AssertEquals(string @string, float single, float single1, float single2) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(FFF)V", AccessFlags = 9)]
public static void AssertEquals(float single, float single1, float single2) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;JJ)V", AccessFlags = 9)]
public static void AssertEquals(string @string, long int64, long int641) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two ints are equal. </para>
/// </summary>
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(JJ)V", AccessFlags = 9)]
public static void AssertEquals(long expected, long actual) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;ZZ)V", AccessFlags = 9)]
public static void AssertEquals(string @string, bool boolean, bool boolean1) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two ints are equal. </para>
/// </summary>
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(ZZ)V", AccessFlags = 9)]
public static void AssertEquals(bool expected, bool actual) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;BB)V", AccessFlags = 9)]
public static void AssertEquals(string @string, sbyte sByte, sbyte sByte1) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;BB)V", AccessFlags = 9, IgnoreFromJava = true)]
public static void AssertEquals(string @string, byte @byte, byte byte1) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two ints are equal. </para>
/// </summary>
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(BB)V", AccessFlags = 9)]
public static void AssertEquals(sbyte expected, sbyte actual) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two ints are equal. </para>
/// </summary>
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(BB)V", AccessFlags = 9, IgnoreFromJava = true)]
public static void AssertEquals(byte expected, byte actual) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;CC)V", AccessFlags = 9)]
public static void AssertEquals(string @string, char @char, char char1) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two ints are equal. </para>
/// </summary>
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(CC)V", AccessFlags = 9)]
public static void AssertEquals(char expected, char actual) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;SS)V", AccessFlags = 9)]
public static void AssertEquals(string @string, short int16, short int161) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two ints are equal. </para>
/// </summary>
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(SS)V", AccessFlags = 9)]
public static void AssertEquals(short expected, short actual) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;II)V", AccessFlags = 9)]
public static void AssertEquals(string @string, int int32, int int321) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two ints are equal. </para>
/// </summary>
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(II)V", AccessFlags = 9)]
public static void AssertEquals(int expected, int actual) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that an object isn't null. </para>
/// </summary>
/// <java-name>
/// assertNotNull
/// </java-name>
[Dot42.DexImport("assertNotNull", "(Ljava/lang/Object;)V", AccessFlags = 9)]
public static void AssertNotNull(object @object) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that an object isn't null. If it is an AssertionFailedError is thrown with the given message. </para>
/// </summary>
/// <java-name>
/// assertNotNull
/// </java-name>
[Dot42.DexImport("assertNotNull", "(Ljava/lang/String;Ljava/lang/Object;)V", AccessFlags = 9)]
public static void AssertNotNull(string message, object @object) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that an object is null. If it isn't an AssertionError is thrown. Message contains: Expected: <null> but was: object</para><para></para>
/// </summary>
/// <java-name>
/// assertNull
/// </java-name>
[Dot42.DexImport("assertNull", "(Ljava/lang/Object;)V", AccessFlags = 9)]
public static void AssertNull(object @object) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that an object is null. If it is not an AssertionFailedError is thrown with the given message. </para>
/// </summary>
/// <java-name>
/// assertNull
/// </java-name>
[Dot42.DexImport("assertNull", "(Ljava/lang/String;Ljava/lang/Object;)V", AccessFlags = 9)]
public static void AssertNull(string message, object @object) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two objects refer to the same object. If they are not an AssertionFailedError is thrown with the given message. </para>
/// </summary>
/// <java-name>
/// assertSame
/// </java-name>
[Dot42.DexImport("assertSame", "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 9)]
public static void AssertSame(string message, object expected, object actual) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two objects refer to the same object. If they are not the same an AssertionFailedError is thrown. </para>
/// </summary>
/// <java-name>
/// assertSame
/// </java-name>
[Dot42.DexImport("assertSame", "(Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 9)]
public static void AssertSame(object expected, object actual) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two objects do not refer to the same object. If they do refer to the same object an AssertionFailedError is thrown with the given message. </para>
/// </summary>
/// <java-name>
/// assertNotSame
/// </java-name>
[Dot42.DexImport("assertNotSame", "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 9)]
public static void AssertNotSame(string message, object expected, object actual) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two objects do not refer to the same object. If they do refer to the same object an AssertionFailedError is thrown. </para>
/// </summary>
/// <java-name>
/// assertNotSame
/// </java-name>
[Dot42.DexImport("assertNotSame", "(Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 9)]
public static void AssertNotSame(object expected, object actual) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>A Listener for test progress </para>
/// </summary>
/// <java-name>
/// junit/framework/TestListener
/// </java-name>
[Dot42.DexImport("junit/framework/TestListener", AccessFlags = 1537)]
public partial interface ITestListener
/* scope: __dot42__ */
{
/// <summary>
/// <para>An error occurred. </para>
/// </summary>
/// <java-name>
/// addError
/// </java-name>
[Dot42.DexImport("addError", "(Ljunit/framework/Test;Ljava/lang/Throwable;)V", AccessFlags = 1025)]
void AddError(global::Junit.Framework.ITest test, global::System.Exception t) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>A failure occurred. </para>
/// </summary>
/// <java-name>
/// addFailure
/// </java-name>
[Dot42.DexImport("addFailure", "(Ljunit/framework/Test;Ljunit/framework/AssertionFailedError;)V", AccessFlags = 1025)]
void AddFailure(global::Junit.Framework.ITest test, global::Junit.Framework.AssertionFailedError t) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>A test ended. </para>
/// </summary>
/// <java-name>
/// endTest
/// </java-name>
[Dot42.DexImport("endTest", "(Ljunit/framework/Test;)V", AccessFlags = 1025)]
void EndTest(global::Junit.Framework.ITest test) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>A test started. </para>
/// </summary>
/// <java-name>
/// startTest
/// </java-name>
[Dot42.DexImport("startTest", "(Ljunit/framework/Test;)V", AccessFlags = 1025)]
void StartTest(global::Junit.Framework.ITest test) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>A <code>TestFailure</code> collects a failed test together with the caught exception. <para>TestResult </para></para>
/// </summary>
/// <java-name>
/// junit/framework/TestFailure
/// </java-name>
[Dot42.DexImport("junit/framework/TestFailure", AccessFlags = 33)]
public partial class TestFailure
/* scope: __dot42__ */
{
/// <java-name>
/// fFailedTest
/// </java-name>
[Dot42.DexImport("fFailedTest", "Ljunit/framework/Test;", AccessFlags = 4)]
protected internal global::Junit.Framework.ITest FFailedTest;
/// <java-name>
/// fThrownException
/// </java-name>
[Dot42.DexImport("fThrownException", "Ljava/lang/Throwable;", AccessFlags = 4)]
protected internal global::System.Exception FThrownException;
/// <summary>
/// <para>Constructs a TestFailure with the given test and exception. </para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljunit/framework/Test;Ljava/lang/Throwable;)V", AccessFlags = 1)]
public TestFailure(global::Junit.Framework.ITest failedTest, global::System.Exception thrownException) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Gets the failed test. </para>
/// </summary>
/// <java-name>
/// failedTest
/// </java-name>
[Dot42.DexImport("failedTest", "()Ljunit/framework/Test;", AccessFlags = 1)]
public virtual global::Junit.Framework.ITest FailedTest() /* MethodBuilder.Create */
{
return default(global::Junit.Framework.ITest);
}
/// <summary>
/// <para>Gets the thrown exception. </para>
/// </summary>
/// <java-name>
/// thrownException
/// </java-name>
[Dot42.DexImport("thrownException", "()Ljava/lang/Throwable;", AccessFlags = 1)]
public virtual global::System.Exception ThrownException() /* MethodBuilder.Create */
{
return default(global::System.Exception);
}
/// <summary>
/// <para>Returns a short description of the failure. </para>
/// </summary>
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// trace
/// </java-name>
[Dot42.DexImport("trace", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string Trace() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// exceptionMessage
/// </java-name>
[Dot42.DexImport("exceptionMessage", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string ExceptionMessage() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// isFailure
/// </java-name>
[Dot42.DexImport("isFailure", "()Z", AccessFlags = 1)]
public virtual bool IsFailure() /* MethodBuilder.Create */
{
return default(bool);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal TestFailure() /* TypeBuilder.AddDefaultConstructor */
{
}
}
/// <summary>
/// <para>Thrown when an assert equals for Strings failed.</para><para>Inspired by a patch from Alex Chaffee </para>
/// </summary>
/// <java-name>
/// junit/framework/ComparisonFailure
/// </java-name>
[Dot42.DexImport("junit/framework/ComparisonFailure", AccessFlags = 33)]
public partial class ComparisonFailure : global::Junit.Framework.AssertionFailedError
/* scope: __dot42__ */
{
/// <summary>
/// <para>Constructs a comparison failure. </para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)]
public ComparisonFailure(string message, string expected, string actual) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns "..." in place of common prefix and "..." in place of common suffix between expected and actual.</para><para><para>Throwable::getMessage() </para></para>
/// </summary>
/// <java-name>
/// getMessage
/// </java-name>
[Dot42.DexImport("getMessage", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetMessage() /* MethodBuilder.Create */
{
return default(string);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal ComparisonFailure() /* TypeBuilder.AddDefaultConstructor */
{
}
}
/// <summary>
/// <para>A <code>TestSuite</code> is a <code>Composite</code> of Tests. It runs a collection of test cases. Here is an example using the dynamic test definition. <pre>
/// TestSuite suite= new TestSuite();
/// suite.addTest(new MathTest("testAdd"));
/// suite.addTest(new MathTest("testDivideByZero"));
/// </pre> </para><para>Alternatively, a TestSuite can extract the tests to be run automatically. To do so you pass the class of your TestCase class to the TestSuite constructor. <pre>
/// TestSuite suite= new TestSuite(MathTest.class);
/// </pre> </para><para>This constructor creates a suite with all the methods starting with "test" that take no arguments.</para><para>A final option is to do the same for a large array of test classes. <pre>
/// Class[] testClasses = { MathTest.class, AnotherTest.class }
/// TestSuite suite= new TestSuite(testClasses);
/// </pre> </para><para><para>Test </para></para>
/// </summary>
/// <java-name>
/// junit/framework/TestSuite
/// </java-name>
[Dot42.DexImport("junit/framework/TestSuite", AccessFlags = 33)]
public partial class TestSuite : global::Junit.Framework.ITest
/* scope: __dot42__ */
{
/// <summary>
/// <para>Constructs an empty TestSuite. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public TestSuite() /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/Class;Ljava/lang/String;)V", AccessFlags = 1)]
public TestSuite(global::System.Type type, string @string) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/Class;)V", AccessFlags = 1)]
public TestSuite(global::System.Type type) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public TestSuite(string @string) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Adds a test to the suite. </para>
/// </summary>
/// <java-name>
/// addTest
/// </java-name>
[Dot42.DexImport("addTest", "(Ljunit/framework/Test;)V", AccessFlags = 1)]
public virtual void AddTest(global::Junit.Framework.ITest test) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Adds the tests from the given class to the suite </para>
/// </summary>
/// <java-name>
/// addTestSuite
/// </java-name>
[Dot42.DexImport("addTestSuite", "(Ljava/lang/Class;)V", AccessFlags = 1)]
public virtual void AddTestSuite(global::System.Type testClass) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>...as the moon sets over the early morning Merlin, Oregon mountains, our intrepid adventurers type... </para>
/// </summary>
/// <java-name>
/// createTest
/// </java-name>
[Dot42.DexImport("createTest", "(Ljava/lang/Class;Ljava/lang/String;)Ljunit/framework/Test;", AccessFlags = 9)]
public static global::Junit.Framework.ITest CreateTest(global::System.Type theClass, string name) /* MethodBuilder.Create */
{
return default(global::Junit.Framework.ITest);
}
/// <summary>
/// <para>Counts the number of test cases that will be run by this test. </para>
/// </summary>
/// <java-name>
/// countTestCases
/// </java-name>
[Dot42.DexImport("countTestCases", "()I", AccessFlags = 1)]
public virtual int CountTestCases() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Gets a constructor which takes a single String as its argument or a no arg constructor. </para>
/// </summary>
/// <java-name>
/// getTestConstructor
/// </java-name>
[Dot42.DexImport("getTestConstructor", "(Ljava/lang/Class;)Ljava/lang/reflect/Constructor;", AccessFlags = 9)]
public static global::System.Reflection.ConstructorInfo GetTestConstructor(global::System.Type theClass) /* MethodBuilder.Create */
{
return default(global::System.Reflection.ConstructorInfo);
}
/// <summary>
/// <para>Runs the tests and collects their result in a TestResult. </para>
/// </summary>
/// <java-name>
/// run
/// </java-name>
[Dot42.DexImport("run", "(Ljunit/framework/TestResult;)V", AccessFlags = 1)]
public virtual void Run(global::Junit.Framework.TestResult result) /* MethodBuilder.Create */
{
}
/// <java-name>
/// runTest
/// </java-name>
[Dot42.DexImport("runTest", "(Ljunit/framework/Test;Ljunit/framework/TestResult;)V", AccessFlags = 1)]
public virtual void RunTest(global::Junit.Framework.ITest test, global::Junit.Framework.TestResult result) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the test at the given index </para>
/// </summary>
/// <java-name>
/// testAt
/// </java-name>
[Dot42.DexImport("testAt", "(I)Ljunit/framework/Test;", AccessFlags = 1)]
public virtual global::Junit.Framework.ITest TestAt(int index) /* MethodBuilder.Create */
{
return default(global::Junit.Framework.ITest);
}
/// <summary>
/// <para>Returns the number of tests in this suite </para>
/// </summary>
/// <java-name>
/// testCount
/// </java-name>
[Dot42.DexImport("testCount", "()I", AccessFlags = 1)]
public virtual int TestCount() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Returns the tests as an enumeration </para>
/// </summary>
/// <java-name>
/// tests
/// </java-name>
[Dot42.DexImport("tests", "()Ljava/util/Enumeration;", AccessFlags = 1)]
public virtual global::Java.Util.IEnumeration<object> Tests() /* MethodBuilder.Create */
{
return default(global::Java.Util.IEnumeration<object>);
}
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Sets the name of the suite. </para>
/// </summary>
/// <java-name>
/// setName
/// </java-name>
[Dot42.DexImport("setName", "(Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void SetName(string name) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the name of the suite. Not all test suites have a name and this method can return null. </para>
/// </summary>
/// <java-name>
/// getName
/// </java-name>
[Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetName() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the name of the suite. Not all test suites have a name and this method can return null. </para>
/// </summary>
/// <java-name>
/// getName
/// </java-name>
public string Name
{
[Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetName(); }
[Dot42.DexImport("setName", "(Ljava/lang/String;)V", AccessFlags = 1)]
set{ SetName(value); }
}
}
/// <summary>
/// <para>A <code>TestResult</code> collects the results of executing a test case. It is an instance of the Collecting Parameter pattern. The test framework distinguishes between <b>failures</b> and <b>errors</b>. A failure is anticipated and checked for with assertions. Errors are unanticipated problems like an ArrayIndexOutOfBoundsException.</para><para><para>Test </para></para>
/// </summary>
/// <java-name>
/// junit/framework/TestResult
/// </java-name>
[Dot42.DexImport("junit/framework/TestResult", AccessFlags = 33)]
public partial class TestResult
/* scope: __dot42__ */
{
/// <java-name>
/// fFailures
/// </java-name>
[Dot42.DexImport("fFailures", "Ljava/util/Vector;", AccessFlags = 4)]
protected internal global::Java.Util.Vector<object> FFailures;
/// <java-name>
/// fErrors
/// </java-name>
[Dot42.DexImport("fErrors", "Ljava/util/Vector;", AccessFlags = 4)]
protected internal global::Java.Util.Vector<object> FErrors;
/// <java-name>
/// fListeners
/// </java-name>
[Dot42.DexImport("fListeners", "Ljava/util/Vector;", AccessFlags = 4)]
protected internal global::Java.Util.Vector<object> FListeners;
/// <java-name>
/// fRunTests
/// </java-name>
[Dot42.DexImport("fRunTests", "I", AccessFlags = 4)]
protected internal int FRunTests;
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public TestResult() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Adds an error to the list of errors. The passed in exception caused the error. </para>
/// </summary>
/// <java-name>
/// addError
/// </java-name>
[Dot42.DexImport("addError", "(Ljunit/framework/Test;Ljava/lang/Throwable;)V", AccessFlags = 33)]
public virtual void AddError(global::Junit.Framework.ITest test, global::System.Exception t) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Adds a failure to the list of failures. The passed in exception caused the failure. </para>
/// </summary>
/// <java-name>
/// addFailure
/// </java-name>
[Dot42.DexImport("addFailure", "(Ljunit/framework/Test;Ljunit/framework/AssertionFailedError;)V", AccessFlags = 33)]
public virtual void AddFailure(global::Junit.Framework.ITest test, global::Junit.Framework.AssertionFailedError t) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Registers a TestListener </para>
/// </summary>
/// <java-name>
/// addListener
/// </java-name>
[Dot42.DexImport("addListener", "(Ljunit/framework/TestListener;)V", AccessFlags = 33)]
public virtual void AddListener(global::Junit.Framework.ITestListener listener) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Unregisters a TestListener </para>
/// </summary>
/// <java-name>
/// removeListener
/// </java-name>
[Dot42.DexImport("removeListener", "(Ljunit/framework/TestListener;)V", AccessFlags = 33)]
public virtual void RemoveListener(global::Junit.Framework.ITestListener listener) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Informs the result that a test was completed. </para>
/// </summary>
/// <java-name>
/// endTest
/// </java-name>
[Dot42.DexImport("endTest", "(Ljunit/framework/Test;)V", AccessFlags = 1)]
public virtual void EndTest(global::Junit.Framework.ITest test) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Gets the number of detected errors. </para>
/// </summary>
/// <java-name>
/// errorCount
/// </java-name>
[Dot42.DexImport("errorCount", "()I", AccessFlags = 33)]
public virtual int ErrorCount() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Returns an Enumeration for the errors </para>
/// </summary>
/// <java-name>
/// errors
/// </java-name>
[Dot42.DexImport("errors", "()Ljava/util/Enumeration;", AccessFlags = 33)]
public virtual global::Java.Util.IEnumeration<object> Errors() /* MethodBuilder.Create */
{
return default(global::Java.Util.IEnumeration<object>);
}
/// <summary>
/// <para>Gets the number of detected failures. </para>
/// </summary>
/// <java-name>
/// failureCount
/// </java-name>
[Dot42.DexImport("failureCount", "()I", AccessFlags = 33)]
public virtual int FailureCount() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Returns an Enumeration for the failures </para>
/// </summary>
/// <java-name>
/// failures
/// </java-name>
[Dot42.DexImport("failures", "()Ljava/util/Enumeration;", AccessFlags = 33)]
public virtual global::Java.Util.IEnumeration<object> Failures() /* MethodBuilder.Create */
{
return default(global::Java.Util.IEnumeration<object>);
}
/// <summary>
/// <para>Runs a TestCase. </para>
/// </summary>
/// <java-name>
/// run
/// </java-name>
[Dot42.DexImport("run", "(Ljunit/framework/TestCase;)V", AccessFlags = 4)]
protected internal virtual void Run(global::Junit.Framework.TestCase test) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Gets the number of run tests. </para>
/// </summary>
/// <java-name>
/// runCount
/// </java-name>
[Dot42.DexImport("runCount", "()I", AccessFlags = 33)]
public virtual int RunCount() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Runs a TestCase. </para>
/// </summary>
/// <java-name>
/// runProtected
/// </java-name>
[Dot42.DexImport("runProtected", "(Ljunit/framework/Test;Ljunit/framework/Protectable;)V", AccessFlags = 1)]
public virtual void RunProtected(global::Junit.Framework.ITest test, global::Junit.Framework.IProtectable p) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Checks whether the test run should stop </para>
/// </summary>
/// <java-name>
/// shouldStop
/// </java-name>
[Dot42.DexImport("shouldStop", "()Z", AccessFlags = 33)]
public virtual bool ShouldStop() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Informs the result that a test will be started. </para>
/// </summary>
/// <java-name>
/// startTest
/// </java-name>
[Dot42.DexImport("startTest", "(Ljunit/framework/Test;)V", AccessFlags = 1)]
public virtual void StartTest(global::Junit.Framework.ITest test) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Marks that the test run should stop. </para>
/// </summary>
/// <java-name>
/// stop
/// </java-name>
[Dot42.DexImport("stop", "()V", AccessFlags = 33)]
public virtual void Stop() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns whether the entire test was successful or not. </para>
/// </summary>
/// <java-name>
/// wasSuccessful
/// </java-name>
[Dot42.DexImport("wasSuccessful", "()Z", AccessFlags = 33)]
public virtual bool WasSuccessful() /* MethodBuilder.Create */
{
return default(bool);
}
}
/// <summary>
/// <para>A <b>Protectable</b> can be run and can throw a Throwable.</para><para><para>TestResult </para></para>
/// </summary>
/// <java-name>
/// junit/framework/Protectable
/// </java-name>
[Dot42.DexImport("junit/framework/Protectable", AccessFlags = 1537)]
public partial interface IProtectable
/* scope: __dot42__ */
{
/// <summary>
/// <para>Run the the following method protected. </para>
/// </summary>
/// <java-name>
/// protect
/// </java-name>
[Dot42.DexImport("protect", "()V", AccessFlags = 1025)]
void Protect() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Thrown when an assertion failed. </para>
/// </summary>
/// <java-name>
/// junit/framework/AssertionFailedError
/// </java-name>
[Dot42.DexImport("junit/framework/AssertionFailedError", AccessFlags = 33)]
public partial class AssertionFailedError : global::Java.Lang.Error
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public AssertionFailedError() /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public AssertionFailedError(string message) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>A <b>Test</b> can be run and collect its results.</para><para><para>TestResult </para></para>
/// </summary>
/// <java-name>
/// junit/framework/Test
/// </java-name>
[Dot42.DexImport("junit/framework/Test", AccessFlags = 1537)]
public partial interface ITest
/* scope: __dot42__ */
{
/// <summary>
/// <para>Counts the number of test cases that will be run by this test. </para>
/// </summary>
/// <java-name>
/// countTestCases
/// </java-name>
[Dot42.DexImport("countTestCases", "()I", AccessFlags = 1025)]
int CountTestCases() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Runs a test and collects its result in a TestResult instance. </para>
/// </summary>
/// <java-name>
/// run
/// </java-name>
[Dot42.DexImport("run", "(Ljunit/framework/TestResult;)V", AccessFlags = 1025)]
void Run(global::Junit.Framework.TestResult result) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>A test case defines the fixture to run multiple tests. To define a test case<br></br> <ol><li><para>implement a subclass of <code>TestCase</code> </para></li><li><para>define instance variables that store the state of the fixture </para></li><li><para>initialize the fixture state by overriding setUp() </para></li><li><para>clean-up after a test by overriding tearDown(). </para></li></ol>Each test runs in its own fixture so there can be no side effects among test runs. Here is an example: <pre>
/// public class MathTest extends TestCase {
/// protected double fValue1;
/// protected double fValue2;
///
/// protected void setUp() {
/// fValue1= 2.0;
/// fValue2= 3.0;
/// }
/// }
/// </pre></para><para>For each test implement a method which interacts with the fixture. Verify the expected results with assertions specified by calling junit.framework.Assert#assertTrue(String, boolean) with a boolean. <pre>
/// public void testAdd() {
/// double result= fValue1 + fValue2;
/// assertTrue(result == 5.0);
/// }
/// </pre></para><para>Once the methods are defined you can run them. The framework supports both a static type safe and more dynamic way to run a test. In the static way you override the runTest method and define the method to be invoked. A convenient way to do so is with an anonymous inner class. <pre>
/// TestCase test= new MathTest("add") {
/// public void runTest() {
/// testAdd();
/// }
/// };
/// test.run();
/// </pre></para><para>The dynamic way uses reflection to implement runTest(). It dynamically finds and invokes a method. In this case the name of the test case has to correspond to the test method to be run. <pre>
/// TestCase test= new MathTest("testAdd");
/// test.run();
/// </pre></para><para>The tests to be run can be collected into a TestSuite. JUnit provides different <b>test runners</b> which can run a test suite and collect the results. A test runner either expects a static method <code>suite</code> as the entry point to get a test to run or it will extract the suite automatically. <pre>
/// public static Test suite() {
/// suite.addTest(new MathTest("testAdd"));
/// suite.addTest(new MathTest("testDivideByZero"));
/// return suite;
/// }
/// </pre> <para>TestResult </para><simplesectsep></simplesectsep><para>TestSuite </para></para>
/// </summary>
/// <java-name>
/// junit/framework/TestCase
/// </java-name>
[Dot42.DexImport("junit/framework/TestCase", AccessFlags = 1057)]
public abstract partial class TestCase : global::Junit.Framework.Assert, global::Junit.Framework.ITest
/* scope: __dot42__ */
{
/// <summary>
/// <para>No-arg constructor to enable serialization. This method is not intended to be used by mere mortals without calling setName(). </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public TestCase() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Constructs a test case with the given name. </para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public TestCase(string name) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Counts the number of test cases executed by run(TestResult result). </para>
/// </summary>
/// <java-name>
/// countTestCases
/// </java-name>
[Dot42.DexImport("countTestCases", "()I", AccessFlags = 1)]
public virtual int CountTestCases() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Creates a default TestResult object</para><para><para>TestResult </para></para>
/// </summary>
/// <java-name>
/// createResult
/// </java-name>
[Dot42.DexImport("createResult", "()Ljunit/framework/TestResult;", AccessFlags = 4)]
protected internal virtual global::Junit.Framework.TestResult CreateResult() /* MethodBuilder.Create */
{
return default(global::Junit.Framework.TestResult);
}
/// <summary>
/// <para>A convenience method to run this test, collecting the results with a default TestResult object.</para><para><para>TestResult </para></para>
/// </summary>
/// <java-name>
/// run
/// </java-name>
[Dot42.DexImport("run", "()Ljunit/framework/TestResult;", AccessFlags = 1)]
public virtual global::Junit.Framework.TestResult Run() /* MethodBuilder.Create */
{
return default(global::Junit.Framework.TestResult);
}
/// <summary>
/// <para>Runs the test case and collects the results in TestResult. </para>
/// </summary>
/// <java-name>
/// run
/// </java-name>
[Dot42.DexImport("run", "(Ljunit/framework/TestResult;)V", AccessFlags = 1)]
public virtual void Run(global::Junit.Framework.TestResult result) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Runs the bare test sequence. </para>
/// </summary>
/// <java-name>
/// runBare
/// </java-name>
[Dot42.DexImport("runBare", "()V", AccessFlags = 1)]
public virtual void RunBare() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Override to run the test and assert its state. </para>
/// </summary>
/// <java-name>
/// runTest
/// </java-name>
[Dot42.DexImport("runTest", "()V", AccessFlags = 4)]
protected internal virtual void RunTest() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Sets up the fixture, for example, open a network connection. This method is called before a test is executed. </para>
/// </summary>
/// <java-name>
/// setUp
/// </java-name>
[Dot42.DexImport("setUp", "()V", AccessFlags = 4)]
protected internal virtual void SetUp() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Tears down the fixture, for example, close a network connection. This method is called after a test is executed. </para>
/// </summary>
/// <java-name>
/// tearDown
/// </java-name>
[Dot42.DexImport("tearDown", "()V", AccessFlags = 4)]
protected internal virtual void TearDown() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns a string representation of the test case </para>
/// </summary>
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Gets the name of a TestCase </para>
/// </summary>
/// <returns>
/// <para>the name of the TestCase </para>
/// </returns>
/// <java-name>
/// getName
/// </java-name>
[Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetName() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Sets the name of a TestCase </para>
/// </summary>
/// <java-name>
/// setName
/// </java-name>
[Dot42.DexImport("setName", "(Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void SetName(string name) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Gets the name of a TestCase </para>
/// </summary>
/// <returns>
/// <para>the name of the TestCase </para>
/// </returns>
/// <java-name>
/// getName
/// </java-name>
public string Name
{
[Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetName(); }
[Dot42.DexImport("setName", "(Ljava/lang/String;)V", AccessFlags = 1)]
set{ SetName(value); }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
**
** Propertybuilder is for client to define properties for a class
**
**
===========================================================*/
using System.Runtime.CompilerServices;
using CultureInfo = System.Globalization.CultureInfo;
namespace System.Reflection.Emit
{
//
// A PropertyBuilder is always associated with a TypeBuilder. The TypeBuilder.DefineProperty
// method will return a new PropertyBuilder to a client.
//
public sealed class PropertyBuilder : PropertyInfo
{
// Constructs a PropertyBuilder.
//
internal PropertyBuilder(
ModuleBuilder mod, // the module containing this PropertyBuilder
string name, // property name
SignatureHelper sig, // property signature descriptor info
PropertyAttributes attr, // property attribute such as DefaultProperty, Bindable, DisplayBind, etc
Type returnType, // return type of the property.
PropertyToken prToken, // the metadata token for this property
TypeBuilder containingType) // the containing type
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
throw new ArgumentException(SR.Argument_EmptyName, nameof(name));
if (name[0] == '\0')
throw new ArgumentException(SR.Argument_IllegalName, nameof(name));
m_name = name;
m_moduleBuilder = mod;
m_signature = sig;
m_attributes = attr;
m_returnType = returnType;
m_prToken = prToken;
m_tkProperty = prToken.Token;
m_containingType = containingType;
}
/// <summary>
/// Set the default value of the Property
/// </summary>
public void SetConstant(object? defaultValue)
{
m_containingType.ThrowIfCreated();
TypeBuilder.SetConstantValue(
m_moduleBuilder,
m_prToken.Token,
m_returnType,
defaultValue);
}
// Return the Token for this property within the TypeBuilder that the
// property is defined within.
public PropertyToken PropertyToken => m_prToken;
public override Module Module => m_containingType.Module;
private void SetMethodSemantics(MethodBuilder mdBuilder, MethodSemanticsAttributes semantics)
{
if (mdBuilder == null)
{
throw new ArgumentNullException(nameof(mdBuilder));
}
m_containingType.ThrowIfCreated();
ModuleBuilder module = m_moduleBuilder;
TypeBuilder.DefineMethodSemantics(
JitHelpers.GetQCallModuleOnStack(ref module),
m_prToken.Token,
semantics,
mdBuilder.GetToken().Token);
}
public void SetGetMethod(MethodBuilder mdBuilder)
{
SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.Getter);
m_getMethod = mdBuilder;
}
public void SetSetMethod(MethodBuilder mdBuilder)
{
SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.Setter);
m_setMethod = mdBuilder;
}
public void AddOtherMethod(MethodBuilder mdBuilder)
{
SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.Other);
}
// Use this function if client decides to form the custom attribute blob themselves
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
if (con == null)
throw new ArgumentNullException(nameof(con));
if (binaryAttribute == null)
throw new ArgumentNullException(nameof(binaryAttribute));
m_containingType.ThrowIfCreated();
TypeBuilder.DefineCustomAttribute(
m_moduleBuilder,
m_prToken.Token,
m_moduleBuilder.GetConstructorToken(con).Token,
binaryAttribute,
false, false);
}
// Use this function if client wishes to build CustomAttribute using CustomAttributeBuilder
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
if (customBuilder == null)
{
throw new ArgumentNullException(nameof(customBuilder));
}
m_containingType.ThrowIfCreated();
customBuilder.CreateCustomAttribute(m_moduleBuilder, m_prToken.Token);
}
// Not supported functions in dynamic module.
public override object GetValue(object? obj, object?[]? index)
{
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
public override object GetValue(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? index, CultureInfo? culture)
{
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
public override void SetValue(object? obj, object? value, object?[]? index)
{
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
public override void SetValue(object? obj, object? value, BindingFlags invokeAttr, Binder? binder, object?[]? index, CultureInfo? culture)
{
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
public override MethodInfo[] GetAccessors(bool nonPublic)
{
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
public override MethodInfo? GetGetMethod(bool nonPublic)
{
if (nonPublic || m_getMethod == null)
return m_getMethod;
// now check to see if m_getMethod is public
if ((m_getMethod.Attributes & MethodAttributes.Public) == MethodAttributes.Public)
return m_getMethod;
return null;
}
public override MethodInfo? GetSetMethod(bool nonPublic)
{
if (nonPublic || m_setMethod == null)
return m_setMethod;
// now check to see if m_setMethod is public
if ((m_setMethod.Attributes & MethodAttributes.Public) == MethodAttributes.Public)
return m_setMethod;
return null;
}
public override ParameterInfo[] GetIndexParameters()
{
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
public override Type PropertyType => m_returnType;
public override PropertyAttributes Attributes => m_attributes;
public override bool CanRead
{
get { if (m_getMethod != null) return true; else return false; }
}
public override bool CanWrite
{
get { if (m_setMethod != null) return true; else return false; }
}
public override object[] GetCustomAttributes(bool inherit)
{
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
public override bool IsDefined(Type attributeType, bool inherit)
{
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
public override string Name => m_name;
public override Type? DeclaringType => m_containingType;
public override Type? ReflectedType => m_containingType;
// These are package private so that TypeBuilder can access them.
private string m_name; // The name of the property
private PropertyToken m_prToken; // The token of this property
private int m_tkProperty;
private ModuleBuilder m_moduleBuilder;
private SignatureHelper m_signature;
private PropertyAttributes m_attributes; // property's attribute flags
private Type m_returnType; // property's return type
private MethodInfo? m_getMethod;
private MethodInfo? m_setMethod;
private TypeBuilder m_containingType;
}
}
| |
using System;
using System.Windows.Forms;
using System.Security.Cryptography;
namespace ExampleCrypto
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string strOriginalData = string.Empty;
string strEncryptedData = string.Empty;
string strDecryptedData = string.Empty;
strOriginalData = "this is original data 1234567890"; // your original data in here
MessageBox.Show("ORIGINAL DATA:\r\n" + strOriginalData);
clsCrypto aes = new clsCrypto();
aes.IV = "this is your IV"; // your IV
aes.KEY = "this is your KEY"; // your KEY
strEncryptedData = aes.Encrypt(strOriginalData, CipherMode.CBC); // your cipher mode
MessageBox.Show("ENCRYPTED DATA:\r\n" + strEncryptedData);
strDecryptedData = aes.Decrypt(strEncryptedData, CipherMode.CBC);
MessageBox.Show("DECRYPTED DATA:\r\n" + strDecryptedData);
}
}
}
2.Create clsCrypto.cs and copy paste follows code in your class and run your code. I used MD5 to generated Initial Vector(IV) and KEY of AES.
using System;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Remoting.Metadata.W3cXsd2001;
namespace ExampleCrypto
{
public class clsCrypto
{
private string _KEY = string.Empty;
protected internal string KEY
{
get
{
return _KEY;
}
set
{
if (!string.IsNullOrEmpty(value))
{
_KEY = value;
}
}
}
private string _IV = string.Empty;
protected internal string IV
{
get
{
return _IV;
}
set
{
if (!string.IsNullOrEmpty(value))
{
_IV = value;
}
}
}
private string CalcMD5(string strInput)
{
string strOutput = string.Empty;
if (!string.IsNullOrEmpty(strInput))
{
try
{
StringBuilder strHex = new StringBuilder();
using (MD5 md5 = MD5.Create())
{
byte[] bytArText = Encoding.Default.GetBytes(strInput);
byte[] bytArHash = md5.ComputeHash(bytArText);
for (int i = 0; i < bytArHash.Length; i++)
{
strHex.Append(bytArHash[i].ToString("X2"));
}
strOutput = strHex.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
return strOutput;
}
private byte[] GetBytesFromHexString(string strInput)
{
byte[] bytArOutput = new byte[] { };
if ((!string.IsNullOrEmpty(strInput)) && strInput.Length % 2 == 0)
{
SoapHexBinary hexBinary = null;
try
{
hexBinary = SoapHexBinary.Parse(strInput);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
bytArOutput = hexBinary.Value;
}
return bytArOutput;
}
private byte[] GenerateIV()
{
byte[] bytArOutput = new byte[] { };
try
{
string strIV = CalcMD5(IV);
bytArOutput = GetBytesFromHexString(strIV);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return bytArOutput;
}
private byte[] GenerateKey()
{
byte[] bytArOutput = new byte[] { };
try
{
string strKey = CalcMD5(KEY);
bytArOutput = GetBytesFromHexString(strKey);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return bytArOutput;
}
protected internal string Encrypt(string strInput, CipherMode cipherMode)
{
string strOutput = string.Empty;
if (!string.IsNullOrEmpty(strInput))
{
try
{
byte[] bytePlainText = Encoding.Default.GetBytes(strInput);
using (RijndaelManaged rijManaged = new RijndaelManaged())
{
rijManaged.Mode = cipherMode;
rijManaged.BlockSize = 128;
rijManaged.KeySize = 128;
rijManaged.IV = GenerateIV();
rijManaged.Key = GenerateKey();
rijManaged.Padding = PaddingMode.Zeros;
ICryptoTransform icpoTransform = rijManaged.CreateEncryptor(rijManaged.Key, rijManaged.IV);
using (MemoryStream memStream = new MemoryStream())
{
using (CryptoStream cpoStream = new CryptoStream(memStream, icpoTransform, CryptoStreamMode.Write))
{
cpoStream.Write(bytePlainText, 0, bytePlainText.Length);
cpoStream.FlushFinalBlock();
}
strOutput = Encoding.Default.GetString(memStream.ToArray());
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
return strOutput;
}
protected internal string Decrypt(string strInput, CipherMode cipherMode)
{
string strOutput = string.Empty;
if (!string.IsNullOrEmpty(strInput))
{
try
{
byte[] byteCipherText = Encoding.Default.GetBytes(strInput);
byte[] byteBuffer = new byte[strInput.Length];
using (RijndaelManaged rijManaged = new RijndaelManaged())
{
rijManaged.Mode = cipherMode;
rijManaged.BlockSize = 128;
rijManaged.KeySize = 128;
rijManaged.IV = GenerateIV();
rijManaged.Key = GenerateKey();
rijManaged.Padding = PaddingMode.Zeros;
ICryptoTransform icpoTransform = rijManaged.CreateDecryptor(rijManaged.Key, rijManaged.IV);
using (MemoryStream memStream = new MemoryStream(byteCipherText))
{
using (CryptoStream cpoStream = new CryptoStream(memStream, icpoTransform, CryptoStreamMode.Read))
{
cpoStream.Read(byteBuffer, 0, byteBuffer.Length);
}
strOutput = Encoding.Default.GetString(byteBuffer);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
return strOutput;
}
}
}
| |
// 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.ServiceModel.Description
{
using System.Globalization;
using System.ServiceModel.Channels;
using System.ServiceModel;
using System.Collections.Generic;
public static class MetadataExchangeBindings
{
private static Binding s_httpBinding;
private static Binding s_httpGetBinding;
private static Binding s_httpsBinding;
private static Binding s_httpsGetBinding;
private static Binding s_tcpBinding;
private static Binding s_pipeBinding;
internal static Binding Http
{
get
{
// don't need to lock because no guarantee of instance identity
if (s_httpBinding == null)
{
s_httpBinding = CreateHttpBinding();
}
return s_httpBinding;
}
}
internal static Binding HttpGet
{
get
{
// don't need to lock because no guarantee of instance identity
if (s_httpGetBinding == null)
{
s_httpGetBinding = CreateHttpGetBinding();
}
return s_httpGetBinding;
}
}
internal static Binding Https
{
get
{
// don't need to lock because no guarantee of instance identity
if (s_httpsBinding == null)
{
s_httpsBinding = CreateHttpsBinding();
}
return s_httpsBinding;
}
}
internal static Binding HttpsGet
{
get
{
// don't need to lock because no guarantee of instance identity
if (s_httpsGetBinding == null)
{
s_httpsGetBinding = CreateHttpsGetBinding();
}
return s_httpsGetBinding;
}
}
internal static Binding Tcp
{
get
{
// don't need to lock because no guarantee of instance identity
if (s_tcpBinding == null)
{
s_tcpBinding = CreateTcpBinding();
}
return s_tcpBinding;
}
}
internal static Binding NamedPipe
{
get
{
// don't need to lock because no guarantee of instance identity
if (s_pipeBinding == null)
{
s_pipeBinding = CreateNamedPipeBinding();
}
return s_pipeBinding;
}
}
public static Binding CreateMexHttpBinding()
{
return MetadataExchangeBindings.CreateHttpBinding();
}
public static Binding CreateMexHttpsBinding()
{
return MetadataExchangeBindings.CreateHttpsBinding();
}
public static Binding CreateMexTcpBinding()
{
return MetadataExchangeBindings.CreateTcpBinding();
}
public static Binding CreateMexNamedPipeBinding()
{
return MetadataExchangeBindings.CreateNamedPipeBinding();
}
internal static Binding GetBindingForScheme(string scheme)
{
Binding binding = null;
TryGetBindingForScheme(scheme, out binding);
return binding;
}
internal static bool TryGetBindingForScheme(string scheme, out Binding binding)
{
if (String.Compare(scheme, "http", StringComparison.OrdinalIgnoreCase) == 0)
{
binding = Http;
}
else if (String.Compare(scheme, "https", StringComparison.OrdinalIgnoreCase) == 0)
{
binding = Https;
}
else if (String.Compare(scheme, "net.tcp", StringComparison.OrdinalIgnoreCase) == 0)
{
binding = Tcp;
}
else if (String.Compare(scheme, "net.pipe", StringComparison.OrdinalIgnoreCase) == 0)
{
binding = NamedPipe;
}
else
{
binding = null;
}
return binding != null;
}
private static WSHttpBinding CreateHttpBinding()
{
WSHttpBinding binding = new WSHttpBinding(SecurityMode.None, reliableSessionEnabled: false);
binding.Name = MetadataStrings.MetadataExchangeStrings.HttpBindingName;
binding.Namespace = MetadataStrings.MetadataExchangeStrings.BindingNamespace;
return binding;
}
private static WSHttpBinding CreateHttpsBinding()
{
WSHttpBinding binding = new WSHttpBinding(
new WSHttpSecurity(SecurityMode.Transport, new HttpTransportSecurity(), new NonDualMessageSecurityOverHttp()), reliableSessionEnabled: false);
binding.Name = MetadataStrings.MetadataExchangeStrings.HttpsBindingName;
binding.Namespace = MetadataStrings.MetadataExchangeStrings.BindingNamespace;
return binding;
}
private static CustomBinding CreateHttpGetBinding()
{
return CreateGetBinding(new HttpTransportBindingElement());
}
private static CustomBinding CreateHttpsGetBinding()
{
return CreateGetBinding(new HttpsTransportBindingElement());
}
private static CustomBinding CreateGetBinding(HttpTransportBindingElement httpTransport)
{
TextMessageEncodingBindingElement textEncoding = new TextMessageEncodingBindingElement();
textEncoding.MessageVersion = MessageVersion.None;
httpTransport.Method = "GET";
httpTransport.InheritBaseAddressSettings = true;
return new CustomBinding(textEncoding, httpTransport);
}
private static CustomBinding CreateTcpBinding()
{
CustomBinding binding = new CustomBinding(MetadataStrings.MetadataExchangeStrings.TcpBindingName, MetadataStrings.MetadataExchangeStrings.BindingNamespace);
TcpTransportBindingElement tcpTransport = new TcpTransportBindingElement();
binding.Elements.Add(tcpTransport);
return binding;
}
private static CustomBinding CreateNamedPipeBinding()
{
throw new NotImplementedException();
}
internal static bool IsSchemeSupported(string scheme)
{
Binding binding;
return TryGetBindingForScheme(scheme, out binding);
}
}
}
| |
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Cloud.ErrorReporting.V1Beta1;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Google.Cloud.ErrorReporting.V1Beta1.Snippets
{
/// <summary>Generated snippets</summary>
public class GeneratedErrorStatsServiceClientSnippets
{
/// <summary>Snippet for ListGroupStatsAsync</summary>
public async Task ListGroupStatsAsync()
{
// Snippet: ListGroupStatsAsync(ProjectName,QueryTimeRange,string,int?,CallSettings)
// Create client
ErrorStatsServiceClient errorStatsServiceClient = await ErrorStatsServiceClient.CreateAsync();
// Initialize request argument(s)
ProjectName projectName = new ProjectName("[PROJECT]");
QueryTimeRange timeRange = new QueryTimeRange();
// Make the request
PagedAsyncEnumerable<ListGroupStatsResponse, ErrorGroupStats> response =
errorStatsServiceClient.ListGroupStatsAsync(projectName, timeRange);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((ErrorGroupStats item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListGroupStatsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ErrorGroupStats item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ErrorGroupStats> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ErrorGroupStats item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListGroupStats</summary>
public void ListGroupStats()
{
// Snippet: ListGroupStats(ProjectName,QueryTimeRange,string,int?,CallSettings)
// Create client
ErrorStatsServiceClient errorStatsServiceClient = ErrorStatsServiceClient.Create();
// Initialize request argument(s)
ProjectName projectName = new ProjectName("[PROJECT]");
QueryTimeRange timeRange = new QueryTimeRange();
// Make the request
PagedEnumerable<ListGroupStatsResponse, ErrorGroupStats> response =
errorStatsServiceClient.ListGroupStats(projectName, timeRange);
// Iterate over all response items, lazily performing RPCs as required
foreach (ErrorGroupStats item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListGroupStatsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ErrorGroupStats item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ErrorGroupStats> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ErrorGroupStats item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListGroupStatsAsync</summary>
public async Task ListGroupStatsAsync_RequestObject()
{
// Snippet: ListGroupStatsAsync(ListGroupStatsRequest,CallSettings)
// Create client
ErrorStatsServiceClient errorStatsServiceClient = await ErrorStatsServiceClient.CreateAsync();
// Initialize request argument(s)
ListGroupStatsRequest request = new ListGroupStatsRequest
{
ProjectNameAsProjectName = new ProjectName("[PROJECT]"),
TimeRange = new QueryTimeRange(),
};
// Make the request
PagedAsyncEnumerable<ListGroupStatsResponse, ErrorGroupStats> response =
errorStatsServiceClient.ListGroupStatsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((ErrorGroupStats item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListGroupStatsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ErrorGroupStats item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ErrorGroupStats> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ErrorGroupStats item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListGroupStats</summary>
public void ListGroupStats_RequestObject()
{
// Snippet: ListGroupStats(ListGroupStatsRequest,CallSettings)
// Create client
ErrorStatsServiceClient errorStatsServiceClient = ErrorStatsServiceClient.Create();
// Initialize request argument(s)
ListGroupStatsRequest request = new ListGroupStatsRequest
{
ProjectNameAsProjectName = new ProjectName("[PROJECT]"),
TimeRange = new QueryTimeRange(),
};
// Make the request
PagedEnumerable<ListGroupStatsResponse, ErrorGroupStats> response =
errorStatsServiceClient.ListGroupStats(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (ErrorGroupStats item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListGroupStatsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ErrorGroupStats item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ErrorGroupStats> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ErrorGroupStats item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListEventsAsync</summary>
public async Task ListEventsAsync()
{
// Snippet: ListEventsAsync(ProjectName,string,string,int?,CallSettings)
// Create client
ErrorStatsServiceClient errorStatsServiceClient = await ErrorStatsServiceClient.CreateAsync();
// Initialize request argument(s)
ProjectName projectName = new ProjectName("[PROJECT]");
string groupId = "";
// Make the request
PagedAsyncEnumerable<ListEventsResponse, ErrorEvent> response =
errorStatsServiceClient.ListEventsAsync(projectName, groupId);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((ErrorEvent item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListEventsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ErrorEvent item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ErrorEvent> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ErrorEvent item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListEvents</summary>
public void ListEvents()
{
// Snippet: ListEvents(ProjectName,string,string,int?,CallSettings)
// Create client
ErrorStatsServiceClient errorStatsServiceClient = ErrorStatsServiceClient.Create();
// Initialize request argument(s)
ProjectName projectName = new ProjectName("[PROJECT]");
string groupId = "";
// Make the request
PagedEnumerable<ListEventsResponse, ErrorEvent> response =
errorStatsServiceClient.ListEvents(projectName, groupId);
// Iterate over all response items, lazily performing RPCs as required
foreach (ErrorEvent item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListEventsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ErrorEvent item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ErrorEvent> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ErrorEvent item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListEventsAsync</summary>
public async Task ListEventsAsync_RequestObject()
{
// Snippet: ListEventsAsync(ListEventsRequest,CallSettings)
// Create client
ErrorStatsServiceClient errorStatsServiceClient = await ErrorStatsServiceClient.CreateAsync();
// Initialize request argument(s)
ListEventsRequest request = new ListEventsRequest
{
ProjectNameAsProjectName = new ProjectName("[PROJECT]"),
GroupId = "",
};
// Make the request
PagedAsyncEnumerable<ListEventsResponse, ErrorEvent> response =
errorStatsServiceClient.ListEventsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((ErrorEvent item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListEventsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ErrorEvent item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ErrorEvent> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ErrorEvent item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListEvents</summary>
public void ListEvents_RequestObject()
{
// Snippet: ListEvents(ListEventsRequest,CallSettings)
// Create client
ErrorStatsServiceClient errorStatsServiceClient = ErrorStatsServiceClient.Create();
// Initialize request argument(s)
ListEventsRequest request = new ListEventsRequest
{
ProjectNameAsProjectName = new ProjectName("[PROJECT]"),
GroupId = "",
};
// Make the request
PagedEnumerable<ListEventsResponse, ErrorEvent> response =
errorStatsServiceClient.ListEvents(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (ErrorEvent item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListEventsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ErrorEvent item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ErrorEvent> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ErrorEvent item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for DeleteEventsAsync</summary>
public async Task DeleteEventsAsync()
{
// Snippet: DeleteEventsAsync(ProjectName,CallSettings)
// Additional: DeleteEventsAsync(ProjectName,CancellationToken)
// Create client
ErrorStatsServiceClient errorStatsServiceClient = await ErrorStatsServiceClient.CreateAsync();
// Initialize request argument(s)
ProjectName projectName = new ProjectName("[PROJECT]");
// Make the request
DeleteEventsResponse response = await errorStatsServiceClient.DeleteEventsAsync(projectName);
// End snippet
}
/// <summary>Snippet for DeleteEvents</summary>
public void DeleteEvents()
{
// Snippet: DeleteEvents(ProjectName,CallSettings)
// Create client
ErrorStatsServiceClient errorStatsServiceClient = ErrorStatsServiceClient.Create();
// Initialize request argument(s)
ProjectName projectName = new ProjectName("[PROJECT]");
// Make the request
DeleteEventsResponse response = errorStatsServiceClient.DeleteEvents(projectName);
// End snippet
}
/// <summary>Snippet for DeleteEventsAsync</summary>
public async Task DeleteEventsAsync_RequestObject()
{
// Snippet: DeleteEventsAsync(DeleteEventsRequest,CallSettings)
// Create client
ErrorStatsServiceClient errorStatsServiceClient = await ErrorStatsServiceClient.CreateAsync();
// Initialize request argument(s)
DeleteEventsRequest request = new DeleteEventsRequest
{
ProjectNameAsProjectName = new ProjectName("[PROJECT]"),
};
// Make the request
DeleteEventsResponse response = await errorStatsServiceClient.DeleteEventsAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteEvents</summary>
public void DeleteEvents_RequestObject()
{
// Snippet: DeleteEvents(DeleteEventsRequest,CallSettings)
// Create client
ErrorStatsServiceClient errorStatsServiceClient = ErrorStatsServiceClient.Create();
// Initialize request argument(s)
DeleteEventsRequest request = new DeleteEventsRequest
{
ProjectNameAsProjectName = new ProjectName("[PROJECT]"),
};
// Make the request
DeleteEventsResponse response = errorStatsServiceClient.DeleteEvents(request);
// End snippet
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using Microsoft.Azure.Commands.Compute.Automation.Models;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Compute.Automation
{
[Cmdlet(VerbsData.Update, ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "Vmss", DefaultParameterSetName = "DefaultParameter", SupportsShouldProcess = true)]
[OutputType(typeof(PSVirtualMachineScaleSet))]
public partial class UpdateAzureRmVmss : ComputeAutomationBaseCmdlet
{
public override void ExecuteCmdlet()
{
base.ExecuteCmdlet();
ExecuteClientAction(() =>
{
if (ShouldProcess(this.VMScaleSetName, VerbsData.Update))
{
string resourceGroupName = this.ResourceGroupName;
string vmScaleSetName = this.VMScaleSetName;
if (this.VirtualMachineScaleSet == null)
{
BuildPatchObject();
}
else
{
BuildPutObject();
}
VirtualMachineScaleSetUpdate parametersupdate = this.VirtualMachineScaleSetUpdate;
VirtualMachineScaleSet parameters = new VirtualMachineScaleSet();
ComputeAutomationAutoMapperProfile.Mapper.Map<PSVirtualMachineScaleSet, VirtualMachineScaleSet>(this.VirtualMachineScaleSet, parameters);
var result = (this.VirtualMachineScaleSetUpdate == null)
? VirtualMachineScaleSetsClient.CreateOrUpdate(resourceGroupName, vmScaleSetName, parameters)
: VirtualMachineScaleSetsClient.Update(resourceGroupName, vmScaleSetName, parametersupdate);
var psObject = new PSVirtualMachineScaleSet();
ComputeAutomationAutoMapperProfile.Mapper.Map<VirtualMachineScaleSet, PSVirtualMachineScaleSet>(result, psObject);
WriteObject(psObject);
}
});
}
[Parameter(
Position = 1,
Mandatory = true,
ValueFromPipelineByPropertyName = true)]
[ResourceManager.Common.ArgumentCompleters.ResourceGroupCompleter()]
public string ResourceGroupName { get; set; }
[Parameter(
Position = 2,
Mandatory = true,
ValueFromPipelineByPropertyName = true)]
[ResourceNameCompleter("Microsoft.Compute/virtualMachineScaleSets", "ResourceGroupName")]
[Alias("Name")]
public string VMScaleSetName { get; set; }
public VirtualMachineScaleSetUpdate VirtualMachineScaleSetUpdate { get; set; }
[Parameter(
Position = 3,
Mandatory = false,
ValueFromPipelineByPropertyName = false,
ValueFromPipeline = true)]
[AllowNull]
public PSVirtualMachineScaleSet VirtualMachineScaleSet { get; set; }
[Parameter(
Mandatory = false)]
[ValidateNotNullOrEmpty]
public string ImageReferenceSku { get; set; }
[Parameter(
ParameterSetName = "ExplicitIdentityParameterSet",
Mandatory = false)]
[ValidateNotNullOrEmpty]
public string[] IdentityId { get; set; }
[Parameter(
Mandatory = false)]
[ValidateNotNullOrEmpty]
[PSArgumentCompleter("Standard_LRS", "Premium_LRS")]
public string ManagedDiskStorageAccountType { get; set; }
[Parameter(
Mandatory = false)]
[ValidateNotNullOrEmpty]
public string PlanPublisher { get; set; }
[Parameter(
Mandatory = false)]
public bool ProvisionVMAgent { get; set; }
[Parameter(
Mandatory = false)]
public bool BootDiagnosticsEnabled { get; set; }
[Parameter(
Mandatory = false)]
public bool Overprovision { get; set; }
[Parameter(
Mandatory = false)]
public int MaxBatchInstancePercent { get; set; }
[Parameter(
Mandatory = false)]
[ValidateNotNullOrEmpty]
public string TimeZone { get; set; }
[Parameter(
Mandatory = false)]
[ValidateNotNullOrEmpty]
public string BootDiagnosticsStorageUri { get; set; }
[Parameter(
Mandatory = false)]
public bool AutomaticOSUpgrade { get; set; }
[Parameter(
Mandatory = false)]
public bool DisableAutoRollback { get; set; }
[Parameter(
Mandatory = false)]
public bool SinglePlacementGroup { get; set; }
[Parameter(
Mandatory = false)]
[ValidateNotNullOrEmpty]
public string CustomData { get; set; }
[Parameter(
Mandatory = false)]
public UpgradeMode UpgradePolicyMode { get; set; }
[Parameter(
Mandatory = false)]
[ValidateNotNullOrEmpty]
public string ImageReferenceId { get; set; }
[Parameter(
Mandatory = false)]
public bool DisablePasswordAuthentication { get; set; }
[Parameter(
Mandatory = false)]
[ValidateNotNullOrEmpty]
public Hashtable Tag { get; set; }
[Parameter(
Mandatory = false)]
[ValidateNotNullOrEmpty]
public string PlanName { get; set; }
[Parameter(
Mandatory = false)]
public int MaxUnhealthyUpgradedInstancePercent { get; set; }
[Parameter(
Mandatory = false)]
[ValidateNotNullOrEmpty]
public string ImageReferencePublisher { get; set; }
[Parameter(
Mandatory = false)]
[ValidateNotNullOrEmpty]
public string PlanProduct { get; set; }
[Parameter(
Mandatory = false)]
[ValidateNotNullOrEmpty]
public string[] VhdContainer { get; set; }
[Parameter(
Mandatory = false)]
[ValidateNotNullOrEmpty]
public string ImageUri { get; set; }
[Parameter(
Mandatory = false)]
[ValidateNotNullOrEmpty]
public string SkuTier { get; set; }
[Parameter(
Mandatory = false)]
public bool EnableAutomaticUpdate { get; set; }
[Parameter(
Mandatory = false)]
[ValidateNotNullOrEmpty]
public string LicenseType { get; set; }
[Parameter(
ParameterSetName = "ExplicitIdentityParameterSet",
Mandatory = true)]
[ValidateNotNullOrEmpty]
public ResourceIdentityType? IdentityType { get; set; }
[Parameter(
Mandatory = false)]
[ValidateNotNullOrEmpty]
public string SkuName { get; set; }
[Parameter(
Mandatory = false)]
[ValidateNotNullOrEmpty]
public string PlanPromotionCode { get; set; }
[Parameter(
Mandatory = false)]
public int MaxUnhealthyInstancePercent { get; set; }
[Parameter(
Mandatory = false)]
public int SkuCapacity { get; set; }
[Parameter(
Mandatory = false)]
public bool OsDiskWriteAccelerator { get; set; }
[Parameter(
Mandatory = false)]
[ValidateNotNullOrEmpty]
public string ImageReferenceOffer { get; set; }
[Parameter(
Mandatory = false)]
[ValidateNotNullOrEmpty]
public string PauseTimeBetweenBatches { get; set; }
[Parameter(
Mandatory = false)]
public CachingTypes OsDiskCaching { get; set; }
[Parameter(
Mandatory = false)]
[ValidateNotNullOrEmpty]
public string ImageReferenceVersion { get; set; }
[Parameter(Mandatory = false, HelpMessage = "Run cmdlet in the background")]
public SwitchParameter AsJob { get; set; }
private void BuildPatchObject()
{
if (this.MyInvocation.BoundParameters.ContainsKey("ImageReferenceSku"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateStorageProfile();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.ImageReference == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.ImageReference = new Microsoft.Azure.Management.Compute.Models.ImageReference();
}
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.ImageReference.Sku = this.ImageReferenceSku;
}
if (this.MyInvocation.BoundParameters.ContainsKey("IdentityId"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
if (this.VirtualMachineScaleSetUpdate.Identity == null)
{
this.VirtualMachineScaleSetUpdate.Identity = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetIdentity();
}
this.VirtualMachineScaleSetUpdate.Identity.UserAssignedIdentities = new Dictionary<string, VirtualMachineScaleSetIdentityUserAssignedIdentitiesValue>();
foreach (var id in this.IdentityId)
{
if (!this.VirtualMachineScaleSetUpdate.Identity.UserAssignedIdentities.ContainsKey(id))
{
this.VirtualMachineScaleSetUpdate.Identity.UserAssignedIdentities.Add(id, new VirtualMachineScaleSetIdentityUserAssignedIdentitiesValue());
}
}
}
if (this.MyInvocation.BoundParameters.ContainsKey("ManagedDiskStorageAccountType"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateStorageProfile();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateOSDisk();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk.ManagedDisk == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk.ManagedDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetManagedDiskParameters();
}
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk.ManagedDisk.StorageAccountType = this.ManagedDiskStorageAccountType;
}
if (this.MyInvocation.BoundParameters.ContainsKey("PlanPublisher"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
if (this.VirtualMachineScaleSetUpdate.Plan == null)
{
this.VirtualMachineScaleSetUpdate.Plan = new Microsoft.Azure.Management.Compute.Models.Plan();
}
this.VirtualMachineScaleSetUpdate.Plan.Publisher = this.PlanPublisher;
}
if (this.MyInvocation.BoundParameters.ContainsKey("ProvisionVMAgent"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateOSProfile();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile.WindowsConfiguration == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile.WindowsConfiguration = new Microsoft.Azure.Management.Compute.Models.WindowsConfiguration();
}
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile.WindowsConfiguration.ProvisionVMAgent = this.ProvisionVMAgent;
}
if (this.MyInvocation.BoundParameters.ContainsKey("BootDiagnosticsEnabled"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.DiagnosticsProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.DiagnosticsProfile = new Microsoft.Azure.Management.Compute.Models.DiagnosticsProfile();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.DiagnosticsProfile.BootDiagnostics == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.DiagnosticsProfile.BootDiagnostics = new Microsoft.Azure.Management.Compute.Models.BootDiagnostics();
}
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.DiagnosticsProfile.BootDiagnostics.Enabled = this.BootDiagnosticsEnabled;
}
if (this.MyInvocation.BoundParameters.ContainsKey("Overprovision"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
this.VirtualMachineScaleSetUpdate.Overprovision = this.Overprovision;
}
if (this.MyInvocation.BoundParameters.ContainsKey("MaxBatchInstancePercent"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
if (this.VirtualMachineScaleSetUpdate.UpgradePolicy == null)
{
this.VirtualMachineScaleSetUpdate.UpgradePolicy = new Microsoft.Azure.Management.Compute.Models.UpgradePolicy();
}
if (this.VirtualMachineScaleSetUpdate.UpgradePolicy.RollingUpgradePolicy == null)
{
this.VirtualMachineScaleSetUpdate.UpgradePolicy.RollingUpgradePolicy = new Microsoft.Azure.Management.Compute.Models.RollingUpgradePolicy();
}
this.VirtualMachineScaleSetUpdate.UpgradePolicy.RollingUpgradePolicy.MaxBatchInstancePercent = this.MaxBatchInstancePercent;
}
if (this.MyInvocation.BoundParameters.ContainsKey("TimeZone"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateOSProfile();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile.WindowsConfiguration == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile.WindowsConfiguration = new Microsoft.Azure.Management.Compute.Models.WindowsConfiguration();
}
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile.WindowsConfiguration.TimeZone = this.TimeZone;
}
if (this.MyInvocation.BoundParameters.ContainsKey("BootDiagnosticsStorageUri"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.DiagnosticsProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.DiagnosticsProfile = new Microsoft.Azure.Management.Compute.Models.DiagnosticsProfile();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.DiagnosticsProfile.BootDiagnostics == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.DiagnosticsProfile.BootDiagnostics = new Microsoft.Azure.Management.Compute.Models.BootDiagnostics();
}
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.DiagnosticsProfile.BootDiagnostics.StorageUri = this.BootDiagnosticsStorageUri;
}
if (this.MyInvocation.BoundParameters.ContainsKey("AutomaticOSUpgrade"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
if (this.VirtualMachineScaleSetUpdate.UpgradePolicy == null)
{
this.VirtualMachineScaleSetUpdate.UpgradePolicy = new Microsoft.Azure.Management.Compute.Models.UpgradePolicy();
}
this.VirtualMachineScaleSetUpdate.UpgradePolicy.AutomaticOSUpgrade = this.AutomaticOSUpgrade;
}
if (this.MyInvocation.BoundParameters.ContainsKey("DisableAutoRollback"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
if (this.VirtualMachineScaleSetUpdate.UpgradePolicy == null)
{
this.VirtualMachineScaleSetUpdate.UpgradePolicy = new Microsoft.Azure.Management.Compute.Models.UpgradePolicy();
}
if (this.VirtualMachineScaleSetUpdate.UpgradePolicy.AutoOSUpgradePolicy == null)
{
this.VirtualMachineScaleSetUpdate.UpgradePolicy.AutoOSUpgradePolicy = new Microsoft.Azure.Management.Compute.Models.AutoOSUpgradePolicy();
}
this.VirtualMachineScaleSetUpdate.UpgradePolicy.AutoOSUpgradePolicy.DisableAutoRollback = this.DisableAutoRollback;
}
if (this.MyInvocation.BoundParameters.ContainsKey("SinglePlacementGroup"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
this.VirtualMachineScaleSetUpdate.SinglePlacementGroup = this.SinglePlacementGroup;
}
if (this.MyInvocation.BoundParameters.ContainsKey("CustomData"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateOSProfile();
}
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile.CustomData = this.CustomData;
}
if (this.MyInvocation.BoundParameters.ContainsKey("UpgradePolicyMode"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
if (this.VirtualMachineScaleSetUpdate.UpgradePolicy == null)
{
this.VirtualMachineScaleSetUpdate.UpgradePolicy = new Microsoft.Azure.Management.Compute.Models.UpgradePolicy();
}
this.VirtualMachineScaleSetUpdate.UpgradePolicy.Mode = this.UpgradePolicyMode;
}
if (this.MyInvocation.BoundParameters.ContainsKey("ImageReferenceId"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateStorageProfile();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.ImageReference == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.ImageReference = new Microsoft.Azure.Management.Compute.Models.ImageReference();
}
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.ImageReference.Id = this.ImageReferenceId;
}
if (this.MyInvocation.BoundParameters.ContainsKey("DisablePasswordAuthentication"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateOSProfile();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile.LinuxConfiguration == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile.LinuxConfiguration = new Microsoft.Azure.Management.Compute.Models.LinuxConfiguration();
}
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile.LinuxConfiguration.DisablePasswordAuthentication = this.DisablePasswordAuthentication;
}
if (this.MyInvocation.BoundParameters.ContainsKey("Tag"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
this.VirtualMachineScaleSetUpdate.Tags = this.Tag.Cast<DictionaryEntry>().ToDictionary(ht => (string)ht.Key, ht => (string)ht.Value);
}
if (this.MyInvocation.BoundParameters.ContainsKey("PlanName"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
if (this.VirtualMachineScaleSetUpdate.Plan == null)
{
this.VirtualMachineScaleSetUpdate.Plan = new Microsoft.Azure.Management.Compute.Models.Plan();
}
this.VirtualMachineScaleSetUpdate.Plan.Name = this.PlanName;
}
if (this.MyInvocation.BoundParameters.ContainsKey("MaxUnhealthyUpgradedInstancePercent"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
if (this.VirtualMachineScaleSetUpdate.UpgradePolicy == null)
{
this.VirtualMachineScaleSetUpdate.UpgradePolicy = new Microsoft.Azure.Management.Compute.Models.UpgradePolicy();
}
if (this.VirtualMachineScaleSetUpdate.UpgradePolicy.RollingUpgradePolicy == null)
{
this.VirtualMachineScaleSetUpdate.UpgradePolicy.RollingUpgradePolicy = new Microsoft.Azure.Management.Compute.Models.RollingUpgradePolicy();
}
this.VirtualMachineScaleSetUpdate.UpgradePolicy.RollingUpgradePolicy.MaxUnhealthyUpgradedInstancePercent = this.MaxUnhealthyUpgradedInstancePercent;
}
if (this.MyInvocation.BoundParameters.ContainsKey("ImageReferencePublisher"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateStorageProfile();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.ImageReference == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.ImageReference = new Microsoft.Azure.Management.Compute.Models.ImageReference();
}
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.ImageReference.Publisher = this.ImageReferencePublisher;
}
if (this.MyInvocation.BoundParameters.ContainsKey("PlanProduct"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
if (this.VirtualMachineScaleSetUpdate.Plan == null)
{
this.VirtualMachineScaleSetUpdate.Plan = new Microsoft.Azure.Management.Compute.Models.Plan();
}
this.VirtualMachineScaleSetUpdate.Plan.Product = this.PlanProduct;
}
if (this.MyInvocation.BoundParameters.ContainsKey("VhdContainer"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateStorageProfile();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateOSDisk();
}
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk.VhdContainers = this.VhdContainer;
}
if (this.MyInvocation.BoundParameters.ContainsKey("ImageUri"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateStorageProfile();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateOSDisk();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk.Image == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk.Image = new Microsoft.Azure.Management.Compute.Models.VirtualHardDisk();
}
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk.Image.Uri = this.ImageUri;
}
if (this.MyInvocation.BoundParameters.ContainsKey("SkuTier"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
if (this.VirtualMachineScaleSetUpdate.Sku == null)
{
this.VirtualMachineScaleSetUpdate.Sku = new Microsoft.Azure.Management.Compute.Models.Sku();
}
this.VirtualMachineScaleSetUpdate.Sku.Tier = this.SkuTier;
}
if (this.MyInvocation.BoundParameters.ContainsKey("EnableAutomaticUpdate"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateOSProfile();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile.WindowsConfiguration == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile.WindowsConfiguration = new Microsoft.Azure.Management.Compute.Models.WindowsConfiguration();
}
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile.WindowsConfiguration.EnableAutomaticUpdates = this.EnableAutomaticUpdate;
}
if (this.MyInvocation.BoundParameters.ContainsKey("LicenseType"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile();
}
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.LicenseType = this.LicenseType;
}
if (this.MyInvocation.BoundParameters.ContainsKey("IdentityType"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
if (this.VirtualMachineScaleSetUpdate.Identity == null)
{
this.VirtualMachineScaleSetUpdate.Identity = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetIdentity();
}
this.VirtualMachineScaleSetUpdate.Identity.Type = this.IdentityType;
}
if (this.MyInvocation.BoundParameters.ContainsKey("SkuName"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
if (this.VirtualMachineScaleSetUpdate.Sku == null)
{
this.VirtualMachineScaleSetUpdate.Sku = new Microsoft.Azure.Management.Compute.Models.Sku();
}
this.VirtualMachineScaleSetUpdate.Sku.Name = this.SkuName;
}
if (this.MyInvocation.BoundParameters.ContainsKey("PlanPromotionCode"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
if (this.VirtualMachineScaleSetUpdate.Plan == null)
{
this.VirtualMachineScaleSetUpdate.Plan = new Microsoft.Azure.Management.Compute.Models.Plan();
}
this.VirtualMachineScaleSetUpdate.Plan.PromotionCode = this.PlanPromotionCode;
}
if (this.MyInvocation.BoundParameters.ContainsKey("MaxUnhealthyInstancePercent"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
if (this.VirtualMachineScaleSetUpdate.UpgradePolicy == null)
{
this.VirtualMachineScaleSetUpdate.UpgradePolicy = new Microsoft.Azure.Management.Compute.Models.UpgradePolicy();
}
if (this.VirtualMachineScaleSetUpdate.UpgradePolicy.RollingUpgradePolicy == null)
{
this.VirtualMachineScaleSetUpdate.UpgradePolicy.RollingUpgradePolicy = new Microsoft.Azure.Management.Compute.Models.RollingUpgradePolicy();
}
this.VirtualMachineScaleSetUpdate.UpgradePolicy.RollingUpgradePolicy.MaxUnhealthyInstancePercent = this.MaxUnhealthyInstancePercent;
}
if (this.MyInvocation.BoundParameters.ContainsKey("SkuCapacity"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
if (this.VirtualMachineScaleSetUpdate.Sku == null)
{
this.VirtualMachineScaleSetUpdate.Sku = new Microsoft.Azure.Management.Compute.Models.Sku();
}
this.VirtualMachineScaleSetUpdate.Sku.Capacity = this.SkuCapacity;
}
if (this.MyInvocation.BoundParameters.ContainsKey("OsDiskWriteAccelerator"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateStorageProfile();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateOSDisk();
}
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk.WriteAcceleratorEnabled = this.OsDiskWriteAccelerator;
}
if (this.MyInvocation.BoundParameters.ContainsKey("ImageReferenceOffer"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateStorageProfile();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.ImageReference == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.ImageReference = new Microsoft.Azure.Management.Compute.Models.ImageReference();
}
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.ImageReference.Offer = this.ImageReferenceOffer;
}
if (this.MyInvocation.BoundParameters.ContainsKey("PauseTimeBetweenBatches"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
if (this.VirtualMachineScaleSetUpdate.UpgradePolicy == null)
{
this.VirtualMachineScaleSetUpdate.UpgradePolicy = new Microsoft.Azure.Management.Compute.Models.UpgradePolicy();
}
if (this.VirtualMachineScaleSetUpdate.UpgradePolicy.RollingUpgradePolicy == null)
{
this.VirtualMachineScaleSetUpdate.UpgradePolicy.RollingUpgradePolicy = new Microsoft.Azure.Management.Compute.Models.RollingUpgradePolicy();
}
this.VirtualMachineScaleSetUpdate.UpgradePolicy.RollingUpgradePolicy.PauseTimeBetweenBatches = this.PauseTimeBetweenBatches;
}
if (this.MyInvocation.BoundParameters.ContainsKey("OsDiskCaching"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateStorageProfile();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateOSDisk();
}
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.OsDisk.Caching = this.OsDiskCaching;
}
if (this.MyInvocation.BoundParameters.ContainsKey("ImageReferenceVersion"))
{
if (this.VirtualMachineScaleSetUpdate == null)
{
this.VirtualMachineScaleSetUpdate = new VirtualMachineScaleSetUpdate();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateVMProfile();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetUpdateStorageProfile();
}
if (this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.ImageReference == null)
{
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.ImageReference = new Microsoft.Azure.Management.Compute.Models.ImageReference();
}
this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.StorageProfile.ImageReference.Version = this.ImageReferenceVersion;
}
if (this.VirtualMachineScaleSetUpdate != null
&& this.VirtualMachineScaleSetUpdate.VirtualMachineProfile != null
&& this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile != null
&& this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile.WindowsConfiguration != null
&& this.VirtualMachineScaleSetUpdate.VirtualMachineProfile.OsProfile.LinuxConfiguration != null)
{
throw new ArgumentException(Microsoft.Azure.Commands.Compute.Properties.Resources.BothWindowsAndLinuxConfigurationsSpecified);
}
}
private void BuildPutObject()
{
if (this.MyInvocation.BoundParameters.ContainsKey("ImageReferenceSku"))
{
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference = new Microsoft.Azure.Management.Compute.Models.ImageReference();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference.Sku = this.ImageReferenceSku;
}
if (this.MyInvocation.BoundParameters.ContainsKey("IdentityId"))
{
if (this.VirtualMachineScaleSet.Identity == null)
{
this.VirtualMachineScaleSet.Identity = new PSVirtualMachineScaleSetIdentity();
}
this.VirtualMachineScaleSet.Identity.UserAssignedIdentities = new Dictionary<string, VirtualMachineScaleSetIdentityUserAssignedIdentitiesValue>();
foreach (var id in this.IdentityId)
{
if (!this.VirtualMachineScaleSet.Identity.UserAssignedIdentities.ContainsKey(id))
{
this.VirtualMachineScaleSet.Identity.UserAssignedIdentities.Add(id, new VirtualMachineScaleSetIdentityUserAssignedIdentitiesValue());
}
}
}
if (this.MyInvocation.BoundParameters.ContainsKey("ManagedDiskStorageAccountType"))
{
WriteWarning("Update-AzureRmVmss: The accepted values for parameter ManagedDiskStorageAccountType will change in an upcoming breaking change release " +
"from StandardLRS and PremiumLRS to Standard_LRS and Premium_LRS, respectively.");
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSDisk();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.ManagedDisk == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.ManagedDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetManagedDiskParameters();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.ManagedDisk.StorageAccountType = this.ManagedDiskStorageAccountType;
}
if (this.MyInvocation.BoundParameters.ContainsKey("PlanPublisher"))
{
if (this.VirtualMachineScaleSet.Plan == null)
{
this.VirtualMachineScaleSet.Plan = new Microsoft.Azure.Management.Compute.Models.Plan();
}
this.VirtualMachineScaleSet.Plan.Publisher = this.PlanPublisher;
}
if (this.MyInvocation.BoundParameters.ContainsKey("ProvisionVMAgent"))
{
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSProfile();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration = new Microsoft.Azure.Management.Compute.Models.WindowsConfiguration();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration.ProvisionVMAgent = this.ProvisionVMAgent;
}
if (this.MyInvocation.BoundParameters.ContainsKey("BootDiagnosticsEnabled"))
{
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.DiagnosticsProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.DiagnosticsProfile = new Microsoft.Azure.Management.Compute.Models.DiagnosticsProfile();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.DiagnosticsProfile.BootDiagnostics == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.DiagnosticsProfile.BootDiagnostics = new Microsoft.Azure.Management.Compute.Models.BootDiagnostics();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.DiagnosticsProfile.BootDiagnostics.Enabled = this.BootDiagnosticsEnabled;
}
if (this.MyInvocation.BoundParameters.ContainsKey("Overprovision"))
{
this.VirtualMachineScaleSet.Overprovision = this.Overprovision;
}
if (this.MyInvocation.BoundParameters.ContainsKey("MaxBatchInstancePercent"))
{
if (this.VirtualMachineScaleSet.UpgradePolicy == null)
{
this.VirtualMachineScaleSet.UpgradePolicy = new Microsoft.Azure.Management.Compute.Models.UpgradePolicy();
}
if (this.VirtualMachineScaleSet.UpgradePolicy.RollingUpgradePolicy == null)
{
this.VirtualMachineScaleSet.UpgradePolicy.RollingUpgradePolicy = new Microsoft.Azure.Management.Compute.Models.RollingUpgradePolicy();
}
this.VirtualMachineScaleSet.UpgradePolicy.RollingUpgradePolicy.MaxBatchInstancePercent = this.MaxBatchInstancePercent;
}
if (this.MyInvocation.BoundParameters.ContainsKey("TimeZone"))
{
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSProfile();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration = new Microsoft.Azure.Management.Compute.Models.WindowsConfiguration();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration.TimeZone = this.TimeZone;
}
if (this.MyInvocation.BoundParameters.ContainsKey("BootDiagnosticsStorageUri"))
{
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.DiagnosticsProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.DiagnosticsProfile = new Microsoft.Azure.Management.Compute.Models.DiagnosticsProfile();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.DiagnosticsProfile.BootDiagnostics == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.DiagnosticsProfile.BootDiagnostics = new Microsoft.Azure.Management.Compute.Models.BootDiagnostics();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.DiagnosticsProfile.BootDiagnostics.StorageUri = this.BootDiagnosticsStorageUri;
}
if (this.MyInvocation.BoundParameters.ContainsKey("AutomaticOSUpgrade"))
{
if (this.VirtualMachineScaleSet.UpgradePolicy == null)
{
this.VirtualMachineScaleSet.UpgradePolicy = new Microsoft.Azure.Management.Compute.Models.UpgradePolicy();
}
this.VirtualMachineScaleSet.UpgradePolicy.AutomaticOSUpgrade = this.AutomaticOSUpgrade;
}
if (this.MyInvocation.BoundParameters.ContainsKey("DisableAutoRollback"))
{
if (this.VirtualMachineScaleSet.UpgradePolicy == null)
{
this.VirtualMachineScaleSet.UpgradePolicy = new Microsoft.Azure.Management.Compute.Models.UpgradePolicy();
}
if (this.VirtualMachineScaleSet.UpgradePolicy.AutoOSUpgradePolicy == null)
{
this.VirtualMachineScaleSet.UpgradePolicy.AutoOSUpgradePolicy = new Microsoft.Azure.Management.Compute.Models.AutoOSUpgradePolicy();
}
this.VirtualMachineScaleSet.UpgradePolicy.AutoOSUpgradePolicy.DisableAutoRollback = this.DisableAutoRollback;
}
if (this.MyInvocation.BoundParameters.ContainsKey("SinglePlacementGroup"))
{
this.VirtualMachineScaleSet.SinglePlacementGroup = this.SinglePlacementGroup;
}
if (this.MyInvocation.BoundParameters.ContainsKey("CustomData"))
{
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSProfile();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.CustomData = this.CustomData;
}
if (this.MyInvocation.BoundParameters.ContainsKey("UpgradePolicyMode"))
{
if (this.VirtualMachineScaleSet.UpgradePolicy == null)
{
this.VirtualMachineScaleSet.UpgradePolicy = new Microsoft.Azure.Management.Compute.Models.UpgradePolicy();
}
this.VirtualMachineScaleSet.UpgradePolicy.Mode = this.UpgradePolicyMode;
}
if (this.MyInvocation.BoundParameters.ContainsKey("ImageReferenceId"))
{
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference = new Microsoft.Azure.Management.Compute.Models.ImageReference();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference.Id = this.ImageReferenceId;
}
if (this.MyInvocation.BoundParameters.ContainsKey("DisablePasswordAuthentication"))
{
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSProfile();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration = new Microsoft.Azure.Management.Compute.Models.LinuxConfiguration();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration.DisablePasswordAuthentication = this.DisablePasswordAuthentication;
}
if (this.MyInvocation.BoundParameters.ContainsKey("Tag"))
{
this.VirtualMachineScaleSet.Tags = this.Tag.Cast<DictionaryEntry>().ToDictionary(ht => (string)ht.Key, ht => (string)ht.Value);
}
if (this.MyInvocation.BoundParameters.ContainsKey("PlanName"))
{
if (this.VirtualMachineScaleSet.Plan == null)
{
this.VirtualMachineScaleSet.Plan = new Microsoft.Azure.Management.Compute.Models.Plan();
}
this.VirtualMachineScaleSet.Plan.Name = this.PlanName;
}
if (this.MyInvocation.BoundParameters.ContainsKey("MaxUnhealthyUpgradedInstancePercent"))
{
if (this.VirtualMachineScaleSet.UpgradePolicy == null)
{
this.VirtualMachineScaleSet.UpgradePolicy = new Microsoft.Azure.Management.Compute.Models.UpgradePolicy();
}
if (this.VirtualMachineScaleSet.UpgradePolicy.RollingUpgradePolicy == null)
{
this.VirtualMachineScaleSet.UpgradePolicy.RollingUpgradePolicy = new Microsoft.Azure.Management.Compute.Models.RollingUpgradePolicy();
}
this.VirtualMachineScaleSet.UpgradePolicy.RollingUpgradePolicy.MaxUnhealthyUpgradedInstancePercent = this.MaxUnhealthyUpgradedInstancePercent;
}
if (this.MyInvocation.BoundParameters.ContainsKey("ImageReferencePublisher"))
{
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference = new Microsoft.Azure.Management.Compute.Models.ImageReference();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference.Publisher = this.ImageReferencePublisher;
}
if (this.MyInvocation.BoundParameters.ContainsKey("PlanProduct"))
{
if (this.VirtualMachineScaleSet.Plan == null)
{
this.VirtualMachineScaleSet.Plan = new Microsoft.Azure.Management.Compute.Models.Plan();
}
this.VirtualMachineScaleSet.Plan.Product = this.PlanProduct;
}
if (this.MyInvocation.BoundParameters.ContainsKey("VhdContainer"))
{
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSDisk();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.VhdContainers = this.VhdContainer;
}
if (this.MyInvocation.BoundParameters.ContainsKey("ImageUri"))
{
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSDisk();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Image == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Image = new Microsoft.Azure.Management.Compute.Models.VirtualHardDisk();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Image.Uri = this.ImageUri;
}
if (this.MyInvocation.BoundParameters.ContainsKey("SkuTier"))
{
if (this.VirtualMachineScaleSet.Sku == null)
{
this.VirtualMachineScaleSet.Sku = new Microsoft.Azure.Management.Compute.Models.Sku();
}
this.VirtualMachineScaleSet.Sku.Tier = this.SkuTier;
}
if (this.MyInvocation.BoundParameters.ContainsKey("EnableAutomaticUpdate"))
{
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSProfile();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration = new Microsoft.Azure.Management.Compute.Models.WindowsConfiguration();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration.EnableAutomaticUpdates = this.EnableAutomaticUpdate;
}
if (this.MyInvocation.BoundParameters.ContainsKey("LicenseType"))
{
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.LicenseType = this.LicenseType;
}
if (this.MyInvocation.BoundParameters.ContainsKey("IdentityType"))
{
if (this.VirtualMachineScaleSet.Identity == null)
{
this.VirtualMachineScaleSet.Identity = new PSVirtualMachineScaleSetIdentity();
}
this.VirtualMachineScaleSet.Identity.Type = this.IdentityType;
}
if (this.MyInvocation.BoundParameters.ContainsKey("SkuName"))
{
if (this.VirtualMachineScaleSet.Sku == null)
{
this.VirtualMachineScaleSet.Sku = new Microsoft.Azure.Management.Compute.Models.Sku();
}
this.VirtualMachineScaleSet.Sku.Name = this.SkuName;
}
if (this.MyInvocation.BoundParameters.ContainsKey("PlanPromotionCode"))
{
if (this.VirtualMachineScaleSet.Plan == null)
{
this.VirtualMachineScaleSet.Plan = new Microsoft.Azure.Management.Compute.Models.Plan();
}
this.VirtualMachineScaleSet.Plan.PromotionCode = this.PlanPromotionCode;
}
if (this.MyInvocation.BoundParameters.ContainsKey("MaxUnhealthyInstancePercent"))
{
if (this.VirtualMachineScaleSet.UpgradePolicy == null)
{
this.VirtualMachineScaleSet.UpgradePolicy = new Microsoft.Azure.Management.Compute.Models.UpgradePolicy();
}
if (this.VirtualMachineScaleSet.UpgradePolicy.RollingUpgradePolicy == null)
{
this.VirtualMachineScaleSet.UpgradePolicy.RollingUpgradePolicy = new Microsoft.Azure.Management.Compute.Models.RollingUpgradePolicy();
}
this.VirtualMachineScaleSet.UpgradePolicy.RollingUpgradePolicy.MaxUnhealthyInstancePercent = this.MaxUnhealthyInstancePercent;
}
if (this.MyInvocation.BoundParameters.ContainsKey("SkuCapacity"))
{
if (this.VirtualMachineScaleSet.Sku == null)
{
this.VirtualMachineScaleSet.Sku = new Microsoft.Azure.Management.Compute.Models.Sku();
}
this.VirtualMachineScaleSet.Sku.Capacity = this.SkuCapacity;
}
if (this.MyInvocation.BoundParameters.ContainsKey("OsDiskWriteAccelerator"))
{
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSDisk();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.WriteAcceleratorEnabled = this.OsDiskWriteAccelerator;
}
if (this.MyInvocation.BoundParameters.ContainsKey("ImageReferenceOffer"))
{
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference = new Microsoft.Azure.Management.Compute.Models.ImageReference();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference.Offer = this.ImageReferenceOffer;
}
if (this.MyInvocation.BoundParameters.ContainsKey("PauseTimeBetweenBatches"))
{
if (this.VirtualMachineScaleSet.UpgradePolicy == null)
{
this.VirtualMachineScaleSet.UpgradePolicy = new Microsoft.Azure.Management.Compute.Models.UpgradePolicy();
}
if (this.VirtualMachineScaleSet.UpgradePolicy.RollingUpgradePolicy == null)
{
this.VirtualMachineScaleSet.UpgradePolicy.RollingUpgradePolicy = new Microsoft.Azure.Management.Compute.Models.RollingUpgradePolicy();
}
this.VirtualMachineScaleSet.UpgradePolicy.RollingUpgradePolicy.PauseTimeBetweenBatches = this.PauseTimeBetweenBatches;
}
if (this.MyInvocation.BoundParameters.ContainsKey("OsDiskCaching"))
{
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSDisk();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Caching = this.OsDiskCaching;
}
if (this.MyInvocation.BoundParameters.ContainsKey("ImageReferenceVersion"))
{
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile();
}
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference = new Microsoft.Azure.Management.Compute.Models.ImageReference();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference.Version = this.ImageReferenceVersion;
}
if (this.VirtualMachineScaleSet != null
&& this.VirtualMachineScaleSet.VirtualMachineProfile != null
&& this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile != null
&& this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration != null
&& this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration != null)
{
throw new ArgumentException(Microsoft.Azure.Commands.Compute.Properties.Resources.BothWindowsAndLinuxConfigurationsSpecified);
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="PageThemeCodeDomTreeGenerator.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Reflection;
using System.ComponentModel;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Globalization;
using System.IO;
using System.Web.UI;
using System.Web.Util;
using Debug=System.Web.Util.Debug;
namespace System.Web.Compilation {
internal class PageThemeCodeDomTreeGenerator : BaseTemplateCodeDomTreeGenerator {
private Hashtable _controlSkinTypeNameCollection = new Hashtable();
private ArrayList _controlSkinBuilderEntryList = new ArrayList();
private int _controlCount = 0;
private CodeTypeReference _controlSkinDelegateType = new CodeTypeReference(typeof(ControlSkinDelegate));
private CodeTypeReference _controlSkinType = new CodeTypeReference(typeof(ControlSkin));
private PageThemeParser _themeParser;
private const string _controlSkinsVarName = "__controlSkins";
private const string _controlSkinsPropertyName = "ControlSkins";
private const string _linkedStyleSheetsVarName = "__linkedStyleSheets";
private const string _linkedStyleSheetsPropertyName = "LinkedStyleSheets";
internal PageThemeCodeDomTreeGenerator(PageThemeParser parser) : base(parser) {
_themeParser = parser;
}
private void AddMemberOverride(string name, Type type, CodeExpression expr) {
CodeMemberProperty member = new CodeMemberProperty();
member.Name = name;
member.Attributes = MemberAttributes.Override | MemberAttributes.Family;
member.Type = new CodeTypeReference(type.FullName);
CodeMethodReturnStatement returnStmt = new CodeMethodReturnStatement(expr);
member.GetStatements.Add(returnStmt);
_sourceDataClass.Members.Add(member);
}
private void BuildControlSkins(CodeStatementCollection statements) {
foreach (ControlSkinBuilderEntry entry in _controlSkinBuilderEntryList) {
string skinID = entry.SkinID;
ControlBuilder builder = entry.Builder;
statements.Add(BuildControlSkinAssignmentStatement(builder, skinID));
}
}
private CodeStatement BuildControlSkinAssignmentStatement(
ControlBuilder builder, string skinID) {
Type controlType = builder.ControlType;
string keyVarName = GetMethodNameForBuilder(buildMethodPrefix, builder) + "_skinKey";
// e.g.
// private static object __BuildControl__control3_skinKey = PageTheme.CreateSkinKey(typeof({controlType}), {skinID});
CodeMemberField field = new CodeMemberField(typeof(object), keyVarName);
field.Attributes = MemberAttributes.Static | MemberAttributes.Private;
CodeMethodInvokeExpression cmie = new CodeMethodInvokeExpression();
cmie.Method = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(PageTheme)), "CreateSkinKey");
cmie.Parameters.Add(new CodeTypeOfExpression(controlType));
cmie.Parameters.Add(new CodePrimitiveExpression(skinID));
field.InitExpression = cmie;
_sourceDataClass.Members.Add(field);
// e.g. this.__namedControlSkins[keyVarName] =
// new System.Web.UI.ControlSkin(typeof(System.Web.UI.WebControls.Label),
// new System.Web.UI.ControlSkinDelegate(this.__BuildControl__control3));
CodeFieldReferenceExpression varExpr = new CodeFieldReferenceExpression(
new CodeThisReferenceExpression(),
_controlSkinsVarName);
CodeIndexerExpression indexerExpr = new CodeIndexerExpression(
varExpr,
new CodeExpression[] {
new CodeVariableReferenceExpression(keyVarName)
}
);
CodeDelegateCreateExpression del = new CodeDelegateCreateExpression(
_controlSkinDelegateType,
new CodeThisReferenceExpression(),
GetMethodNameForBuilder(buildMethodPrefix, builder));
CodeObjectCreateExpression valueExpr = new CodeObjectCreateExpression(_controlSkinType);
valueExpr.Parameters.Add(new CodeTypeOfExpression(controlType));
valueExpr.Parameters.Add(del);
return new CodeAssignStatement(indexerExpr, valueExpr);
}
private void BuildControlSkinMember() {
// e.g.
// private System.Collections.Specialized.HybridDictionary __cssFileList =
// new System.Collections.Specialized.HybridDictionary(2);
int initialSize = _controlSkinBuilderEntryList.Count;
CodeMemberField field = new CodeMemberField(typeof(HybridDictionary).FullName, _controlSkinsVarName);
CodeObjectCreateExpression expr = new CodeObjectCreateExpression(typeof(HybridDictionary));
expr.Parameters.Add(new CodePrimitiveExpression(initialSize));
field.InitExpression = expr;
_sourceDataClass.Members.Add(field);
}
private void BuildControlSkinProperty() {
// e.g.
// protected override System.Collections.IDictionary ControlSkins {
// get { return this.__controlSkins; }
// }
CodeFieldReferenceExpression accessExpr = new CodeFieldReferenceExpression(
new CodeThisReferenceExpression(),
_controlSkinsVarName);
AddMemberOverride(_controlSkinsPropertyName, typeof(IDictionary), accessExpr);
}
private void BuildLinkedStyleSheetMember() {
// e.g.
// private System.String[] __linkedStyleSheets = new String[] {
// "linkedStyleSheet1 vdirs",
// "linkedStyleSheet2 vdirs",
// }
CodeMemberField field = new CodeMemberField(typeof(String[]), _linkedStyleSheetsVarName);
if (_themeParser.CssFileList != null && _themeParser.CssFileList.Count > 0) {
CodeExpression[] cssFiles = new CodeExpression[_themeParser.CssFileList.Count];
int i = 0;
foreach(String cssFile in _themeParser.CssFileList) {
cssFiles[i++] = new CodePrimitiveExpression(cssFile);
}
CodeArrayCreateExpression initExpr = new CodeArrayCreateExpression(typeof(String), cssFiles);
field.InitExpression = initExpr;
}
else {
field.InitExpression = new CodePrimitiveExpression(null);
}
_sourceDataClass.Members.Add(field);
}
private void BuildLinkedStyleSheetProperty() {
// e.g.
// protected override String[] LinkedStyleSheets {
// get { return this.__linkedStyleSheets; }
// }
CodeFieldReferenceExpression accessExpr = new CodeFieldReferenceExpression(
new CodeThisReferenceExpression(),
_linkedStyleSheetsVarName);
AddMemberOverride(_linkedStyleSheetsPropertyName, typeof(String[]), accessExpr);
}
protected override void BuildInitStatements(CodeStatementCollection trueStatements, CodeStatementCollection topLevelStatements) {
base.BuildInitStatements(trueStatements, topLevelStatements);
BuildControlSkins(topLevelStatements);
}
protected override void BuildMiscClassMembers() {
base.BuildMiscClassMembers();
AddMemberOverride(templateSourceDirectoryName, typeof(String),
new CodePrimitiveExpression(_themeParser.VirtualDirPath.VirtualPathString));
BuildSourceDataTreeFromBuilder(_themeParser.RootBuilder,
false /*fInTemplate*/, false /*topLevelControlInTemplate*/, null /*pse*/);
BuildControlSkinMember();
BuildControlSkinProperty();
BuildLinkedStyleSheetMember();
BuildLinkedStyleSheetProperty();
}
protected override void BuildSourceDataTreeFromBuilder(ControlBuilder builder,
bool fInTemplate, bool topLevelControlInTemplate,
PropertyEntry pse) {
// Don't do anything for code blocks
if (builder is CodeBlockBuilder)
return;
// Is the current builder for a template?
bool fTemplate = (builder is TemplateBuilder);
// Is the current builder the root builder?
bool fRootBuilder = (builder == _themeParser.RootBuilder);
// Is this a control theme?
bool fControlSkin = !fInTemplate && !fTemplate && topLevelControlInTemplate;
// Ignore the ID attribute, always auto generate ID.
_controlCount++;
builder.ID = "__control" + _controlCount.ToString(NumberFormatInfo.InvariantInfo);
builder.IsGeneratedID = true;
// Check for the SkinID property.
if (fControlSkin && !(builder is DataBoundLiteralControlBuilder)) {
Type ctrlType = builder.ControlType;
Debug.Assert(typeof(Control).IsAssignableFrom(ctrlType));
Debug.Assert(ThemeableAttribute.IsTypeThemeable(ctrlType));
string skinID = builder.SkinID;
object skinKey = PageTheme.CreateSkinKey(builder.ControlType, skinID);
if (_controlSkinTypeNameCollection.Contains(skinKey)) {
if (String.IsNullOrEmpty(skinID)) {
throw new HttpParseException(SR.GetString(SR.Page_theme_default_theme_already_defined,
builder.ControlType.FullName), null, builder.VirtualPath, null, builder.Line);
}
else {
throw new HttpParseException(SR.GetString(SR.Page_theme_skinID_already_defined, skinID),
null, builder.VirtualPath, null, builder.Line);
}
}
_controlSkinTypeNameCollection.Add(skinKey, true);
_controlSkinBuilderEntryList.Add(new ControlSkinBuilderEntry(builder, skinID));
}
// Process the children
// only root builders and template builders are processed.
if (builder.SubBuilders != null) {
foreach (object child in builder.SubBuilders) {
if (child is ControlBuilder) {
bool isTopLevelCtrlInTemplate = fTemplate && typeof(Control).IsAssignableFrom(((ControlBuilder)child).ControlType);
BuildSourceDataTreeFromBuilder((ControlBuilder)child, fInTemplate, isTopLevelCtrlInTemplate, null);
}
}
}
foreach (TemplatePropertyEntry entry in builder.TemplatePropertyEntries) {
BuildSourceDataTreeFromBuilder(((TemplatePropertyEntry)entry).Builder, true, false /*topLevelControlInTemplate*/, entry);
}
foreach (ComplexPropertyEntry entry in builder.ComplexPropertyEntries) {
if (!(entry.Builder is StringPropertyBuilder)) {
BuildSourceDataTreeFromBuilder(((ComplexPropertyEntry)entry).Builder, fInTemplate, false /*topLevelControlInTemplate*/, entry);
}
}
// Build a Build method for the control
// fControlSkin indicates whether the method is a theme build method.
if (!fRootBuilder) {
BuildBuildMethod(builder, fTemplate, fInTemplate, topLevelControlInTemplate, pse,
fControlSkin);
}
// Build a Render method for the control, unless it has no code
if (!fControlSkin && builder.HasAspCode) {
BuildRenderMethod(builder, fTemplate);
}
// Build a method to extract values from the template
BuildExtractMethod(builder);
// Build a property binding method for the control
BuildPropertyBindingMethod(builder, fControlSkin);
}
internal override CodeExpression BuildStringPropertyExpression(PropertyEntry pse) {
// Make the UrlProperty based on virtualDirPath for control themes.
if (pse.PropertyInfo != null) {
UrlPropertyAttribute urlAttrib = Attribute.GetCustomAttribute(pse.PropertyInfo, typeof(UrlPropertyAttribute)) as UrlPropertyAttribute;
if (urlAttrib != null) {
if (pse is SimplePropertyEntry) {
SimplePropertyEntry spse = (SimplePropertyEntry)pse;
string strValue = (string)spse.Value;
if (UrlPath.IsRelativeUrl(strValue) && !UrlPath.IsAppRelativePath(strValue)) {
spse.Value = UrlPath.MakeVirtualPathAppRelative(UrlPath.Combine(_themeParser.VirtualDirPath.VirtualPathString, strValue));
}
}
else {
Debug.Assert(pse is ComplexPropertyEntry);
ComplexPropertyEntry cpe = (ComplexPropertyEntry)pse;
StringPropertyBuilder builder = (StringPropertyBuilder)cpe.Builder;
string strValue = (string)builder.BuildObject();
if (UrlPath.IsRelativeUrl(strValue) && !UrlPath.IsAppRelativePath(strValue)) {
cpe.Builder = new StringPropertyBuilder(UrlPath.MakeVirtualPathAppRelative(UrlPath.Combine(_themeParser.VirtualDirPath.VirtualPathString, strValue)));
}
}
}
}
return base.BuildStringPropertyExpression(pse);
}
protected override CodeAssignStatement BuildTemplatePropertyStatement(CodeExpression ctrlRefExpr) {
// e.g. __ctrl.AppRelativeTemplateSourceDirectory = this.AppRelativeTemplateSourceDirectory;
CodeAssignStatement assign = new CodeAssignStatement();
assign.Left = new CodePropertyReferenceExpression(ctrlRefExpr, templateSourceDirectoryName);
assign.Right = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), templateSourceDirectoryName);
return assign;
}
protected override string GetGeneratedClassName() {
string className = _themeParser.VirtualDirPath.FileName;
className = System.Web.UI.Util.MakeValidTypeNameFromString(className);
return className;
}
protected override bool UseResourceLiteralString(string s) {
// never use resource literal string, page theme does not support the required methods.
return false;
}
// Don't build the Profile property in Theme classes
protected override bool NeedProfileProperty { get { return false; } }
private class ControlSkinBuilderEntry {
private ControlBuilder _builder;
private string _id;
public ControlSkinBuilderEntry (ControlBuilder builder, string skinID) {
_builder = builder;
_id = skinID;
}
public ControlBuilder Builder {
get { return _builder; }
}
public String SkinID {
get { return _id == null? String.Empty : _id; }
}
}
}
}
| |
// [Twin] Copyright eBay Inc., Twin authors, and other contributors.
// This file is provided to you under the terms of the Apache License, Version 2.0.
// See LICENSE.txt and NOTICE.txt for license and copyright information.
using System;
using System.Collections.Generic;
using System.Text;
using Twin.Model;
using System.Windows;
using System.IO;
using Twin.Proxy;
using System.Windows.Automation;
using Twin.Generic;
namespace Twin.View {
class Elements {
public static object Get(ElementRequest request) {
return PersistedObject.Get(request.Target, request.Session);
}
public static object GetFocused(SessionRequest request) {
return PersistedObject.Get(Element.Create(AutomationElement.FocusedElement, request.Session.Process.Id), request.Session);
}
public static object SetFocused(SessionRequest request) {
Dictionary<string,object> element = (Dictionary<string,object>)request.Body["focusedElement"];
Guid guid = new Guid((string)element["uuid"]);
Element elt = (Element)request.Session[guid];
elt.Focus();
return null;
}
public static object Close(ElementRequest request) {
request.Target.Close();
return null;
}
public static object GetExists(ElementRequest request) {
return request.Target.Exists;
}
const double PollInterval = 1.0;
public static object PollExists(ElementRequest request) {
bool target = (bool)request.Body["value"];
double timeout = request.Body.ContainsKey("timeout") ? Convert.ToDouble(request.Body["timeout"]) : 0;
if(timeout > 0) {
Logging.Logger.Current.Trace("Waiting up to {0} for exists={1}", timeout, target);
long startTicks = DateTime.Now.Ticks;
long targetTicks = startTicks + (long)(10000000 * timeout);
while (true) {
if (request.Target.Exists == target)
break;
int deficitMs = (int) (targetTicks - DateTime.Now.Ticks) / 10000;
if (deficitMs <= 0)
break;
System.Threading.Thread.Sleep((int)Math.Min(deficitMs, (int)(PollInterval * 1000)));
}
}
bool exists = request.Target.Exists;
Logging.Logger.Current.Trace("Finished waiting, element exists={0}", exists);
if (exists != target)
throw new TwinException(ResponseStatus.InvalidElementState, "Element did not reach exists state " + target);
return null;
}
public static object GetParent(ElementRequest request) {
return PersistedObject.Get(request.Target.Parent, request.Session);
}
public static object SendKeys(ElementRequest request) {
string text = (string)request.Body["keys"];
request.Target.Focus();
try {
System.Windows.Forms.SendKeys.SendWait(text);
} catch {
// if the argument is invalid (e.g. foo{XYZ}) then the "foo" gets kept in a buffer
// and sent with the next SendKeys. ideally we could flush this somehow but
// making sure it's sent now is better than nothing
try { System.Windows.Forms.SendKeys.SendWait(""); } catch {}
throw;
}
return null;
}
public static object GetToggleState(ElementRequest request) {
return request.Target.ToggleState;
}
public static object SetToggleState(ElementRequest request) {
if (request.Body.ContainsKey("state"))
request.Target.ToggleState = Convert.ToBoolean(request.Body["state"]);
else
request.Target.Toggle();
return request.Target.ToggleState;
}
public static object GetSelected(ElementRequest request) {
return request.Target.Selected;
}
public static object SetSelected(ElementRequest request) {
request.Target.Selected = (bool)request.Body["selected"];
return null;
}
public static object GetEnabled(ElementRequest request) {
return request.Target.Enabled;
}
public static object GetName(ElementRequest request) {
return request.Target.Name;
}
public static object GetValue(ElementRequest request) {
return request.Target.Value;
}
public static object GetExpanded(ElementRequest request) {
return request.Target.Expanded;
}
public static object SetExpanded(ElementRequest request) {
request.Target.Expanded = (bool)request.Body["expanded"];
return null;
}
public static object SetValue(ElementRequest request) {
request.Target.Value = (string)request.Body["value"];
return null;
}
public static object GetValueOptions(ElementRequest request) {
JSONResponse response = new JSONResponse();
if (request.Target.IsValueReadOnly()) {
response.Options = new string[] { "GET", "POST", "OPTIONS" };
} else {
response.Options = new string[] { "GET", "OPTIONS" };
}
return response;
}
public static object SetSize(ElementRequest request) {
double width = Convert.ToDouble(request.Body["width"]);
double height = Convert.ToDouble(request.Body["height"]);
request.Target.Size = new Size(width, height);
return null;
}
public static object SetLocation(ElementRequest request) {
double x = Convert.ToDouble(request.Body["x"]);
double y = Convert.ToDouble(request.Body["y"]);
request.Target.Location = new Point(x, y);
return null;
}
public static object GetBounds(ElementRequest request) {
Dictionary<string, object> data = new Dictionary<string, object>();
Rect bounds = request.Target.Bounds;
data["width"] = bounds.Width;
data["height"] = bounds.Height;
data["x"] = bounds.X;
data["y"] = bounds.Y;
return data;
}
public static object SetBounds(ElementRequest request) {
double x = Convert.ToDouble(request.Body["x"]);
double y = Convert.ToDouble(request.Body["y"]);
double width = Convert.ToDouble(request.Body["width"]);
double height = Convert.ToDouble(request.Body["height"]);
request.Target.Bounds = new Rect(x, y, width, height);
return null;
}
public static object GetWindowState(ElementRequest request) {
return request.Target.WindowState.ToString();
}
public static object SetWindowState(ElementRequest request) {
request.Target.WindowState = (WindowVisualState)Enum.Parse(typeof(WindowVisualState), (string)request.Body["state"], true);
return null;
}
public static object GetSelectionContainer(ElementRequest request) {
return PersistedObject.Get(request.Target.SelectionContainer, request.Session);
}
public static object GetSelection(ElementRequest request) {
Dictionary<string, object> result = new Dictionary<string, object>();
result["multiple"] = request.Target.SelectionAllowsMultiple;
result["required"] = request.Target.SelectionIsRequired;
List<object> values = new List<object>();
foreach (Element elt in request.Target.Selection)
values.Add(PersistedObject.Get(elt, request.Session));
result["values"] = values;
return result;
}
public static object GetScreenshot(ElementRequest request) {
Dictionary<string, object> data = new Dictionary<string, object>();
Rect defaultRect = new Rect(0, 0, 0, 0);
Rect bounds = defaultRect;
if (request.Body != null) {
if (request.Body.ContainsKey("x"))
bounds.X = Convert.ToDouble(request.Body["x"]);
if (request.Body.ContainsKey("y"))
bounds.Y = Convert.ToDouble(request.Body["y"]);
if (request.Body.ContainsKey("width"))
bounds.Width = Convert.ToDouble(request.Body["width"]);
if (request.Body.ContainsKey("height"))
bounds.Height = Convert.ToDouble(request.Body["height"]);
}
System.Drawing.Bitmap bitmap = (bounds == defaultRect) ? request.Target.CaptureScreenshot() : request.Target.CaptureScreenshot(bounds);
byte[] imageData = BitmapToPNG(bitmap);
bitmap.Dispose();
data["contentType"] = "image/png";
data["data"] = Convert.ToBase64String(imageData);
return data;
}
public static object Click(ElementRequest request) {
int button = 0;
double x = double.NaN;
double y = double.NaN;
if (request.Body != null) {
if (request.Body.ContainsKey("x"))
x = Convert.ToDouble(request.Body["x"]);
if (request.Body.ContainsKey("y"))
y = Convert.ToDouble(request.Body["y"]);
if (request.Body.ContainsKey("button")) {
switch (((string)request.Body["button"]).ToLowerInvariant()) {
case "left":
button = 1;
break;
case "right":
button = 2;
break;
case "middle":
button = 3;
break;
default:
throw new ArgumentOutOfRangeException("button", request.Body["button"], "Should be left/middle/right");
}
}
}
if (button == 0 && double.IsNaN(x) && double.IsNaN(y)) {
request.Target.Click();
} else {
if (button == 0)
button = 1;
if (double.IsNaN(x) && double.IsNaN(y)) {
request.Target.Click(button);
} else if (double.IsNaN(x) || double.IsNaN(y)) {
throw new ArgumentNullException((double.IsNaN(x) ? "x" : "y"), "If either x or y is set, both must be");
} else {
request.Target.Click(button, x, y);
}
}
return null;
}
public static object Scroll(ElementRequest request) {
ScrollAxis axis = (ScrollAxis)request.Session[new Guid(request.Parameters["axis"])];
double position = Convert.ToDouble(request.Body["position"]);
axis.Position = position;
return null;
}
public static object GetScrollPosition(ElementRequest request) {
ScrollAxis axis = (ScrollAxis)request.Session[new Guid(request.Parameters["axis"])];
return axis.Position;
}
public static object GetScrollerX(ElementRequest request) {
return PersistedObject.Get(request.Target.GetScrollAxis(OrientationType.Horizontal), request.Session);
}
public static object GetScrollerY(ElementRequest request) {
return PersistedObject.Get(request.Target.GetScrollAxis(OrientationType.Vertical), request.Session);
}
private static byte[] BitmapToPNG(System.Drawing.Bitmap bitmap) {
MemoryStream stream = new MemoryStream();
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
return stream.ToArray();
}
}
}
| |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace Google.Protobuf.Reflection
{
/// <summary>
/// Describes a .proto file, including everything defined within.
/// IDescriptor is implemented such that the File property returns this descriptor,
/// and the FullName is the same as the Name.
/// </summary>
public sealed class FileDescriptor : IDescriptor
{
private FileDescriptor(ByteString descriptorData, FileDescriptorProto proto, FileDescriptor[] dependencies, DescriptorPool pool, bool allowUnknownDependencies, GeneratedClrTypeInfo generatedCodeInfo)
{
SerializedData = descriptorData;
DescriptorPool = pool;
Proto = proto;
Dependencies = new ReadOnlyCollection<FileDescriptor>((FileDescriptor[]) dependencies.Clone());
PublicDependencies = DeterminePublicDependencies(this, proto, dependencies, allowUnknownDependencies);
pool.AddPackage(Package, this);
MessageTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.MessageType,
(message, index) =>
new MessageDescriptor(message, this, null, index, generatedCodeInfo.NestedTypes[index]));
EnumTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.EnumType,
(enumType, index) =>
new EnumDescriptor(enumType, this, null, index, generatedCodeInfo.NestedEnums[index]));
Services = DescriptorUtil.ConvertAndMakeReadOnly(proto.Service,
(service, index) =>
new ServiceDescriptor(service, this, index));
}
/// <summary>
/// Computes the full name of a descriptor within this file, with an optional parent message.
/// </summary>
internal string ComputeFullName(MessageDescriptor parent, string name)
{
if (parent != null)
{
return parent.FullName + "." + name;
}
if (Package.Length > 0)
{
return Package + "." + name;
}
return name;
}
/// <summary>
/// Extracts public dependencies from direct dependencies. This is a static method despite its
/// first parameter, as the value we're in the middle of constructing is only used for exceptions.
/// </summary>
private static IList<FileDescriptor> DeterminePublicDependencies(FileDescriptor @this, FileDescriptorProto proto, FileDescriptor[] dependencies, bool allowUnknownDependencies)
{
var nameToFileMap = new Dictionary<string, FileDescriptor>();
foreach (var file in dependencies)
{
nameToFileMap[file.Name] = file;
}
var publicDependencies = new List<FileDescriptor>();
for (int i = 0; i < proto.PublicDependency.Count; i++)
{
int index = proto.PublicDependency[i];
if (index < 0 || index >= proto.Dependency.Count)
{
throw new DescriptorValidationException(@this, "Invalid public dependency index.");
}
string name = proto.Dependency[index];
FileDescriptor file = nameToFileMap[name];
if (file == null)
{
if (!allowUnknownDependencies)
{
throw new DescriptorValidationException(@this, "Invalid public dependency: " + name);
}
// Ignore unknown dependencies.
}
else
{
publicDependencies.Add(file);
}
}
return new ReadOnlyCollection<FileDescriptor>(publicDependencies);
}
/// <value>
/// The descriptor in its protocol message representation.
/// </value>
internal FileDescriptorProto Proto { get; }
/// <value>
/// The file name.
/// </value>
public string Name => Proto.Name;
/// <summary>
/// The package as declared in the .proto file. This may or may not
/// be equivalent to the .NET namespace of the generated classes.
/// </summary>
public string Package => Proto.Package;
/// <value>
/// Unmodifiable list of top-level message types declared in this file.
/// </value>
public IList<MessageDescriptor> MessageTypes { get; }
/// <value>
/// Unmodifiable list of top-level enum types declared in this file.
/// </value>
public IList<EnumDescriptor> EnumTypes { get; }
/// <value>
/// Unmodifiable list of top-level services declared in this file.
/// </value>
public IList<ServiceDescriptor> Services { get; }
/// <value>
/// Unmodifiable list of this file's dependencies (imports).
/// </value>
public IList<FileDescriptor> Dependencies { get; }
/// <value>
/// Unmodifiable list of this file's public dependencies (public imports).
/// </value>
public IList<FileDescriptor> PublicDependencies { get; }
/// <value>
/// The original serialized binary form of this descriptor.
/// </value>
public ByteString SerializedData { get; }
/// <value>
/// Implementation of IDescriptor.FullName - just returns the same as Name.
/// </value>
string IDescriptor.FullName => Name;
/// <value>
/// Implementation of IDescriptor.File - just returns this descriptor.
/// </value>
FileDescriptor IDescriptor.File => this;
/// <value>
/// Pool containing symbol descriptors.
/// </value>
internal DescriptorPool DescriptorPool { get; }
/// <summary>
/// Finds a type (message, enum, service or extension) in the file by name. Does not find nested types.
/// </summary>
/// <param name="name">The unqualified type name to look for.</param>
/// <typeparam name="T">The type of descriptor to look for</typeparam>
/// <returns>The type's descriptor, or null if not found.</returns>
public T FindTypeByName<T>(String name)
where T : class, IDescriptor
{
// Don't allow looking up nested types. This will make optimization
// easier later.
if (name.IndexOf('.') != -1)
{
return null;
}
if (Package.Length > 0)
{
name = Package + "." + name;
}
T result = DescriptorPool.FindSymbol<T>(name);
if (result != null && result.File == this)
{
return result;
}
return null;
}
/// <summary>
/// Builds a FileDescriptor from its protocol buffer representation.
/// </summary>
/// <param name="descriptorData">The original serialized descriptor data.
/// We have only limited proto2 support, so serializing FileDescriptorProto
/// would not necessarily give us this.</param>
/// <param name="proto">The protocol message form of the FileDescriptor.</param>
/// <param name="dependencies">FileDescriptors corresponding to all of the
/// file's dependencies, in the exact order listed in the .proto file. May be null,
/// in which case it is treated as an empty array.</param>
/// <param name="allowUnknownDependencies">Whether unknown dependencies are ignored (true) or cause an exception to be thrown (false).</param>
/// <param name="generatedCodeInfo">Details about generated code, for the purposes of reflection.</param>
/// <exception cref="DescriptorValidationException">If <paramref name="proto"/> is not
/// a valid descriptor. This can occur for a number of reasons, such as a field
/// having an undefined type or because two messages were defined with the same name.</exception>
private static FileDescriptor BuildFrom(ByteString descriptorData, FileDescriptorProto proto, FileDescriptor[] dependencies, bool allowUnknownDependencies, GeneratedClrTypeInfo generatedCodeInfo)
{
// Building descriptors involves two steps: translating and linking.
// In the translation step (implemented by FileDescriptor's
// constructor), we build an object tree mirroring the
// FileDescriptorProto's tree and put all of the descriptors into the
// DescriptorPool's lookup tables. In the linking step, we look up all
// type references in the DescriptorPool, so that, for example, a
// FieldDescriptor for an embedded message contains a pointer directly
// to the Descriptor for that message's type. We also detect undefined
// types in the linking step.
if (dependencies == null)
{
dependencies = new FileDescriptor[0];
}
DescriptorPool pool = new DescriptorPool(dependencies);
FileDescriptor result = new FileDescriptor(descriptorData, proto, dependencies, pool, allowUnknownDependencies, generatedCodeInfo);
// Validate that the dependencies we've been passed (as FileDescriptors) are actually the ones we
// need.
if (dependencies.Length != proto.Dependency.Count)
{
throw new DescriptorValidationException(
result,
"Dependencies passed to FileDescriptor.BuildFrom() don't match " +
"those listed in the FileDescriptorProto.");
}
result.CrossLink();
return result;
}
private void CrossLink()
{
foreach (MessageDescriptor message in MessageTypes)
{
message.CrossLink();
}
foreach (ServiceDescriptor service in Services)
{
service.CrossLink();
}
}
/// <summary>
/// Creates a descriptor for generated code.
/// </summary>
/// <remarks>
/// This method is only designed to be used by the results of generating code with protoc,
/// which creates the appropriate dependencies etc. It has to be public because the generated
/// code is "external", but should not be called directly by end users.
/// </remarks>
public static FileDescriptor FromGeneratedCode(
byte[] descriptorData,
FileDescriptor[] dependencies,
GeneratedClrTypeInfo generatedCodeInfo)
{
FileDescriptorProto proto;
try
{
proto = FileDescriptorProto.Parser.ParseFrom(descriptorData);
}
catch (InvalidProtocolBufferException e)
{
throw new ArgumentException("Failed to parse protocol buffer descriptor for generated code.", e);
}
try
{
// When building descriptors for generated code, we allow unknown
// dependencies by default.
return BuildFrom(ByteString.CopyFrom(descriptorData), proto, dependencies, true, generatedCodeInfo);
}
catch (DescriptorValidationException e)
{
throw new ArgumentException($"Invalid embedded descriptor for \"{proto.Name}\".", e);
}
}
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String" /> that represents this instance.
/// </returns>
public override string ToString()
{
return $"FileDescriptor for {Name}";
}
/// <summary>
/// Returns the file descriptor for descriptor.proto.
/// </summary>
/// <remarks>
/// This is used for protos which take a direct dependency on <c>descriptor.proto</c>, typically for
/// annotations. While <c>descriptor.proto</c> is a proto2 file, it is built into the Google.Protobuf
/// runtime for reflection purposes. The messages are internal to the runtime as they would require
/// proto2 semantics for full support, but the file descriptor is available via this property. The
/// C# codegen in protoc automatically uses this property when it detects a dependency on <c>descriptor.proto</c>.
/// </remarks>
/// <value>
/// The file descriptor for <c>descriptor.proto</c>.
/// </value>
public static FileDescriptor DescriptorProtoFileDescriptor { get { return DescriptorReflection.Descriptor; } }
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Network.Fluent
{
using Microsoft.Azure.Management.Network.Fluent.Models;
using Microsoft.Azure.Management.Network.Fluent.NetworkSecurityGroup.Definition;
using Microsoft.Azure.Management.Network.Fluent.NetworkSecurityGroup.Update;
using Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Definition;
using Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Update;
using Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.UpdateDefinition;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Definition;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Update;
using System.Collections.Generic;
internal partial class NetworkSecurityRuleImpl
{
/// <summary>
/// Gets the type of access the rule enforces.
/// </summary>
string Microsoft.Azure.Management.Network.Fluent.INetworkSecurityRule.Access
{
get
{
return this.Access();
}
}
/// <summary>
/// Gets the user-defined description of the security rule.
/// </summary>
string Microsoft.Azure.Management.Network.Fluent.INetworkSecurityRule.Description
{
get
{
return this.Description();
}
}
/// <summary>
/// Gets the destination address prefix the rule applies to, expressed using the CIDR notation in the format: "###.###.###.###/##",
/// and "" means "any".
/// </summary>
string Microsoft.Azure.Management.Network.Fluent.INetworkSecurityRule.DestinationAddressPrefix
{
get
{
return this.DestinationAddressPrefix();
}
}
/// <summary>
/// Gets the list of destination address prefixes the rule applies to, expressed using the CIDR notation in the format: "###.###.###.###/##",
/// and "" means "any", or IP addresses.
/// </summary>
System.Collections.Generic.IReadOnlyList<string> Microsoft.Azure.Management.Network.Fluent.INetworkSecurityRule.DestinationAddressPrefixes
{
get
{
return this.DestinationAddressPrefixes();
}
}
/// <summary>
/// Gets list of application security group ids specified as destination.
/// </summary>
System.Collections.Generic.ISet<string> Microsoft.Azure.Management.Network.Fluent.INetworkSecurityRule.DestinationApplicationSecurityGroupIds
{
get
{
return this.DestinationApplicationSecurityGroupIds();
}
}
/// <summary>
/// Gets the destination port range that the rule applies to, in the format "##-##", where "" means any.
/// </summary>
string Microsoft.Azure.Management.Network.Fluent.INetworkSecurityRule.DestinationPortRange
{
get
{
return this.DestinationPortRange();
}
}
/// <summary>
/// Gets the destination port ranges that the rule applies to, in the format "##-##", where "" means any.
/// </summary>
System.Collections.Generic.IReadOnlyList<string> Microsoft.Azure.Management.Network.Fluent.INetworkSecurityRule.DestinationPortRanges
{
get
{
return this.DestinationPortRanges();
}
}
/// <summary>
/// Gets the direction of the network traffic that the network security rule applies to.
/// </summary>
string Microsoft.Azure.Management.Network.Fluent.INetworkSecurityRule.Direction
{
get
{
return this.Direction();
}
}
/// <summary>
/// Gets the name of the resource.
/// </summary>
string Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasName.Name
{
get
{
return this.Name();
}
}
/// <summary>
/// Gets the priority number of this rule based on which this rule will be applied relative to the priority numbers of any other rules specified
/// for this network security group.
/// </summary>
int Microsoft.Azure.Management.Network.Fluent.INetworkSecurityRule.Priority
{
get
{
return this.Priority();
}
}
/// <summary>
/// Gets the network protocol the rule applies to.
/// </summary>
string Microsoft.Azure.Management.Network.Fluent.INetworkSecurityRule.Protocol
{
get
{
return this.Protocol();
}
}
/// <summary>
/// Gets the source address prefix the rule applies to, expressed using the CIDR notation in the format: "###.###.###.###/##",
/// and "" means "any".
/// </summary>
string Microsoft.Azure.Management.Network.Fluent.INetworkSecurityRule.SourceAddressPrefix
{
get
{
return this.SourceAddressPrefix();
}
}
/// <summary>
/// Gets the list of source address prefixes the rule applies to, expressed using the CIDR notation in the format: "###.###.###.###/##",
/// and "" means "any", or IP addresses.
/// </summary>
System.Collections.Generic.IReadOnlyList<string> Microsoft.Azure.Management.Network.Fluent.INetworkSecurityRule.SourceAddressPrefixes
{
get
{
return this.SourceAddressPrefixes();
}
}
/// <summary>
/// Gets list of application security group ids specified as source.
/// </summary>
System.Collections.Generic.ISet<string> Microsoft.Azure.Management.Network.Fluent.INetworkSecurityRule.SourceApplicationSecurityGroupIds
{
get
{
return this.SourceApplicationSecurityGroupIds();
}
}
/// <summary>
/// Gets the source port range that the rule applies to, in the format "##-##", where "" means "any".
/// </summary>
string Microsoft.Azure.Management.Network.Fluent.INetworkSecurityRule.SourcePortRange
{
get
{
return this.SourcePortRange();
}
}
/// <summary>
/// Gets the source port ranges that the rule applies to, in the format "##-##", where "" means "any".
/// </summary>
System.Collections.Generic.IReadOnlyList<string> Microsoft.Azure.Management.Network.Fluent.INetworkSecurityRule.SourcePortRanges
{
get
{
return this.SourcePortRanges();
}
}
/// <summary>
/// Allows inbound traffic.
/// </summary>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Definition.IWithSourceAddressOrSecurityGroup<NetworkSecurityGroup.Definition.IWithCreate> NetworkSecurityRule.Definition.IWithDirectionAccess<NetworkSecurityGroup.Definition.IWithCreate>.AllowInbound()
{
return this.AllowInbound();
}
/// <summary>
/// Allows inbound traffic.
/// </summary>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.UpdateDefinition.IWithSourceAddressOrSecurityGroup<NetworkSecurityGroup.Update.IUpdate> NetworkSecurityRule.UpdateDefinition.IWithDirectionAccess<NetworkSecurityGroup.Update.IUpdate>.AllowInbound()
{
return this.AllowInbound();
}
/// <summary>
/// Allows inbound traffic.
/// </summary>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Update.IUpdate NetworkSecurityRule.Update.IWithDirectionAccess.AllowInbound()
{
return this.AllowInbound();
}
/// <summary>
/// Allows outbound traffic.
/// </summary>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Definition.IWithSourceAddressOrSecurityGroup<NetworkSecurityGroup.Definition.IWithCreate> NetworkSecurityRule.Definition.IWithDirectionAccess<NetworkSecurityGroup.Definition.IWithCreate>.AllowOutbound()
{
return this.AllowOutbound();
}
/// <summary>
/// Allows outbound traffic.
/// </summary>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.UpdateDefinition.IWithSourceAddressOrSecurityGroup<NetworkSecurityGroup.Update.IUpdate> NetworkSecurityRule.UpdateDefinition.IWithDirectionAccess<NetworkSecurityGroup.Update.IUpdate>.AllowOutbound()
{
return this.AllowOutbound();
}
/// <summary>
/// Allows outbound traffic.
/// </summary>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Update.IUpdate NetworkSecurityRule.Update.IWithDirectionAccess.AllowOutbound()
{
return this.AllowOutbound();
}
/// <summary>
/// Attaches the child definition to the parent resource update.
/// </summary>
/// <return>The next stage of the parent definition.</return>
NetworkSecurityGroup.Update.IUpdate Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Update.IInUpdate<NetworkSecurityGroup.Update.IUpdate>.Attach()
{
return this.Attach();
}
/// <summary>
/// Attaches the child definition to the parent resource definiton.
/// </summary>
/// <return>The next stage of the parent definition.</return>
NetworkSecurityGroup.Definition.IWithCreate Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Definition.IInDefinition<NetworkSecurityGroup.Definition.IWithCreate>.Attach()
{
return this.Attach();
}
/// <summary>
/// Blocks inbound traffic.
/// </summary>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Definition.IWithSourceAddressOrSecurityGroup<NetworkSecurityGroup.Definition.IWithCreate> NetworkSecurityRule.Definition.IWithDirectionAccess<NetworkSecurityGroup.Definition.IWithCreate>.DenyInbound()
{
return this.DenyInbound();
}
/// <summary>
/// Blocks inbound traffic.
/// </summary>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.UpdateDefinition.IWithSourceAddressOrSecurityGroup<NetworkSecurityGroup.Update.IUpdate> NetworkSecurityRule.UpdateDefinition.IWithDirectionAccess<NetworkSecurityGroup.Update.IUpdate>.DenyInbound()
{
return this.DenyInbound();
}
/// <summary>
/// Blocks inbound traffic.
/// </summary>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Update.IUpdate NetworkSecurityRule.Update.IWithDirectionAccess.DenyInbound()
{
return this.DenyInbound();
}
/// <summary>
/// Blocks outbound traffic.
/// </summary>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Definition.IWithSourceAddressOrSecurityGroup<NetworkSecurityGroup.Definition.IWithCreate> NetworkSecurityRule.Definition.IWithDirectionAccess<NetworkSecurityGroup.Definition.IWithCreate>.DenyOutbound()
{
return this.DenyOutbound();
}
/// <summary>
/// Blocks outbound traffic.
/// </summary>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.UpdateDefinition.IWithSourceAddressOrSecurityGroup<NetworkSecurityGroup.Update.IUpdate> NetworkSecurityRule.UpdateDefinition.IWithDirectionAccess<NetworkSecurityGroup.Update.IUpdate>.DenyOutbound()
{
return this.DenyOutbound();
}
/// <summary>
/// Blocks outbound traffic.
/// </summary>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Update.IUpdate NetworkSecurityRule.Update.IWithDirectionAccess.DenyOutbound()
{
return this.DenyOutbound();
}
/// <summary>
/// Specifies the traffic source address prefix to which this rule applies.
/// </summary>
/// <param name="cidr">An IP address prefix expressed in the CIDR notation.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Definition.IWithSourcePort<NetworkSecurityGroup.Definition.IWithCreate> NetworkSecurityRule.Definition.IWithSourceAddressOrSecurityGroup<NetworkSecurityGroup.Definition.IWithCreate>.FromAddress(string cidr)
{
return this.FromAddress(cidr);
}
/// <summary>
/// Specifies the traffic source address prefix to which this rule applies.
/// </summary>
/// <param name="cidr">An IP address prefix expressed in the CIDR notation.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.UpdateDefinition.IWithSourcePort<NetworkSecurityGroup.Update.IUpdate> NetworkSecurityRule.UpdateDefinition.IWithSourceAddressOrSecurityGroup<NetworkSecurityGroup.Update.IUpdate>.FromAddress(string cidr)
{
return this.FromAddress(cidr);
}
/// <summary>
/// Specifies the traffic source address prefix to which this rule applies.
/// </summary>
/// <param name="cidr">An IP address prefix expressed in the CIDR notation.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Update.IUpdate NetworkSecurityRule.Update.IWithSourceAddressOrSecurityGroup.FromAddress(string cidr)
{
return this.FromAddress(cidr);
}
/// <summary>
/// Specifies the traffic source address prefixes to which this rule applies.
/// </summary>
/// <param name="addresses">IP address prefixes in CIDR notation or IP addresses.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Definition.IWithSourcePort<NetworkSecurityGroup.Definition.IWithCreate> NetworkSecurityRule.Definition.IWithSourceAddressOrSecurityGroup<NetworkSecurityGroup.Definition.IWithCreate>.FromAddresses(params string[] addresses)
{
return this.FromAddresses(addresses);
}
/// <summary>
/// Specifies the traffic source address prefixes to which this rule applies.
/// </summary>
/// <param name="addresses">IP address prefixes in CIDR notation or IP addresses.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.UpdateDefinition.IWithSourcePort<NetworkSecurityGroup.Update.IUpdate> NetworkSecurityRule.UpdateDefinition.IWithSourceAddressOrSecurityGroup<NetworkSecurityGroup.Update.IUpdate>.FromAddresses(params string[] addresses)
{
return this.FromAddresses(addresses);
}
/// <summary>
/// Specifies the traffic source address prefixes to which this rule applies.
/// </summary>
/// <param name="addresses">IP address prefixes in CIDR notation or IP addresses.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Update.IUpdate NetworkSecurityRule.Update.IWithSourceAddressOrSecurityGroup.FromAddresses(params string[] addresses)
{
return this.FromAddresses(addresses);
}
/// <summary>
/// Specifies that the rule applies to any traffic source address.
/// </summary>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Definition.IWithSourcePort<NetworkSecurityGroup.Definition.IWithCreate> NetworkSecurityRule.Definition.IWithSourceAddressOrSecurityGroup<NetworkSecurityGroup.Definition.IWithCreate>.FromAnyAddress()
{
return this.FromAnyAddress();
}
/// <summary>
/// Specifies that the rule applies to any traffic source address.
/// </summary>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.UpdateDefinition.IWithSourcePort<NetworkSecurityGroup.Update.IUpdate> NetworkSecurityRule.UpdateDefinition.IWithSourceAddressOrSecurityGroup<NetworkSecurityGroup.Update.IUpdate>.FromAnyAddress()
{
return this.FromAnyAddress();
}
/// <summary>
/// Specifies that the rule applies to any traffic source address.
/// </summary>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Update.IUpdate NetworkSecurityRule.Update.IWithSourceAddressOrSecurityGroup.FromAnyAddress()
{
return this.FromAnyAddress();
}
/// <summary>
/// Makes this rule apply to any source port.
/// </summary>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Update.IUpdate NetworkSecurityRule.Update.IWithSourcePort.FromAnyPort()
{
return this.FromAnyPort();
}
/// <summary>
/// Makes this rule apply to any source port.
/// </summary>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Definition.IWithDestinationAddressOrSecurityGroup<NetworkSecurityGroup.Definition.IWithCreate> NetworkSecurityRule.Definition.IWithSourcePort<NetworkSecurityGroup.Definition.IWithCreate>.FromAnyPort()
{
return this.FromAnyPort();
}
/// <summary>
/// Makes this rule apply to any source port.
/// </summary>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.UpdateDefinition.IWithDestinationAddressOrSecurityGroup<NetworkSecurityGroup.Update.IUpdate> NetworkSecurityRule.UpdateDefinition.IWithSourcePort<NetworkSecurityGroup.Update.IUpdate>.FromAnyPort()
{
return this.FromAnyPort();
}
/// <summary>
/// Specifies the source port to which this rule applies.
/// </summary>
/// <param name="port">The source port number.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Update.IUpdate NetworkSecurityRule.Update.IWithSourcePort.FromPort(int port)
{
return this.FromPort(port);
}
/// <summary>
/// Specifies the source port to which this rule applies.
/// </summary>
/// <param name="port">The source port number.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Definition.IWithDestinationAddressOrSecurityGroup<NetworkSecurityGroup.Definition.IWithCreate> NetworkSecurityRule.Definition.IWithSourcePort<NetworkSecurityGroup.Definition.IWithCreate>.FromPort(int port)
{
return this.FromPort(port);
}
/// <summary>
/// Specifies the source port to which this rule applies.
/// </summary>
/// <param name="port">The source port number.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.UpdateDefinition.IWithDestinationAddressOrSecurityGroup<NetworkSecurityGroup.Update.IUpdate> NetworkSecurityRule.UpdateDefinition.IWithSourcePort<NetworkSecurityGroup.Update.IUpdate>.FromPort(int port)
{
return this.FromPort(port);
}
/// <summary>
/// Specifies the source port range to which this rule applies.
/// </summary>
/// <param name="from">The starting port number.</param>
/// <param name="to">The ending port number.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Update.IUpdate NetworkSecurityRule.Update.IWithSourcePort.FromPortRange(int from, int to)
{
return this.FromPortRange(from, to);
}
/// <summary>
/// Specifies the source port range to which this rule applies.
/// </summary>
/// <param name="from">The starting port number.</param>
/// <param name="to">The ending port number.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Definition.IWithDestinationAddressOrSecurityGroup<NetworkSecurityGroup.Definition.IWithCreate> NetworkSecurityRule.Definition.IWithSourcePort<NetworkSecurityGroup.Definition.IWithCreate>.FromPortRange(int from, int to)
{
return this.FromPortRange(from, to);
}
/// <summary>
/// Specifies the source port range to which this rule applies.
/// </summary>
/// <param name="from">The starting port number.</param>
/// <param name="to">The ending port number.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.UpdateDefinition.IWithDestinationAddressOrSecurityGroup<NetworkSecurityGroup.Update.IUpdate> NetworkSecurityRule.UpdateDefinition.IWithSourcePort<NetworkSecurityGroup.Update.IUpdate>.FromPortRange(int from, int to)
{
return this.FromPortRange(from, to);
}
/// <summary>
/// Specifies the source port ranges to which this rule applies.
/// </summary>
/// <param name="ranges">The starting port ranges.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Update.IUpdate NetworkSecurityRule.Update.IWithSourcePort.FromPortRanges(params string[] ranges)
{
return this.FromPortRanges(ranges);
}
/// <summary>
/// Specifies the source port ranges to which this rule applies.
/// </summary>
/// <param name="ranges">The starting port ranges.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Definition.IWithDestinationAddressOrSecurityGroup<NetworkSecurityGroup.Definition.IWithCreate> NetworkSecurityRule.Definition.IWithSourcePort<NetworkSecurityGroup.Definition.IWithCreate>.FromPortRanges(params string[] ranges)
{
return this.FromPortRanges(ranges);
}
/// <summary>
/// Specifies the source port ranges to which this rule applies.
/// </summary>
/// <param name="ranges">The starting port ranges.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.UpdateDefinition.IWithDestinationAddressOrSecurityGroup<NetworkSecurityGroup.Update.IUpdate> NetworkSecurityRule.UpdateDefinition.IWithSourcePort<NetworkSecurityGroup.Update.IUpdate>.FromPortRanges(params string[] ranges)
{
return this.FromPortRanges(ranges);
}
/// <summary>
/// Specifies the traffic destination address range to which this rule applies.
/// </summary>
/// <param name="cidr">An IP address range expressed in the CIDR notation.</param>
/// <return>The next stage of the update.</return>
NetworkSecurityRule.Update.IUpdate NetworkSecurityRule.Update.IWithDestinationAddressOrSecurityGroup.ToAddress(string cidr)
{
return this.ToAddress(cidr);
}
/// <summary>
/// Specifies the traffic destination address range to which this rule applies.
/// </summary>
/// <param name="cidr">An IP address range expressed in the CIDR notation.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Definition.IWithDestinationPort<NetworkSecurityGroup.Definition.IWithCreate> NetworkSecurityRule.Definition.IWithDestinationAddressOrSecurityGroup<NetworkSecurityGroup.Definition.IWithCreate>.ToAddress(string cidr)
{
return this.ToAddress(cidr);
}
/// <summary>
/// Specifies the traffic destination address range to which this rule applies.
/// </summary>
/// <param name="cidr">An IP address range expressed in the CIDR notation.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.UpdateDefinition.IWithDestinationPort<NetworkSecurityGroup.Update.IUpdate> NetworkSecurityRule.UpdateDefinition.IWithDestinationAddressOrSecurityGroup<NetworkSecurityGroup.Update.IUpdate>.ToAddress(string cidr)
{
return this.ToAddress(cidr);
}
/// <summary>
/// Specifies the traffic destination address prefixes to which this rule applies.
/// </summary>
/// <param name="addresses">IP address prefixes in CIDR notation or IP addresses.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Update.IUpdate NetworkSecurityRule.Update.IWithDestinationAddressOrSecurityGroup.ToAddresses(params string[] addresses)
{
return this.ToAddresses(addresses);
}
/// <summary>
/// Specifies the traffic destination address prefixes to which this rule applies.
/// </summary>
/// <param name="addresses">IP address prefixes in CIDR notation or IP addresses.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Definition.IWithDestinationPort<NetworkSecurityGroup.Definition.IWithCreate> NetworkSecurityRule.Definition.IWithDestinationAddressOrSecurityGroup<NetworkSecurityGroup.Definition.IWithCreate>.ToAddresses(params string[] addresses)
{
return this.ToAddresses(addresses);
}
/// <summary>
/// Specifies the traffic destination address prefixes to which this rule applies.
/// </summary>
/// <param name="addresses">IP address prefixes in CIDR notation or IP addresses.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.UpdateDefinition.IWithDestinationPort<NetworkSecurityGroup.Update.IUpdate> NetworkSecurityRule.UpdateDefinition.IWithDestinationAddressOrSecurityGroup<NetworkSecurityGroup.Update.IUpdate>.ToAddresses(params string[] addresses)
{
return this.ToAddresses(addresses);
}
/// <summary>
/// Makes the rule apply to any traffic destination address.
/// </summary>
/// <return>The next stage of the update.</return>
NetworkSecurityRule.Update.IUpdate NetworkSecurityRule.Update.IWithDestinationAddressOrSecurityGroup.ToAnyAddress()
{
return this.ToAnyAddress();
}
/// <summary>
/// Makes the rule apply to any traffic destination address.
/// </summary>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Definition.IWithDestinationPort<NetworkSecurityGroup.Definition.IWithCreate> NetworkSecurityRule.Definition.IWithDestinationAddressOrSecurityGroup<NetworkSecurityGroup.Definition.IWithCreate>.ToAnyAddress()
{
return this.ToAnyAddress();
}
/// <summary>
/// Makes the rule apply to any traffic destination address.
/// </summary>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.UpdateDefinition.IWithDestinationPort<NetworkSecurityGroup.Update.IUpdate> NetworkSecurityRule.UpdateDefinition.IWithDestinationAddressOrSecurityGroup<NetworkSecurityGroup.Update.IUpdate>.ToAnyAddress()
{
return this.ToAnyAddress();
}
/// <summary>
/// Makes this rule apply to any destination port.
/// </summary>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Definition.IWithProtocol<NetworkSecurityGroup.Definition.IWithCreate> NetworkSecurityRule.Definition.IWithDestinationPort<NetworkSecurityGroup.Definition.IWithCreate>.ToAnyPort()
{
return this.ToAnyPort();
}
/// <summary>
/// Makes this rule apply to any destination port.
/// </summary>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.UpdateDefinition.IWithProtocol<NetworkSecurityGroup.Update.IUpdate> NetworkSecurityRule.UpdateDefinition.IWithDestinationPort<NetworkSecurityGroup.Update.IUpdate>.ToAnyPort()
{
return this.ToAnyPort();
}
/// <summary>
/// Makes this rule apply to any destination port.
/// </summary>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Update.IUpdate NetworkSecurityRule.Update.IWithDestinationPort.ToAnyPort()
{
return this.ToAnyPort();
}
/// <summary>
/// Specifies the destination port to which this rule applies.
/// </summary>
/// <param name="port">The destination port number.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Definition.IWithProtocol<NetworkSecurityGroup.Definition.IWithCreate> NetworkSecurityRule.Definition.IWithDestinationPort<NetworkSecurityGroup.Definition.IWithCreate>.ToPort(int port)
{
return this.ToPort(port);
}
/// <summary>
/// Specifies the destination port to which this rule applies.
/// </summary>
/// <param name="port">The destination port number.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.UpdateDefinition.IWithProtocol<NetworkSecurityGroup.Update.IUpdate> NetworkSecurityRule.UpdateDefinition.IWithDestinationPort<NetworkSecurityGroup.Update.IUpdate>.ToPort(int port)
{
return this.ToPort(port);
}
/// <summary>
/// Specifies the destination port to which this rule applies.
/// </summary>
/// <param name="port">The destination port number.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Update.IUpdate NetworkSecurityRule.Update.IWithDestinationPort.ToPort(int port)
{
return this.ToPort(port);
}
/// <summary>
/// Specifies the destination port range to which this rule applies.
/// </summary>
/// <param name="from">The starting port number.</param>
/// <param name="to">The ending port number.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Definition.IWithProtocol<NetworkSecurityGroup.Definition.IWithCreate> NetworkSecurityRule.Definition.IWithDestinationPort<NetworkSecurityGroup.Definition.IWithCreate>.ToPortRange(int from, int to)
{
return this.ToPortRange(from, to);
}
/// <summary>
/// Specifies the destination port range to which this rule applies.
/// </summary>
/// <param name="from">The starting port number.</param>
/// <param name="to">The ending port number.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.UpdateDefinition.IWithProtocol<NetworkSecurityGroup.Update.IUpdate> NetworkSecurityRule.UpdateDefinition.IWithDestinationPort<NetworkSecurityGroup.Update.IUpdate>.ToPortRange(int from, int to)
{
return this.ToPortRange(from, to);
}
/// <summary>
/// Specifies the destination port range to which this rule applies.
/// </summary>
/// <param name="from">The starting port number.</param>
/// <param name="to">The ending port number.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Update.IUpdate NetworkSecurityRule.Update.IWithDestinationPort.ToPortRange(int from, int to)
{
return this.ToPortRange(from, to);
}
/// <summary>
/// Specifies the destination port ranges to which this rule applies.
/// </summary>
/// <param name="ranges">The destination port ranges.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Definition.IWithProtocol<NetworkSecurityGroup.Definition.IWithCreate> NetworkSecurityRule.Definition.IWithDestinationPort<NetworkSecurityGroup.Definition.IWithCreate>.ToPortRanges(params string[] ranges)
{
return this.ToPortRanges(ranges);
}
/// <summary>
/// Specifies the destination port ranges to which this rule applies.
/// </summary>
/// <param name="ranges">The destination port ranges.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.UpdateDefinition.IWithProtocol<NetworkSecurityGroup.Update.IUpdate> NetworkSecurityRule.UpdateDefinition.IWithDestinationPort<NetworkSecurityGroup.Update.IUpdate>.ToPortRanges(params string[] ranges)
{
return this.ToPortRanges(ranges);
}
/// <summary>
/// Specifies the destination port ranges to which this rule applies.
/// </summary>
/// <param name="ranges">The destination port ranges.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Update.IUpdate NetworkSecurityRule.Update.IWithDestinationPort.ToPortRanges(params string[] ranges)
{
return this.ToPortRanges(ranges);
}
/// <summary>
/// Makes this rule apply to any supported protocol.
/// </summary>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Definition.IWithAttach<NetworkSecurityGroup.Definition.IWithCreate> NetworkSecurityRule.Definition.IWithProtocol<NetworkSecurityGroup.Definition.IWithCreate>.WithAnyProtocol()
{
return this.WithAnyProtocol();
}
/// <summary>
/// Makes this rule apply to any supported protocol.
/// </summary>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.UpdateDefinition.IWithAttach<NetworkSecurityGroup.Update.IUpdate> NetworkSecurityRule.UpdateDefinition.IWithProtocol<NetworkSecurityGroup.Update.IUpdate>.WithAnyProtocol()
{
return this.WithAnyProtocol();
}
/// <summary>
/// Makes this rule apply to any supported protocol.
/// </summary>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Update.IUpdate NetworkSecurityRule.Update.IWithProtocol.WithAnyProtocol()
{
return this.WithAnyProtocol();
}
/// <summary>
/// Specifies a description for this security rule.
/// </summary>
/// <param name="descrtiption">A text description to associate with the security rule.</param>
/// <return>The next stage.</return>
NetworkSecurityRule.UpdateDefinition.IWithAttach<NetworkSecurityGroup.Update.IUpdate> NetworkSecurityRule.UpdateDefinition.IWithAttach<NetworkSecurityGroup.Update.IUpdate>.WithDescription(string descrtiption)
{
return this.WithDescription(descrtiption);
}
/// <summary>
/// Specifies a description for this security rule.
/// </summary>
/// <param name="description">The text description to associate with this security rule.</param>
/// <return>The next stage.</return>
NetworkSecurityRule.Definition.IWithAttach<NetworkSecurityGroup.Definition.IWithCreate> NetworkSecurityRule.Definition.IWithDescription<NetworkSecurityGroup.Definition.IWithCreate>.WithDescription(string description)
{
return this.WithDescription(description);
}
/// <summary>
/// Specifies a description for this security rule.
/// </summary>
/// <param name="description">A text description to associate with this security rule.</param>
/// <return>The next stage.</return>
NetworkSecurityRule.Update.IUpdate NetworkSecurityRule.Update.IUpdate.WithDescription(string description)
{
return this.WithDescription(description);
}
/// <summary>
/// Sets the application security group specified as destination.
/// </summary>
/// <param name="id">Application security group id.</param>
/// <return>The next stage of the update.</return>
NetworkSecurityRule.Update.IUpdate NetworkSecurityRule.Update.IWithDestinationAddressOrSecurityGroup.WithDestinationApplicationSecurityGroup(string id)
{
return this.WithDestinationApplicationSecurityGroup(id);
}
/// <summary>
/// Sets the application security group specified as destination.
/// </summary>
/// <param name="id">Application security group id.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Definition.IWithDestinationPort<NetworkSecurityGroup.Definition.IWithCreate> NetworkSecurityRule.Definition.IWithDestinationAddressOrSecurityGroup<NetworkSecurityGroup.Definition.IWithCreate>.WithDestinationApplicationSecurityGroup(string id)
{
return this.WithDestinationApplicationSecurityGroup(id);
}
/// <summary>
/// Sets the application security group specified as destination.
/// </summary>
/// <param name="id">Application security group id.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.UpdateDefinition.IWithDestinationPort<NetworkSecurityGroup.Update.IUpdate> NetworkSecurityRule.UpdateDefinition.IWithDestinationAddressOrSecurityGroup<NetworkSecurityGroup.Update.IUpdate>.WithDestinationApplicationSecurityGroup(string id)
{
return this.WithDestinationApplicationSecurityGroup(id);
}
/// <summary>
/// Specifies the priority to assign to this rule.
/// Security rules are applied in the order of their assigned priority.
/// </summary>
/// <param name="priority">The priority number in the range 100 to 4096.</param>
/// <return>The next stage of the update.</return>
NetworkSecurityRule.UpdateDefinition.IWithAttach<NetworkSecurityGroup.Update.IUpdate> NetworkSecurityRule.UpdateDefinition.IWithAttach<NetworkSecurityGroup.Update.IUpdate>.WithPriority(int priority)
{
return this.WithPriority(priority);
}
/// <summary>
/// Specifies the priority to assign to this rule.
/// Security rules are applied in the order of their assigned priority.
/// </summary>
/// <param name="priority">The priority number in the range 100 to 4096.</param>
/// <return>The next stage.</return>
NetworkSecurityRule.Definition.IWithAttach<NetworkSecurityGroup.Definition.IWithCreate> NetworkSecurityRule.Definition.IWithPriority<NetworkSecurityGroup.Definition.IWithCreate>.WithPriority(int priority)
{
return this.WithPriority(priority);
}
/// <summary>
/// Specifies the priority to assign to this security rule.
/// Security rules are applied in the order of their assigned priority.
/// </summary>
/// <param name="priority">The priority number in the range 100 to 4096.</param>
/// <return>The next stage of the update.</return>
NetworkSecurityRule.Update.IUpdate NetworkSecurityRule.Update.IUpdate.WithPriority(int priority)
{
return this.WithPriority(priority);
}
/// <summary>
/// Specifies the protocol that this rule applies to.
/// </summary>
/// <param name="protocol">One of the supported protocols.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Definition.IWithAttach<NetworkSecurityGroup.Definition.IWithCreate> NetworkSecurityRule.Definition.IWithProtocol<NetworkSecurityGroup.Definition.IWithCreate>.WithProtocol(SecurityRuleProtocol protocol)
{
return this.WithProtocol(protocol);
}
/// <summary>
/// Specifies the protocol that this rule applies to.
/// </summary>
/// <param name="protocol">One of the supported protocols.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.UpdateDefinition.IWithAttach<NetworkSecurityGroup.Update.IUpdate> NetworkSecurityRule.UpdateDefinition.IWithProtocol<NetworkSecurityGroup.Update.IUpdate>.WithProtocol(SecurityRuleProtocol protocol)
{
return this.WithProtocol(protocol);
}
/// <summary>
/// Specifies the protocol that this rule applies to.
/// </summary>
/// <param name="protocol">One of the supported protocols.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Update.IUpdate NetworkSecurityRule.Update.IWithProtocol.WithProtocol(SecurityRuleProtocol protocol)
{
return this.WithProtocol(protocol);
}
/// <summary>
/// Sets the application security group specified as source.
/// </summary>
/// <param name="id">Application security group id.</param>
/// <return>The next stage of the definition.</return>
NetworkSecurityRule.Definition.IWithSourcePort<NetworkSecurityGroup.Definition.IWithCreate> NetworkSecurityRule.Definition.IWithSourceAddressOrSecurityGroup<NetworkSecurityGroup.Definition.IWithCreate>.WithSourceApplicationSecurityGroup(string id)
{
return this.WithSourceApplicationSecurityGroup(id);
}
/// <summary>
/// Sets the application security group specified as source.
/// </summary>
/// <param name="id">Application security group id.</param>
/// <return>The next stage of the update.</return>
NetworkSecurityRule.UpdateDefinition.IWithSourcePort<NetworkSecurityGroup.Update.IUpdate> NetworkSecurityRule.UpdateDefinition.IWithSourceAddressOrSecurityGroup<NetworkSecurityGroup.Update.IUpdate>.WithSourceApplicationSecurityGroup(string id)
{
return this.WithSourceApplicationSecurityGroup(id);
}
/// <summary>
/// Sets the application security group specified as source.
/// </summary>
/// <param name="id">Application security group id.</param>
/// <return>The next stage of the update.</return>
NetworkSecurityRule.Update.IUpdate NetworkSecurityRule.Update.IWithSourceAddressOrSecurityGroup.WithSourceApplicationSecurityGroup(string id)
{
return this.WithSourceApplicationSecurityGroup(id);
}
}
}
| |
using System;
using System.Diagnostics;
using CupCake.Core.Metadata;
using CupCake.Messages;
using CupCake.Messages.Blocks;
using CupCake.Messages.Receive;
using CupCake.Messages.Send;
namespace CupCake.World
{
/// <summary>
/// Represents a block in the world.
/// </summary>
[DebuggerDisplay("Block = {Block}, Data = {DebuggerData()}")]
public class WorldBlock : MetadataProvider
{
private BlockData _data;
internal WorldBlock(MetadataPlatform metadataPlatform, Layer layer, int x, int y, Block block)
: base(metadataPlatform)
{
this.Layer = layer;
this.X = x;
this.Y = y;
this.SetBlock(block);
}
/// <summary>
/// Gets the metadata key.
/// </summary>
/// <value>
/// The metadata key.
/// </value>
protected override object MetadataKey
{
get { return new Point3D(this.Layer, this.X, this.Y); }
}
/// <summary>
/// Gets the layer.
/// </summary>
/// <value>
/// The layer.
/// </value>
public Layer Layer { get; private set; }
/// <summary>
/// Gets the x coordinate of this block.
/// </summary>
/// <value>
/// The x coordinate of this block.
/// </value>
public int X { get; private set; }
/// <summary>
/// Gets the y coordinate of this block.
/// </summary>
/// <value>
/// The y coordinate of this block.
/// </value>
public int Y { get; private set; }
/// <summary>
/// Gets the type of the block.
/// </summary>
/// <value>
/// The type of the block.
/// </value>
public virtual BlockType BlockType { get; private set; }
/// <summary>
/// Gets the block.
/// </summary>
/// <value>
/// The block.
/// </value>
public Block Block { get; private set; }
/// <summary>
/// Gets the metadata.
/// </summary>
/// <value>
/// The metadata.
/// </value>
[Obsolete("Use the Get<T> and Set<T> methods instead.")]
public MetadataStore Metadata
{
get { return this.MetadataStore; }
}
/// <summary>
/// Gets the Text. (Only on sign or label blocks)
/// </summary>
/// <value>
/// The text.
/// </value>
/// <exception cref="System.InvalidOperationException">This property can only be accessed on Sign or Label blocks.</exception>
public string Text
{
get
{
if (this.BlockType != BlockType.Sign && this.BlockType != BlockType.Label)
throw new InvalidOperationException("This property can only be accessed on Sign or Label blocks.");
return this._data.Text;
}
}
/// <summary>
/// Gets the TextColor. (Only on label blocks)
/// </summary>
/// <value>
/// The text color.
/// </value>
/// <exception cref="System.InvalidOperationException">This property can only be accessed on Label blocks.</exception>
public string TextColor
{
get
{
if (this.BlockType != BlockType.Label)
throw new InvalidOperationException("This property can only be accessed on Label blocks.");
return this._data.TextColor;
}
}
/// <summary>
/// Gets the world portal target. (Only on world portal blocks)
/// </summary>
/// <value>
/// The world portal target.
/// </value>
/// <exception cref="System.InvalidOperationException">This property can only be accessed on WorldPortal blocks.</exception>
public string WorldPortalTarget
{
get
{
if (this.BlockType != BlockType.WorldPortal)
throw new InvalidOperationException("This property can only be accessed on WorldPortal blocks.");
return this._data.WorldPortalTarget;
}
}
/// <summary>
/// Gets the coins to collect. (Only on coin doors)
/// </summary>
/// <value>
/// The coins to collect.
/// </value>
/// <exception cref="System.InvalidOperationException">This property can only be accessed on CoinDoor blocks.</exception>
public uint CoinsToCollect
{
get
{
if (this.BlockType != BlockType.CoinDoor)
throw new InvalidOperationException("This property can only be accessed on CoinDoor blocks.");
return this._data.CoinsToCollect;
}
}
/// <summary>
/// Gets the purple id.
/// </summary>
/// <value>
/// The coins to collect.
/// </value>
/// <exception cref="System.InvalidOperationException">This property can only be accessed on Purple Door or Gate blocks.</exception>
public uint PurpleId
{
get
{
if (this.BlockType != BlockType.Purple)
throw new InvalidOperationException("This property can only be accessed on CoinDoor blocks.");
return this._data.PurpleId;
}
}
/// <summary>
/// Gets the deaths required.
/// </summary>
/// <value>
/// The amount of deaths required.
/// </value>
/// <exception cref="System.InvalidOperationException">This property can only be accessed on Death Door or Gate blocks.</exception>
public uint DeathsRequired
{
get
{
if (this.BlockType != BlockType.Death)
throw new InvalidOperationException("This property can only be accessed on Death blocks.");
return this._data.DeathsRequired;
}
}
/// <summary>
/// Gets the portal identifier. (Only on portal blocks)
/// </summary>
/// <value>
/// The portal identifier.
/// </value>
/// <exception cref="System.InvalidOperationException">This property can only be accessed on Portal blocks.</exception>
public uint PortalId
{
get
{
if (this.BlockType != BlockType.Portal)
throw new InvalidOperationException("This property can only be accessed on Portal blocks.");
return this._data.PortalId;
}
}
/// <summary>
/// Gets the portal target. (Only on portal blocks)
/// </summary>
/// <value>
/// The portal target.
/// </value>
/// <exception cref="System.InvalidOperationException">This property can only be accessed on Portal blocks.</exception>
public uint PortalTarget
{
get
{
if (this.BlockType != BlockType.Portal)
throw new InvalidOperationException("This property can only be accessed on Portal blocks.");
return this._data.PortalTarget;
}
}
/// <summary>
/// Gets the portal rotation. (Only on portal blocks)
/// </summary>
/// <value>
/// The portal rotation.
/// </value>
/// <exception cref="System.InvalidOperationException">This property can only be accessed on Portal blocks.</exception>
public PortalRotation PortalRotation
{
get
{
if (this.BlockType != BlockType.Portal)
throw new InvalidOperationException("This property can only be accessed on Portal blocks.");
return this._data.PortalRotation;
}
}
/// <summary>
/// Gets the sound identifier. (Only on sound blocks)
/// </summary>
/// <value>
/// The sound identifier.
/// </value>
/// <exception cref="System.InvalidOperationException">This property can only be accessed on Sound blocks.</exception>
public uint SoundId
{
get
{
if (this.BlockType != BlockType.Sound)
throw new InvalidOperationException("This property can only be accessed on Sound blocks.");
return this._data.SoundId;
}
}
/// <summary>
/// Gets the piano identifier. (Only on piano blocks)
/// </summary>
/// <value>
/// The piano identifier.
/// </value>
/// <exception cref="System.InvalidOperationException">This property can only be accessed on Piano blocks.</exception>
public PianoId PianoId
{
get
{
if (!BlockUtils.IsPiano(this.Block))
throw new InvalidOperationException("This property can only be accessed on Piano blocks.");
return (PianoId)this.SoundId;
}
}
/// <summary>
/// Gets the percussion identifier. (Only on drum blocks)
/// </summary>
/// <value>
/// The percussion identifier.
/// </value>
/// <exception cref="System.InvalidOperationException">This property can only be accessed on Drum blocks.</exception>
public PercussionId PercussionId
{
get
{
if (!BlockUtils.IsDrum(this.Block))
throw new InvalidOperationException("This property can only be accessed on Drum blocks.");
return (PercussionId)this.SoundId;
}
}
/// <summary>
/// Gets the rotation. (Only on rotatable blocks)
/// </summary>
/// <value>
/// The rotation.
/// </value>
/// <exception cref="System.InvalidOperationException">This property can only be accessed on Rotatable blocks.</exception>
public uint Rotation
{
get
{
if (this.BlockType != BlockType.Rotatable)
throw new InvalidOperationException("This property can only be accessed on Rotatable blocks.");
return this._data.Rotation;
}
}
/// <summary>
/// Gets the spike rotation. (Only on spike blocks)
/// </summary>
/// <value>
/// The spike rotation.
/// </value>
/// <exception cref="System.InvalidOperationException">This property can only be accessed on Spike blocks.</exception>
public SpikeRotation SpikeRotation
{
get
{
if (!BlockUtils.IsSpike(this.Block))
throw new InvalidOperationException("This property can only be accessed on Spike blocks.");
return (SpikeRotation)this.Rotation;
}
}
/// <summary>
/// Gets the scifi straight rotation. (Only on scifi straight blocks)
/// </summary>
/// <value>
/// The scifi straight rotation.
/// </value>
/// <exception cref="System.InvalidOperationException">This property can only be accessed on SciFiStraight blocks.</exception>
public SciFiStraightRotation SciFiStraightRotation
{
get
{
if (!BlockUtils.IsSciFiStraight(this.Block))
throw new InvalidOperationException("This property can only be accessed on SciFiStraight blocks.");
return (SciFiStraightRotation)this.Rotation;
}
}
/// <summary>
/// Gets the scifi slope rotation. (Only on scifi slope blocks)
/// </summary>
/// <value>
/// The scifi slope rotation.
/// </value>
/// <exception cref="System.InvalidOperationException">This property can only be accessed on SciFiSlope blocks.</exception>
public SciFiSlopeRotation SciFiSlopeRotation
{
get
{
if (!BlockUtils.IsSciFiSlope(this.Block))
throw new InvalidOperationException("This property can only be accessed on SciFiSlope blocks.");
return (SciFiSlopeRotation)this.Rotation;
}
}
internal void SetBlock(Block block)
{
this.BlockType = BlockType.Normal;
this.Block = block;
this._data = new BlockData();
}
internal void SetCoinDoor(CoinDoorBlock block, uint coinsToCollect)
{
this.BlockType = BlockType.CoinDoor;
this.Block = (Block)block;
this._data = new BlockData
{
CoinsToCollect = coinsToCollect
};
}
internal void SetPurpleDoor(PurpleDoorBlock block, uint purpleId)
{
this.BlockType = BlockType.Purple;
this.Block = (Block)block;
this._data = new BlockData
{
PurpleId = purpleId
};
}
internal void SetDeathDoor(DeathDoorBlock block, uint deathsRequired)
{
this.BlockType = BlockType.Purple;
this.Block = (Block)block;
this._data = new BlockData
{
DeathsRequired = deathsRequired
};
}
internal void SetPortal(PortalBlock block, uint portalId, uint portalTarget, PortalRotation portalRotation)
{
this.BlockType = BlockType.Portal;
this.Block = (Block)block;
this._data = new BlockData
{
PortalId = portalId,
PortalTarget = portalTarget,
PortalRotation = portalRotation
};
}
internal void SetSound(SoundBlock block, uint soundId)
{
this.BlockType = BlockType.Sound;
this.Block = (Block)block;
this._data = new BlockData
{
SoundId = soundId
};
}
internal void SetRotatable(RotatableBlock block, uint rotation)
{
this.BlockType = BlockType.Rotatable;
this.Block = (Block)block;
this._data = new BlockData
{
Rotation = rotation
};
}
internal void SetSign(SignBlock block, string text)
{
this.BlockType = BlockType.Sign;
this.Block = (Block)block;
this._data = new BlockData
{
Text = text
};
}
internal void SetLabel(LabelBlock block, string text, string textColor)
{
this.BlockType = BlockType.Label;
this.Block = (Block)block;
this._data = new BlockData
{
Text = text,
TextColor = textColor
};
}
internal void SetWorldPortal(WorldPortalBlock block, string worldId)
{
this.BlockType = BlockType.WorldPortal;
this.Block = (Block)block;
this._data = new BlockData
{
WorldPortalTarget = worldId
};
}
/// <summary>
/// Determines whether the IBlockPlaceSendEvent has the same values as this block.
/// </summary>
/// <param name="other">The IBlockPlaceSendEvent to evaluate.</param>
/// <returns></returns>
/// <exception cref="System.NotSupportedException">The given send message is not supported.</exception>
public bool IsSame(IBlockPlaceSendEvent other)
{
if (other == null)
{
return false;
}
bool result = this.Block == other.Block;
if (other is BlockPlaceSendEvent)
{
return result;
}
var coinEvent = other as CoinDoorPlaceSendEvent;
if (coinEvent != null)
{
if (this._data.CoinsToCollect != coinEvent.CoinsToCollect)
result = false;
return result;
}
var signEvent = other as SignPlaceSendEvent;
if (signEvent != null)
{
if (this._data.Text != signEvent.Text)
result = false;
return result;
}
var labelEvent = other as LabelPlaceSendEvent;
if (labelEvent != null)
{
if (this._data.Text != labelEvent.Text)
result = false;
if (this._data.TextColor != labelEvent.TextColor)
result = false;
return result;
}
var deathDoor = other as DeathDoorPlaceSendEvent;
if (deathDoor != null)
{
if (this._data.DeathsRequired != deathDoor.DeathsRequired)
result = false;
return result;
}
var purpleDoor = other as PurpleDoorPlaceSendEvent;
if (purpleDoor != null)
{
if (this._data.PurpleId != purpleDoor.PurpleId)
result = false;
return result;
}
var worldPortalEvent = other as WorldPortalPlaceSendEvent;
if (worldPortalEvent != null)
{
if (this._data.WorldPortalTarget != worldPortalEvent.WorldPortalTarget)
result = false;
return result;
}
var rotatableEvent = other as RotatablePlaceSendEvent;
if (rotatableEvent != null)
{
if (this._data.Rotation != rotatableEvent.Rotation)
result = false;
return result;
}
var soundEvent = other as SoundPlaceSendEvent;
if (soundEvent != null)
{
if (this._data.SoundId != soundEvent.SoundId)
result = false;
return result;
}
var portalEvent = other as PortalPlaceSendEvent;
if (portalEvent != null)
{
if (this._data.PortalId != portalEvent.PortalId ||
this._data.PortalTarget != portalEvent.PortalTarget ||
this._data.PortalRotation != portalEvent.PortalRotation)
result = false;
return result;
}
throw new NotSupportedException("The given send message is not supported.");
}
/// <summary>
/// Creates an <see cref="IBlockPlaceSendEvent" /> object with this block's data.
/// </summary>
/// <returns></returns>
/// <exception cref="System.NotSupportedException">The given send message is not supported.</exception>
public IBlockPlaceSendEvent ToEvent()
{
switch (this.BlockType)
{
case BlockType.Normal:
return new BlockPlaceSendEvent(this.Layer, this.X, this.Y, this.Block);
case BlockType.CoinDoor:
return new CoinDoorPlaceSendEvent(this.Layer, this.X, this.Y, (CoinDoorBlock)this.Block,
this.CoinsToCollect);
case BlockType.Portal:
return new PortalPlaceSendEvent(this.Layer, this.X, this.Y, (PortalBlock)this.Block, this.PortalId,
this.PortalTarget, this.PortalRotation);
case BlockType.Sound:
return new SoundPlaceSendEvent(this.Layer, this.X, this.Y, (SoundBlock)this.Block, this.SoundId);
case BlockType.Sign:
return new SignPlaceSendEvent(this.Layer, this.X, this.Y, (SignBlock)this.Block, this.Text);
case BlockType.Label:
return new LabelPlaceSendEvent(this.Layer, this.X, this.Y, (LabelBlock)this.Block, this.Text, this.TextColor);
case BlockType.Rotatable:
return new RotatablePlaceSendEvent(this.Layer, this.X, this.Y, (RotatableBlock)this.Block,
this.Rotation);
case BlockType.WorldPortal:
return new WorldPortalPlaceSendEvent(this.Layer, this.X, this.Y, (WorldPortalBlock)this.Block,
this.WorldPortalTarget);
case BlockType.Death:
return new DeathDoorPlaceSendEvent(this.Layer, this.X, this.Y, (DeathDoorBlock)this.Block, this.DeathsRequired);
case BlockType.Purple:
return new PurpleDoorPlaceSendEvent(this.Layer, this.X, this.Y, (PurpleDoorBlock)this.Block, this.PurpleId);
default:
throw new NotSupportedException("The given send message is not supported.");
}
}
// ReSharper disable once UnusedMember.Local
private string DebuggerData()
{
switch (this.BlockType)
{
case BlockType.Normal:
return String.Format("Layer = {0}", this.Layer);
case BlockType.CoinDoor:
return String.Format("CoinsToCollect = {0}", this.CoinsToCollect);
case BlockType.Purple:
return String.Format("Purple ID = {0}", this.PurpleId);
case BlockType.Death:
return String.Format("Deaths Required = {0}", this.DeathsRequired);
case BlockType.Rotatable:
return String.Format("Rotation = {0}", this.Rotation);
case BlockType.Sound:
return String.Format("SoundId = {0}", this.SoundId);
case BlockType.Sign:
return String.Format("Text = {0}", this.Text);
case BlockType.Label:
return String.Format("Text = {0}, TextColor = {1}", this.Text, this.TextColor);
case BlockType.Portal:
return String.Format("Id = {0}, Target = {1}, Rotation = {2}", this.PortalId, this.PortalTarget,
this.PortalRotation);
case BlockType.WorldPortal:
return String.Format("Target = {0}", this.WorldPortalTarget);
default:
return String.Empty;
}
}
/// <summary>
/// Clones this instance.
/// </summary>
/// <returns></returns>
public WorldBlock Clone()
{
return new WorldBlock(this.MetadataPlatform, this.Layer, this.X, this.Y, this.Block)
{
_data = this._data.Clone(),
BlockType = this.BlockType
};
}
private struct BlockData
{
internal string Text { get; set; }
internal string TextColor { get; set; }
internal string WorldPortalTarget { get; set; }
internal uint CoinsToCollect { get; set; }
internal uint PurpleId { get; set; }
internal uint DeathsRequired { get; set; }
internal uint PortalId { get; set; }
internal uint PortalTarget { get; set; }
internal PortalRotation PortalRotation { get; set; }
internal uint SoundId { get; set; }
internal uint Rotation { get; set; }
internal BlockData Clone()
{
return new BlockData
{
Text = this.Text,
TextColor = this.TextColor,
WorldPortalTarget = this.WorldPortalTarget,
CoinsToCollect = this.CoinsToCollect,
PurpleId = this.PurpleId,
DeathsRequired = this.DeathsRequired,
PortalId = this.PortalId,
PortalTarget = this.PortalTarget,
PortalRotation = this.PortalRotation,
SoundId = this.SoundId,
Rotation = this.Rotation
};
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.RecoveryServices.SiteRecovery
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.RecoveryServices;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for ReplicationFabricsOperations.
/// </summary>
public static partial class ReplicationFabricsOperationsExtensions
{
/// <summary>
/// Renews certificate for the fabric.
/// </summary>
/// <remarks>
/// Renews the connection certificate for the ASR replication fabric.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// fabric name to renew certs for.
/// </param>
/// <param name='renewCertificate'>
/// Renew certificate input.
/// </param>
public static Fabric RenewCertificate(this IReplicationFabricsOperations operations, string fabricName, RenewCertificateInput renewCertificate)
{
return operations.RenewCertificateAsync(fabricName, renewCertificate).GetAwaiter().GetResult();
}
/// <summary>
/// Renews certificate for the fabric.
/// </summary>
/// <remarks>
/// Renews the connection certificate for the ASR replication fabric.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// fabric name to renew certs for.
/// </param>
/// <param name='renewCertificate'>
/// Renew certificate input.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Fabric> RenewCertificateAsync(this IReplicationFabricsOperations operations, string fabricName, RenewCertificateInput renewCertificate, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.RenewCertificateWithHttpMessagesAsync(fabricName, renewCertificate, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Perform failover of the process server.
/// </summary>
/// <remarks>
/// The operation to move replications from a process server to another process
/// server.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// The name of the fabric containing the process server.
/// </param>
/// <param name='failoverProcessServerRequest'>
/// The input to the failover process
/// server operation.
/// </param>
public static Fabric ReassociateGateway(this IReplicationFabricsOperations operations, string fabricName, FailoverProcessServerRequest failoverProcessServerRequest)
{
return operations.ReassociateGatewayAsync(fabricName, failoverProcessServerRequest).GetAwaiter().GetResult();
}
/// <summary>
/// Perform failover of the process server.
/// </summary>
/// <remarks>
/// The operation to move replications from a process server to another process
/// server.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// The name of the fabric containing the process server.
/// </param>
/// <param name='failoverProcessServerRequest'>
/// The input to the failover process
/// server operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Fabric> ReassociateGatewayAsync(this IReplicationFabricsOperations operations, string fabricName, FailoverProcessServerRequest failoverProcessServerRequest, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ReassociateGatewayWithHttpMessagesAsync(fabricName, failoverProcessServerRequest, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Checks the consistency of the ASR fabric.
/// </summary>
/// <remarks>
/// The operation to perform a consistency check on the fabric.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
public static Fabric CheckConsistency(this IReplicationFabricsOperations operations, string fabricName)
{
return operations.CheckConsistencyAsync(fabricName).GetAwaiter().GetResult();
}
/// <summary>
/// Checks the consistency of the ASR fabric.
/// </summary>
/// <remarks>
/// The operation to perform a consistency check on the fabric.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Fabric> CheckConsistencyAsync(this IReplicationFabricsOperations operations, string fabricName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CheckConsistencyWithHttpMessagesAsync(fabricName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the site.
/// </summary>
/// <remarks>
/// The operation to delete or remove an Azure Site Recovery fabric.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// ASR fabric to delete
/// </param>
public static void Delete(this IReplicationFabricsOperations operations, string fabricName)
{
operations.DeleteAsync(fabricName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the site.
/// </summary>
/// <remarks>
/// The operation to delete or remove an Azure Site Recovery fabric.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// ASR fabric to delete
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IReplicationFabricsOperations operations, string fabricName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(fabricName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets the details of an ASR fabric.
/// </summary>
/// <remarks>
/// Gets the details of an Azure Site Recovery fabric.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
public static Fabric Get(this IReplicationFabricsOperations operations, string fabricName)
{
return operations.GetAsync(fabricName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the details of an ASR fabric.
/// </summary>
/// <remarks>
/// Gets the details of an Azure Site Recovery fabric.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Fabric> GetAsync(this IReplicationFabricsOperations operations, string fabricName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(fabricName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates an Azure Site Recoery fabric.
/// </summary>
/// <remarks>
/// The operation to create an Azure Site Recovery fabric (for e.g. Hyper-V
/// site)
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// Name of the ASR fabric.
/// </param>
/// <param name='input'>
/// Fabric creation input.
/// </param>
public static Fabric Create(this IReplicationFabricsOperations operations, string fabricName, FabricCreationInput input)
{
return operations.CreateAsync(fabricName, input).GetAwaiter().GetResult();
}
/// <summary>
/// Creates an Azure Site Recoery fabric.
/// </summary>
/// <remarks>
/// The operation to create an Azure Site Recovery fabric (for e.g. Hyper-V
/// site)
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// Name of the ASR fabric.
/// </param>
/// <param name='input'>
/// Fabric creation input.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Fabric> CreateAsync(this IReplicationFabricsOperations operations, string fabricName, FabricCreationInput input, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateWithHttpMessagesAsync(fabricName, input, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Purges the site.
/// </summary>
/// <remarks>
/// The operation to purge(force delete) an Azure Site Recovery fabric.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// ASR fabric to purge.
/// </param>
public static void Purge(this IReplicationFabricsOperations operations, string fabricName)
{
operations.PurgeAsync(fabricName).GetAwaiter().GetResult();
}
/// <summary>
/// Purges the site.
/// </summary>
/// <remarks>
/// The operation to purge(force delete) an Azure Site Recovery fabric.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// ASR fabric to purge.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PurgeAsync(this IReplicationFabricsOperations operations, string fabricName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.PurgeWithHttpMessagesAsync(fabricName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets the list of ASR fabrics
/// </summary>
/// <remarks>
/// Gets a list of the Azure Site Recovery fabrics in the vault.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<Fabric> List(this IReplicationFabricsOperations operations)
{
return operations.ListAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the list of ASR fabrics
/// </summary>
/// <remarks>
/// Gets a list of the Azure Site Recovery fabrics in the vault.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Fabric>> ListAsync(this IReplicationFabricsOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Renews certificate for the fabric.
/// </summary>
/// <remarks>
/// Renews the connection certificate for the ASR replication fabric.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// fabric name to renew certs for.
/// </param>
/// <param name='renewCertificate'>
/// Renew certificate input.
/// </param>
public static Fabric BeginRenewCertificate(this IReplicationFabricsOperations operations, string fabricName, RenewCertificateInput renewCertificate)
{
return operations.BeginRenewCertificateAsync(fabricName, renewCertificate).GetAwaiter().GetResult();
}
/// <summary>
/// Renews certificate for the fabric.
/// </summary>
/// <remarks>
/// Renews the connection certificate for the ASR replication fabric.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// fabric name to renew certs for.
/// </param>
/// <param name='renewCertificate'>
/// Renew certificate input.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Fabric> BeginRenewCertificateAsync(this IReplicationFabricsOperations operations, string fabricName, RenewCertificateInput renewCertificate, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginRenewCertificateWithHttpMessagesAsync(fabricName, renewCertificate, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Perform failover of the process server.
/// </summary>
/// <remarks>
/// The operation to move replications from a process server to another process
/// server.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// The name of the fabric containing the process server.
/// </param>
/// <param name='failoverProcessServerRequest'>
/// The input to the failover process
/// server operation.
/// </param>
public static Fabric BeginReassociateGateway(this IReplicationFabricsOperations operations, string fabricName, FailoverProcessServerRequest failoverProcessServerRequest)
{
return operations.BeginReassociateGatewayAsync(fabricName, failoverProcessServerRequest).GetAwaiter().GetResult();
}
/// <summary>
/// Perform failover of the process server.
/// </summary>
/// <remarks>
/// The operation to move replications from a process server to another process
/// server.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// The name of the fabric containing the process server.
/// </param>
/// <param name='failoverProcessServerRequest'>
/// The input to the failover process
/// server operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Fabric> BeginReassociateGatewayAsync(this IReplicationFabricsOperations operations, string fabricName, FailoverProcessServerRequest failoverProcessServerRequest, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginReassociateGatewayWithHttpMessagesAsync(fabricName, failoverProcessServerRequest, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Checks the consistency of the ASR fabric.
/// </summary>
/// <remarks>
/// The operation to perform a consistency check on the fabric.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
public static Fabric BeginCheckConsistency(this IReplicationFabricsOperations operations, string fabricName)
{
return operations.BeginCheckConsistencyAsync(fabricName).GetAwaiter().GetResult();
}
/// <summary>
/// Checks the consistency of the ASR fabric.
/// </summary>
/// <remarks>
/// The operation to perform a consistency check on the fabric.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Fabric> BeginCheckConsistencyAsync(this IReplicationFabricsOperations operations, string fabricName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCheckConsistencyWithHttpMessagesAsync(fabricName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the site.
/// </summary>
/// <remarks>
/// The operation to delete or remove an Azure Site Recovery fabric.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// ASR fabric to delete
/// </param>
public static void BeginDelete(this IReplicationFabricsOperations operations, string fabricName)
{
operations.BeginDeleteAsync(fabricName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the site.
/// </summary>
/// <remarks>
/// The operation to delete or remove an Azure Site Recovery fabric.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// ASR fabric to delete
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IReplicationFabricsOperations operations, string fabricName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeleteWithHttpMessagesAsync(fabricName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Creates an Azure Site Recoery fabric.
/// </summary>
/// <remarks>
/// The operation to create an Azure Site Recovery fabric (for e.g. Hyper-V
/// site)
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// Name of the ASR fabric.
/// </param>
/// <param name='input'>
/// Fabric creation input.
/// </param>
public static Fabric BeginCreate(this IReplicationFabricsOperations operations, string fabricName, FabricCreationInput input)
{
return operations.BeginCreateAsync(fabricName, input).GetAwaiter().GetResult();
}
/// <summary>
/// Creates an Azure Site Recoery fabric.
/// </summary>
/// <remarks>
/// The operation to create an Azure Site Recovery fabric (for e.g. Hyper-V
/// site)
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// Name of the ASR fabric.
/// </param>
/// <param name='input'>
/// Fabric creation input.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Fabric> BeginCreateAsync(this IReplicationFabricsOperations operations, string fabricName, FabricCreationInput input, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateWithHttpMessagesAsync(fabricName, input, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Purges the site.
/// </summary>
/// <remarks>
/// The operation to purge(force delete) an Azure Site Recovery fabric.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// ASR fabric to purge.
/// </param>
public static void BeginPurge(this IReplicationFabricsOperations operations, string fabricName)
{
operations.BeginPurgeAsync(fabricName).GetAwaiter().GetResult();
}
/// <summary>
/// Purges the site.
/// </summary>
/// <remarks>
/// The operation to purge(force delete) an Azure Site Recovery fabric.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// ASR fabric to purge.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginPurgeAsync(this IReplicationFabricsOperations operations, string fabricName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginPurgeWithHttpMessagesAsync(fabricName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets the list of ASR fabrics
/// </summary>
/// <remarks>
/// Gets a list of the Azure Site Recovery fabrics in the vault.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Fabric> ListNext(this IReplicationFabricsOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the list of ASR fabrics
/// </summary>
/// <remarks>
/// Gets a list of the Azure Site Recovery fabrics in the vault.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Fabric>> ListNextAsync(this IReplicationFabricsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Runtime.Serialization;
using System.Security.Permissions;
namespace System.Management
{
[Serializable]
internal sealed class IWbemClassObjectFreeThreaded : IDisposable, ISerializable
{
private readonly static string name;
public static Guid IID_IWbemClassObject;
private IntPtr pWbemClassObject;
private const string SerializationBlobName = "flatWbemClassObject";
static IWbemClassObjectFreeThreaded()
{
IWbemClassObjectFreeThreaded.name = typeof(IWbemClassObjectFreeThreaded).FullName;
IWbemClassObjectFreeThreaded.IID_IWbemClassObject = new Guid("DC12A681-737F-11CF-884D-00AA004B2E24");
}
public IWbemClassObjectFreeThreaded(IntPtr pWbemClassObject)
{
this.pWbemClassObject = IntPtr.Zero;
this.pWbemClassObject = pWbemClassObject;
}
public IWbemClassObjectFreeThreaded(SerializationInfo info, StreamingContext context)
{
this.pWbemClassObject = IntPtr.Zero;
byte[] value = info.GetValue("flatWbemClassObject", typeof(byte[])) as byte[];
if (value != null)
{
this.DeserializeFromBlob(value);
return;
}
else
{
throw new SerializationException();
}
}
public int BeginEnumeration_(int lEnumFlags)
{
if (this.pWbemClassObject != IntPtr.Zero)
{
int num = WmiNetUtilsHelper.BeginEnumeration_f(8, this.pWbemClassObject, lEnumFlags);
GC.KeepAlive(this);
return num;
}
else
{
throw new ObjectDisposedException(IWbemClassObjectFreeThreaded.name);
}
}
public int BeginMethodEnumeration_(int lEnumFlags)
{
if (this.pWbemClassObject != IntPtr.Zero)
{
int num = WmiNetUtilsHelper.BeginMethodEnumeration_f(22, this.pWbemClassObject, lEnumFlags);
GC.KeepAlive(this);
return num;
}
else
{
throw new ObjectDisposedException(IWbemClassObjectFreeThreaded.name);
}
}
public int Clone_(out IWbemClassObjectFreeThreaded ppCopy)
{
IntPtr intPtr;
if (this.pWbemClassObject != IntPtr.Zero)
{
int cloneF = WmiNetUtilsHelper.Clone_f(12, this.pWbemClassObject, out intPtr);
if (cloneF >= 0)
{
ppCopy = new IWbemClassObjectFreeThreaded(intPtr);
}
else
{
ppCopy = null;
}
GC.KeepAlive(this);
return cloneF;
}
else
{
throw new ObjectDisposedException(IWbemClassObjectFreeThreaded.name);
}
}
/*
[DllImport("ole32.dll", CharSet=CharSet.None)]
private static extern void CoMarshalInterface(IStream pStm, ref Guid riid, IntPtr Unk, uint dwDestContext, IntPtr pvDestContext, uint mshlflags);
*/
private static void CoMarshalInterface (IStream pStm, ref Guid riid, IntPtr Unk, uint dwDestContext, IntPtr pvDestContext, uint mshlflags)
{
}
public int CompareTo_ (bool lFlags, IWbemClassObjectFreeThreaded pCompareTo)
{
return CompareTo_ (lFlags ? 1 : 0, pCompareTo);
}
public int CompareTo_(int lFlags, IWbemClassObjectFreeThreaded pCompareTo)
{
if (this.pWbemClassObject != IntPtr.Zero)
{
int num = WmiNetUtilsHelper.CompareTo_f(16, this.pWbemClassObject, lFlags, pCompareTo.pWbemClassObject);
GC.KeepAlive(this);
return num;
}
else
{
throw new ObjectDisposedException(IWbemClassObjectFreeThreaded.name);
}
}
/*
[DllImport("ole32.dll", CharSet=CharSet.None)]
private static extern IntPtr CoUnmarshalInterface(IStream pStm, ref Guid riid);
[DllImport("ole32.dll", CharSet=CharSet.None)]
private static extern IStream CreateStreamOnHGlobal(IntPtr hGlobal, int fDeleteOnRelease);
*/
private static IntPtr CoUnmarshalInterface(IStream pStm, ref Guid riid)
{
return IntPtr.Zero;
}
private static IStream CreateStreamOnHGlobal(IntPtr hGlobal, int fDeleteOnRelease)
{
return null;
}
public int Delete_(string wszName)
{
if (this.pWbemClassObject != IntPtr.Zero)
{
int num = WmiNetUtilsHelper.Delete_f(6, this.pWbemClassObject, wszName);
GC.KeepAlive(this);
return num;
}
else
{
throw new ObjectDisposedException(IWbemClassObjectFreeThreaded.name);
}
}
public int DeleteMethod_(string wszName)
{
if (this.pWbemClassObject != IntPtr.Zero)
{
int num = WmiNetUtilsHelper.DeleteMethod_f(21, this.pWbemClassObject, wszName);
GC.KeepAlive(this);
return num;
}
else
{
throw new ObjectDisposedException(IWbemClassObjectFreeThreaded.name);
}
}
private void DeserializeFromBlob(byte[] rg)
{
IntPtr zero = IntPtr.Zero;
IStream stream = null;
try
{
this.pWbemClassObject = IntPtr.Zero;
zero = Marshal.AllocHGlobal((int)rg.Length);
Marshal.Copy(rg, 0, zero, (int)rg.Length);
stream = IWbemClassObjectFreeThreaded.CreateStreamOnHGlobal(zero, 0);
this.pWbemClassObject = IWbemClassObjectFreeThreaded.CoUnmarshalInterface(stream, ref IWbemClassObjectFreeThreaded.IID_IWbemClassObject);
}
finally
{
if (stream != null)
{
Marshal.ReleaseComObject(stream);
}
if (zero != IntPtr.Zero)
{
Marshal.FreeHGlobal(zero);
}
}
}
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public void Dispose()
{
this.Dispose_(false);
}
private void Dispose_(bool finalization)
{
if (this.pWbemClassObject != IntPtr.Zero)
{
if (Marshal.IsComObject (this.pWbemClassObject)) {
Marshal.Release(this.pWbemClassObject);
}
this.pWbemClassObject = IntPtr.Zero;
}
GC.SuppressFinalize(this);
}
public int EndEnumeration_()
{
if (this.pWbemClassObject != IntPtr.Zero)
{
int endEnumerationF = WmiNetUtilsHelper.EndEnumeration_f(10, this.pWbemClassObject);
GC.KeepAlive(this);
return endEnumerationF;
}
else
{
throw new ObjectDisposedException(IWbemClassObjectFreeThreaded.name);
}
}
public int EndMethodEnumeration_()
{
if (this.pWbemClassObject != IntPtr.Zero)
{
int endMethodEnumerationF = WmiNetUtilsHelper.EndMethodEnumeration_f(24, this.pWbemClassObject);
GC.KeepAlive(this);
return endMethodEnumerationF;
}
else
{
throw new ObjectDisposedException(IWbemClassObjectFreeThreaded.name);
}
}
~IWbemClassObjectFreeThreaded()
{
try
{
this.Dispose_(true);
}
finally
{
//this.Finalize();
}
}
public int Get_(string wszName, int lFlags, ref object pVal, ref int pType, ref int plFlavor)
{
if (this.pWbemClassObject != IntPtr.Zero)
{
int num = WmiNetUtilsHelper.Get_f(4, this.pWbemClassObject, wszName, lFlags, out pVal, out pType, out plFlavor);
if (num == -2147217393 && string.Compare(wszName, "__path", StringComparison.OrdinalIgnoreCase) == 0)
{
num = 0;
pType = 8;
plFlavor = 64;
pVal = DBNull.Value;
}
GC.KeepAlive(this);
return num;
}
else
{
throw new ObjectDisposedException(IWbemClassObjectFreeThreaded.name);
}
}
/*
[DllImport("ole32.dll", CharSet=CharSet.None)]
private static extern IntPtr GetHGlobalFromStream(IStream pstm);
*/
private static IntPtr GetHGlobalFromStream (IStream pstm)
{
return IntPtr.Zero;
}
public int GetMethod_(string wszName, int lFlags, out IWbemClassObjectFreeThreaded ppInSignature, out IWbemClassObjectFreeThreaded ppOutSignature)
{
IntPtr intPtr;
IntPtr intPtr1;
if (this.pWbemClassObject != IntPtr.Zero)
{
int num = WmiNetUtilsHelper.GetMethod_f(19, this.pWbemClassObject, wszName, lFlags, out intPtr, out intPtr1);
ppInSignature = null;
ppOutSignature = null;
if (num >= 0)
{
if (intPtr != IntPtr.Zero)
{
ppInSignature = new IWbemClassObjectFreeThreaded(intPtr);
}
if (intPtr1 != IntPtr.Zero)
{
ppOutSignature = new IWbemClassObjectFreeThreaded(intPtr1);
}
}
GC.KeepAlive(this);
return num;
}
else
{
throw new ObjectDisposedException(IWbemClassObjectFreeThreaded.name);
}
}
public int GetMethodOrigin_(string wszMethodName, out string pstrClassName)
{
if (this.pWbemClassObject != IntPtr.Zero)
{
int num = WmiNetUtilsHelper.GetMethodOrigin_f(26, this.pWbemClassObject, wszMethodName, out pstrClassName);
GC.KeepAlive(this);
return num;
}
else
{
throw new ObjectDisposedException(IWbemClassObjectFreeThreaded.name);
}
}
public int GetMethodQualifierSet_(string wszMethod, out IWbemQualifierSetFreeThreaded ppQualSet)
{
IntPtr intPtr;
if (this.pWbemClassObject != IntPtr.Zero)
{
int num = WmiNetUtilsHelper.GetMethodQualifierSet_f(25, this.pWbemClassObject, wszMethod, out intPtr);
if (num >= 0)
{
ppQualSet = new IWbemQualifierSetFreeThreaded(intPtr);
}
else
{
ppQualSet = null;
}
GC.KeepAlive(this);
return num;
}
else
{
throw new ObjectDisposedException(IWbemClassObjectFreeThreaded.name);
}
}
public int GetNames_(string wszQualifierName, int lFlags, ref object pQualifierVal, out string[] pNames)
{
if (this.pWbemClassObject != IntPtr.Zero)
{
int num = WmiNetUtilsHelper.GetNames_f(7, this.pWbemClassObject, wszQualifierName, lFlags, ref pQualifierVal, out pNames);
GC.KeepAlive(this);
return num;
}
else
{
throw new ObjectDisposedException(IWbemClassObjectFreeThreaded.name);
}
}
public int GetObjectText_(int lFlags, out string pstrObjectText)
{
if (this.pWbemClassObject != IntPtr.Zero)
{
int num = WmiNetUtilsHelper.GetObjectText_f(13, this.pWbemClassObject, lFlags, out pstrObjectText);
GC.KeepAlive(this);
return num;
}
else
{
throw new ObjectDisposedException(IWbemClassObjectFreeThreaded.name);
}
}
public int GetPropertyOrigin_(string wszName, out string pstrClassName)
{
if (this.pWbemClassObject != IntPtr.Zero)
{
int num = WmiNetUtilsHelper.GetPropertyOrigin_f(17, this.pWbemClassObject, wszName, out pstrClassName);
GC.KeepAlive(this);
return num;
}
else
{
throw new ObjectDisposedException(IWbemClassObjectFreeThreaded.name);
}
}
public int GetPropertyQualifierSet_(string wszProperty, out IWbemQualifierSetFreeThreaded ppQualSet)
{
IntPtr intPtr;
if (this.pWbemClassObject != IntPtr.Zero)
{
int num = WmiNetUtilsHelper.GetPropertyQualifierSet_f(11, this.pWbemClassObject, wszProperty, out intPtr);
if (num >= 0)
{
ppQualSet = new IWbemQualifierSetFreeThreaded(intPtr);
}
else
{
ppQualSet = null;
}
GC.KeepAlive(this);
return num;
}
else
{
throw new ObjectDisposedException(IWbemClassObjectFreeThreaded.name);
}
}
public int GetQualifierSet_(out IWbemQualifierSetFreeThreaded ppQualSet)
{
IntPtr intPtr;
if (this.pWbemClassObject != IntPtr.Zero)
{
int getQualifierSetF = WmiNetUtilsHelper.GetQualifierSet_f(3, this.pWbemClassObject, out intPtr);
if (getQualifierSetF >= 0)
{
ppQualSet = new IWbemQualifierSetFreeThreaded(intPtr);
}
else
{
ppQualSet = null;
}
GC.KeepAlive(this);
return getQualifierSetF;
}
else
{
throw new ObjectDisposedException(IWbemClassObjectFreeThreaded.name);
}
}
private static IntPtr GlobalLock(IntPtr hGlobal)
{
return hGlobal;
}
private static int GlobalUnlock(IntPtr pData)
{
return 0;
}
public int InheritsFrom_(string strAncestor)
{
if (this.pWbemClassObject != IntPtr.Zero)
{
int num = WmiNetUtilsHelper.InheritsFrom_f(18, this.pWbemClassObject, strAncestor);
GC.KeepAlive(this);
return num;
}
else
{
throw new ObjectDisposedException(IWbemClassObjectFreeThreaded.name);
}
}
public int Next_(int lFlags, ref string strName, ref object pVal, ref int pType, ref int plFlavor)
{
if (this.pWbemClassObject != IntPtr.Zero)
{
pVal = null;
strName = null;
int num = WmiNetUtilsHelper.Next_f(9, this.pWbemClassObject, lFlags, out strName, out pVal, out pType, out plFlavor);
GC.KeepAlive(this);
return num;
}
else
{
throw new ObjectDisposedException(IWbemClassObjectFreeThreaded.name);
}
}
public int NextMethod_(int lFlags, out string pstrName, out IWbemClassObjectFreeThreaded ppInSignature, out IWbemClassObjectFreeThreaded ppOutSignature)
{
IntPtr intPtr;
IntPtr intPtr1;
if (this.pWbemClassObject != IntPtr.Zero)
{
int num = WmiNetUtilsHelper.NextMethod_f(23, this.pWbemClassObject, lFlags, out pstrName, out intPtr, out intPtr1);
ppInSignature = null;
ppOutSignature = null;
if (num >= 0)
{
if (intPtr != IntPtr.Zero)
{
ppInSignature = new IWbemClassObjectFreeThreaded(intPtr);
}
if (intPtr1 != IntPtr.Zero)
{
ppOutSignature = new IWbemClassObjectFreeThreaded(intPtr1);
}
}
GC.KeepAlive(this);
return num;
}
else
{
throw new ObjectDisposedException(IWbemClassObjectFreeThreaded.name);
}
}
public static implicit operator IntPtr(IWbemClassObjectFreeThreaded wbemClassObject)
{
if (wbemClassObject != null)
{
return wbemClassObject.pWbemClassObject;
}
else
{
return IntPtr.Zero;
}
}
public int Put_(string wszName, int lFlags, ref object pVal, int Type)
{
if (this.pWbemClassObject != IntPtr.Zero)
{
int num = WmiNetUtilsHelper.Put_f(5, this.pWbemClassObject, wszName, lFlags, ref pVal, Type);
GC.KeepAlive(this);
return num;
}
else
{
throw new ObjectDisposedException(IWbemClassObjectFreeThreaded.name);
}
}
public int PutMethod_(string wszName, int lFlags, IWbemClassObjectFreeThreaded pInSignature, IWbemClassObjectFreeThreaded pOutSignature)
{
if (this.pWbemClassObject != IntPtr.Zero)
{
int num = WmiNetUtilsHelper.PutMethod_f(20, this.pWbemClassObject, wszName, lFlags, pInSignature, pOutSignature);
GC.KeepAlive(this);
return num;
}
else
{
throw new ObjectDisposedException(IWbemClassObjectFreeThreaded.name);
}
}
private byte[] SerializeToBlob()
{
System.Runtime.InteropServices.ComTypes.STATSTG sTATSTG;
byte[] numArray = null;
IStream stream = null;
IntPtr zero = IntPtr.Zero;
try
{
stream = IWbemClassObjectFreeThreaded.CreateStreamOnHGlobal(IntPtr.Zero, 1);
IWbemClassObjectFreeThreaded.CoMarshalInterface(stream, ref IWbemClassObjectFreeThreaded.IID_IWbemClassObject, this.pWbemClassObject, 2, IntPtr.Zero, 2);
stream.Stat(out sTATSTG, 0);
numArray = new byte[sTATSTG.cbSize];
zero = IWbemClassObjectFreeThreaded.GlobalLock(IWbemClassObjectFreeThreaded.GetHGlobalFromStream(stream));
Marshal.Copy(zero, numArray, 0, (int)sTATSTG.cbSize);
}
finally
{
if (zero != IntPtr.Zero)
{
IWbemClassObjectFreeThreaded.GlobalUnlock(zero);
}
if (stream != null)
{
Marshal.ReleaseComObject(stream);
}
}
GC.KeepAlive(this);
return numArray;
}
public int SpawnDerivedClass_(int lFlags, out IWbemClassObjectFreeThreaded ppNewClass)
{
IntPtr intPtr;
if (this.pWbemClassObject != IntPtr.Zero)
{
int num = WmiNetUtilsHelper.SpawnDerivedClass_f(14, this.pWbemClassObject, lFlags, out intPtr);
if (num >= 0)
{
ppNewClass = new IWbemClassObjectFreeThreaded(intPtr);
}
else
{
ppNewClass = null;
}
GC.KeepAlive(this);
return num;
}
else
{
throw new ObjectDisposedException(IWbemClassObjectFreeThreaded.name);
}
}
public int SpawnInstance_(int lFlags, out IWbemClassObjectFreeThreaded ppNewInstance)
{
IntPtr intPtr;
if (this.pWbemClassObject != IntPtr.Zero)
{
int num = WmiNetUtilsHelper.SpawnInstance_f(15, this.pWbemClassObject, lFlags, out intPtr);
if (num >= 0)
{
ppNewInstance = new IWbemClassObjectFreeThreaded(intPtr);
}
else
{
ppNewInstance = null;
}
GC.KeepAlive(this);
return num;
}
else
{
throw new ObjectDisposedException(IWbemClassObjectFreeThreaded.name);
}
}
[SecurityPermission(SecurityAction.Demand, SerializationFormatter=true)]
void System.Runtime.Serialization.ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("flatWbemClassObject", this.SerializeToBlob());
}
private enum MSHCTX
{
MSHCTX_LOCAL,
MSHCTX_NOSHAREDMEM,
MSHCTX_DIFFERENTMACHINE,
MSHCTX_INPROC
}
private enum MSHLFLAGS
{
MSHLFLAGS_NORMAL,
MSHLFLAGS_TABLESTRONG,
MSHLFLAGS_TABLEWEAK,
MSHLFLAGS_NOPING
}
private enum STATFLAG
{
STATFLAG_DEFAULT,
STATFLAG_NONAME
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Audio.Track;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Utils;
using osu.Framework.Screens;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.IO.Archives;
using osu.Game.Overlays;
using osu.Game.Screens.Backgrounds;
using osu.Game.Skinning;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Screens.Menu
{
public abstract class IntroScreen : StartupScreen
{
/// <summary>
/// Whether we have loaded the menu previously.
/// </summary>
public bool DidLoadMenu { get; private set; }
/// <summary>
/// A hash used to find the associated beatmap if already imported.
/// </summary>
protected abstract string BeatmapHash { get; }
/// <summary>
/// A source file to use as an import source if the intro beatmap is not yet present.
/// Should be within the "Tracks" namespace of game resources.
/// </summary>
protected abstract string BeatmapFile { get; }
protected IBindable<bool> MenuVoice { get; private set; }
protected IBindable<bool> MenuMusic { get; private set; }
private WorkingBeatmap initialBeatmap;
protected ITrack Track { get; private set; }
private const int exit_delay = 3000;
private Sample seeya;
protected virtual string SeeyaSampleName => "Intro/seeya";
private LeasedBindable<WorkingBeatmap> beatmap;
private MainMenu mainMenu;
[Resolved]
private AudioManager audio { get; set; }
[Resolved]
private MusicController musicController { get; set; }
/// <summary>
/// Whether the <see cref="Track"/> is provided by osu! resources, rather than a user beatmap.
/// Only valid during or after <see cref="LogoArriving"/>.
/// </summary>
protected bool UsingThemedIntro { get; private set; }
[BackgroundDependencyLoader]
private void load(OsuConfigManager config, SkinManager skinManager, BeatmapManager beatmaps, Framework.Game game)
{
// prevent user from changing beatmap while the intro is still runnning.
beatmap = Beatmap.BeginLease(false);
MenuVoice = config.GetBindable<bool>(OsuSetting.MenuVoice);
MenuMusic = config.GetBindable<bool>(OsuSetting.MenuMusic);
seeya = audio.Samples.Get(SeeyaSampleName);
BeatmapSetInfo setInfo = null;
// if the user has requested not to play theme music, we should attempt to find a random beatmap from their collection.
if (!MenuMusic.Value)
{
var sets = beatmaps.GetAllUsableBeatmapSets(IncludedDetails.Minimal);
if (sets.Count > 0)
{
setInfo = beatmaps.QueryBeatmapSet(s => s.ID == sets[RNG.Next(0, sets.Count - 1)].ID);
initialBeatmap = beatmaps.GetWorkingBeatmap(setInfo.Beatmaps[0]);
}
}
// we generally want a song to be playing on startup, so use the intro music even if a user has specified not to if no other track is available.
if (setInfo == null)
{
if (!loadThemedIntro())
{
// if we detect that the theme track or beatmap is unavailable this is either first startup or things are in a bad state.
// this could happen if a user has nuked their files store. for now, reimport to repair this.
var import = beatmaps.Import(new ZipArchiveReader(game.Resources.GetStream($"Tracks/{BeatmapFile}"), BeatmapFile)).Result;
import.Protected = true;
beatmaps.Update(import);
loadThemedIntro();
}
}
bool loadThemedIntro()
{
setInfo = beatmaps.QueryBeatmapSet(b => b.Hash == BeatmapHash);
if (setInfo == null)
return false;
return (initialBeatmap = beatmaps.GetWorkingBeatmap(setInfo.Beatmaps[0])) != null;
}
}
public override void OnResuming(IScreen last)
{
this.FadeIn(300);
double fadeOutTime = exit_delay;
var track = musicController.CurrentTrack;
// ensure the track doesn't change or loop as we are exiting.
track.Looping = false;
Beatmap.Disabled = true;
// we also handle the exit transition.
if (MenuVoice.Value)
{
seeya.Play();
// if playing the outro voice, we have more time to have fun with the background track.
// initially fade to almost silent then ramp out over the remaining time.
const double initial_fade = 200;
track
.VolumeTo(0.03f, initial_fade).Then()
.VolumeTo(0, fadeOutTime - initial_fade, Easing.In);
}
else
{
fadeOutTime = 500;
// if outro voice is turned off, just do a simple fade out.
track.VolumeTo(0, fadeOutTime, Easing.Out);
}
//don't want to fade out completely else we will stop running updates.
Game.FadeTo(0.01f, fadeOutTime).OnComplete(_ => this.Exit());
base.OnResuming(last);
}
public override void OnSuspending(IScreen next)
{
base.OnSuspending(next);
initialBeatmap = null;
}
protected override BackgroundScreen CreateBackground() => new BackgroundScreenBlack();
protected void StartTrack()
{
// Only start the current track if it is the menu music. A beatmap's track is started when entering the Main Menu.
if (UsingThemedIntro)
Track.Start();
}
protected override void LogoArriving(OsuLogo logo, bool resuming)
{
base.LogoArriving(logo, resuming);
logo.Colour = Color4.White;
logo.Triangles = false;
logo.Ripple = false;
if (!resuming)
{
beatmap.Value = initialBeatmap;
Track = initialBeatmap.Track;
UsingThemedIntro = !initialBeatmap.Track.IsDummyDevice;
// ensure the track starts at maximum volume
musicController.CurrentTrack.FinishTransforms();
logo.MoveTo(new Vector2(0.5f));
logo.ScaleTo(Vector2.One);
logo.Hide();
}
else
{
const int quick_appear = 350;
var initialMovementTime = logo.Alpha > 0.2f ? quick_appear : 0;
logo.MoveTo(new Vector2(0.5f), initialMovementTime, Easing.OutQuint);
logo
.ScaleTo(1, initialMovementTime, Easing.OutQuint)
.FadeIn(quick_appear, Easing.OutQuint)
.Then()
.RotateTo(20, exit_delay * 1.5f)
.FadeOut(exit_delay);
}
}
protected void PrepareMenuLoad() => LoadComponentAsync(mainMenu = new MainMenu());
protected void LoadMenu()
{
beatmap.Return();
DidLoadMenu = true;
this.Push(mainMenu);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Text.Tests
{
public class DecoderConvert2Decoder : Decoder
{
private Decoder _decoder = null;
public DecoderConvert2Decoder()
{
_decoder = Encoding.UTF8.GetDecoder();
}
public override int GetCharCount(byte[] bytes, int index, int count)
{
return _decoder.GetCharCount(bytes, index, count);
}
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
{
return _decoder.GetChars(bytes, byteIndex, byteCount, chars, charIndex);
}
public override void Reset()
{
_decoder.Reset();
}
}
// Convert(System.Byte[],System.Int32,System.Int32,System.Char[],System.Int32,System.Int32,System.Boolean,System.Int32@,System.Int32@,System.Boolean@)
public class DecoderConvert2
{
private const int c_SIZE_OF_ARRAY = 127;
private readonly RandomDataGenerator _generator = new RandomDataGenerator();
// PosTest1: Call Convert to convert an arbitrary byte array to character array by using ASCII decoder
[Fact]
public void PosTest1()
{
Decoder decoder = Encoding.UTF8.GetDecoder();
char[] chars = new char[c_SIZE_OF_ARRAY];
byte[] bytes = new byte[c_SIZE_OF_ARRAY];
for (int i = 0; i < bytes.Length; ++i)
{
bytes[i] = _generator.GetByte(-55);
}
int bytesUsed;
int charsUsed;
bool completed;
decoder.Convert(bytes, 0, bytes.Length, chars, 0, chars.Length, true, out bytesUsed, out charsUsed, out completed);
decoder.Reset();
decoder.Convert(bytes, 0, bytes.Length, chars, 0, chars.Length, false, out bytesUsed, out charsUsed, out completed);
decoder.Reset();
}
// PosTest2: Call Convert to convert an arbitrary byte array to character array by using Unicode decoder"
[Fact]
public void PosTest2()
{
Decoder decoder = Encoding.Unicode.GetDecoder();
char[] chars = new char[c_SIZE_OF_ARRAY];
byte[] bytes = new byte[c_SIZE_OF_ARRAY * 2];
for (int i = 0; i < bytes.Length; ++i)
{
bytes[i] = _generator.GetByte(-55);
}
int bytesUsed;
int charsUsed;
bool completed;
decoder.Convert(bytes, 0, bytes.Length, chars, 0, chars.Length, true, out bytesUsed, out charsUsed, out completed);
decoder.Reset();
decoder.Convert(bytes, 0, bytes.Length, chars, 0, chars.Length, false, out bytesUsed, out charsUsed, out completed);
decoder.Reset();
}
// PosTest3: Call Convert to convert a ASCII byte array to character array by using ASCII decoder
[Fact]
public void PosTest3()
{
Decoder decoder = Encoding.UTF8.GetDecoder();
char[] chars = new char[c_SIZE_OF_ARRAY];
byte[] bytes = new byte[c_SIZE_OF_ARRAY];
char[] expected = new char[c_SIZE_OF_ARRAY];
for (int i = 0; i < bytes.Length; ++i)
{
bytes[i] = (byte)i;
}
for (int i = 0; i < expected.Length; ++i)
{
expected[i] = (char)('\0' + i);
}
VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, chars.Length, true, bytes.Length, chars.Length, true, expected, "003.1");
decoder.Reset();
VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, chars.Length, false, bytes.Length, chars.Length, true, expected, "003.2");
decoder.Reset();
}
// PosTest4: Call Convert to convert a ASCII byte array with user implemented decoder
[Fact]
public void PosTest4()
{
byte[] bytes = new byte[c_SIZE_OF_ARRAY];
char[] chars = new char[bytes.Length];
char[] expected = new char[bytes.Length];
for (int i = 0; i < bytes.Length; ++i)
{
bytes[i] = (byte)i;
}
for (int i = 0; i < expected.Length; ++i)
{
expected[i] = (char)('\0' + i);
}
Decoder decoder = new DecoderConvert2Decoder();
VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, chars.Length, true, bytes.Length, chars.Length, true, expected, "004.1");
decoder.Reset();
VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, chars.Length, false, bytes.Length, chars.Length, true, expected, "004.2");
decoder.Reset();
}
// PosTest5: Call Convert to convert partial of a ASCII byte array with ASCII decoder
[Fact]
public void PosTest5()
{
byte[] bytes = new byte[c_SIZE_OF_ARRAY];
char[] chars = new char[bytes.Length];
Decoder decoder = Encoding.UTF8.GetDecoder();
for (int i = 0; i < bytes.Length; ++i)
{
bytes[i] = (byte)i;
}
VerificationHelper(decoder, bytes, 0, 1, chars, 0, 1, false, 1, 1, true, "005.1");
decoder.Reset();
VerificationHelper(decoder, bytes, 0, 1, chars, 0, 1, true, 1, 1, true, "005.2");
decoder.Reset();
// Verify maxBytes is large than character count
VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, chars.Length - 1, false, bytes.Length - 1, chars.Length - 1, false, "005.3");
decoder.Reset();
VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, chars.Length - 1, true, bytes.Length - 1, chars.Length - 1, false, "005.4");
decoder.Reset();
}
// PosTest6: Call Convert to convert a ASCII character array with Unicode encoder
[Fact]
public void PosTest6()
{
byte[] bytes = new byte[c_SIZE_OF_ARRAY];
char[] chars = new char[bytes.Length];
for (int i = 0; i < bytes.Length; ++i)
{
bytes[i] = (byte)i;
}
Decoder decoder = Encoding.Unicode.GetDecoder();
VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, chars.Length, false, bytes.Length, chars.Length / 2, true, "006.1");
decoder.Reset();
// There will be 1 byte left unconverted after previous statement, and set flush = false should left this 1 byte in the buffer.
VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, chars.Length, true, bytes.Length, chars.Length / 2 + 1, true, "006.2");
decoder.Reset();
}
// PosTest7: Call Convert to convert partial of a ASCII character array with Unicode encoder
[Fact]
public void PosTest7()
{
byte[] bytes = new byte[c_SIZE_OF_ARRAY];
char[] chars = new char[bytes.Length];
Decoder decoder = Encoding.Unicode.GetDecoder();
for (int i = 0; i < bytes.Length; ++i)
{
bytes[i] = (byte)i;
}
VerificationHelper(decoder, bytes, 0, 2, chars, 0, 1, false, 2, 1, true, "007.1");
decoder.Reset();
VerificationHelper(decoder, bytes, 0, 2, chars, 0, 1, true, 2, 1, true, "007.2");
decoder.Reset();
VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, 1, false, 2, 1, false, "007.3");
decoder.Reset();
VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, 1, true, 2, 1, false, "007.4");
decoder.Reset();
}
// PosTest8: Call Convert to convert a Unicode character array with Unicode encoder
[Fact]
public void PosTest8()
{
char[] expected = "\u8FD9\u4E2A\u4E00\u4E2A\u6D4B\u8BD5".ToCharArray();
byte[] bytes = new byte[] {
217,
143,
42,
78,
0,
78,
42,
78,
75,
109,
213,
139
};
char[] chars = new char[expected.Length];
Decoder decoder = Encoding.Unicode.GetDecoder();
VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, chars.Length, false, bytes.Length, chars.Length, true, expected, "008.1");
decoder.Reset();
VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, chars.Length, true, bytes.Length, chars.Length, true, expected, "008.2");
decoder.Reset();
}
// PosTest9: Call Convert to convert partial of a Unicode character array with Unicode encoder
[Fact]
public void PosTest9()
{
char[] expected = "\u8FD9".ToCharArray();
char[] chars = new char[expected.Length];
byte[] bytes = new byte[] {
217,
143,
42,
78,
0,
78,
42,
78,
75,
109,
213,
139
};
Decoder decoder = Encoding.Unicode.GetDecoder();
VerificationHelper(decoder, bytes, 0, 2, chars, 0, 1, false, 2, 1, true, expected, "009.1");
decoder.Reset();
VerificationHelper(decoder, bytes, 0, 2, chars, 0, 1, true, 2, 1, true, expected, "009.2");
decoder.Reset();
VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, 1, false, 2, 1, false, expected, "009.3");
decoder.Reset();
VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, 1, true, 2, 1, false, expected, "009.4");
decoder.Reset();
}
// PosTest10: Call Convert with ASCII decoder and convert nothing
[Fact]
public void PosTest10()
{
byte[] bytes = new byte[c_SIZE_OF_ARRAY];
char[] chars = new char[bytes.Length];
Decoder decoder = Encoding.Unicode.GetDecoder();
for (int i = 0; i < bytes.Length; ++i)
{
bytes[i] = (byte)i;
}
VerificationHelper(decoder, bytes, 0, 0, chars, 0, 0, false, 0, 0, true, "010.1");
decoder.Reset();
VerificationHelper(decoder, bytes, 0, 0, chars, 0, chars.Length, true, 0, 0, true, "010.2");
decoder.Reset();
}
private void VerificationHelper(Decoder decoder, byte[] bytes,
int byteIndex,
int byteCount,
char[] chars,
int charIndex,
int charCount,
bool flush,
int desiredBytesUsed,
int desiredCharsUsed,
bool desiredCompleted,
string errorno)
{
int bytesUsed;
int charsUsed;
bool completed;
decoder.Convert(bytes, byteIndex, byteCount, chars, charIndex, charCount, flush, out bytesUsed,
out charsUsed, out completed);
Assert.Equal(desiredBytesUsed, bytesUsed);
Assert.Equal(desiredCharsUsed, charsUsed);
Assert.Equal(desiredCompleted, completed);
}
private void VerificationHelper(Decoder decoder, byte[] bytes,
int byteIndex,
int byteCount,
char[] chars,
int charIndex,
int charCount,
bool flush,
int desiredBytesUsed,
int desiredCharsUsed,
bool desiredCompleted,
char[] desiredChars,
string errorno)
{
VerificationHelper(decoder, bytes, byteIndex, byteCount, chars, charIndex, charCount, flush, desiredBytesUsed,
desiredCharsUsed, desiredCompleted, errorno + ".1");
Assert.Equal(desiredChars.Length, chars.Length);
for (int i = 0; i < chars.Length; ++i)
{
Assert.Equal(desiredChars[i], chars[i]);
}
}
}
}
| |
// LCDCallOfDuty
// Copyright 2015 Tim Potze
//
// 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.Drawing;
using System.Linq;
using LCDCallOfDuty.ModernWarfare;
using LCDCallOfDuty.Utils;
using LogiFrame;
namespace LCDCallOfDuty.TabPages
{
public class ServerInfoTabPage : ServerTabPage
{
private readonly LCDLine _line;
private readonly LCDLabel _mapNameLabel;
private readonly LCDLabel _playerCountLabel;
private readonly List<LCDLabel> _playerLabels = new List<LCDLabel>();
private readonly Timer _refreshTimer;
private readonly LCDMarquee _serverNameMarquee;
private Player[] _players;
private int _scrollPos;
public ServerInfoTabPage(CodApp app) : base(app)
{
if (app == null) throw new ArgumentNullException(nameof(app));
Icon = new LCDLabel
{
Text = "S",
Font = PixelFonts.Title,
AutoSize = true
};
_refreshTimer = new Timer {Interval = 30000};
_refreshTimer.Tick += (sender, args) => Refresh();
_serverNameMarquee = new LCDMarquee
{
Text = "Server name",
Size = new Size(Width, 7),
Font = PixelFonts.Title,
Location = new Point(0, 0),
Interval = 150,
BreakSteps = 6
};
_mapNameLabel = new LCDLabel
{
Text = "Map name",
Size = new Size(100, 5),
Font = PixelFonts.Capitals,
Location = new Point(0, 7)
};
_playerCountLabel = new LCDLabel
{
Text = "00/00",
TextAlign = ContentAlignment.TopRight,
Size = new Size(50, 5),
Font = PixelFonts.Capitals,
Location = new Point(Width - 50, 7)
};
_line = new LCDLine
{
Start = new Point(0, 13),
End = new Point(Width - 1, 13)
};
Controls.Add(_serverNameMarquee);
Controls.Add(_mapNameLabel);
Controls.Add(_playerCountLabel);
Controls.Add(_line);
}
private void DrawPlayers()
{
SuspendLayout();
RemovePlayers();
if (_players == null || _players.Length == 0)
{
ResumeLayout();
return;
}
var playerCount = _players.Length;
if (_scrollPos*4 >= playerCount)
_scrollPos = 0;
var players = _players.Skip(_scrollPos*4).Take(4).ToArray();
var n = Math.Min(4, players.Length);
for (var y = 0; y < n; y++)
{
var player = players[y];
var yp = 17 + y*6;
var nameLabel = new LCDLabel
{
Text = player.Name.RemoveColors(),
Size = new Size(75, 5),
Font = PixelFonts.Capitals,
Location = new Point(0, yp)
};
_playerLabels.Add(nameLabel);
Controls.Add(nameLabel);
var scoreLabel = new LCDLabel
{
Text = player.Score.ToString(),
TextAlign = ContentAlignment.TopRight,
Size = new Size(25, 5),
Font = PixelFonts.Capitals,
Location = new Point(100, yp)
};
_playerLabels.Add(scoreLabel);
Controls.Add(scoreLabel);
var pingLabel = new LCDLabel
{
Text = player.Ping.ToString(),
TextAlign = ContentAlignment.TopRight,
Size = new Size(20, 5),
Font = PixelFonts.Capitals,
Location = new Point(Width - 20, yp)
};
_playerLabels.Add(pingLabel);
Controls.Add(pingLabel);
}
ResumeLayout();
}
private void RemovePlayers()
{
foreach (var l in _playerLabels)
Controls.Remove(l);
_playerLabels.Clear();
}
private bool IsBot(string name)
{
var startsWithBot = name.StartsWith("bot");
var numbers = name.Skip(3).All(c => c >= '0' && c <= '9');
return startsWithBot && numbers;
}
private int TryParseInt(string value)
{
int result;
return int.TryParse(value, out result) ? result : 0;
}
#region Overrides of ServerTabPage
protected override async void Refresh()
{
SuspendLayout();
if (App.CurrentServer == null)
{
RemovePlayers();
_serverNameMarquee.Text = "No servers were found in your favorites list!";
_mapNameLabel.Visible = false;
_playerCountLabel.Visible = false;
}
else
{
try
{
var result = await App.CurrentServer.Query().TimeoutAfter(TimeSpan.FromMilliseconds(1000));
var players = result.Players.Where(p => !IsBot(p.Name)).ToArray();
var playerCount = players.Length;
var botCount = result.Players.Count() - playerCount;
_serverNameMarquee.Text = result.Variables.Get("sv_hostname").RemoveColors();
_mapNameLabel.Text = result.Variables.Get("mapname").Substring(3);
_mapNameLabel.Visible = true;
_playerCountLabel.Text = $"{playerCount}/{TryParseInt(result.Variables["sv_maxclients"]) - botCount}";
_playerCountLabel.Visible = true;
_players = players.ToArray();
DrawPlayers();
}
catch
{
RemovePlayers();
_serverNameMarquee.Text = "Could not connect to server";
_mapNameLabel.Text = $"{App.CurrentServer.Ip}:{App.CurrentServer.Port}";
_playerCountLabel.Visible = false;
}
}
ResumeLayout();
}
#endregion
#region Overrides of LCDControl
protected override void OnVisibleChanged()
{
if (_refreshTimer != null)
_refreshTimer.Enabled = Visible;
base.OnVisibleChanged();
}
protected override void OnButtonPress(ButtonEventArgs e)
{
switch (e.Button)
{
case 0:
_scrollPos--;
if (_scrollPos < 0)
_scrollPos = _players?.Length/4 - (_players?.Length%4 > 0 ? 0 : 1) ?? 0;
DrawPlayers();
e.PreventPropagation = true;
break;
case 1:
_scrollPos = (_scrollPos + 1)%
(Math.Max(1, (int) Math.Ceiling((float) (_players?.Length ?? 1)/4)));
DrawPlayers();
e.PreventPropagation = true;
break;
}
base.OnButtonPress(e);
}
#endregion
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoad.Business.ERCLevel
{
/// <summary>
/// D08_Region (editable child object).<br/>
/// This is a generated base class of <see cref="D08_Region"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="D09_CityObjects"/> of type <see cref="D09_CityColl"/> (1:M relation to <see cref="D10_City"/>)<br/>
/// This class is an item of <see cref="D07_RegionColl"/> collection.
/// </remarks>
[Serializable]
public partial class D08_Region : BusinessBase<D08_Region>
{
#region Static Fields
private static int _lastID;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Region_ID"/> property.
/// </summary>
public static readonly PropertyInfo<int> Region_IDProperty = RegisterProperty<int>(p => p.Region_ID, "Regions ID");
/// <summary>
/// Gets the Regions ID.
/// </summary>
/// <value>The Regions ID.</value>
public int Region_ID
{
get { return GetProperty(Region_IDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Region_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Region_NameProperty = RegisterProperty<string>(p => p.Region_Name, "Regions Name");
/// <summary>
/// Gets or sets the Regions Name.
/// </summary>
/// <value>The Regions Name.</value>
public string Region_Name
{
get { return GetProperty(Region_NameProperty); }
set { SetProperty(Region_NameProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="D09_Region_SingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<D09_Region_Child> D09_Region_SingleObjectProperty = RegisterProperty<D09_Region_Child>(p => p.D09_Region_SingleObject, "D09 Region Single Object", RelationshipTypes.Child);
/// <summary>
/// Gets the D09 Region Single Object ("self load" child property).
/// </summary>
/// <value>The D09 Region Single Object.</value>
public D09_Region_Child D09_Region_SingleObject
{
get { return GetProperty(D09_Region_SingleObjectProperty); }
private set { LoadProperty(D09_Region_SingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="D09_Region_ASingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<D09_Region_ReChild> D09_Region_ASingleObjectProperty = RegisterProperty<D09_Region_ReChild>(p => p.D09_Region_ASingleObject, "D09 Region ASingle Object", RelationshipTypes.Child);
/// <summary>
/// Gets the D09 Region ASingle Object ("self load" child property).
/// </summary>
/// <value>The D09 Region ASingle Object.</value>
public D09_Region_ReChild D09_Region_ASingleObject
{
get { return GetProperty(D09_Region_ASingleObjectProperty); }
private set { LoadProperty(D09_Region_ASingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="D09_CityObjects"/> property.
/// </summary>
public static readonly PropertyInfo<D09_CityColl> D09_CityObjectsProperty = RegisterProperty<D09_CityColl>(p => p.D09_CityObjects, "D09 City Objects", RelationshipTypes.Child);
/// <summary>
/// Gets the D09 City Objects ("self load" child property).
/// </summary>
/// <value>The D09 City Objects.</value>
public D09_CityColl D09_CityObjects
{
get { return GetProperty(D09_CityObjectsProperty); }
private set { LoadProperty(D09_CityObjectsProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="D08_Region"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="D08_Region"/> object.</returns>
internal static D08_Region NewD08_Region()
{
return DataPortal.CreateChild<D08_Region>();
}
/// <summary>
/// Factory method. Loads a <see cref="D08_Region"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="D08_Region"/> object.</returns>
internal static D08_Region GetD08_Region(SafeDataReader dr)
{
D08_Region obj = new D08_Region();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="D08_Region"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public D08_Region()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="D08_Region"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
LoadProperty(Region_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
LoadProperty(D09_Region_SingleObjectProperty, DataPortal.CreateChild<D09_Region_Child>());
LoadProperty(D09_Region_ASingleObjectProperty, DataPortal.CreateChild<D09_Region_ReChild>());
LoadProperty(D09_CityObjectsProperty, DataPortal.CreateChild<D09_CityColl>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="D08_Region"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Region_IDProperty, dr.GetInt32("Region_ID"));
LoadProperty(Region_NameProperty, dr.GetString("Region_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Loads child objects.
/// </summary>
internal void FetchChildren()
{
LoadProperty(D09_Region_SingleObjectProperty, D09_Region_Child.GetD09_Region_Child(Region_ID));
LoadProperty(D09_Region_ASingleObjectProperty, D09_Region_ReChild.GetD09_Region_ReChild(Region_ID));
LoadProperty(D09_CityObjectsProperty, D09_CityColl.GetD09_CityColl(Region_ID));
}
/// <summary>
/// Inserts a new <see cref="D08_Region"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(D06_Country parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddD08_Region", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Parent_Country_ID", parent.Country_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Region_ID", ReadProperty(Region_IDProperty)).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@Region_Name", ReadProperty(Region_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(Region_IDProperty, (int) cmd.Parameters["@Region_ID"].Value);
}
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="D08_Region"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
if (!IsDirty)
return;
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateD08_Region", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Region_ID", ReadProperty(Region_IDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Region_Name", ReadProperty(Region_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Self deletes the <see cref="D08_Region"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
// flushes all pending data operations
FieldManager.UpdateChildren(this);
using (var cmd = new SqlCommand("DeleteD08_Region", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Region_ID", ReadProperty(Region_IDProperty)).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
// removes all previous references to children
LoadProperty(D09_Region_SingleObjectProperty, DataPortal.CreateChild<D09_Region_Child>());
LoadProperty(D09_Region_ASingleObjectProperty, DataPortal.CreateChild<D09_Region_ReChild>());
LoadProperty(D09_CityObjectsProperty, DataPortal.CreateChild<D09_CityColl>());
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Reflection;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
////////////////////////////////////////////////////////////////////////////////
//
// MethodSymbol - a symbol representing a method. Parent is a struct, interface
// or class (aggregate). No children.
internal class MethodSymbol : MethodOrPropertySymbol
{
private MethodKindEnum _methKind; // An extra bit to prevent sign-extension
private bool _inferenceMustFail; // Inference must fail if there are no type variables or if
private bool _checkedInfMustFail; // there is a type variable used in no parameter.
private MethodSymbol _convNext; // For linked list of conversion operators.
private PropertySymbol _prop; // For property accessors, this is the PropertySymbol.
private EventSymbol _evt; // For event accessors, this is the EventSymbol.
public bool isExtension; // is the method a extension method
public bool isExternal; // Has external definition.
public bool isVirtual; // Virtual member?
public bool isAbstract; // Abstract method?
public bool isVarargs; // has varargs
public MemberInfo AssociatedMemberInfo;
public TypeArray typeVars; // All the type variables for a generic method, as declarations.
// If there is a type variable in the method which is used in no parameter,
// then inference must fail. Since this is expensive to check, we cache
// the result of the first call.
public bool InferenceMustFail()
{
if (_checkedInfMustFail)
{
return _inferenceMustFail;
}
Debug.Assert(!_inferenceMustFail);
_checkedInfMustFail = true;
for (int ivar = 0; ivar < typeVars.Size; ivar++)
{
TypeParameterType var = typeVars.ItemAsTypeParameterType(ivar);
// See if type var is used in a parameter.
for (int ipar = 0; ; ipar++)
{
if (ipar >= Params.Size)
{
// This type variable is not in any parameter.
_inferenceMustFail = true;
return true;
}
if (TypeManager.TypeContainsType(Params.Item(ipar), var))
{
break;
}
}
}
// All type variables are used in a parameter.
return false;
}
public bool IsExtension()
{
return isExtension;
}
public MethodKindEnum MethKind()
{
return _methKind;
}
public bool IsConstructor()
{
return _methKind == MethodKindEnum.Constructor;
}
public bool IsNullableConstructor()
{
return getClass().isPredefAgg(PredefinedType.PT_G_OPTIONAL) &&
Params.Size == 1 &&
Params.Item(0).IsGenericParameter &&
IsConstructor();
}
public bool IsDestructor() // Is a destructor
{
return _methKind == MethodKindEnum.Destructor;
}
public bool isPropertyAccessor() // true if this method is a property set or get method
{
return _methKind == MethodKindEnum.PropAccessor;
}
public bool isEventAccessor() // true if this method is an event add/remove method
{
return _methKind == MethodKindEnum.EventAccessor;
}
private bool isExplicit() // is user defined explicit conversion operator
{
return _methKind == MethodKindEnum.ExplicitConv;
}
public bool isImplicit() // is user defined implicit conversion operator
{
return _methKind == MethodKindEnum.ImplicitConv;
}
public bool isInvoke() // Invoke method on a delegate - isn't user callable
{
return _methKind == MethodKindEnum.Invoke;
}
public void SetMethKind(MethodKindEnum mk)
{
_methKind = mk;
}
public MethodSymbol ConvNext()
{
Debug.Assert(isImplicit() || isExplicit());
return _convNext;
}
public void SetConvNext(MethodSymbol conv)
{
Debug.Assert(isImplicit() || isExplicit());
Debug.Assert(conv == null || conv.isImplicit() || conv.isExplicit());
_convNext = conv;
}
public PropertySymbol getProperty()
{
Debug.Assert(isPropertyAccessor());
return _prop;
}
public void SetProperty(PropertySymbol prop)
{
Debug.Assert(isPropertyAccessor());
_prop = prop;
}
public EventSymbol getEvent()
{
Debug.Assert(isEventAccessor());
return _evt;
}
public void SetEvent(EventSymbol evt)
{
Debug.Assert(isEventAccessor());
_evt = evt;
}
public bool isConversionOperator()
{
return (isExplicit() || isImplicit());
}
public new bool isUserCallable()
{
return !isOperator && !isAnyAccessor();
}
private bool isAnyAccessor()
{
return isPropertyAccessor() || isEventAccessor();
}
/*
* returns true if this property is a set accessor
*/
public bool isSetAccessor()
{
if (!isPropertyAccessor())
{
return false;
}
PropertySymbol property = getProperty();
if (property == null)
{
Debug.Assert(false, "cannot find property for accessor");
return false;
}
return (this == property.methSet);
}
}
// ----------------------------------------------------------------------------
//
// InterfaceImplementationMethodSymbol
//
// an explicit method impl generated by the compiler
// used for CMOD_OPT interop
// ----------------------------------------------------------------------------
internal sealed class InterfaceImplementationMethodSymbol : MethodSymbol
{
}
internal sealed class IteratorFinallyMethodSymbol : MethodSymbol
{
}
}
| |
namespace SIL.Windows.Forms.WritingSystems
{
partial class LanguageLookupControl
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(LanguageLookupControl));
this._listView = new System.Windows.Forms.ListView();
this.PrimaryNameHeader = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.codeHeader = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.countryHeader = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this._searchText = new System.Windows.Forms.TextBox();
this._searchTimer = new System.Windows.Forms.Timer(this.components);
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this._cannotFindLanguageLink = new System.Windows.Forms.LinkLabel();
this._desiredLanguageLabel = new System.Windows.Forms.Label();
this._desiredLanguageDisplayName = new System.Windows.Forms.TextBox();
this._L10NSharpExtender = new L10NSharp.UI.L10NSharpExtender(this.components);
this._showRegionalDialectsCheckBox = new System.Windows.Forms.CheckBox();
this._scriptsAndVariantsLink = new System.Windows.Forms.LinkLabel();
this._scriptsAndVariantsLabel = new System.Windows.Forms.Label();
this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this._L10NSharpExtender)).BeginInit();
this.flowLayoutPanel1.SuspendLayout();
this.SuspendLayout();
//
// _listView
//
this._listView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this._listView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.PrimaryNameHeader,
this.codeHeader,
this.countryHeader});
this._listView.FullRowSelect = true;
this._listView.HideSelection = false;
this._listView.Location = new System.Drawing.Point(0, 29);
this._listView.Name = "_listView";
this._listView.Size = new System.Drawing.Size(577, 265);
this._listView.TabIndex = 1;
this._listView.UseCompatibleStateImageBehavior = false;
this._listView.View = System.Windows.Forms.View.Details;
this._listView.SelectedIndexChanged += new System.EventHandler(this.OnSelectedIndexChanged);
this._listView.DoubleClick += new System.EventHandler(this.listView1_DoubleClick);
//
// PrimaryNameHeader
//
this._L10NSharpExtender.SetLocalizableToolTip(this.PrimaryNameHeader, null);
this._L10NSharpExtender.SetLocalizationComment(this.PrimaryNameHeader, null);
this._L10NSharpExtender.SetLocalizingId(this.PrimaryNameHeader, "LanguageLookup.PrimaryNameHeader");
this.PrimaryNameHeader.Text = "Name";
this.PrimaryNameHeader.Width = 194;
//
// codeHeader
//
this._L10NSharpExtender.SetLocalizableToolTip(this.codeHeader, null);
this._L10NSharpExtender.SetLocalizationComment(this.codeHeader, null);
this._L10NSharpExtender.SetLocalizingId(this.codeHeader, "LanguageLookup.CodeHeader");
this.codeHeader.Text = "Code";
this.codeHeader.Width = 72;
//
// countryHeader
//
this._L10NSharpExtender.SetLocalizableToolTip(this.countryHeader, null);
this._L10NSharpExtender.SetLocalizationComment(this.countryHeader, null);
this._L10NSharpExtender.SetLocalizingId(this.countryHeader, "LanguageLookup.CountryHeader");
this.countryHeader.Text = "Country";
this.countryHeader.Width = 305;
//
// _searchText
//
this._L10NSharpExtender.SetLocalizableToolTip(this._searchText, null);
this._L10NSharpExtender.SetLocalizationComment(this._searchText, null);
this._L10NSharpExtender.SetLocalizationPriority(this._searchText, L10NSharp.LocalizationPriority.NotLocalizable);
this._L10NSharpExtender.SetLocalizingId(this._searchText, "LanguageLookup.LookupISOControl._searchText");
this._searchText.Location = new System.Drawing.Point(0, 3);
this._searchText.Name = "_searchText";
this._searchText.Size = new System.Drawing.Size(228, 20);
this._searchText.TabIndex = 0;
this._searchText.TextChanged += new System.EventHandler(this._searchText_TextChanged);
//
// _searchTimer
//
this._searchTimer.Tick += new System.EventHandler(this._searchTimer_Tick);
//
// pictureBox1
//
this.pictureBox1.BackColor = System.Drawing.Color.White;
this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
this._L10NSharpExtender.SetLocalizableToolTip(this.pictureBox1, null);
this._L10NSharpExtender.SetLocalizationComment(this.pictureBox1, null);
this._L10NSharpExtender.SetLocalizingId(this.pictureBox1, "LanguageLookup.LookupISOControl.pictureBox1");
this.pictureBox1.Location = new System.Drawing.Point(210, 5);
this.pictureBox1.Margin = new System.Windows.Forms.Padding(0);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(15, 15);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pictureBox1.TabIndex = 11;
this.pictureBox1.TabStop = false;
//
// _cannotFindLanguageLink
//
this._cannotFindLanguageLink.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this._cannotFindLanguageLink.AutoSize = true;
this._L10NSharpExtender.SetLocalizableToolTip(this._cannotFindLanguageLink, null);
this._L10NSharpExtender.SetLocalizationComment(this._cannotFindLanguageLink, null);
this._L10NSharpExtender.SetLocalizingId(this._cannotFindLanguageLink, "LanguageLookup._cannotFindLanguageLink");
this._cannotFindLanguageLink.Location = new System.Drawing.Point(-2, 359);
this._cannotFindLanguageLink.Name = "_cannotFindLanguageLink";
this._cannotFindLanguageLink.Size = new System.Drawing.Size(127, 13);
this._cannotFindLanguageLink.TabIndex = 12;
this._cannotFindLanguageLink.TabStop = true;
this._cannotFindLanguageLink.Text = "Can\'t find your language?";
this._cannotFindLanguageLink.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this._cannotFindLanguageLink_LinkClicked);
//
// _desiredLanguageLabel
//
this._desiredLanguageLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this._desiredLanguageLabel.AutoSize = true;
this._L10NSharpExtender.SetLocalizableToolTip(this._desiredLanguageLabel, null);
this._L10NSharpExtender.SetLocalizationComment(this._desiredLanguageLabel, null);
this._L10NSharpExtender.SetLocalizingId(this._desiredLanguageLabel, "LanguageLookup.DesiredLanguageDisplayNameLabel");
this._desiredLanguageLabel.Location = new System.Drawing.Point(58, 308);
this._desiredLanguageLabel.Name = "_desiredLanguageLabel";
this._desiredLanguageLabel.Size = new System.Drawing.Size(309, 13);
this._desiredLanguageLabel.TabIndex = 14;
this._desiredLanguageLabel.Text = "You can change how the language name will be displayed here:";
this._desiredLanguageLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// _desiredLanguageDisplayName
//
this._desiredLanguageDisplayName.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this._desiredLanguageDisplayName.Font = new System.Drawing.Font("Segoe UI", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this._desiredLanguageDisplayName.ForeColor = System.Drawing.Color.RoyalBlue;
this._L10NSharpExtender.SetLocalizableToolTip(this._desiredLanguageDisplayName, null);
this._L10NSharpExtender.SetLocalizationComment(this._desiredLanguageDisplayName, null);
this._L10NSharpExtender.SetLocalizingId(this._desiredLanguageDisplayName, "LanguageLookup.LookupISOControl._desiredLanguageDisplayName");
this._desiredLanguageDisplayName.Location = new System.Drawing.Point(373, 300);
this._desiredLanguageDisplayName.Name = "_desiredLanguageDisplayName";
this._desiredLanguageDisplayName.Size = new System.Drawing.Size(204, 33);
this._desiredLanguageDisplayName.TabIndex = 13;
this._desiredLanguageDisplayName.TextChanged += new System.EventHandler(this._desiredLanguageDisplayName_TextChanged);
//
// _L10NSharpExtender
//
this._L10NSharpExtender.LocalizationManagerId = "Palaso";
this._L10NSharpExtender.PrefixForNewItems = "LanguageLookup";
//
// _showRegionalDialectsCheckBox
//
this._showRegionalDialectsCheckBox.AutoSize = true;
this._L10NSharpExtender.SetLocalizableToolTip(this._showRegionalDialectsCheckBox, null);
this._L10NSharpExtender.SetLocalizationComment(this._showRegionalDialectsCheckBox, null);
this._L10NSharpExtender.SetLocalizingId(this._showRegionalDialectsCheckBox, "LanguageLookup.ShowRegionalDialectsLabel");
this._showRegionalDialectsCheckBox.Location = new System.Drawing.Point(235, 5);
this._showRegionalDialectsCheckBox.Name = "_showRegionalDialectsCheckBox";
this._showRegionalDialectsCheckBox.Size = new System.Drawing.Size(132, 17);
this._showRegionalDialectsCheckBox.TabIndex = 16;
this._showRegionalDialectsCheckBox.Text = "Show regional dialects";
this._showRegionalDialectsCheckBox.UseVisualStyleBackColor = true;
this._showRegionalDialectsCheckBox.CheckedChanged += new System.EventHandler(this._showRegionalDialectsCheckBox_CheckedChanged);
//
// _scriptsAndVariantsLink
//
this._scriptsAndVariantsLink.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this._scriptsAndVariantsLink.AutoSize = true;
this._scriptsAndVariantsLink.Enabled = false;
this._L10NSharpExtender.SetLocalizableToolTip(this._scriptsAndVariantsLink, null);
this._L10NSharpExtender.SetLocalizationComment(this._scriptsAndVariantsLink, null);
this._L10NSharpExtender.SetLocalizingId(this._scriptsAndVariantsLink, "LanguageLookup._scriptsAndVariantsLink");
this._scriptsAndVariantsLink.Location = new System.Drawing.Point(3, 0);
this._scriptsAndVariantsLink.Name = "_scriptsAndVariantsLink";
this._scriptsAndVariantsLink.Size = new System.Drawing.Size(101, 13);
this._scriptsAndVariantsLink.TabIndex = 17;
this._scriptsAndVariantsLink.TabStop = true;
this._scriptsAndVariantsLink.Text = "Script and Variant";
this._scriptsAndVariantsLink.Visible = false;
this._scriptsAndVariantsLink.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this._scriptsAndVariants_LinkClicked);
//
// _scriptsAndVariantsLabel
//
this._scriptsAndVariantsLabel.AutoSize = true;
this._L10NSharpExtender.SetLocalizableToolTip(this._scriptsAndVariantsLabel, null);
this._L10NSharpExtender.SetLocalizationComment(this._scriptsAndVariantsLabel, null);
this._L10NSharpExtender.SetLocalizingId(this._scriptsAndVariantsLabel, "LanguageLookup._scriptsAndVariantsLabel");
this._scriptsAndVariantsLabel.Location = new System.Drawing.Point(110, 0);
this._scriptsAndVariantsLabel.Name = "_scriptsAndVariantsLabel";
this._scriptsAndVariantsLabel.Size = new System.Drawing.Size(108, 13);
this._scriptsAndVariantsLabel.TabIndex = 18;
this._scriptsAndVariantsLabel.Text = "my script variant label";
this._scriptsAndVariantsLabel.Visible = false;
//
// flowLayoutPanel1
//
this.flowLayoutPanel1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.flowLayoutPanel1.Controls.Add(this._scriptsAndVariantsLink);
this.flowLayoutPanel1.Controls.Add(this._scriptsAndVariantsLabel);
this.flowLayoutPanel1.Location = new System.Drawing.Point(-5, 336);
this.flowLayoutPanel1.Name = "flowLayoutPanel1";
this.flowLayoutPanel1.Size = new System.Drawing.Size(247, 19);
this.flowLayoutPanel1.TabIndex = 18;
//
// LanguageLookupControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.flowLayoutPanel1);
this.Controls.Add(this._showRegionalDialectsCheckBox);
this.Controls.Add(this._desiredLanguageLabel);
this.Controls.Add(this._desiredLanguageDisplayName);
this.Controls.Add(this._cannotFindLanguageLink);
this.Controls.Add(this.pictureBox1);
this.Controls.Add(this._listView);
this.Controls.Add(this._searchText);
this._L10NSharpExtender.SetLocalizableToolTip(this, null);
this._L10NSharpExtender.SetLocalizationComment(this, null);
this._L10NSharpExtender.SetLocalizingId(this, "LanguageLookup.LookupISOControl.LookupISOControl");
this.Name = "LanguageLookupControl";
this.Size = new System.Drawing.Size(580, 372);
this.Load += new System.EventHandler(this.OnLoad);
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this._L10NSharpExtender)).EndInit();
this.flowLayoutPanel1.ResumeLayout(false);
this.flowLayoutPanel1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ListView _listView;
private System.Windows.Forms.ColumnHeader PrimaryNameHeader;
private System.Windows.Forms.ColumnHeader codeHeader;
private System.Windows.Forms.TextBox _searchText;
private System.Windows.Forms.Timer _searchTimer;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.LinkLabel _cannotFindLanguageLink;
private System.Windows.Forms.ColumnHeader countryHeader;
private System.Windows.Forms.Label _desiredLanguageLabel;
private System.Windows.Forms.TextBox _desiredLanguageDisplayName;
private L10NSharp.UI.L10NSharpExtender _L10NSharpExtender;
private System.Windows.Forms.CheckBox _showRegionalDialectsCheckBox;
private System.Windows.Forms.LinkLabel _scriptsAndVariantsLink;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
private System.Windows.Forms.Label _scriptsAndVariantsLabel;
}
}
| |
#pragma warning disable 109, 114, 219, 429, 168, 162
public class Reflect : global::haxe.lang.HxObject
{
public Reflect(global::haxe.lang.EmptyObject empty)
{
unchecked
{
#line 48 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Reflect.hx"
{
}
}
#line default
}
public Reflect()
{
unchecked
{
#line 48 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Reflect.hx"
global::Reflect.__hx_ctor__Reflect(this);
}
#line default
}
public static void __hx_ctor__Reflect(global::Reflect __temp_me9)
{
unchecked
{
#line 48 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Reflect.hx"
{
}
}
#line default
}
public static bool hasField(object o, string field)
{
if (o is haxe.lang.IHxObject)
return ((haxe.lang.IHxObject) o).__hx_getField(field, haxe.lang.FieldLookup.hash(field), false, true, false) != haxe.lang.Runtime.undefined;
return haxe.lang.Runtime.slowHasField(o, field);
}
public static object field(object o, string field)
{
if (o is haxe.lang.IHxObject)
return ((haxe.lang.IHxObject) o).__hx_getField(field, haxe.lang.FieldLookup.hash(field), false, false, false);
return haxe.lang.Runtime.slowGetField(o, field, false);
}
public static void setField(object o, string field, object @value)
{
if (o is haxe.lang.IHxObject)
((haxe.lang.IHxObject) o).__hx_setField(field, haxe.lang.FieldLookup.hash(field), value, false);
else
haxe.lang.Runtime.slowSetField(o, field, value);
}
public static object getProperty(object o, string field)
{
if (o is haxe.lang.IHxObject)
return ((haxe.lang.IHxObject) o).__hx_getField(field, haxe.lang.FieldLookup.hash(field), false, false, true);
if (haxe.lang.Runtime.slowHasField(o, "get_" + field))
return haxe.lang.Runtime.slowCallField(o, "get_" + field, null);
return haxe.lang.Runtime.slowGetField(o, field, false);
}
public static void setProperty(object o, string field, object @value)
{
if (o is haxe.lang.IHxObject)
((haxe.lang.IHxObject) o).__hx_setField(field, haxe.lang.FieldLookup.hash(field), value, true);
else if (haxe.lang.Runtime.slowHasField(o, "set_" + field))
haxe.lang.Runtime.slowCallField(o, "set_" + field, new Array<object>(new object[]{value}));
else
haxe.lang.Runtime.slowSetField(o, field, value);
}
public static object callMethod(object o, object func, global::Array args)
{
return ((haxe.lang.Function) func).__hx_invokeDynamic(args);
}
public static global::Array<object> fields(object o)
{
if (o is haxe.lang.IHxObject)
{
Array<object> ret = new Array<object>();
((haxe.lang.IHxObject) o).__hx_getFields(ret);
return ret;
} else if (o is System.Type) {
return Type.getClassFields( (System.Type) o);
} else {
return new Array<object>();
}
}
public static bool isFunction(object f)
{
return f is haxe.lang.Function;
}
public static int compare<T>(T a, T b)
{
return haxe.lang.Runtime.compare(a, b);
}
public static bool compareMethods(object f1, object f2)
{
if (f1 == f2)
return true;
if (f1 is haxe.lang.Closure && f2 is haxe.lang.Closure)
{
haxe.lang.Closure f1c = (haxe.lang.Closure) f1;
haxe.lang.Closure f2c = (haxe.lang.Closure) f2;
return haxe.lang.Runtime.refEq(f1c.obj, f2c.obj) && f1c.field.Equals(f2c.field);
}
return false;
}
public static bool isObject(object v)
{
return v != null && !(v is haxe.lang.Enum || v is haxe.lang.Function || v is System.ValueType);
}
public static bool isEnumValue(object v)
{
return v != null && (v is haxe.lang.Enum || v is System.Enum);
}
public static bool deleteField(object o, string field)
{
return (o is haxe.lang.DynamicObject && ((haxe.lang.DynamicObject) o).__hx_deleteField(field, haxe.lang.FieldLookup.hash(field)));
}
public static T copy<T>(T o)
{
unchecked
{
#line 198 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Reflect.hx"
object o2 = new global::haxe.lang.DynamicObject(new global::Array<int>(new int[]{}), new global::Array<object>(new object[]{}), new global::Array<int>(new int[]{}), new global::Array<double>(new double[]{}));
{
#line 199 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Reflect.hx"
int _g = 0;
#line 199 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Reflect.hx"
global::Array<object> _g1 = global::Reflect.fields(o);
#line 199 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Reflect.hx"
while (( _g < _g1.length ))
{
#line 199 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Reflect.hx"
string f = global::haxe.lang.Runtime.toString(_g1[_g]);
#line 199 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Reflect.hx"
++ _g;
global::Reflect.setField(o2, f, global::Reflect.field(o, f));
}
}
return global::haxe.lang.Runtime.genericCast<T>(o2);
}
#line default
}
public static object makeVarArgs(global::haxe.lang.Function f)
{
unchecked
{
#line 207 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Reflect.hx"
return new global::haxe.lang.VarArgsFunction(((global::haxe.lang.Function) (f) ));
}
#line default
}
public static new object __hx_createEmpty()
{
unchecked
{
#line 48 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Reflect.hx"
return new global::Reflect(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) ));
}
#line default
}
public static new object __hx_create(global::Array arr)
{
unchecked
{
#line 48 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Reflect.hx"
return new global::Reflect();
}
#line default
}
}
| |
#if !NOT_UNITY3D
using System;
using System.Collections.Generic;
using System.Linq;
using ModestTree;
using UnityEngine;
using UnityEngine.Serialization;
using Zenject.Internal;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace Zenject
{
public abstract class Context : MonoBehaviour
{
[FormerlySerializedAs("Installers")]
[SerializeField]
List<MonoInstaller> _installers = new List<MonoInstaller>();
[SerializeField]
List<MonoInstaller> _installerPrefabs = new List<MonoInstaller>();
[SerializeField]
List<ScriptableObjectInstaller> _scriptableObjectInstallers = new List<ScriptableObjectInstaller>();
List<InstallerBase> _normalInstallers = new List<InstallerBase>();
List<Type> _normalInstallerTypes = new List<Type>();
public IEnumerable<MonoInstaller> Installers
{
get { return _installers; }
set
{
_installers.Clear();
_installers.AddRange(value);
}
}
public IEnumerable<MonoInstaller> InstallerPrefabs
{
get { return _installerPrefabs; }
set
{
_installerPrefabs.Clear();
_installerPrefabs.AddRange(value);
}
}
public IEnumerable<ScriptableObjectInstaller> ScriptableObjectInstallers
{
get { return _scriptableObjectInstallers; }
set
{
_scriptableObjectInstallers.Clear();
_scriptableObjectInstallers.AddRange(value);
}
}
// Unlike other installer types this has to be set through code
public IEnumerable<Type> NormalInstallerTypes
{
get { return _normalInstallerTypes; }
set
{
Assert.That(value.All(x => x != null && x.DerivesFrom<InstallerBase>()));
_normalInstallerTypes.Clear();
_normalInstallerTypes.AddRange(value);
}
}
// Unlike other installer types this has to be set through code
public IEnumerable<InstallerBase> NormalInstallers
{
get { return _normalInstallers; }
set
{
_normalInstallers.Clear();
_normalInstallers.AddRange(value);
}
}
public abstract DiContainer Container
{
get;
}
public abstract IEnumerable<GameObject> GetRootGameObjects();
public void AddNormalInstallerType(Type installerType)
{
Assert.IsNotNull(installerType);
Assert.That(installerType.DerivesFrom<InstallerBase>());
_normalInstallerTypes.Add(installerType);
}
public void AddNormalInstaller(InstallerBase installer)
{
_normalInstallers.Add(installer);
}
void CheckInstallerPrefabTypes(List<MonoInstaller> installers, List<MonoInstaller> installerPrefabs)
{
foreach (var installer in installers)
{
Assert.IsNotNull(installer, "Found null installer in Context '{0}'", this.name);
#if UNITY_EDITOR
Assert.That(PrefabUtility.GetPrefabType(installer.gameObject) != PrefabType.Prefab,
"Found prefab with name '{0}' in the Installer property of Context '{1}'. You should use the property 'InstallerPrefabs' for this instead.", installer.name, this.name);
#endif
}
foreach (var installerPrefab in installerPrefabs)
{
Assert.IsNotNull(installerPrefab, "Found null prefab in Context");
// We'd like to do this but this is actually a valid case sometimes
// (eg. loading an asset bundle with a scene containing a scene context when inside unity editor)
//#if UNITY_EDITOR
//Assert.That(PrefabUtility.GetPrefabType(installerPrefab.gameObject) == PrefabType.Prefab,
//"Found non-prefab with name '{0}' in the InstallerPrefabs property of Context '{1}'. You should use the property 'Installer' for this instead",
//installerPrefab.name, this.name);
//#endif
Assert.That(installerPrefab.GetComponent<MonoInstaller>() != null,
"Expected to find component with type 'MonoInstaller' on given installer prefab '{0}'", installerPrefab.name);
}
}
protected void InstallInstallers()
{
InstallInstallers(
_normalInstallers, _normalInstallerTypes, _scriptableObjectInstallers, _installers, _installerPrefabs);
}
protected void InstallInstallers(
List<InstallerBase> normalInstallers,
List<Type> normalInstallerTypes,
List<ScriptableObjectInstaller> scriptableObjectInstallers,
List<MonoInstaller> installers,
List<MonoInstaller> installerPrefabs)
{
CheckInstallerPrefabTypes(installers, installerPrefabs);
// Ideally we would just have one flat list of all the installers
// since that way the user has complete control over the order, but
// that's not possible since Unity does not allow serializing lists of interfaces
// (and it has to be an inteface since the scriptable object installers only share
// the interface)
//
// So the best we can do is have a hard-coded order in terms of the installer type
//
// The order is:
// - Normal installers given directly via code
// - ScriptableObject installers
// - MonoInstallers in the scene
// - Prefab Installers
//
// We put ScriptableObject installers before the MonoInstallers because
// ScriptableObjectInstallers are often used for settings (including settings
// that are injected into other installers like MonoInstallers)
var allInstallers = normalInstallers.Cast<IInstaller>()
.Concat(scriptableObjectInstallers.Cast<IInstaller>())
.Concat(installers.Cast<IInstaller>()).ToList();
foreach (var installerPrefab in installerPrefabs)
{
Assert.IsNotNull(installerPrefab, "Found null installer prefab in '{0}'", this.GetType());
var installerGameObject = GameObject.Instantiate(installerPrefab.gameObject);
installerGameObject.transform.SetParent(this.transform, false);
var installer = installerGameObject.GetComponent<MonoInstaller>();
Assert.IsNotNull(installer, "Could not find installer component on prefab '{0}'", installerPrefab.name);
allInstallers.Add(installer);
}
foreach (var installerType in normalInstallerTypes)
{
((InstallerBase)Container.Instantiate(installerType)).InstallBindings();
}
foreach (var installer in allInstallers)
{
Assert.IsNotNull(installer,
"Found null installer in '{0}'", this.GetType());
Container.Inject(installer);
installer.InstallBindings();
}
}
protected void InstallSceneBindings(List<MonoBehaviour> injectableMonoBehaviours)
{
foreach (var binding in injectableMonoBehaviours.OfType<ZenjectBinding>())
{
if (binding == null)
{
continue;
}
if (binding.Context == null || (binding.UseSceneContext && this is SceneContext))
{
binding.Context = this;
}
}
// We'd prefer to use GameObject.FindObjectsOfType<ZenjectBinding>() here
// instead but that doesn't find inactive gameobjects
// TODO: Consider changing this
// Maybe ZenjectBinding could add itself to a registry class on Awake/OnEnable
// then we could avoid calling the slow Resources.FindObjectsOfTypeAll here
foreach (var binding in Resources.FindObjectsOfTypeAll<ZenjectBinding>())
{
if (binding == null)
{
continue;
}
// This is necessary for cases where the ZenjectBinding is inside a GameObjectContext
// since it won't be caught in the other loop above
if (this is SceneContext)
{
if (binding.Context == null && binding.UseSceneContext
&& binding.gameObject.scene == this.gameObject.scene)
{
binding.Context = this;
}
}
if (binding.Context == this)
{
InstallZenjectBinding(binding);
}
}
}
void InstallZenjectBinding(ZenjectBinding binding)
{
if (!binding.enabled)
{
return;
}
if (binding.Components == null || binding.Components.IsEmpty())
{
ModestTree.Log.Warn("Found empty list of components on ZenjectBinding on object '{0}'", binding.name);
return;
}
string identifier = null;
if (binding.Identifier.Trim().Length > 0)
{
identifier = binding.Identifier;
}
foreach (var component in binding.Components)
{
var bindType = binding.BindType;
if (component == null)
{
ModestTree.Log.Warn("Found null component in ZenjectBinding on object '{0}'", binding.name);
continue;
}
var componentType = component.GetType();
switch (bindType)
{
case ZenjectBinding.BindTypes.Self:
{
Container.Bind(componentType).WithId(identifier).FromInstance(component);
break;
}
case ZenjectBinding.BindTypes.BaseType:
{
Container.Bind(componentType.BaseType()).WithId(identifier).FromInstance(component);
break;
}
case ZenjectBinding.BindTypes.AllInterfaces:
{
Container.Bind(componentType.Interfaces()).WithId(identifier).FromInstance(component);
break;
}
case ZenjectBinding.BindTypes.AllInterfacesAndSelf:
{
Container.Bind(componentType.Interfaces().Concat(new[] { componentType }).ToArray()).WithId(identifier).FromInstance(component);
break;
}
default:
{
throw Assert.CreateException();
}
}
}
}
protected abstract void GetInjectableMonoBehaviours(List<MonoBehaviour> components);
}
}
#endif
| |
// This file is part of Wintermute Engine
// For conditions of distribution and use, see copyright notice in license.txt
// http://dead-code.org/redir.php?target=wme
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
// Delarations of native Win32 functions/structs/constants
// Taken from DX SDK (modified)
namespace DeadCode.WME.Global
{
public class NativeMethods
{
#region Win32 User Messages / Structures
/// <summary>Window messages</summary>
public enum WindowMessage : uint
{
// Misc messages
Destroy = 0x0002,
Close = 0x0010,
Quit = 0x0012,
Paint = 0x000F,
SetCursor = 0x0020,
Activate = 0x0006,
ActivateApplication = 0x001C,
NonClientActivate = 0x0086,
EnterMenuLoop = 0x0211,
ExitMenuLoop = 0x0212,
NonClientHitTest = 0x0084,
PowerBroadcast = 0x0218,
SystemCommand = 0x0112,
GetMinMax = 0x0024,
// Keyboard messages
KeyDown = 0x0100,
KeyUp = 0x0101,
Character = 0x0102,
SystemKeyDown = 0x0104,
SystemKeyUp = 0x0105,
SystemCharacter = 0x0106,
// Mouse messages
MouseMove = 0x0200,
LeftButtonDown = 0x0201,
LeftButtonUp = 0x0202,
LeftButtonDoubleClick = 0x0203,
RightButtonDown = 0x0204,
RightButtonUp = 0x0205,
RightButtonDoubleClick = 0x0206,
MiddleButtonDown = 0x0207,
MiddleButtonUp = 0x0208,
MiddleButtonDoubleClick = 0x0209,
NcLeftButtonDown = 0x0A1,
NcRightButtonDown = 0x0A4,
NcMiddleButtonDown = 0x0A7,
MouseWheel = 0x020a,
XButtonDown = 0x020B,
XButtonUp = 0x020c,
XButtonDoubleClick = 0x020d,
MouseFirst = LeftButtonDown, // Skip mouse move, it happens a lot and there is another message for that
MouseLast = XButtonDoubleClick,
// Sizing
EnterSizeMove = 0x0231,
ExitSizeMove = 0x0232,
Size = 0x0005,
}
/// <summary>Mouse buttons</summary>
public enum MouseButtons
{
Left = 0x0001,
Right = 0x0002,
Middle = 0x0010,
Side1 = 0x0020,
Side2 = 0x0040,
}
/// <summary>Keyboard events</summary>
public enum KeyboardEvent
{
KeyUp = 0x0002, //KEYEVENTF_KEYUP
}
/// <summary>Extended window styles</summary>
[Flags]
public enum WindowStyleEx
{
ToolWindow = 0x00000080,
NoActivate = 0x08000000,
TopMost = 0x00000008,
}
/// <summary>Windows Message</summary>
[StructLayout(LayoutKind.Sequential)]
public struct Message
{
public IntPtr hWnd;
public WindowMessage msg;
public IntPtr wParam;
public IntPtr lParam;
public uint time;
public System.Drawing.Point p;
}
/// <summary>MinMax Info structure</summary>
[StructLayout(LayoutKind.Sequential)]
public struct MinMaxInformation
{
public System.Drawing.Point reserved;
public System.Drawing.Point MaxSize;
public System.Drawing.Point MaxPosition;
public System.Drawing.Point MinTrackSize;
public System.Drawing.Point MaxTrackSize;
}
/// <summary>Monitor Info structure</summary>
[StructLayout(LayoutKind.Sequential)]
public struct MonitorInformation
{
public uint Size; // Size of this structure
public System.Drawing.Rectangle MonitorRectangle;
public System.Drawing.Rectangle WorkRectangle;
public uint Flags; // Possible flags
}
[StructLayout(LayoutKind.Sequential)]
public struct PeekMsg
{
public IntPtr hWnd;
public Message msg;
public IntPtr wParam;
public IntPtr lParam;
public uint time;
public System.Drawing.Point p;
}
#endregion
#region Windows API calls
[System.Security.SuppressUnmanagedCodeSecurity] // We won't use this maliciously
[System.Runtime.InteropServices.DllImport("winmm.dll")]
public static extern IntPtr timeBeginPeriod(uint period);
[System.Security.SuppressUnmanagedCodeSecurity] // We won't use this maliciously
[DllImport("kernel32")]
public static extern bool QueryPerformanceFrequency(ref long PerformanceFrequency);
[System.Security.SuppressUnmanagedCodeSecurity] // We won't use this maliciously
[DllImport("kernel32")]
public static extern bool QueryPerformanceCounter(ref long PerformanceCount);
[System.Security.SuppressUnmanagedCodeSecurity] // We won't use this maliciously
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern bool GetMonitorInfo(IntPtr hWnd, ref MonitorInformation info);
[System.Security.SuppressUnmanagedCodeSecurity] // We won't use this maliciously
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr MonitorFromWindow(IntPtr hWnd, uint flags);
[System.Security.SuppressUnmanagedCodeSecurity] // We won't use this maliciously
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern short GetAsyncKeyState(uint key);
[System.Security.SuppressUnmanagedCodeSecurity] // We won't use this maliciously
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SetCapture(IntPtr handle);
[System.Security.SuppressUnmanagedCodeSecurity] // We won't use this maliciously
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern bool ReleaseCapture();
[System.Security.SuppressUnmanagedCodeSecurity] // We won't use this maliciously
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int GetCaretBlinkTime();
[System.Security.SuppressUnmanagedCodeSecurity] // We won't use this maliciously
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern bool PeekMessage(out Message msg, IntPtr hWnd, uint messageFilterMin, uint messageFilterMax, uint flags);
[System.Security.SuppressUnmanagedCodeSecurity] // We won't use this maliciously
[DllImport("user32")]
public static extern int SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
[System.Security.SuppressUnmanagedCodeSecurity] // We won't use this maliciously
[DllImport("user32")]
public static extern IntPtr GetParent(IntPtr hWndChild);
[System.Security.SuppressUnmanagedCodeSecurity] // We won't use this maliciously
[DllImport("user32")]
public static extern int ShowWindow(IntPtr hWnd, int nCmdShow);
[System.Security.SuppressUnmanagedCodeSecurity] // We won't use this maliciously
[DllImport("user32", CharSet = CharSet.Auto)]
public extern static int SendMessage(IntPtr handle, int msg, int wParam, IntPtr lParam);
[System.Security.SuppressUnmanagedCodeSecurity] // We won't use this maliciously
[DllImport("user32", CharSet = CharSet.Auto)]
public extern static int PostMessage(IntPtr handle, int msg, int wParam, IntPtr lParam);
[System.Security.SuppressUnmanagedCodeSecurity] // We won't use this maliciously
[DllImport("user32")]
public extern static void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);
[System.Security.SuppressUnmanagedCodeSecurity] // We won't use this maliciously
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle);
[System.Security.SuppressUnmanagedCodeSecurity] // We won't use this maliciously
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool PeekMessage(out PeekMsg msg, IntPtr hWnd, uint messageFilterMin, uint messageFilterMax, uint flags);
#endregion
#region Class Methods
private NativeMethods() { } // No creation
/// <summary>Returns the low word</summary>
public static short LoWord(uint l)
{
return (short)(l & 0xffff);
}
/// <summary>Returns the high word</summary>
public static short HiWord(uint l)
{
return (short)(l >> 16);
}
/// <summary>Makes two shorts into a long</summary>
public static uint MakeUInt32(short l, short r)
{
return (uint)((l & 0xffff) | ((r & 0xffff) << 16));
}
/// <summary>Is this key down right now</summary>
public static bool IsKeyDown(System.Windows.Forms.Keys key)
{
return (GetAsyncKeyState((int)System.Windows.Forms.Keys.ShiftKey) & 0x8000) != 0;
}
#endregion
}
}
| |
using System.Collections.Generic;
using UnityEngine;
using System.Collections;
using Hashtable = ExitGames.Client.Photon.Hashtable;
/// <summary>
/// Makes a scene object pickup-able. Needs a PhotonView which belongs to the scene.
/// </summary>
/// <remarks>Includes a OnPhotonSerializeView implementation that </remarks>
[RequireComponent(typeof(PhotonView))]
public class PickupItem : Photon.MonoBehaviour, IPunObservable
{
///<summary>Enables you to define a timeout when the picked up item should re-spawn at the same place it was before.</summary>
/// <remarks>
/// Set in Inspector per GameObject! The value in code is just the default.
///
/// If you don't want an item to respawn, set SecondsBeforeRespawn == 0.
/// If an item does not respawn, it could be consumed or carried around and dropped somewhere else.
///
/// A respawning item should stick to a fixed position. It should not be observed at all (in any PhotonView).
/// It can only be consumed and can't be dropped somewhere else (cause that would double the item).
///
/// This script uses PunRespawn() as RPC and as method that gets called by Invoke() after a timeout.
/// No matter if the item respawns timed or by Drop, that method makes sure (temporary) owner and other status-values
/// are being re-set.
/// </remarks>
public float SecondsBeforeRespawn = 2;
/// <summary>The most likely trigger to pick up an item. Set in inspector!</summary>
/// <remarks>Edit the collider and set collision masks to avoid pickups by random objects.</remarks>
public bool PickupOnTrigger;
/// <summary>If the pickup item is currently yours. Interesting in OnPickedUp(PickupItem item).</summary>
public bool PickupIsMine;
/// <summary>GameObject to send an event "OnPickedUp(PickupItem item)" to.</summary>
/// <remarks>
/// Implement OnPickedUp(PickupItem item) {} in some script on the linked game object.
/// The item will be "this" and item.PickupIsMine will help you to find if this pickup was done by "this player".
/// </remarks>
public MonoBehaviour OnPickedUpCall;
// these values are internally used. they are public for debugging only
/// <summary>If this client sent a pickup. To avoid sending multiple pickup requests before reply is there.</summary>
public bool SentPickup;
/// <summary>Timestamp when to respawn the item (compared to PhotonNetwork.time). </summary>
public double TimeOfRespawn; // needed when we want to update new players when a PickupItem respawns
/// <summary></summary>
public int ViewID { get { return this.photonView.viewID; } }
public static HashSet<PickupItem> DisabledPickupItems = new HashSet<PickupItem>();
public void OnTriggerEnter(Collider other)
{
// we only call Pickup() if "our" character collides with this PickupItem.
// note: if you "position" remote characters by setting their translation, triggers won't be hit.
PhotonView otherpv = other.GetComponent<PhotonView>();
if (this.PickupOnTrigger && otherpv != null && otherpv.isMine)
{
//Debug.Log("OnTriggerEnter() calls Pickup().");
this.Pickup();
}
}
public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
{
// read the description in SecondsBeforeRespawn
if (stream.isWriting && SecondsBeforeRespawn <= 0)
{
stream.SendNext(this.gameObject.transform.position);
}
else
{
// this will directly apply the last received position for this PickupItem. No smoothing. Usually not needed though.
Vector3 lastIncomingPos = (Vector3)stream.ReceiveNext();
this.gameObject.transform.position = lastIncomingPos;
}
}
public void Pickup()
{
if (this.SentPickup)
{
// skip sending more pickups until the original pickup-RPC got back to this client
return;
}
this.SentPickup = true;
this.photonView.RPC("PunPickup", PhotonTargets.AllViaServer);
}
/// <summary>Makes use of RPC PunRespawn to drop an item (sent through server for all).</summary>
public void Drop()
{
if (this.PickupIsMine)
{
this.photonView.RPC("PunRespawn", PhotonTargets.AllViaServer);
}
}
/// <summary>Makes use of RPC PunRespawn to drop an item (sent through server for all).</summary>
public void Drop(Vector3 newPosition)
{
if (this.PickupIsMine)
{
this.photonView.RPC("PunRespawn", PhotonTargets.AllViaServer, newPosition);
}
}
[PunRPC]
public void PunPickup(PhotonMessageInfo msgInfo)
{
// when this client's RPC gets executed, this client no longer waits for a sent pickup and can try again
if (msgInfo.sender.isLocal) this.SentPickup = false;
// In this solution, picked up items are disabled. They can't be picked up again this way, etc.
// You could check "active" first, if you're not interested in failed pickup-attempts.
if (!this.gameObject.GetActive())
{
// optional logging:
Debug.Log("Ignored PU RPC, cause item is inactive. " + this.gameObject + " SecondsBeforeRespawn: " + SecondsBeforeRespawn + " TimeOfRespawn: " + this.TimeOfRespawn + " respawn in future: " + (TimeOfRespawn > PhotonNetwork.time));
return; // makes this RPC being ignored
}
// if the RPC isn't ignored by now, this is a successful pickup. this might be "my" pickup and we should do a callback
this.PickupIsMine = msgInfo.sender.isLocal;
// call the method OnPickedUp(PickupItem item) if a GameObject was defined as callback target
if (this.OnPickedUpCall != null)
{
// you could also skip callbacks for items that are not picked up by this client by using: if (this.PickupIsMine)
this.OnPickedUpCall.SendMessage("OnPickedUp", this);
}
// setup a respawn (or none, if the item has to be dropped)
if (SecondsBeforeRespawn <= 0)
{
this.PickedUp(0.0f); // item doesn't auto-respawn. must be dropped
}
else
{
// how long it is until this item respanws, depends on the pickup time and the respawn time
double timeSinceRpcCall = (PhotonNetwork.time - msgInfo.timestamp);
double timeUntilRespawn = SecondsBeforeRespawn - timeSinceRpcCall;
//Debug.Log("msg timestamp: " + msgInfo.timestamp + " time until respawn: " + timeUntilRespawn);
if (timeUntilRespawn > 0)
{
this.PickedUp((float)timeUntilRespawn);
}
}
}
internal void PickedUp(float timeUntilRespawn)
{
// this script simply disables the GO for a while until it respawns.
this.gameObject.SetActive(false);
PickupItem.DisabledPickupItems.Add(this);
this.TimeOfRespawn = 0;
if (timeUntilRespawn > 0)
{
this.TimeOfRespawn = PhotonNetwork.time + timeUntilRespawn;
Invoke("PunRespawn", timeUntilRespawn);
}
}
[PunRPC]
internal void PunRespawn(Vector3 pos)
{
Debug.Log("PunRespawn with Position.");
this.PunRespawn();
this.gameObject.transform.position = pos;
}
[PunRPC]
internal void PunRespawn()
{
#if DEBUG
// debugging: in some cases, the respawn is "late". it's unclear why! just be aware of this.
double timeDiffToRespawnTime = PhotonNetwork.time - this.TimeOfRespawn;
if (timeDiffToRespawnTime > 0.1f) Debug.LogWarning("SpawnSpectre time is wrong by: " + timeDiffToRespawnTime + " (this is not an error. you just need to be aware of this.)");
#endif
// if this is called from another thread, we might want to do this in OnEnable() instead of here (depends on Invoke's implementation)
PickupItem.DisabledPickupItems.Remove(this);
this.TimeOfRespawn = 0;
this.PickupIsMine = false;
if (this.gameObject != null)
{
this.gameObject.SetActive(true);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="BatchParser.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.UI {
using System;
using System.IO;
using System.Web.Configuration;
using System.Collections;
using System.Collections.Specialized;
using System.Threading;
using System.Globalization;
using System.Web.Hosting;
using System.Web.Caching;
using System.Web.Util;
using System.Web.Compilation;
using HttpException = System.Web.HttpException;
using Debug=System.Web.Util.Debug;
using System.Text.RegularExpressions;
internal abstract class DependencyParser : BaseParser {
private VirtualPath _virtualPath;
private StringSet _virtualPathDependencies;
// Used to detect circular references
private StringSet _circularReferenceChecker = new CaseInsensitiveStringSet();
// The <pages> config section
private PagesSection _pagesConfig;
protected PagesSection PagesConfig {
get { return _pagesConfig; }
}
internal void Init(VirtualPath virtualPath) {
CurrentVirtualPath = virtualPath;
_virtualPath = virtualPath;
_pagesConfig = MTConfigUtil.GetPagesConfig(virtualPath);
}
internal ICollection GetVirtualPathDependencies() {
// Always set the culture to Invariant when parsing (ASURT 99071)
Thread currentThread = Thread.CurrentThread;
CultureInfo prevCulture = currentThread.CurrentCulture;
HttpRuntime.SetCurrentThreadCultureWithAssert(CultureInfo.InvariantCulture);
try {
try {
PrepareParse();
ParseFile();
}
finally {
// Restore the previous culture
HttpRuntime.SetCurrentThreadCultureWithAssert(prevCulture);
}
}
catch { throw; } // Prevent Exception Filter Security Issue (ASURT 122835)
return _virtualPathDependencies;
}
protected void AddDependency(VirtualPath virtualPath) {
virtualPath = ResolveVirtualPath(virtualPath);
Debug.Trace("Template", "Parsed dependency: " + _virtualPath + " depends on " + virtualPath);
if (_virtualPathDependencies == null)
_virtualPathDependencies = new CaseInsensitiveStringSet();
_virtualPathDependencies.Add(virtualPath.VirtualPathString);
}
internal abstract string DefaultDirectiveName { get; }
protected virtual void PrepareParse() {}
private void ParseFile() {
ParseFile(null /*physicalPath*/, _virtualPath);
}
private void ParseFile(string physicalPath, VirtualPath virtualPath) {
// Determine the file used for the circular references checker. Normally,
// we use the virtualPath, but we use the physical path if it specified,
// as is the case for <!-- #include file="foo.inc" -->
string fileToReferenceCheck = physicalPath != null ? physicalPath : virtualPath.VirtualPathString;
// Check for circular references of include files
if (_circularReferenceChecker.Contains(fileToReferenceCheck)) {
throw new HttpException(
SR.GetString(SR.Circular_include));
}
// Add the current file to the circular references checker.
_circularReferenceChecker.Add(fileToReferenceCheck);
try {
// Open a TextReader either from the physical or virtual path
TextReader reader;
if (physicalPath != null) {
using (reader = Util.ReaderFromFile(physicalPath, virtualPath)) {
ParseReader(reader);
}
}
else {
using (Stream stream = virtualPath.OpenFile()) {
reader = Util.ReaderFromStream(stream, virtualPath);
ParseReader(reader);
}
}
}
finally {
// Remove the current file from the circular references checker
_circularReferenceChecker.Remove(fileToReferenceCheck);
}
}
private void ParseReader(TextReader input) {
ParseString(input.ReadToEnd());
}
private void ParseString(string text) {
int textPos = 0;
for (;;) {
Match match;
// 1: scan for text up to the next tag.
if ((match = textRegex.Match(text, textPos)).Success) {
textPos = match.Index + match.Length;
}
// we might be done now
if (textPos == text.Length)
break;
// 2: handle constructs that start with <
// Check to see if it's a directive (i.e. <%@ %> block)
if ((match = directiveRegex.Match(text, textPos)).Success) {
IDictionary directive = CollectionsUtil.CreateCaseInsensitiveSortedList();
string directiveName = ProcessAttributes(match, directive);
ProcessDirective(directiveName, directive);
textPos = match.Index + match.Length;
}
else if ((match = includeRegex.Match(text, textPos)).Success) {
ProcessServerInclude(match);
textPos = match.Index + match.Length;
}
else if ((match = commentRegex.Match(text, textPos)).Success) {
// Just skip it
textPos = match.Index + match.Length;
}
else {
int newPos = text.IndexOf("<%@", textPos, StringComparison.Ordinal);
// 2nd condition is used to catch invalid directives, e.g. <%@ attr="value_without_end_quote >
if (newPos == -1 || newPos == textPos) {
return;
}
textPos = newPos;
}
// we might be done now
if (textPos == text.Length)
return;
}
}
/*
* Process a server side include. e.g. <!-- #include file="foo.inc" -->
*/
private void ProcessServerInclude(Match match) {
string pathType = match.Groups["pathtype"].Value;
string filename = match.Groups["filename"].Value;
if (filename.Length == 0) return;
VirtualPath newVirtualPath;
string newPhysicalPath = null;
if (StringUtil.EqualsIgnoreCase(pathType, "file")) {
if (UrlPath.IsAbsolutePhysicalPath(filename)) {
// If it's an absolute physical path, use it as is
newPhysicalPath = filename;
// Reuse the current virtual path
newVirtualPath = CurrentVirtualPath;
}
else {
// If it's relative, just treat it as virtual
newVirtualPath = ResolveVirtualPath(VirtualPath.Create(filename));
}
}
else if (StringUtil.EqualsIgnoreCase(pathType, "virtual")) {
newVirtualPath = ResolveVirtualPath(VirtualPath.Create(filename));
}
else {
// Unknown #include type: ignore it
return;
}
VirtualPath prevVirtualPath = _virtualPath;
try {
_virtualPath = newVirtualPath;
// Parse the included file recursively
ParseFile(newPhysicalPath, newVirtualPath);
}
finally {
// Restore the paths
_virtualPath = prevVirtualPath;
}
}
/*
* Process a <%@ %> block
*/
internal virtual void ProcessDirective(string directiveName, IDictionary directive) {
// Get all the directives into a bag
// Check for the main directive (e.g. "page" for an aspx)
if (directiveName == null ||
StringUtil.EqualsIgnoreCase(directiveName, DefaultDirectiveName) ) {
ProcessMainDirective(directive);
}
else if (StringUtil.EqualsIgnoreCase(directiveName, "register")) {
VirtualPath src = Util.GetAndRemoveVirtualPathAttribute(directive, "src");
if (src != null) {
AddDependency(src);
}
}
else if (StringUtil.EqualsIgnoreCase(directiveName, "reference")) {
VirtualPath virtualPath = Util.GetAndRemoveVirtualPathAttribute(directive, "virtualpath");
if (virtualPath != null)
AddDependency(virtualPath);
VirtualPath page = Util.GetAndRemoveVirtualPathAttribute(directive, "page");
if (page != null)
AddDependency(page);
VirtualPath control = Util.GetAndRemoveVirtualPathAttribute(directive, "control");
if (control != null)
AddDependency(control);
}
else if (StringUtil.EqualsIgnoreCase(directiveName, "assembly")) {
VirtualPath src = Util.GetAndRemoveVirtualPathAttribute(directive, "src");
if (src != null)
AddDependency(src);
}
}
private void ProcessMainDirective(IDictionary mainDirective) {
// Go through all the attributes on the directive
foreach (DictionaryEntry entry in mainDirective) {
string attribName = ((string)entry.Key).ToLower(CultureInfo.InvariantCulture);
// Parse out the device name, if any
string name;
string deviceName = Util.ParsePropertyDeviceFilter(attribName, out name);
// Process the attribute
ProcessMainDirectiveAttribute(deviceName, name, (string) entry.Value);
}
}
internal virtual void ProcessMainDirectiveAttribute(string deviceName, string name,
string value) {
// A "src" attribute is equivalent to an imported source file
if (name == "src") {
string src = Util.GetNonEmptyAttribute(name, value);
AddDependency(VirtualPath.Create(src));
}
}
/*
* Adds attributes and their values to the attribs
*/
private string ProcessAttributes(Match match, IDictionary attribs) {
string ret = null;
CaptureCollection attrnames = match.Groups["attrname"].Captures;
CaptureCollection attrvalues = match.Groups["attrval"].Captures;
CaptureCollection equalsign = match.Groups["equal"].Captures;
for (int i = 0; i < attrnames.Count; i++) {
string attribName = attrnames[i].ToString();
string attribValue = attrvalues[i].ToString();
bool fHasEqual = (equalsign[i].ToString().Length > 0);
if (attribName != null && !fHasEqual && ret == null) {
ret = attribName;
continue;
}
try {
if (attribs != null)
attribs.Add(attribName, attribValue);
}
catch (ArgumentException) {}
}
return ret;
}
}
internal abstract class TemplateControlDependencyParser : DependencyParser {
internal override void ProcessMainDirectiveAttribute(string deviceName, string name,
string value) {
switch (name) {
case "masterpagefile":
value = value.Trim();
if (value.Length > 0) {
// Add a dependency on the master, whether it has a device filter or not
AddDependency(VirtualPath.Create(value));
}
break;
default:
// We didn't handle the attribute. Try the base class
base.ProcessMainDirectiveAttribute(deviceName, name, value);
break;
}
}
}
internal class PageDependencyParser : TemplateControlDependencyParser {
internal override string DefaultDirectiveName {
get { return PageParser.defaultDirectiveName; }
}
protected override void PrepareParse() {
if (PagesConfig != null) {
if (PagesConfig.MasterPageFileInternal != null && PagesConfig.MasterPageFileInternal.Length != 0)
AddDependency(VirtualPath.Create(PagesConfig.MasterPageFileInternal));
}
}
internal override void ProcessDirective(string directiveName, IDictionary directive) {
base.ProcessDirective(directiveName, directive);
if (StringUtil.EqualsIgnoreCase(directiveName, "previousPageType") ||
StringUtil.EqualsIgnoreCase(directiveName, "masterType")) {
VirtualPath virtualPath = Util.GetAndRemoveVirtualPathAttribute(directive, "virtualPath");
if (virtualPath != null)
AddDependency(virtualPath);
}
}
}
internal class UserControlDependencyParser : TemplateControlDependencyParser {
internal override string DefaultDirectiveName {
get { return UserControlParser.defaultDirectiveName; }
}
}
internal class MasterPageDependencyParser : UserControlDependencyParser {
internal override string DefaultDirectiveName {
get { return MasterPageParser.defaultDirectiveName; }
}
internal override void ProcessDirective(string directiveName, IDictionary directive) {
base.ProcessDirective(directiveName, directive);
if (StringUtil.EqualsIgnoreCase(directiveName, "masterType")) {
VirtualPath virtualPath = Util.GetAndRemoveVirtualPathAttribute(directive, "virtualPath");
if (virtualPath != null)
AddDependency(virtualPath);
}
}
}
}
| |
using GuruComponents.Netrix.WebEditing;
using GuruComponents.Netrix.ComInterop;
using System;
using System.ComponentModel;
using System.Web.UI.WebControls;
using GuruComponents.Netrix.Events;
using GuruComponents.Netrix.Designer;
using System.Collections;
using GuruComponents.Netrix.UserInterface.TypeEditors;
using System.Web.UI.Design;
using System.Web.UI;
using System.Drawing;
using GuruComponents.Netrix.AspDotNetDesigner;
namespace GuruComponents.Netrix.WebEditing.Elements
{
/// <summary>
/// A generic class for access to methods which can't handle System.Web.UI.Control based elements.
/// </summary>
/// <remarks>
/// Internally this class is used to resolve and show User Controls loaded from ASCX files.
/// </remarks>
public class AscxElement : System.Web.UI.UserControl, IElement
{
private IHtmlEditor editor;
private Interop.IHTMLElement peer;
private Interop.IHTMLElement2 peer2;
private Interop.IHTMLElement3 peer3;
private DesignTimeBehavior behavior;
private IElementBehavior elementBehavior;
/// <summary>
/// Behavior
/// </summary>
[Browsable(false)]
public DesignTimeBehavior Behavior
{
get { return behavior; }
}
/// <summary>
/// Ctor
/// </summary>
public AscxElement() : base()
{
}
/// <summary>
/// ctor
/// </summary>
/// <param name="editor"></param>
/// <param name="peer"></param>
internal AscxElement(IHtmlEditor editor, Interop.IHTMLElement peer) : this(editor, peer, null)
{
}
/// <summary>
/// ctor
/// </summary>
/// <param name="editor"></param>
/// <param name="peer"></param>
/// <param name="behavior"></param>
internal AscxElement(IHtmlEditor editor, Interop.IHTMLElement peer, DesignTimeBehavior behavior)
{
this.editor = editor;
this.peer = peer;
this.peer2 = (Interop.IHTMLElement2)peer;
this.peer3 = (Interop.IHTMLElement3)peer;
this.behavior = behavior;
}
/// <summary>
/// Add peer. This is internally used und shall never be called from user code.
/// </summary>
/// <param name="element"></param>
protected internal void AssociatePeer(Interop.IHTMLElement element)
{
this.peer = element;
this.peer2 = (Interop.IHTMLElement2)element;
this.peer3 = (Interop.IHTMLElement3)element;
this.behavior = null;
}
/// <summary>
/// ctor
/// </summary>
/// <param name="element"></param>
/// <param name="behavior"></param>
internal protected void AssociatePeer(Interop.IHTMLElement element, DesignTimeBehavior behavior)
{
this.peer = element;
this.peer2 = (Interop.IHTMLElement2)element;
this.peer3 = (Interop.IHTMLElement3)element;
this.behavior = behavior;
}
#region IElement Members
event DocumentEventHandler IElement.LoseCapture { add { } remove { } }
event DocumentEventHandler IElement.Click{ add{} remove{} }
event DocumentEventHandler IElement.DblClick{ add{} remove{} }
event DocumentEventHandler IElement.DragStart{ add{} remove{} }
event DocumentEventHandler IElement.Focus{ add{} remove{} }
event DocumentEventHandler IElement.Drop{ add{} remove{} }
event DocumentEventHandler IElement.Blur{ add{} remove{} }
event DocumentEventHandler IElement.DragOver{ add{} remove{} }
event DocumentEventHandler IElement.DragEnter{ add{} remove{} }
event DocumentEventHandler IElement.DragLeave{ add{} remove{} }
event DocumentEventHandler IElement.KeyDown{ add{} remove{} }
event DocumentEventHandler IElement.KeyPress{ add{} remove{} }
event DocumentEventHandler IElement.KeyUp{ add{} remove{} }
event DocumentEventHandler IElement.MouseDown{ add{} remove{} }
event DocumentEventHandler IElement.ResizeStart{ add{} remove{} }
event DocumentEventHandler IElement.ResizeEnd{ add{} remove{} }
event DocumentEventHandler IElement.MouseEnter{ add{} remove{} }
event DocumentEventHandler IElement.MouseLeave{ add{} remove{} }
event DocumentEventHandler IElement.MouseMove{ add{} remove{} }
event DocumentEventHandler IElement.MouseOut{ add{} remove{} }
event DocumentEventHandler IElement.MouseOver{ add{} remove{} }
event DocumentEventHandler IElement.MouseUp{ add{} remove{} }
event DocumentEventHandler IElement.SelectStart{ add{} remove{} }
event DocumentEventHandler IElement.LayoutComplete{ add{} remove{} }
event DocumentEventHandler IElement.Load{ add{} remove{} }
event DocumentEventHandler IElement.MouseWheel{ add{} remove{} }
event DocumentEventHandler IElement.MoveEnd{ add{} remove{} }
event DocumentEventHandler IElement.MoveStart{ add{} remove{} }
event DocumentEventHandler IElement.Activate{ add{} remove{} }
event DocumentEventHandler IElement.BeforeActivate{ add{} remove{} }
event DocumentEventHandler IElement.BeforeCopy{ add{} remove{} }
event DocumentEventHandler IElement.BeforeCut{ add{} remove{} }
event DocumentEventHandler IElement.BeforePaste{ add{} remove{} }
event DocumentEventHandler IElement.ContextMenu{ add{} remove{} }
event DocumentEventHandler IElement.Copy{ add{} remove{} }
event DocumentEventHandler IElement.Cut{ add{} remove{} }
event DocumentEventHandler IElement.Deactivate{ add{} remove{} }
event DocumentEventHandler IElement.Drag{ add{} remove{} }
event DocumentEventHandler IElement.DragEnd{ add{} remove{} }
event DocumentEventHandler IElement.FocusIn{ add{} remove{} }
event DocumentEventHandler IElement.FocusOut{ add{} remove{} }
event DocumentEventHandler IElement.FilterChange{ add{} remove{} }
event DocumentEventHandler IElement.Abort{ add{} remove{} }
event DocumentEventHandler IElement.Change{ add{} remove{} }
event DocumentEventHandler IElement.Select{ add{} remove{} }
event DocumentEventHandler IElement.SelectionChange{ add{} remove{} }
event DocumentEventHandler IElement.Stop{ add{} remove{} }
event DocumentEventHandler IElement.BeforeDeactivate{ add{} remove{} }
event DocumentEventHandler IElement.ControlSelect{ add{} remove{} }
event DocumentEventHandler IElement.EditFocus{ add{} remove{} }
event DocumentEventHandler IElement.Error{ add{} remove{} }
event DocumentEventHandler IElement.Move{ add{} remove{} }
event DocumentEventHandler IElement.Paste{ add{} remove{} }
event DocumentEventHandler IElement.PropertyChange{ add{} remove{} }
event DocumentEventHandler IElement.Resize{ add{} remove{} }
event DocumentEventHandler IElement.Scroll{ add{} remove{} }
event DocumentEventHandler IElement.Paged { add{} remove{} }
[Browsable(false)]
IExtendedProperties IElement.ExtendedProperties
{
get { throw new Exception("The method or operation is not implemented."); }
}
[Browsable(false)]
string IElement.UniqueName
{
get { return ""; }
}
/// <summary>
/// Selectable
/// </summary>
/// <returns></returns>
public bool IsSelectable()
{
return editor.Selection.IsSelectableElement(this);
}
/// <summary>
/// Position style.
/// </summary>
[Browsable(false)]
public bool IsAbsolutePositioned
{
get { return peer.GetStyle().GetPosition().Equals("absolute"); }
}
[Browsable(false)]
bool IElement.IsTextEdit
{
get { throw new Exception("The method or operation is not implemented."); }
}
/// <summary>
/// Insert an element
/// </summary>
/// <param name="method"></param>
/// <param name="element"></param>
public void InsertAdjacentElement(InsertWhere method, IElement element)
{
if (element == null) return;
peer2.InsertAdjacentElement(method.ToString(), element.GetBaseElement());
}
/// <summary>
/// Insert Html
/// </summary>
/// <param name="method"></param>
/// <param name="html"></param>
public void InsertAdjacentHtml(InsertWhere method, string html)
{
peer.InsertAdjacentHTML(method.ToString(), html);
}
/// <summary>
/// Insert text.
/// </summary>
/// <param name="method"></param>
/// <param name="text"></param>
public void InsertAdjacentText(InsertWhere method, string text)
{
peer.InsertAdjacentText(method.ToString(), text);
}
/// <summary>
/// Get area of element.
/// </summary>
/// <returns></returns>
public System.Drawing.Rectangle GetAbsoluteArea()
{
return new Rectangle(peer2.GetClientLeft(), peer2.GetClientTop(), peer2.GetClientWidth(), peer2.GetClientHeight());
}
/// <summary>
/// The peer element (generic base element)
/// </summary>
/// <returns></returns>
public Interop.IHTMLElement GetBaseElement()
{
return peer;
}
/// <summary>
/// Editor reference.
/// </summary>
[Browsable(false)]
public IHtmlEditor HtmlEditor
{
get
{
return editor;
}
set
{
editor = value;
}
}
/// <summary>
/// Is editable in browse mode.
/// </summary>
[Browsable(false)]
public bool ContentEditable
{
get
{
return (peer3 == null) ? false : peer3.contentEditable.Equals("true");
}
set
{
peer3.contentEditable = (value) ? "true" : "false";
}
}
/// <summary>
/// Supports atomic selection.
/// </summary>
public bool AtomicSelection
{
get
{
string sel = GetStringAttribute("ATOMICSELECTION");
return (sel.ToLower().Equals("true"));
}
set
{
SetStringAttribute("ATOMICSELECTION", value ? "true" : "false");
}
}
/// <summary>
/// Is selectable
/// </summary>
public bool Unselectable
{
get
{
string sel = GetStringAttribute("UNSELECTABLE");
return (sel.ToLower().Equals("on"));
}
set
{
SetStringAttribute("UNSELECTABLE", value ? "on" : "off");
}
}
/// <summary>
/// Access to the binary behavior manager at element level.
/// </summary>
[Browsable(false)]
public IElementBehavior ElementBehaviors
{
get
{
if (elementBehavior == null)
{
elementBehavior = new ElementBehavior(this);
}
return elementBehavior;
}
}
/// <summary>
/// Not supported
/// </summary>
[Browsable(false)]
string IElement.InnerHtml
{
get
{
throw new Exception("The method or operation is not implemented.");
}
set
{
throw new Exception("The method or operation is not implemented.");
}
}
/// <summary>
/// Thre outer HTML. Set path not implemented.
/// </summary>
[Browsable(false)]
public string OuterHtml
{
get
{
return peer.GetOuterHTML();
}
set
{
throw new Exception("The method or operation is not implemented.");
}
}
[Browsable(false)]
string IElement.InnerText
{
get
{
throw new Exception("The method or operation is not implemented.");
}
set
{
throw new Exception("The method or operation is not implemented.");
}
}
/// <summary>
/// Tag's name.
/// </summary>
public string TagName
{
get { return (peer == null) ? "UserControl" : peer.GetTagName(); }
}
/// <summary>
/// Self reference.
/// </summary>
[Browsable(false)]
public IElement TagElement
{
get { return this; }
}
/// <summary>
/// Alias for designer
/// </summary>
public string Alias
{
get { return (peer2 == null) ? "uc" : peer2.GetScopeName(); }
}
/// <summary>
/// Name of element
/// </summary>
public string ElementName
{
get { return String.Format("{0}:{1}", Alias, TagName); }
}
Control IElement.GetChild(int index)
{
throw new Exception("The method or operation is not implemented.");
}
Control IElement.GetChild(string name)
{
throw new Exception("The method or operation is not implemented.");
}
ElementCollection IElement.GetChildren()
{
throw new Exception("The method or operation is not implemented.");
}
Control IElement.GetParent()
{
throw new Exception("The method or operation is not implemented.");
}
/// <summary>
/// Get
/// </summary>
/// <returns></returns>
public string GetStyle()
{
return peer.GetStyle().GetCssText();
}
/// <summary>
/// Set
/// </summary>
/// <param name="CssText"></param>
public void SetStyle(string CssText)
{
peer.GetStyle().SetCssText(CssText);
}
/// <summary>
///
/// </summary>
/// <param name="styleName"></param>
/// <returns></returns>
public string GetStyleAttribute(string styleName)
{
throw new Exception("The method or operation is not implemented.");
}
void IElement.SetStyleAttribute(string styleName, string styleText)
{
throw new Exception("The method or operation is not implemented.");
}
void IElement.RemoveStyleAttribute(string styleName)
{
throw new Exception("The method or operation is not implemented.");
}
/// <summary>
/// Set
/// </summary>
/// <param name="attribute"></param>
/// <param name="value"></param>
public void SetAttribute(string attribute, object value)
{
SetNativeAttribute(attribute, value);
}
/// <summary>
/// Remove
/// </summary>
/// <param name="attribute"></param>
public void RemoveAttribute(string attribute)
{
peer.RemoveAttribute(attribute, 0);
}
/// <summary>
/// Get
/// </summary>
/// <param name="attribute"></param>
/// <returns></returns>
public object GetAttribute(string attribute)
{
return GetNativeAttribute(attribute);
}
[Browsable(false)]
IElementDom IElement.ElementDom
{
get { throw new NotImplementedException("The method or operation is not implemented."); }
}
[Browsable(false)]
GuruComponents.Netrix.WebEditing.Styles.IEffectiveStyle IElement.EffectiveStyle
{
get { throw new NotImplementedException("The method or operation is not implemented."); }
}
[Browsable(false)]
GuruComponents.Netrix.WebEditing.Styles.IElementStyle IElement.RuntimeStyle
{
get { throw new NotImplementedException("The method or operation is not implemented."); }
}
[Browsable(false)]
GuruComponents.Netrix.WebEditing.Styles.IElementStyle IElement.CurrentStyle
{
get { throw new NotImplementedException("The method or operation is not implemented."); }
}
#endregion
# region internal methods
/// <summary>
/// Universal access to any attribute.
/// </summary>
/// <remarks>
/// The type returned may vary depended on the internal type.
/// </remarks>
/// <param name="attribute">The name of the attribute.</param>
/// <returns>The object which is the value of the attribute.</returns>
private object GetNativeAttribute(string attribute)
{
if (peer == null) return null;
object local2;
attribute = (attribute.Equals("http-equiv")) ? "httpequiv" : attribute;
try
{
object[] locals = new object[1];
locals[0] = null;
peer.GetAttribute(attribute, 0, locals);
object local1 = locals[0];
if (local1 is DBNull)
{
local1 = null;
}
local2 = local1;
}
catch
{
local2 = null;
}
return local2;
}
private void SetNativeAttribute(string attr, object value)
{
peer.SetAttribute(attr, value, 0);
}
/// <summary>
/// Returns an attribute's value which is supposedly string.
/// </summary>
/// <param name="attribute">Name of attribute.</param>
/// <returns>String representation of value.</returns>
protected internal virtual string GetStringAttribute(string attribute)
{
return GetStringAttribute(attribute, String.Empty);
}
/// <summary>
/// Returns an attribute's value which is supposedly string.
/// </summary>
/// <param name="attribute">Name of attribute.</param>
/// <param name="defaultValue"></param>
/// <returns>String representation of value.</returns>
protected internal virtual string GetStringAttribute(string attribute, string defaultValue)
{
object local = GetAttribute(attribute);
if (local == null)
{
return defaultValue;
}
if (local is String)
{
return (string)local;
}
else
{
return defaultValue;
}
}
/// <summary>
///
/// </summary>
/// <param name="attribute"></param>
/// <param name="value"></param>
protected internal void SetStringAttribute(string attribute, string value)
{
SetStringAttribute(attribute, value, String.Empty);
}
/// <summary>
///
/// </summary>
/// <param name="attribute"></param>
/// <param name="value"></param>
/// <param name="defaultValue"></param>
protected internal void SetStringAttribute(string attribute, string value, string defaultValue)
{
if (value == null || value.Equals(defaultValue))
{
RemoveAttribute(attribute);
return;
}
SetAttribute(attribute, value);
}
# endregion
[Browsable(false)]
CssStyleCollection IElement.Style
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
public class CollectionFlow
{
public class A { }
public A[] As;
public void ArrayInitializerFlow()
{
var a = new A();
var @as = new[] { a };
Sink(@as[0]); // flow
SinkElem(@as); // flow
Sink(First(@as)); // flow
}
public void ArrayInitializerNoFlow(A other)
{
var a = new A();
var @as = new[] { other };
Sink(@as[0]); // no flow
SinkElem(@as); // no flow
Sink(First(@as)); // no flow
}
public void ArrayInitializerCSharp6Flow()
{
var a = new A();
var c = new CollectionFlow() { As = { [0] = a } };
Sink(c.As[0]); // flow
SinkElem(c.As); // flow
Sink(First(c.As)); // flow
}
public void ArrayInitializerCSharp6NoFlow(A other)
{
var a = new A();
var c = new CollectionFlow() { As = { [0] = other } };
Sink(c.As[0]); // no flow
SinkElem(c.As); // no flow
Sink(First(c.As)); // no flow
}
public void ArrayAssignmentFlow()
{
var a = new A();
var @as = new A[1];
@as[0] = a;
Sink(@as[0]); // flow
SinkElem(@as); // flow
Sink(First(@as)); // flow
}
public void ArrayAssignmentNoFlow(A other)
{
var a = new A();
var @as = new A[1];
@as[0] = other;
Sink(@as[0]); // no flow
SinkElem(@as); // no flow
Sink(First(@as)); // no flow
}
public void ListAssignmentFlow()
{
var a = new A();
var list = new List<A>();
list[0] = a;
Sink(list[0]); // flow
SinkListElem(list); // flow
Sink(ListFirst(list)); // flow
}
public void ListAssignmentNoFlow(A other)
{
var list = new List<A>();
list[0] = other;
Sink(list[0]); // no flow
SinkListElem(list); // no flow
Sink(ListFirst(list)); // no flow
}
public void ListInitializerFlow()
{
var a = new A();
var list = new List<A>() { a };
Sink(list[0]); // flow
SinkListElem(list); // flow
Sink(ListFirst(list)); // flow
}
public void ListInitializerNoFlow(A other)
{
var list = new List<A>() { other };
Sink(list[0]); // no flow
SinkListElem(list); // no flow
Sink(ListFirst(list)); // no flow
}
public void ListAddFlow()
{
var a = new A();
var list = new List<A>();
list.Add(a);
Sink(list[0]); // flow
SinkListElem(list); // flow
Sink(ListFirst(list)); // flow
}
public void ListAddNoFlow(A other)
{
var list = new List<A>();
list.Add(other);
Sink(list[0]); // no flow
SinkListElem(list); // no flow
Sink(ListFirst(list)); // no flow
}
public void DictionaryAssignmentFlow()
{
var a = new A();
var dict = new Dictionary<int, A>();
dict[0] = a;
Sink(dict[0]); // flow
SinkDictValue(dict); // flow
Sink(DictIndexZero(dict)); // flow
Sink(DictFirstValue(dict)); // flow
Sink(DictValuesFirst(dict)); // flow
}
public void DictionaryAssignmentNoFlow(A other)
{
var dict = new Dictionary<int, A>();
dict[0] = other;
Sink(dict[0]); // no flow
SinkDictValue(dict); // no flow
Sink(DictIndexZero(dict)); // no flow
Sink(DictFirstValue(dict)); // no flow
Sink(DictValuesFirst(dict)); // no flow
}
public void DictionaryValueInitializerFlow()
{
var a = new A();
var dict = new Dictionary<int, A>() { { 0, a } };
Sink(dict[0]); // flow
SinkDictValue(dict); // flow
Sink(DictIndexZero(dict)); // flow
Sink(DictFirstValue(dict)); // flow
Sink(DictValuesFirst(dict)); // flow
}
public void DictionaryValueInitializerNoFlow(A other)
{
var dict = new Dictionary<int, A>() { { 0, other } };
Sink(dict[0]); // no flow
SinkDictValue(dict); // no flow
Sink(DictIndexZero(dict)); // no flow
Sink(DictFirstValue(dict)); // no flow
Sink(DictValuesFirst(dict)); // no flow
}
public void DictionaryValueInitializerCSharp6Flow()
{
var a = new A();
var dict = new Dictionary<int, A>() { [0] = a };
Sink(dict[0]); // flow
SinkDictValue(dict); // flow
Sink(DictIndexZero(dict)); // flow
Sink(DictFirstValue(dict)); // flow
Sink(DictValuesFirst(dict)); // flow
}
public void DictionaryValueInitializerCSharp6NoFlow(A other)
{
var a = new A();
var dict = new Dictionary<int, A>() { [0] = other };
Sink(dict[0]); // no flow
SinkDictValue(dict); // no flow
Sink(DictIndexZero(dict)); // no flow
Sink(DictFirstValue(dict)); // no flow
Sink(DictValuesFirst(dict)); // no flow
}
public void DictionaryKeyInitializerFlow()
{
var a = new A();
var dict = new Dictionary<A, int>() { { a, 0 } };
Sink(dict.Keys.First()); // flow
SinkDictKey(dict); // flow
Sink(DictKeysFirst(dict)); // flow
Sink(DictFirstKey(dict)); // flow
}
public void DictionaryKeyInitializerNoFlow(A other)
{
var dict = new Dictionary<A, int>() { { other, 0 } };
Sink(dict.Keys.First()); // no flow
SinkDictKey(dict); // no flow
Sink(DictKeysFirst(dict)); // no flow
Sink(DictFirstKey(dict)); // no flow
}
public void DictionaryKeyInitializerCSharp6Flow()
{
var a = new A();
var dict = new Dictionary<A, int>() { [a] = 0 };
Sink(dict.Keys.First()); // flow
SinkDictKey(dict); // flow
Sink(DictKeysFirst(dict)); // flow
Sink(DictFirstKey(dict)); // flow
}
public void DictionaryKeyInitializerCSharp6NoFlow(A other)
{
var dict = new Dictionary<A, int>() { [other] = 0 };
Sink(dict.Keys.First()); // no flow
SinkDictKey(dict); // no flow
Sink(DictKeysFirst(dict)); // no flow
Sink(DictFirstKey(dict)); // no flow
}
public void ForeachFlow()
{
var a = new A();
var @as = new[] { a };
foreach (var x in @as)
Sink(x); // flow
}
public void ForeachNoFlow(A other)
{
var @as = new[] { other };
foreach (var x in @as)
Sink(x); // no flow
}
public void ArrayGetEnumeratorFlow()
{
var a = new A();
var @as = new[] { a };
var enumerator = @as.GetEnumerator();
while (enumerator.MoveNext())
Sink(enumerator.Current); // flow
}
public void ArrayGetEnumeratorNoFlow(A other)
{
var @as = new[] { other };
var enumerator = @as.GetEnumerator();
while (enumerator.MoveNext())
Sink(enumerator.Current); // no flow
}
public void ListGetEnumeratorFlow()
{
var a = new A();
var list = new List<A>();
list.Add(a);
var enumerator = list.GetEnumerator();
while (enumerator.MoveNext())
Sink(enumerator.Current); // flow
}
public void ListGetEnumeratorNoFlow(A other)
{
var list = new List<A>();
list.Add(other);
var enumerator = list.GetEnumerator();
while (enumerator.MoveNext())
Sink(enumerator.Current); // no flow
}
public void SelectFlow()
{
var a = new A();
var list = new List<KeyValuePair<A, int>>();
list.Add(new KeyValuePair<A, int>(a, 0));
list.Select(kvp =>
{
Sink(kvp.Key); // flow
return kvp.Value;
});
}
public void SelectNoFlow()
{
var a = new A();
var list = new List<KeyValuePair<A, int>>();
list.Add(new KeyValuePair<A, int>(a, 0));
list.Select(kvp =>
{
Sink(kvp.Value); // no flow
return kvp.Value;
});
}
void SetArray(A[] array, A element) => array[0] = element;
public void ArraySetterFlow()
{
var a = new A();
var @as = new A[1];
SetArray(@as, a);
Sink(@as[0]); // flow
SinkElem(@as); // flow
Sink(First(@as)); // flow
}
public void ArraySetterNoFlow(A other)
{
var a = new A();
var @as = new A[1];
SetArray(@as, other);
Sink(@as[0]); // no flow
SinkElem(@as); // no flow
Sink(First(@as)); // no flow
}
void SetList(List<A> list, A element) => list.Add(element);
public void ListSetterFlow()
{
var a = new A();
var list = new List<A>();
SetList(list, a);
Sink(list[0]); // flow
SinkListElem(list); // flow
Sink(ListFirst(list)); // flow
}
public void ListSetterNoFlow(A other)
{
var list = new List<A>();
SetList(list, other);
Sink(list[0]); // no flow
SinkListElem(list); // no flow
Sink(ListFirst(list)); // no flow
}
public void ParamsFlow()
{
SinkParams(new A()); // flow
SinkParams(null, new A()); // flow
SinkParams(null, new A(), null); // flow
SinkParams(new A[] { new A() }); // flow
}
public void ParamsNoFlow(A other)
{
SinkParams(other); // no flow
SinkParams(null, other); // no flow
SinkParams(null, other, null); // no flow
SinkParams(new A[] { other }); // no flow
}
public void ListAddClearNoFlow()
{
var a = new A();
var list = new List<A>();
list.Add(a);
list.Clear();
Sink(list[0]); // no flow
SinkListElem(list); // no flow
Sink(ListFirst(list)); // no flow
}
public static void Sink<T>(T t) { }
public static void SinkElem<T>(T[] ts) => Sink(ts[0]);
public static void SinkListElem<T>(IList<T> list) => Sink(list[0]);
public static void SinkDictValue<T>(IDictionary<int, T> dict) => Sink(dict[0]);
public static void SinkDictKey<T>(IDictionary<T, int> dict) => Sink(dict.Keys.First());
public static T First<T>(T[] ts) => ts[0];
public static T ListFirst<T>(IList<T> list) => list[0];
public static T DictIndexZero<T>(IDictionary<int, T> dict) => dict[0];
public static T DictFirstValue<T>(IDictionary<int, T> dict) => dict.First().Value;
public static T DictValuesFirst<T>(IDictionary<int, T> dict) => dict.Values.First();
public static T DictKeysFirst<T>(IDictionary<T, int> dict) => dict.Keys.First();
public static T DictFirstKey<T>(IDictionary<T, int> dict) => dict.First().Key;
public static void SinkParams<T>(params T[] args) => Sink(args[0]);
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Linq;
using System.Web.UI.WebControls;
using WebsitePanel.Providers.HostedSolution;
using WebsitePanel.EnterpriseServer;
using WebsitePanel.EnterpriseServer.Base.HostedSolution;
using System.Collections.Generic;
using System.Web.UI;
namespace WebsitePanel.Portal.ExchangeServer
{
public partial class ExchangeMailboxes : WebsitePanelModuleBase
{
private bool ArchivingBoxes
{
get
{
return PanelRequest.Ctl.ToLower().Contains("archiving");
}
}
private PackageContext cntx;
private ServiceLevel[] ServiceLevels;
protected void Page_Load(object sender, EventArgs e)
{
ClientScriptManager cs = Page.ClientScript;
cs.RegisterClientScriptInclude("jquery", ResolveUrl("~/JavaScript/jquery-1.4.4.min.js"));
locTitle.Text = ArchivingBoxes ? GetLocalizedString("locTitleArchiving.Text") : GetLocalizedString("locTitle.Text");
btnCreateMailbox.Visible = !ArchivingBoxes;
cntx = PackagesHelper.GetCachedPackageContext(PanelSecurity.PackageId);
if (!IsPostBack)
{
chkMailboxes.Checked = true;
chkResourceMailboxes.Checked = true;
chkSharedMailboxes.Checked = true;
BindStats();
}
BindServiceLevels();
if (cntx.Quotas.ContainsKey(Quotas.EXCHANGE2007_ISCONSUMER))
{
if (cntx.Quotas[Quotas.EXCHANGE2007_ISCONSUMER].QuotaAllocatedValue != 1)
{
gvMailboxes.Columns[6].Visible = false;
}
}
gvMailboxes.Columns[4].Visible = cntx.Groups.ContainsKey(ResourceGroups.ServiceLevels);
}
private void BindServiceLevels()
{
ServiceLevels = ES.Services.Organizations.GetSupportServiceLevels();
}
private void BindStats()
{
// quota values
OrganizationStatistics stats = ES.Services.ExchangeServer.GetOrganizationStatisticsByOrganization(PanelRequest.ItemID);
mailboxesQuota.QuotaUsedValue = stats.CreatedMailboxes;
mailboxesQuota.QuotaValue = stats.AllocatedMailboxes;
if (stats.AllocatedMailboxes != -1) mailboxesQuota.QuotaAvailable = stats.AllocatedMailboxes - stats.CreatedMailboxes;
if (cntx != null && cntx.Groups.ContainsKey(ResourceGroups.ServiceLevels)) BindServiceLevelsStats(stats);
}
private void BindServiceLevelsStats(OrganizationStatistics stats)
{
List<ServiceLevelQuotaValueInfo> serviceLevelQuotas = new List<ServiceLevelQuotaValueInfo>();
foreach (var quota in stats.ServiceLevels)
{
serviceLevelQuotas.Add(new ServiceLevelQuotaValueInfo
{
QuotaName = quota.QuotaName,
QuotaDescription = quota.QuotaDescription + " in this Organization:",
QuotaTypeId = quota.QuotaTypeId,
QuotaValue = quota.QuotaAllocatedValue,
QuotaUsedValue = quota.QuotaUsedValue,
QuotaAvailable = quota.QuotaAllocatedValue - quota.QuotaUsedValue
});
}
dlServiceLevelQuotas.DataSource = serviceLevelQuotas;
dlServiceLevelQuotas.DataBind();
}
protected void btnCreateMailbox_Click(object sender, EventArgs e)
{
Response.Redirect(EditUrl("ItemID", PanelRequest.ItemID.ToString(), "create_mailbox",
"SpaceID=" + PanelSecurity.PackageId));
}
public string GetMailboxEditUrl(string accountId)
{
return EditUrl("SpaceID", PanelSecurity.PackageId.ToString(), "mailbox_settings",
"AccountID=" + accountId,
"ItemID=" + PanelRequest.ItemID);
}
protected void odsAccountsPaged_Selected(object sender, ObjectDataSourceStatusEventArgs e)
{
if (e.Exception != null)
{
messageBox.ShowErrorMessage("EXCHANGE_GET_MAILBOXES", e.Exception);
e.ExceptionHandled = true;
}
}
public string GetAccountImage(int accountTypeId, bool vip)
{
ExchangeAccountType accountType = (ExchangeAccountType)accountTypeId;
string imgName = "mailbox_16.gif";
if (accountType == ExchangeAccountType.Contact)
imgName = "contact_16.gif";
else if (accountType == ExchangeAccountType.DistributionList)
imgName = "dlist_16.gif";
else if (accountType == ExchangeAccountType.Room)
imgName = "room_16.gif";
else if (accountType == ExchangeAccountType.Equipment)
imgName = "equipment_16.gif";
else if (accountType == ExchangeAccountType.SharedMailbox)
imgName = "shared_16.gif";
if (vip && cntx.Groups.ContainsKey(ResourceGroups.ServiceLevels)) imgName = "vip_user_16.png";
return GetThemedImage("Exchange/" + imgName);
}
public string GetStateImage(bool locked, bool disabled)
{
string imgName = "enabled.png";
if (locked)
imgName = "locked.png";
else
if (disabled)
imgName = "disabled.png";
return GetThemedImage("Exchange/" + imgName);
}
protected void gvMailboxes_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DeleteItem")
{
// delete mailbox
int accountId = Utils.ParseInt(e.CommandArgument.ToString(), 0);
try
{
int result = ES.Services.ExchangeServer.DisableMailbox(PanelRequest.ItemID, accountId);
if (result < 0)
{
messageBox.ShowResultMessage(result);
return;
}
// rebind grid
gvMailboxes.DataBind();
// bind stats
BindStats();
}
catch (Exception ex)
{
messageBox.ShowErrorMessage("EXCHANGE_DELETE_MAILBOX", ex);
}
}
}
protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
{
gvMailboxes.PageSize = Convert.ToInt16(ddlPageSize.SelectedValue);
// rebind grid
gvMailboxes.DataBind();
// bind stats
BindStats();
}
public string GetOrganizationUserEditUrl(string accountId)
{
return EditUrl("SpaceID", PanelSecurity.PackageId.ToString(), "edit_user",
"AccountID=" + accountId,
"ItemID=" + PanelRequest.ItemID,
"Context=User");
}
protected void odsAccountsPaged_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
e.InputParameters["archiving"] = ArchivingBoxes;
}
public ServiceLevel GetServiceLevel(int levelId)
{
ServiceLevel serviceLevel = ServiceLevels.Where(x => x.LevelId == levelId).DefaultIfEmpty(new ServiceLevel { LevelName = "", LevelDescription = "" }).FirstOrDefault();
bool enable = !string.IsNullOrEmpty(serviceLevel.LevelName);
enable = enable ? cntx.Quotas.ContainsKey(Quotas.SERVICE_LEVELS + serviceLevel.LevelName) : false;
enable = enable ? cntx.Quotas[Quotas.SERVICE_LEVELS + serviceLevel.LevelName].QuotaAllocatedValue != 0 : false;
if (!enable)
{
serviceLevel.LevelName = "";
serviceLevel.LevelDescription = "";
}
return serviceLevel;
}
protected void chkMailboxes_CheckedChanged(object sender, EventArgs e)
{
List<string> accountTypes = new List<string>();
if ((!chkMailboxes.Checked)&&(!chkSharedMailboxes.Checked)&&(!chkResourceMailboxes.Checked))
chkMailboxes.Checked = true;
if (chkMailboxes.Checked)
accountTypes.Add("1");
if (chkSharedMailboxes.Checked)
accountTypes.Add("10");
if (chkResourceMailboxes.Checked)
accountTypes.AddRange(new string[] {"5","6"});
odsAccountsPaged.SelectParameters["accountTypes"].DefaultValue = string.Join(",", accountTypes);
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_OXNSPI
{
using System;
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestTools;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// This class contains all the test cases designed to test the server behavior for the NSPI calls related to Ambiguous Name Resolution process.
/// </summary>
[TestClass]
public class S03_ANRRelatedBehavior : TestSuiteBase
{
#region Test Suite Initialization
/// <summary>
/// Initialize the test suite.
/// </summary>
/// <param name="testContext">The test context instance.</param>
[ClassInitialize]
public static void ClassInitialize(TestContext testContext)
{
TestClassBase.Initialize(testContext);
}
/// <summary>
/// Reset the test environment.
/// </summary>
[ClassCleanup]
public static void ClassCleanup()
{
TestClassBase.Cleanup();
}
#endregion
/// <summary>
/// This test case is designed to verify the requirements related to NspiResolveNames operation returning success.
/// </summary>
[TestCategory("MSOXNSPI"), TestMethod()]
public void MSOXNSPI_S03_TC01_ResolveNamesSuccess()
{
this.CheckProductSupported();
if (this.Transport == "mapi_http")
{
Site.Assert.Inconclusive("This case cannot run, since MAPIHTTP transport does not support ResolveNames operation for 8-bit character set string.");
}
#region Call NspiBind to initiate a session between the client and the server.
uint flags = 0;
STAT stat = new STAT();
stat.InitiateStat();
FlatUID_r guid = new FlatUID_r
{
Ab = new byte[16]
};
FlatUID_r? serverGuid = guid;
this.Result = this.ProtocolAdatper.NspiBind(flags, stat, ref serverGuid);
Site.Assert.AreEqual<ErrorCodeValue>(ErrorCodeValue.Success, this.Result, "NspiBind should return Success!");
#endregion
#region Call NspiResolveNames method with a specific list of names and propertyTag value with null.
StringsArray_r strArray;
strArray.CValues = 5;
strArray.LppszA = new string[strArray.CValues];
strArray.LppszA[0] = Common.GetConfigurationPropertyValue("User1Name", this.Site);
strArray.LppszA[1] = string.Empty;
strArray.LppszA[2] = Common.GetConfigurationPropertyValue("AmbiguousName", this.Site);
strArray.LppszA[3] = null;
strArray.LppszA[4] = Constants.UnresolvedName;
PropertyTagArray_r? propTags = null;
PropertyTagArray_r? mids;
PropertyRowSet_r? rowOfResolveNames;
this.Result = this.ProtocolAdatper.NspiResolveNames((uint)0, stat, propTags, strArray, out mids, out rowOfResolveNames);
#region Capture
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXNSPI_R1392");
// Verify MS-OXNSPI requirement: MS-OXNSPI_R1392
Site.CaptureRequirementIfAreEqual<ErrorCodeValue>(
ErrorCodeValue.Success,
this.Result,
1392,
@"[In NspiResolveNames] [Server Processing Rules: Upon receiving message NspiResolveNames, the server MUST process the data from the message subject to the following constraints:] [Constraint 8] If no other return values have been specified by these constraints [constraints 1-8], the server MUST return the return value ""Success"".");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXNSPI_R1342");
// Verify MS-OXNSPI requirement: MS-OXNSPI_R1342
// If the mids which contains Minimal Entry ID returned from the server is not null,
// it illustrates that the server must report the Minimal Entry ID that is the result of the ANR process.
this.Site.CaptureRequirementIfIsNotNull(
mids,
1342,
@"[In NspiResolveNames] The server reports the Minimal Entry ID that is the result of the ANR process.");
this.VerifyPropertyRowSetIsNotNullForNspiResolveNames(rowOfResolveNames);
this.VerifyIsRESOLVEDMIDInANRMatchString(mids.Value.AulPropTag[0]);
this.VerifyIsUNRESOLVEDMIDInANREmptyString(mids.Value.AulPropTag[1]);
this.VerifyIsAMBIGUOUSMIDInANRAmbiguousString(mids.Value.AulPropTag[2]);
this.VerifyIsUNRESOLVEDMIDInANRNullString(mids.Value.AulPropTag[3]);
this.VerifyIsUNRESOLVEDMIDInANRNotFound(mids.Value.AulPropTag[4]);
this.VerifyIsResultOfANRProcessIsMID(mids);
// Since if the whole ANR results are verified and the NspiResolveNames is invoked,
// it must take a set of string values in an 8-bit character set and perform ANR on those strings,
// this requirement can be captured directly.
this.Site.CaptureRequirement(
1341,
@"[In NspiResolveNames] The NspiResolveNames method takes a set of string values in an 8-bit character set and performs ANR (as specified in section 3.1.4.7) on those strings.");
// Since all the returned Minimal Entry IDs are verified according to the order of the input string array, this requirement can be captured directly.
this.Site.CaptureRequirement(
1375,
@"[In NspiResolveNames] [Server Processing Rules: Upon receiving message NspiResolveNames, the server MUST process the data from the message subject to the following constraints:] [Constraint 6] These Minimal Entry IDs [IDs which server constructs and returns to client] are those that result from applying the ANR process, as specified in section 3.1.4.7, to the strings in the input parameter paStr.");
#endregion Capture
#endregion
#region Call NspiResolveNames method with a specific list of names and propertyTag value without null.
PropertyTagArray_r propTagsWithProperties = new PropertyTagArray_r
{
CValues = 3,
AulPropTag = new uint[3]
{
(uint)AulProp.PidTagEntryId,
(uint)AulProp.PidTagDisplayName,
(uint)AulProp.PidTagObjectType
}
};
this.Result = this.ProtocolAdatper.NspiResolveNames((uint)0, stat, propTagsWithProperties, strArray, out mids, out rowOfResolveNames);
Site.Assert.AreEqual(ErrorCodeValue.Success, this.Result, "NspiResolveNames should return Success!");
PropertyRow_r rowValue = rowOfResolveNames.Value.ARow[0];
string resolvedName = System.Text.UnicodeEncoding.UTF8.GetString(rowValue.LpProps[1].Value.LpszA);
#region Capture
// Check whether MID_RESOLVED is returned.
bool isMIDRESOLVEDContained = false;
for (int i = 0; i < mids.Value.CValues; i++)
{
if (mids.Value.AulPropTag[i] == 0x0000002)
{
isMIDRESOLVEDContained = true;
break;
}
}
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXNSPI_R1343");
// Verify MS-OXNSPI requirement: MS-OXNSPI_R1343
// The rowOfResolveNames which contains a PropertyRowSet_r structure is returned from the server. If it is not null and MID_RESOLVED is returned,
// it illustrates that certain property values are returned for any valid Minimal Entry IDs identified by the ANR process.
this.Site.CaptureRequirementIfIsTrue(
rowOfResolveNames != null && isMIDRESOLVEDContained,
1343,
@"[In NspiResolveNames] Certain property values are returned for any valid Minimal Entry IDs identified by the ANR process.");
// Add the debug information
this.Site.Log.Add(
LogEntryKind.Debug,
"Verify MS-OXNSPI_R1349, the display name of the resolved address book for paStr {0} is {1}.",
Common.GetConfigurationPropertyValue("User1Name", this.Site),
resolvedName);
// Verify MS-OXNSPI requirement: MS-OXNSPI_R1349
this.Site.CaptureRequirementIfIsTrue(
resolvedName.Equals(Common.GetConfigurationPropertyValue("User1Name", this.Site), StringComparison.CurrentCultureIgnoreCase),
1349,
"[In NspiResolveNames] [paStr] Specifies the values the client is requesting the server to do ANR on.");
Site.Assert.AreEqual<uint>((uint)AulProp.PidTagEntryId, rowOfResolveNames.Value.ARow[0].LpProps[0].PropTag, "The first property returned should be PidTagEntryId. Now the returned property is {0}.", rowOfResolveNames.Value.ARow[0].LpProps[0].PropTag);
Site.Assert.AreEqual<uint>((uint)AulProp.PidTagDisplayName, rowOfResolveNames.Value.ARow[0].LpProps[1].PropTag, "The second property returned should be PidTagDisplayName. Now the returned property is {0}.", rowOfResolveNames.Value.ARow[0].LpProps[1].PropTag);
Site.Assert.AreEqual<uint>((uint)AulProp.PidTagObjectType, rowOfResolveNames.Value.ARow[0].LpProps[2].PropTag, "The third property returned should be PidTagObjectType. Now the returned property is {0}.", rowOfResolveNames.Value.ARow[0].LpProps[2].PropTag);
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXNSPI_R1347");
// Verify MS-OXNSPI requirement: MS-OXNSPI_R1347
// Since the null value of pPropTags has been set in step "Call NspiResolveNames method with a specific list of names",
// and the above three asserts ensure that it is a reference to a PropertyTagArray_r value containing a list of the proptags of the columns that the client requests to be returned for each row.
// So R1347 can be captured directly.
this.Site.CaptureRequirement(
1347,
@"[In NspiResolveNames] pPropTags: The value NULL or a reference to a PropertyTagArray_r value containing a list of the proptags of the columns that the client requests to be returned for each row returned.");
#endregion Capture
#endregion
#region Call NspiUnbind method to destroy the context handle.
uint returnValue = this.ProtocolAdatper.NspiUnbind(0);
Site.Assert.AreEqual<uint>(1, returnValue, "NspiUnbind method should return 1 (Success).");
#endregion
}
/// <summary>
/// This test case is designed to verify the requirements related to NspiResolveNamesW operation returning success.
/// </summary>
[TestCategory("MSOXNSPI"), TestMethod()]
public void MSOXNSPI_S03_TC02_ResolveNamesWSuccess()
{
this.CheckProductSupported();
this.CheckMAPIHTTPTransportSupported();
#region Call NspiBind to initiate a session between the client and the server.
uint flags = 0;
STAT stat = new STAT();
stat.InitiateStat();
FlatUID_r guid = new FlatUID_r
{
Ab = new byte[16]
};
FlatUID_r? serverGuid = guid;
this.Result = this.ProtocolAdatper.NspiBind(flags, stat, ref serverGuid);
Site.Assert.AreEqual<ErrorCodeValue>(ErrorCodeValue.Success, this.Result, "NspiBind should return Success!");
#endregion
#region Call NspiResolveNamesW method with a specific list of names and propertyTag value with null.
uint reservedOfResolveNamesW = 0;
WStringsArray_r wstrArray;
wstrArray.CValues = 5;
wstrArray.LppszW = new string[wstrArray.CValues];
wstrArray.LppszW[0] = Common.GetConfigurationPropertyValue("User1Name", this.Site);
wstrArray.LppszW[1] = string.Empty;
wstrArray.LppszW[2] = Common.GetConfigurationPropertyValue("AmbiguousName", this.Site);
wstrArray.LppszW[3] = null;
wstrArray.LppszW[4] = Constants.UnresolvedName;
PropertyTagArray_r? propTags = null;
PropertyTagArray_r? mids;
PropertyRowSet_r? rowOfResolveNamesW;
this.Result = this.ProtocolAdatper.NspiResolveNamesW(reservedOfResolveNamesW, stat, propTags, wstrArray, out mids, out rowOfResolveNamesW);
#region Capture
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXNSPI_R1443");
// Verify MS-OXNSPI requirement: MS-OXNSPI_R1443
Site.CaptureRequirementIfAreEqual<ErrorCodeValue>(
ErrorCodeValue.Success,
this.Result,
1443,
@"[In NspiResolveNamesW] [Server Processing Rules: Upon receiving message NspiResolveNamesW, the server MUST process the data from the message subject to the following constraints:] [Constraint 8] If no other return values have been specified by these constraints [constraints 1-8], the server MUST return the return value ""Success"".");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXNSPI_R1394");
// Verify MS-OXNSPI requirement: MS-OXNSPI_R1394
// If the mids which contains Minimal Entry ID returned from the server is not null,
// it illustrates that the server must report the Minimal Entry ID that is the result of the ANR process.
this.Site.CaptureRequirementIfIsNotNull(
mids,
1394,
@"[In NspiResolveNamesW] The server reports the Minimal Entry IDs that are the result of the ANR process.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXNSPI_R1650");
// Verify MS-OXNSPI requirement: MS-OXNSPI_R1650
Site.CaptureRequirementIfIsNotNull(
mids,
1650,
"[In NspiResolveNamesW] [ppMIds] On return, contains a list of Minimal Entry IDs that match the array of strings, as specified in the input parameter paWStr.");
this.VerifyPropertyRowSetIsNotNullForNspiResolveNamesW(rowOfResolveNamesW);
this.VerifyIsRESOLVEDMIDInANRMatchString(mids.Value.AulPropTag[0]);
this.VerifyIsUNRESOLVEDMIDInANREmptyString(mids.Value.AulPropTag[1]);
this.VerifyIsAMBIGUOUSMIDInANRAmbiguousString(mids.Value.AulPropTag[2]);
this.VerifyIsUNRESOLVEDMIDInANRNullString(mids.Value.AulPropTag[3]);
this.VerifyIsUNRESOLVEDMIDInANRNotFound(mids.Value.AulPropTag[4]);
this.VerifyIsResultOfANRProcessIsMID(mids);
// Since if the whole ANR results are verified and the NspiResolveNamesW is invoked,
// it must take a set of string values in an 8-bit character set and perform ANR on those strings,
// this requirement can be captured directly.
this.Site.CaptureRequirement(
1393,
@"[In NspiResolveNamesW] The NspiResolveNamesW method takes a set of string values in the Unicode character set and performs ANR (as specified in section 3.1.4.7) on those strings.");
// Since all the returned Minimal Entry IDs are verified according to the order of the input string array, this requirement can be captured directly.
this.Site.CaptureRequirement(
1426,
@"[In NspiResolveNamesW] [Server Processing Rules: Upon receiving message NspiResolveNamesW, the server MUST process the data from the message subject to the following constraints:] [Constraint 6] These Minimal Entry IDs are those that result from the ANR process, as specified in section 3.1.4.7, to the strings in the input parameter paWStr.");
#endregion Capture
#endregion
#region Call NspiResolveNamesW method with a specific list of names and propertyTag value without null.
PropertyTagArray_r propTagsWithProperties = new PropertyTagArray_r
{
CValues = 3,
AulPropTag = new uint[3]
{
(uint)AulProp.PidTagEntryId,
(uint)AulProp.PidTagDisplayName,
(uint)AulProp.PidTagObjectType
}
};
this.Result = this.ProtocolAdatper.NspiResolveNamesW(reservedOfResolveNamesW, stat, propTagsWithProperties, wstrArray, out mids, out rowOfResolveNamesW);
Site.Assert.AreEqual(ErrorCodeValue.Success, this.Result, "NspiResolveNamesW should return Success!");
Site.Assert.AreNotEqual<int>(0, rowOfResolveNamesW.Value.ARow.Length, "At least one address book object should be matched.");
#region Capture
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXNSPI_R1395");
// Verify MS-OXNSPI requirement: MS-OXNSPI_R1395
// The rowOfResolveNamesW which contains a PropertyRowSet_r structure is returned from the server. If it is not null,
// it illustrates that certain property values are returned for any valid Minimal Entry IDs identified by the ANR process.
this.Site.CaptureRequirementIfIsNotNull(
rowOfResolveNamesW,
1395,
@"[In NspiResolveNamesW] Certain property values are returned for any valid Minimal Entry IDs identified by the ANR process.");
Site.Assert.AreEqual<uint>((uint)AulProp.PidTagEntryId, rowOfResolveNamesW.Value.ARow[0].LpProps[0].PropTag, "The first property returned should be PidTagEntryId. Now the returned property is {0}.", rowOfResolveNamesW.Value.ARow[0].LpProps[0].PropTag);
Site.Assert.AreEqual<uint>((uint)AulProp.PidTagDisplayName, rowOfResolveNamesW.Value.ARow[0].LpProps[1].PropTag, "The second property returned should be PidTagDisplayName. Now the returned property is {0}.", rowOfResolveNamesW.Value.ARow[0].LpProps[1].PropTag);
Site.Assert.AreEqual<uint>((uint)AulProp.PidTagObjectType, rowOfResolveNamesW.Value.ARow[0].LpProps[2].PropTag, "The third property returned should be PidTagObjectType. Now the returned property is {0}.", rowOfResolveNamesW.Value.ARow[0].LpProps[2].PropTag);
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXNSPI_R1399");
// Verify MS-OXNSPI requirement: MS-OXNSPI_R1399
// Since the null value of pPropTags has been set in step "Call NspiResolveNamesW method with a specific list of names",
// and the above three asserts ensure that it is a reference to a PropertyTagArray_r value containing a list of the proptags of the columns that the client requests to be returned for each row.
// So R1347 can be captured directly.
this.Site.CaptureRequirement(
1399,
@"[In NspiResolveNamesW] pPropTags: The value NULL or a reference to a PropertyTagArray_r containing a list of the proptags of the columns that the client requests to be returned for each row returned.");
#endregion Capture
#endregion
#region Call NspiUnbind method to destroy the context handle.
uint returnValue = this.ProtocolAdatper.NspiUnbind(0);
Site.Assert.AreEqual<uint>(1, returnValue, "NspiUnbind method should return 1 (Success).");
#endregion
}
/// <summary>
/// This test case is designed to verify the related requirements about string values returned from NspiResolveNames operation.
/// </summary>
[TestCategory("MSOXNSPI"), TestMethod()]
public void MSOXNSPI_S03_TC03_ResolveNamesStringConversion()
{
this.CheckProductSupported();
if (this.Transport == "mapi_http")
{
Site.Assert.Inconclusive("This case cannot run, since MAPIHTTP transport does not support ResolveNames operation for 8-bit character set string.");
}
#region Call NspiBind to initiate a session between the client and the server.
uint flags = 0;
STAT stat = new STAT();
stat.InitiateStat();
FlatUID_r guid = new FlatUID_r
{
Ab = new byte[16]
};
FlatUID_r? serverGuid = guid;
this.Result = this.ProtocolAdatper.NspiBind(flags, stat, ref serverGuid);
Site.Assert.AreEqual(ErrorCodeValue.Success, this.Result, "NspiBind should return Success!");
#endregion
#region Call NspiResolveNames to require the string properties to be different with their native types.
StringsArray_r strArray;
strArray.CValues = 1;
strArray.LppszA = new string[strArray.CValues];
strArray.LppszA[0] = Common.GetConfigurationPropertyValue("User2Name", this.Site);
PropertyTagArray_r tags = new PropertyTagArray_r
{
CValues = 2,
AulPropTag = new uint[]
{
AdapterHelper.ConvertStringToString8((uint)AulProp.PidTagAddressBookDisplayNamePrintable),
AdapterHelper.ConvertString8ToString((uint)AulProp.PidTagDisplayName)
}
};
PropertyTagArray_r? mids;
PropertyRowSet_r? rowOfResolveNames;
this.Result = this.ProtocolAdatper.NspiResolveNames((uint)0, stat, tags, strArray, out mids, out rowOfResolveNames);
Site.Assert.AreEqual(ErrorCodeValue.Success, this.Result, "NspiResolveNames should return Success!");
Site.Assert.IsNotNull(rowOfResolveNames, "PropertyRowSet_r value should not null. The row number is {0}.", rowOfResolveNames == null ? 0 : rowOfResolveNames.Value.CRows);
Site.Assert.AreNotEqual<int>(0, rowOfResolveNames.Value.ARow.Length, "At least one address book object should be matched.");
PropertyRow_r rowValue = rowOfResolveNames.Value.ARow[0];
string resolveddisplayNamePrintable = System.Text.UnicodeEncoding.UTF8.GetString(rowValue.LpProps[0].Value.LpszA);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXNSPI_R1977: The value of PidTagAddressBookDisplayNamePrintable is {0}.", resolveddisplayNamePrintable);
// Verify MS-OXNSPI requirement: MS-OXNSPI_R1977
// The field LpszA indicates an 8-bit character string value.
Site.CaptureRequirementIfIsTrue(
resolveddisplayNamePrintable.StartsWith(strArray.LppszA[0], StringComparison.Ordinal),
1977,
"[In Conversion Rules for String Values Specified by the Server to the Client] In NspiResolveNames method, String values can be returned in 8-bit character representation in the output parameter ppRows.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXNSPI_R1976");
string reslovedName = System.Text.UnicodeEncoding.Unicode.GetString(rowValue.LpProps[1].Value.LpszW);
// Verify MS-OXNSPI requirement: MS-OXNSPI_R1976
// The field LpszW indicates a single Unicode string value.
Site.CaptureRequirementIfAreEqual<string>(
strArray.LppszA[0].ToLower(System.Globalization.CultureInfo.CurrentCulture),
reslovedName.ToLower(System.Globalization.CultureInfo.CurrentCulture),
1976,
"[In Conversion Rules for String Values Specified by the Server to the Client] In NspiResolveNames method, String values can be returned in Unicode representation in the output parameter ppRows.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXNSPI_R1938");
// Verify MS-OXNSPI requirement: MS-OXNSPI_R1938
// The native type of PidTagAddressBookDisplayNamePrintable is PtypString and the client has requested this property with PtypString8.
Site.CaptureRequirementIfAreEqual<uint>(
AdapterHelper.ConvertStringToString8((uint)AulProp.PidTagAddressBookDisplayNamePrintable),
rowValue.LpProps[0].PropTag,
1938,
"[In Conversion Rules for String Values Specified by the Server to the Client] [For method NspiResolveNames] If the native type of a property is PtypString and the client has requested that property with the type PtypString8, the server MUST convert the Unicode representation to an 8-bit character representation in the code page specified by the CodePage field of the pStat parameter prior to returning the value.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXNSPI_R1954");
// Verify MS-OXNSPI requirement: MS-OXNSPI_R1954
// The native type of PidTagDisplayName is PtypString8 and the client has requested this property with PtypString.
Site.CaptureRequirementIfAreEqual<uint>(
AdapterHelper.ConvertString8ToString((uint)AulProp.PidTagDisplayName),
rowValue.LpProps[1].PropTag,
1954,
"[In Conversion Rules for String Values Specified by the Server to the Client] [For method NspiResolveNames] If the native type of a property is PtypString8 and the client has requested that property with the type PtypString, the server MUST convert the 8-bit character representation to a Unicode representation prior to returning the value.");
#endregion
#region Call NspiResolveNames to require the string properties to be the same as their native types.
strArray.CValues = 1;
strArray.LppszA = new string[strArray.CValues];
strArray.LppszA[0] = Common.GetConfigurationPropertyValue("User2Name", this.Site);
tags = new PropertyTagArray_r
{
CValues = 2,
AulPropTag = new uint[]
{
(uint)AulProp.PidTagAddressBookDisplayNamePrintable,
(uint)AulProp.PidTagDisplayName
}
};
this.Result = this.ProtocolAdatper.NspiResolveNames((uint)0, stat, tags, strArray, out mids, out rowOfResolveNames);
Site.Assert.AreEqual(ErrorCodeValue.Success, this.Result, "NspiResolveNames should return Success!");
Site.Assert.IsNotNull(rowOfResolveNames, "PropertyRowSet_r value should not null. The row number is {0}.", rowOfResolveNames == null ? 0 : rowOfResolveNames.Value.CRows);
Site.Assert.AreNotEqual<int>(0, rowOfResolveNames.Value.ARow.Length, "At least one address book object should be matched.");
rowValue = rowOfResolveNames.Value.ARow[0];
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXNSPI_R1946");
// Verify MS-OXNSPI requirement: MS-OXNSPI_R1938
// The native type of PidTagAddressBookDisplayNamePrintable is PtypString and the client has requested this property with PtypString.
Site.CaptureRequirementIfAreEqual<uint>(
(uint)AulProp.PidTagAddressBookDisplayNamePrintable,
rowValue.LpProps[0].PropTag,
1946,
"[In Conversion Rules for String Values Specified by the Server to the Client] [For method NspiResolveNames] If the native type of a property is PtypString and the client has requested that property with the type PtypString, the server MUST return the Unicode representation unmodified.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXNSPI_R1962");
// Verify MS-OXNSPI requirement: MS-OXNSPI_R1962
// The native type of PidTagDisplayName is PtypString8 and the client has requested this property with PtypString8.
Site.CaptureRequirementIfAreEqual<uint>(
(uint)AulProp.PidTagDisplayName,
rowValue.LpProps[1].PropTag,
1962,
"[In Conversion Rules for String Values Specified by the Server to the Client] [For method NspiResolveNames] If the native type of a property is PtypString8 and the client has requested that property with the type PtypString8, the server MUST return the 8-bit character representation unmodified.");
#endregion
#region Call NspiUnbind method to destroy the context handle.
uint returnValue = this.ProtocolAdatper.NspiUnbind(0);
Site.Assert.AreEqual<uint>(1, returnValue, "NspiUnbind method should return 1 (Success).");
#endregion
}
/// <summary>
/// This test case is designed to verify the related requirements about string values returned from NspiResolveNamesW operation.
/// </summary>
[TestCategory("MSOXNSPI"), TestMethod()]
public void MSOXNSPI_S03_TC04_ResolveNamesWStringConversion()
{
this.CheckProductSupported();
this.CheckMAPIHTTPTransportSupported();
#region Call NspiBind to initiate a session between the client and the server.
uint flags = 0;
STAT stat = new STAT();
stat.InitiateStat();
FlatUID_r guid = new FlatUID_r
{
Ab = new byte[16]
};
FlatUID_r? serverGuid = guid;
this.Result = this.ProtocolAdatper.NspiBind(flags, stat, ref serverGuid);
Site.Assert.AreEqual(ErrorCodeValue.Success, this.Result, "NspiBind should return Success!");
#endregion
#region Call NspiResolveNamesW to require the string properties to be different with their native type.
uint reservedOfResolveNamesW = 0;
WStringsArray_r wstrArray;
wstrArray.CValues = 1;
wstrArray.LppszW = new string[wstrArray.CValues];
wstrArray.LppszW[0] = Common.GetConfigurationPropertyValue("User2Name", this.Site);
PropertyTagArray_r propTags = new PropertyTagArray_r
{
CValues = 2,
AulPropTag = new uint[]
{
AdapterHelper.ConvertStringToString8((uint)AulProp.PidTagAddressBookDisplayNamePrintable),
AdapterHelper.ConvertString8ToString((uint)AulProp.PidTagDisplayName)
}
};
PropertyTagArray_r? mids;
PropertyRowSet_r? rowOfResolveNamesW;
this.Result = this.ProtocolAdatper.NspiResolveNamesW(reservedOfResolveNamesW, stat, propTags, wstrArray, out mids, out rowOfResolveNamesW);
Site.Assert.AreEqual(ErrorCodeValue.Success, this.Result, "NspiResolveNamesW should return Success!");
Site.Assert.IsNotNull(rowOfResolveNamesW, "PropertyRowSet_r value should not null. The row number is {0}.", rowOfResolveNamesW == null ? 0 : rowOfResolveNamesW.Value.CRows);
Site.Assert.AreNotEqual<int>(0, rowOfResolveNamesW.Value.ARow.Length, "At least one address book object should be matched.");
PropertyRow_r rowValue = rowOfResolveNamesW.Value.ARow[0];
string resolvedDisplayNamePrintable = System.Text.UnicodeEncoding.UTF8.GetString(rowValue.LpProps[0].Value.LpszA);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXNSPI_R1979: The value of PidTagAddressBookDisplayNamePrintable is {0}.", resolvedDisplayNamePrintable);
// Verify MS-OXNSPI requirement: MS-OXNSPI_R1979
// The field LpszA indicates an 8-bit character string value.
Site.CaptureRequirementIfIsTrue(
resolvedDisplayNamePrintable.StartsWith(wstrArray.LppszW[0], StringComparison.Ordinal),
1979,
"[In Conversion Rules for String Values Specified by the Server to the Client] In NspiResolveNamesW method, String values can be returned in 8-bit character representation in the output parameter ppRows.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXNSPI_R1978");
string reslovedName = System.Text.UnicodeEncoding.Unicode.GetString(rowValue.LpProps[1].Value.LpszW);
// Verify MS-OXNSPI requirement: MS-OXNSPI_R1978
// The field LpszW indicates a single Unicode string value.
Site.CaptureRequirementIfAreEqual<string>(
wstrArray.LppszW[0].ToLower(System.Globalization.CultureInfo.CurrentCulture),
reslovedName.ToLower(System.Globalization.CultureInfo.CurrentCulture),
1978,
"[In Conversion Rules for String Values Specified by the Server to the Client] In NspiResolveNamesW method, String values can be returned in Unicode representation in the output parameter ppRows.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXNSPI_R1939");
// Verify MS-OXNSPI requirement: MS-OXNSPI_R1939
// The native type of PidTagAddressBookDisplayNamePrintable is PtypString and the client has requested this property with PtypString8.
Site.CaptureRequirementIfAreEqual<uint>(
AdapterHelper.ConvertStringToString8((uint)AulProp.PidTagAddressBookDisplayNamePrintable),
rowValue.LpProps[0].PropTag,
1939,
"[In Conversion Rules for String Values Specified by the Server to the Client] [For method NspiResolveNamesW] If the native type of a property is PtypString and the client has requested that property with the type PtypString8, the server MUST convert the Unicode representation to an 8-bit character representation in the code page specified by the CodePage field of the pStat parameter prior to returning the value.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXNSPI_R1955");
// Verify MS-OXNSPI requirement: MS-OXNSPI_R1955
// The native type of PidTagDisplayName is PtypString8 and the client has requested this property with PtypString.
Site.CaptureRequirementIfAreEqual<uint>(
AdapterHelper.ConvertString8ToString((uint)AulProp.PidTagDisplayName),
rowValue.LpProps[1].PropTag,
1955,
"[In Conversion Rules for String Values Specified by the Server to the Client] [For method NspiResolveNamesW] If the native type of a property is PtypString8 and the client has requested that property with the type PtypString, the server MUST convert the 8-bit character representation to a Unicode representation prior to returning the value.");
#endregion
#region Call NspiResolveNamesW to require the string properties to be the same as their native types.
wstrArray.CValues = 1;
wstrArray.LppszW = new string[wstrArray.CValues];
wstrArray.LppszW[0] = Common.GetConfigurationPropertyValue("User2Name", this.Site);
propTags = new PropertyTagArray_r
{
CValues = 2,
AulPropTag = new uint[]
{
(uint)AulProp.PidTagAddressBookDisplayNamePrintable,
(uint)AulProp.PidTagDisplayName
}
};
this.Result = this.ProtocolAdatper.NspiResolveNamesW(reservedOfResolveNamesW, stat, propTags, wstrArray, out mids, out rowOfResolveNamesW);
Site.Assert.AreEqual(ErrorCodeValue.Success, this.Result, "NspiResolveNamesW should return Success!");
Site.Assert.IsNotNull(rowOfResolveNamesW, "PropertyRowSet_r value should not null. The row number is {0}.", rowOfResolveNamesW == null ? 0 : rowOfResolveNamesW.Value.CRows);
Site.Assert.AreNotEqual<int>(0, rowOfResolveNamesW.Value.ARow.Length, "At least one address book object should be matched.");
rowValue = rowOfResolveNamesW.Value.ARow[0];
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXNSPI_R1946");
// Verify MS-OXNSPI requirement: MS-OXNSPI_R1947
// The native type of PidTagAddressBookDisplayNamePrintable is PtypString and the client has requested this property with PtypString.
Site.CaptureRequirementIfAreEqual<uint>(
(uint)AulProp.PidTagAddressBookDisplayNamePrintable,
rowValue.LpProps[0].PropTag,
1947,
"[In Conversion Rules for String Values Specified by the Server to the Client] [For method NspiResolveNamesW] If the native type of a property is PtypString and the client has requested that property with the type PtypString, the server MUST return the Unicode representation unmodified.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXNSPI_R1963");
// Verify MS-OXNSPI requirement: MS-OXNSPI_R1963
// The native type of PidTagDisplayName is PtypString8 and the client has requested this property with PtypString8.
Site.CaptureRequirementIfAreEqual<uint>(
(uint)AulProp.PidTagDisplayName,
rowValue.LpProps[1].PropTag,
1963,
"[In Conversion Rules for String Values Specified by the Server to the Client] [For method NspiResolveNamesW] If the native type of a property is PtypString8 and the client has requested that property with the type PtypString8, the server MUST return the 8-bit character representation unmodified.");
#endregion
#region Call NspiUnbind method to destroy the context handle.
uint returnValue = this.ProtocolAdatper.NspiUnbind(0);
Site.Assert.AreEqual<uint>(1, returnValue, "NspiUnbind method should return 1 (Success).");
#endregion
}
#region Private methods
/// <summary>
/// Check whether PropertyRowSet_r is not null.
/// </summary>
/// <param name="rowOfResolveNamesW">Contain the address book container rows that the server returns in response to the request.</param>
private void VerifyPropertyRowSetIsNotNullForNspiResolveNamesW(PropertyRowSet_r? rowOfResolveNamesW)
{
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXNSPI_R1430");
// Verify MS-OXNSPI requirement: MS-OXNSPI_R1430
// The rowOfResolveNamesW which contains a PropertyRowSet_r structure is returned from the server. If it is not null,
// it illustrates that the server must have constructed it.
Site.CaptureRequirementIfIsNotNull(
rowOfResolveNamesW,
1430,
@"[In NspiResolveNamesW] [Server Processing Rules: Upon receiving message NspiResolveNamesW, the server MUST process the data from the message subject to the following constraints:] [Constraint 7] Subject to the prior constraints, the server MUST construct a PropertyRowSet_r to return to the client.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXNSPI_R1405");
// Verify MS-OXNSPI requirement: MS-OXNSPI_R1405
Site.CaptureRequirementIfIsNotNull(
rowOfResolveNamesW,
1405,
@"[In NspiResolveNamesW] [ppRows: A reference to a PropertyRowSet_r structure (section 2.2.4), ] which contains the address book container rows that the server returns in response to the request. ");
}
/// <summary>
/// Check whether PropertyRowSet_r is not null.
/// </summary>
/// <param name="rowOfResolveNames">Contain the address book container rows that the server returns in response to the request.</param>
private void VerifyPropertyRowSetIsNotNullForNspiResolveNames(PropertyRowSet_r? rowOfResolveNames)
{
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXNSPI_R1379");
// Verify MS-OXNSPI requirement: MS-OXNSPI_R1379
// The rowOfResolveNames which contains a PropertyRowSet_r structure is returned from the server. If it is not null,
// it illustrates that the server must have constructed it.
Site.CaptureRequirementIfIsNotNull(
rowOfResolveNames,
1379,
@"[In NspiResolveNames] [Server Processing Rules: Upon receiving message NspiResolveNames, the server MUST process the data from the message subject to the following constraints:] [Constraint 7] Subject to the prior constraints, the server MUST construct a PropertyRowSet_r to return to the client.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXNSPI_R1354");
// Verify MS-OXNSPI requirement: MS-OXNSPI_R1354
Site.CaptureRequirementIfIsNotNull(
rowOfResolveNames,
1354,
@"[In NspiResolveNames] [ppRows: A reference to a PropertyRowSet_r structure (section 2.2.4), ] which contains the address book container rows that the server returns in response to the request. ");
}
/// <summary>
/// Check whether the result of the Ambiguous Name Resolution is Minimal Entry ID UNRESOLVED when the input string is not found.
/// </summary>
/// <param name="aulPropTag">A PropertyTag of PropertyTagArray_r. Its value should be 0, which means the ANR process is unable to map a string to any objects in the address book.</param>
private void VerifyIsUNRESOLVEDMIDInANRNotFound(uint aulPropTag)
{
if (this.Transport == "ncacn_http" || this.Transport == "ncacn_ip_tcp")
{
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXNSPI_R88");
// Verify MS-OXNSPI requirement: MS-OXNSPI_R88
// According to the Open Specification, if the server is unable to map the string to any objects in the address book,
// the result of the ANR process is the Minimal Entry ID with the value MID_UNRESOLVE.
Site.CaptureRequirementIfAreEqual<uint>(
(uint)ANRMinEntryID.MID_UNRESOLVED,
aulPropTag,
88,
@"[In Ambiguous Name Resolution Minimal Entry IDs] MID_UNRESOLVED (0x00000000): The ANR process was unable to map a string to any objects in the address book.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXNSPI_R618");
// Verify MS-OXNSPI requirement: MS-OXNSPI_R618
Site.CaptureRequirementIfAreEqual<uint>(
(uint)ANRMinEntryID.MID_UNRESOLVED,
aulPropTag,
618,
@"[In Ambiguous Name Resolution] If the server is unable to map the string to any objects in the address book, the result of the ANR process is the Minimal Entry ID with the value MID_UNRESOLVED.");
}
}
/// <summary>
/// Check whether the result of the Ambiguous Name Resolution is Minimal Entry ID UNRESOLVED when the input string is null.
/// </summary>
/// <param name="aulPropTag">A PropertyTag of PropertyTagArray_r. Its value should be 0, which means the ANR process is unable to map a string to any objects in the address book.</param>
private void VerifyIsUNRESOLVEDMIDInANRNullString(uint aulPropTag)
{
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXNSPI_R623");
// Verify MS-OXNSPI requirement: MS-OXNSPI_R623
// If the value that the client is requesting is set to NULL, and the returned Minimal Entry ID is MID_UNRESOLVED, MS-OXNSPI_R623 can be verified.
Site.CaptureRequirementIfAreEqual<uint>(
(uint)ANRMinEntryID.MID_UNRESOLVED,
aulPropTag,
623,
@"[In Ambiguous Name Resolution] The server MUST map the NULL string to the Minimal Entry ID MID_UNRESOLVED.");
}
/// <summary>
/// Check whether the result of the Ambiguous Name Resolution is Minimal Entry ID UNRESOLVED when the input string is empty.
/// </summary>
/// <param name="aulPropTag">A PropertyTag of PropertyTagArray_r. Its value should be 0, which means the ANR process is unable to map a string to any objects in the address book.</param>
private void VerifyIsUNRESOLVEDMIDInANREmptyString(uint aulPropTag)
{
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXNSPI_R624");
// Verify MS-OXNSPI requirement: MS-OXNSPI_R624
// If the value that the client is requesting is set to an empty string, and the returned Minimal Entry ID is MID_UNRESOLVED, MS-OXNSPI_R624 can be verified.
Site.CaptureRequirementIfAreEqual<uint>(
(uint)ANRMinEntryID.MID_UNRESOLVED,
aulPropTag,
624,
@"[In Ambiguous Name Resolution] The server MUST map a zero-length string to the Minimal Entry ID MID_UNRESOLVED.");
}
/// <summary>
/// Check whether the result of the Ambiguous Name Resolution is Minimal Entry ID RESOLVED when the input string is exactly matched.
/// </summary>
/// <param name="aulPropTag">A PropertyTag of PropertyTagArray_r. Its value should be 2, which means the ANR process maps a string to a single object in the address book.</param>
private void VerifyIsRESOLVEDMIDInANRMatchString(uint aulPropTag)
{
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXNSPI_R90");
// Verify MS-OXNSPI requirement: MS-OXNSPI_R90
Site.CaptureRequirementIfAreEqual<uint>(
(uint)ANRMinEntryID.MID_RESOLVED,
aulPropTag,
90,
@"[In Ambiguous Name Resolution Minimal Entry IDs] MID_RESOLVED (0x0000002): The ANR process mapped a string to a single object in the address book.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXNSPI_R622");
// Verify MS-OXNSPI requirement: MS-OXNSPI_R622
Site.CaptureRequirementIfAreEqual<uint>(
(uint)ANRMinEntryID.MID_RESOLVED,
aulPropTag,
622,
@"[In Ambiguous Name Resolution] If the server is able to map the string to exactly one object in the address book,
the result of the ANR process is the Minimal Entry ID with the value MID_RESOLVED.");
}
/// <summary>
/// Check whether the result of the Ambiguous Name Resolution is Minimal Entry ID RESOLVED when the input string is matched to multiple objects.
/// </summary>
/// <param name="aulPropTag">A PropertyTag of PropertyTagArray_r. Its value should be 1, which means the ANR process maps a string to multiple objects in the address book.</param>
private void VerifyIsAMBIGUOUSMIDInANRAmbiguousString(uint aulPropTag)
{
if (this.Transport == "ncacn_http" || this.Transport == "ncacn_ip_tcp")
{
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXNSPI_R89");
// Verify MS-OXNSPI requirement: MS-OXNSPI_R89
// According to the Open Specification, if the server is able to map the string to more than one object in the address book,
// the result of the ANR process is the Minimal Entry ID with the value MID_AMBIGUOUS.
Site.CaptureRequirementIfAreEqual<uint>(
(uint)ANRMinEntryID.MID_AMBIGUOUS,
aulPropTag,
89,
@"[In Ambiguous Name Resolution Minimal Entry IDs] MID_AMBIGUOUS (0x0000001): The ANR process mapped a string to multiple objects in the address book.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXNSPI_R620");
// Verify MS-OXNSPI requirement: MS-OXNSPI_R620
Site.CaptureRequirementIfAreEqual<uint>(
(uint)ANRMinEntryID.MID_AMBIGUOUS,
aulPropTag,
620,
@"[In Ambiguous Name Resolution] If the server is able to map the string to more than one object in the address book, the result of the ANR process is the Minimal Entry ID with the value MID_AMBIGUOUS.");
}
}
/// <summary>
/// Check whether the specific result of the Ambiguous Name Resolution process is Minimal Entry ID RESOLVED.
/// </summary>
/// <param name="mids">A PropertyTagArray_r value which contains a list of Minimal Entry IDs that match the array of strings.</param>
private void VerifyIsResultOfANRProcessIsMID(PropertyTagArray_r? mids)
{
for (int i = 0; i < mids.Value.AulPropTag.Length; i++)
{
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXNSPI_R616, the property tag {0} of minimal entry id is {1}", i, mids.Value.AulPropTag[i]);
// Verify MS-OXNSPI requirement: MS-OXNSPI_R616
bool isVerifiedR616 = mids.Value.AulPropTag[i] == (uint)ANRMinEntryID.MID_AMBIGUOUS ||
mids.Value.AulPropTag[i] == (uint)ANRMinEntryID.MID_RESOLVED ||
mids.Value.AulPropTag[i] == (uint)ANRMinEntryID.MID_UNRESOLVED;
this.Site.CaptureRequirementIfIsTrue(
isVerifiedR616,
616,
@"[In Ambiguous Name Resolution] The specific result of an ANR process is a Minimal Entry ID.");
}
}
#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.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using Microsoft.Research.DataStructures;
namespace Microsoft.Research.CodeAnalysis
{
abstract internal class GenericNecessaryConditionsGenerator<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions, AElement>
: IEdgeVisit<APC, Local, Parameter, Method, Field, Type, Variable, AElement>
where Variable : IEquatable<Variable>
where Expression : IEquatable<Expression>
where Type : IEquatable<Type>
where LogOptions : IFrameworkLogOptions
{
#region object invariant
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(this.Mdriver != null);
Contract.Invariant(this.CFG != null);
Contract.Invariant(this.underVisit != null);
Contract.Invariant(this.timeout != null);
Contract.Invariant(this.mutator != null);
}
#endregion
#region State
protected const int MaxDepth = 400;
readonly protected APC pcCondition;
readonly protected IFactQuery<BoxedExpression, Variable> facts;
readonly protected IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions> Mdriver;
readonly protected ExpressionReader<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable> ExpressionReader;
readonly protected SimpleSatisfyProcedure<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> SatisfyProcedure;
readonly protected ICFG CFG;
readonly protected Set<APC> underVisit;
readonly protected TimeOutChecker timeout;
private BoxedExpression ___falseExp;
protected BoxedExpression False
{
get
{
Contract.Ensures(Contract.Result<BoxedExpression>() != null);
if (this.___falseExp == null)
{
this.___falseExp = BoxedExpression.ConstBool(false, this.Mdriver.MetaDataDecoder);
}
return this.___falseExp;
}
}
protected ReplaceSymbolicValueForAccessPath<Local, Parameter, Method, Field, Property, Event, Type, Variable, Expression, Attribute, Assembly> mutator;
public bool LoopHit { protected set; get; }
#endregion
#region Constructor
public GenericNecessaryConditionsGenerator(
APC pcCondition,
IFactQuery<BoxedExpression, Variable> facts,
IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions> mdriver,
TimeOutChecker timeout)
{
Contract.Requires(mdriver != null);
this.pcCondition = pcCondition;
this.facts = facts;
this.Mdriver = mdriver;
this.CFG = this.Mdriver.StackLayer.Decoder.Context.MethodContext.CFG;
this.underVisit = new Set<APC>();
this.timeout = timeout;
this.ExpressionReader = new ExpressionReader<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable>();
this.SatisfyProcedure = new SimpleSatisfyProcedure<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly>(mdriver.MetaDataDecoder);
this.LoopHit = false;
this.mutator = new ReplaceSymbolicValueForAccessPath<Local, Parameter, Method, Field, Property, Event, Type, Variable, Expression, Attribute, Assembly>(mdriver.Context, mdriver.MetaDataDecoder);
}
#endregion
#region Properties
protected bool TraceInference { get { return this.Mdriver.Options.TraceInference; } }
protected ExpressionInPreState Converter(APC pc, BoxedExpression exp)
{
return PreconditionSuggestion.ExpressionInPreState(exp, this.Mdriver.Context, this.Mdriver.MetaDataDecoder, pc, allowedKinds: ExpressionInPreStateKind.All);
}
#endregion
#region Abstract members
abstract protected AElement NoCondition { get; }
abstract protected bool IsNoCondition(AElement el);
abstract protected bool ShoudStopTheVisit(APC pc, AElement pre, int depth, out APC nextPC, out AElement nextCondition);
#endregion
#region Visit
protected void Visit(APC pc, AElement pre, int depth)
{
APC lastPC;
AElement preConditionAtTheBlockEntry;
if(ShoudStopTheVisit(pc, pre, depth, out lastPC, out preConditionAtTheBlockEntry))
{
return;
}
pre = preConditionAtTheBlockEntry;
pc = lastPC;
var md = this.Mdriver;
foreach (var prePC in CFG.Predecessors(lastPC))
{
// nothing to do
if (md.BasicFacts.IsUnreachable(prePC))
{
continue;
}
// Widening: stop after one iteration
if (this.underVisit.Contains(lastPC))
{
this.LoopHit = true;
Trace("Applying simple 1-iteration widening", pre);
return;
}
if (CFG.IsForwardBackEdgeTarget(pc))
{
Trace("Reached the target of a forward backedge", pre);
this.LoopHit = true;
this.underVisit.Add(lastPC);
Visit(prePC, md.BackwardTransfer(pc, prePC, pre, this), depth + 1);
this.underVisit.Remove(lastPC);
}
else
{
var newPre = md.BackwardTransfer(pc, prePC, pre, this);
Visit(prePC, newPre, depth + 1);
}
}
}
protected APC VisitBlock(APC pc, AElement preCondition, out AElement newPrecondition)
{
var pcHead = pc.FirstInBlock();
newPrecondition = preCondition;
APC prePC;
while (CFG.HasSinglePredecessor(pc, out prePC))
{
// We found the head!
if (pc.Equals(pcHead))
{
return pcHead;
}
// nothing to do, kill search
if (this.Mdriver.BasicFacts.IsUnreachable(pc))
{
Trace("Killing path as pc is unreachable", newPrecondition);
newPrecondition = this.NoCondition;
return pc;
}
newPrecondition = this.Mdriver.BackwardTransfer(pc, prePC, newPrecondition, this);
if(this.IsNoCondition(newPrecondition))
{
Trace("Killing path as we the underlyng analysis returned bottom", newPrecondition);
return pc;
}
pc = prePC;
}
return pc;
}
/// <summary>
/// Helper to be called from implementation of ShouldStopTheVisit
/// </summary>
/// <param name="depth"></param>
/// <param name="pre"></param>
/// <returns></returns>
protected bool WentTooFar(int depth, AElement pre)
{
this.timeout.CheckTimeOut("Precondition (Backwards) computation");
if (depth >= MaxDepth)
{
Trace("Killing the path: Too deep", pre);
return true;
}
return false;
}
#endregion
#region Helpers
protected BoxedExpression RemoveVacuousPremiseAndCheckForContradiction(APC to, BoxedExpression exp, ref bool contradiction)
{
var outcome = this.facts.IsTrue(to, exp);
switch (outcome)
{
case ProofOutcome.Top:
return exp;
case ProofOutcome.True:
return null; // vacuous premise
case ProofOutcome.Bottom:
case ProofOutcome.False:
contradiction = true;
return null;
default:
Contract.Assert(false, "Impossible");
return null;
}
}
/// <summary>
/// if bop in {\gt, \geq} then make bop { \lt, \leq } and swap left with right
/// </summary>
static protected void Normalize(ref BinaryOperator bop, ref BoxedExpression left, ref BoxedExpression right)
{
Contract.Requires(left != null);
Contract.Requires(right != null);
Contract.Ensures(Contract.ValueAtReturn(out left) != null);
Contract.Ensures(Contract.ValueAtReturn(out right) != null);
if (bop == BinaryOperator.Cgt || bop == BinaryOperator.Cge)
{
bop = bop == BinaryOperator.Cgt ? BinaryOperator.Clt : BinaryOperator.Cle;
var tmp = right;
right = left;
left = tmp;
}
}
#endregion
#region Transfer functions
abstract public AElement Rename(APC from, APC to, AElement pre, IFunctionalMap<Variable, Variable> renaming);
virtual public AElement Arglist(APC pc, Variable dest, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement BranchCond(APC pc, APC target, BranchOperator bop, Variable value1, Variable value2, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement BranchTrue(APC pc, APC target, Variable cond, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement BranchFalse(APC pc, APC target, Variable cond, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Branch(APC pc, APC target, bool leave, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Break(APC pc, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Call<TypeList, ArgList>(APC pc, Method method, bool tail, bool virt, TypeList extraVarargs, Variable dest, ArgList args, AElement pre)
where TypeList : IIndexable<Type>
where ArgList : IIndexable<Variable>
{
BreakHere(pc, pre);
return pre;
}
virtual public AElement Calli<TypeList, ArgList>(APC pc, Type returnType, TypeList argTypes, bool tail, bool instance, Variable dest, Variable fp, ArgList args, AElement pre)
where TypeList : IIndexable<Type>
where ArgList : IIndexable<Variable>
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Ckfinite(APC pc, Variable dest, Variable source, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Cpblk(APC pc, bool @volatile, Variable destaddr, Variable srcaddr, Variable len, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Endfilter(APC pc, Variable decision, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Endfinally(APC pc, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Initblk(APC pc, bool @volatile, Variable destaddr, Variable value, Variable len, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Jmp(APC pc, Method method, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Ldarg(APC pc, Parameter argument, bool isOld, Variable dest, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Ldarga(APC pc, Parameter argument, bool isOld, Variable dest, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Ldftn(APC pc, Method method, Variable dest, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Ldind(APC pc, Type type, bool @volatile, Variable dest, Variable ptr, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Ldloc(APC pc, Local local, Variable dest, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Ldloca(APC pc, Local local, Variable dest, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Localloc(APC pc, Variable dest, Variable size, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Nop(APC pc, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Pop(APC pc, Variable source, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Return(APC pc, Variable source, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Starg(APC pc, Parameter argument, Variable source, AElement pre)
{
BreakHere(pc, pre); return pre;
}
public AElement Stind(APC pc, Type type, bool @volatile, Variable ptr, Variable value, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Stloc(APC pc, Local local, Variable source, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Switch(APC pc, Type type, IEnumerable<Pair<object, APC>> cases, Variable value, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Box(APC pc, Type type, Variable dest, Variable source, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement ConstrainedCallvirt<TypeList, ArgList>(APC pc, Method method, bool tail, Type constraint, TypeList extraVarargs, Variable dest, ArgList args, AElement pre)
where TypeList : IIndexable<Type>
where ArgList : IIndexable<Variable>
{
BreakHere(pc, pre);
return pre;
}
virtual public AElement Castclass(APC pc, Type type, Variable dest, Variable obj, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Cpobj(APC pc, Type type, Variable destptr, Variable srcptr, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Initobj(APC pc, Type type, Variable ptr, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Ldelem(APC pc, Type type, Variable dest, Variable array, Variable index, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Ldelema(APC pc, Type type, bool @readonly, Variable dest, Variable array, Variable index, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Ldfld(APC pc, Field field, bool @volatile, Variable dest, Variable obj, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Ldflda(APC pc, Field field, Variable dest, Variable obj, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Ldlen(APC pc, Variable dest, Variable array, AElement pre)
{
BreakHere(pc, pre);
return pre;
}
virtual public AElement Ldsfld(APC pc, Field field, bool @volatile, Variable dest, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Ldsflda(APC pc, Field field, Variable dest, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Ldtypetoken(APC pc, Type type, Variable dest, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Ldfieldtoken(APC pc, Field field, Variable dest, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Ldmethodtoken(APC pc, Method method, Variable dest, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Ldvirtftn(APC pc, Method method, Variable dest, Variable obj, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Mkrefany(APC pc, Type type, Variable dest, Variable obj, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Newarray<ArgList>(APC pc, Type type, Variable dest, ArgList len, AElement pre) where ArgList : IIndexable<Variable>
{
BreakHere(pc, pre);
return pre;
}
virtual public AElement Newobj<ArgList>(APC pc, Method ctor, Variable dest, ArgList args, AElement pre) where ArgList : IIndexable<Variable>
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Refanytype(APC pc, Variable dest, Variable source, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Refanyval(APC pc, Type type, Variable dest, Variable source, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Rethrow(APC pc, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Stelem(APC pc, Type type, Variable array, Variable index, Variable value, AElement pre)
{
BreakHere(pc, pre);
return pre;
}
virtual public AElement Stfld(APC pc, Field field, bool @volatile, Variable obj, Variable value, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Stsfld(APC pc, Field field, bool @volatile, Variable value, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Throw(APC pc, Variable exn, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Unbox(APC pc, Type type, Variable dest, Variable obj, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Unboxany(APC pc, Type type, Variable dest, Variable obj, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Entry(APC pc, Method method, AElement pre)
{
BreakHere(pc, pre); return pre;
}
[ContractVerification(true)]
virtual public AElement Assume(APC pc, string tag, Variable condition, object provenance, AElement pre)
{
BreakHere(pc, pre, "assume " + tag);
return pre;
}
virtual public AElement Assert(APC pc, string tag, Variable condition, object provenance, AElement pre)
{
BreakHere(pc, pre, "assert");
return pre;
}
virtual public AElement Ldstack(APC pc, int offset, Variable dest, Variable source, bool isOld, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Ldstacka(APC pc, int offset, Variable dest, Variable source, Type origParamType, bool isOld, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Ldresult(APC pc, Type type, Variable dest, Variable source, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement BeginOld(APC pc, APC matchingEnd, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement EndOld(APC pc, APC matchingBegin, Type type, Variable dest, Variable source, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Binary(APC pc, BinaryOperator op, Variable dest, Variable s1, Variable s2, AElement pre)
{
BreakHere(pc, pre);
return pre;
}
virtual public AElement Isinst(APC pc, Type type, Variable dest, Variable obj, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Ldconst(APC pc, object constant, Type type, Variable dest, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Ldnull(APC pc, Variable dest, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Sizeof(APC pc, Type type, Variable dest, AElement pre)
{
BreakHere(pc, pre); return pre;
}
virtual public AElement Unary(APC pc, UnaryOperator op, bool overflow, bool unsigned, Variable dest, Variable source, AElement pre)
{
BreakHere(pc, pre);
return pre;
}
#region Helpers
protected bool AtLeastOnePremisIsNotFalse(APC pc, List<BoxedExpression> list)
{
if (list != null && list.Count > 0)
{
var facts = this.facts;
foreach (var p in list)
{
if (facts.IsTrue(pc, p) != ProofOutcome.False)
{
return true;
}
}
return false;
}
return true;
}
protected bool AreTheSame(APC pc, Variable dest, BoxedExpression right)
{
Contract.Requires(right != null);
if (right.UnderlyingVariable != null)
{
if (dest.Equals(right.UnderlyingVariable))
{
return true;
}
// give a shot to dest == (conv) right.Variable
// this is essentially a special case for the IL instruction (convi4)arr.Length
var refined = BoxedExpression.Convert(this.Mdriver.Context.ExpressionContext.Refine(this.Mdriver.CFG.Post(pc), dest), this.Mdriver.ExpressionDecoder);
UnaryOperator uop;
BoxedExpression left;
if (refined != null && refined.UnderlyingVariable != null &&
(refined.UnderlyingVariable.Equals(right.UnderlyingVariable))
|| (refined.IsUnaryExpression(out uop, out left) && uop.IsConversionOperator() && right.UnderlyingVariable.Equals(left.UnderlyingVariable)
))
{
return true;
}
}
return false;
}
protected BoxedExpression.BinaryExpressionMethodCall MakeMethodCallExpression(Method method, Variable var, FList<PathElement> accessPath)
{
return new BoxedExpression.BinaryExpressionMethodCall(/* dummy? */ BinaryOperator.Add,
BoxedExpression.Var(var, accessPath, this.Mdriver.MetaDataDecoder.System_Object), this.Mdriver.MetaDataDecoder.Name(method));
}
protected BoxedExpression MakeZeroExp(APC pc, Variable dest)
{
var t = this.Mdriver.Context.ValueContext.GetType(this.Mdriver.Context.MethodContext.CFG.Post(pc), dest);
BoxedExpression zeroExp;
if (t.IsNormal)
{
object value;
if (this.Mdriver.MetaDataDecoder.IsStruct(t.Value))
{
value = this.Mdriver.MetaDataDecoder.System_Boolean.Equals(t.Value) ? (object)false : (object)0;
}
else
{
value = null;
}
zeroExp = BoxedExpression.Const(value, t.Value, this.Mdriver.MetaDataDecoder);
}
else
{
zeroExp = BoxedExpression.Const(null, this.Mdriver.MetaDataDecoder.System_Object, this.Mdriver.MetaDataDecoder);
}
return zeroExp;
}
[Conditional("DEBUG")]
protected void BreakHere(APC pc, AElement pre, string instr = null)
{
if (this.TraceInference)
{
Console.WriteLine("Visiting: {0}-{1} with {2}", pc.ToString(), instr, pre.ToString());
}
}
[Conditional("DEBUG")]
protected void Trace(string s)
{
if (this.TraceInference)
{
Console.WriteLine("[Backwards] " + s);
}
}
[Conditional("DEBUG")]
protected void Trace(string s, AElement pre)
{
if (this.TraceInference)
{
Console.WriteLine("[Backwards] " + s + ": " + pre.ToString());
}
}
#endregion
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
namespace CorvusAlba.MyLittleLispy.Runtime
{
public class Context
{
private readonly Stack<Frame> _callStack = new Stack<Frame>();
private readonly Dictionary<string, Func<Node[], Value>> _specialForms;
private readonly Frame _globalFrame;
private Parser _parser;
private bool _evalMacro = true;
public Frame CurrentFrame
{
get
{
return _callStack.Peek();
}
}
private Value InvokeCondClause(Expression clause, Value condition = null)
{
var tail = clause.Tail.ToArray();
var first = tail[0].Quote(this);
if (first is SymbolValue && first.To<string>() == "=>")
{
if (condition != null)
{
return new Closure(this, null, new Expression(tail.Skip(1).
Concat(new[] { condition.ToExpression() })), true);
}
throw new SyntaxErrorException();
}
return new Closure(this, null, new Expression(new[] { new Symbol(new SymbolValue("begin")) }.
Concat(tail).ToArray()), true);
}
public Context(Parser parser)
{
_parser = parser;
_specialForms = new Dictionary<string, Func<Node[], Value>>
{
{"define", args => Define(args[0], new Expression(new [] { new Symbol(new SymbolValue("begin")) }.
Concat(args.Skip(1)).ToArray())) },
{"defmacro", args => DefineMacro(args[0].Quote(this).To<string>(), args[1], new Expression(new [] { new Symbol(new SymbolValue("begin")) }.
Concat(args.Skip(2)).ToArray())) },
{
"macroexpand", args =>
{
_evalMacro = false;
var result = Trampoline(args[0].Eval(this)).ToExpression().Eval(this);
_evalMacro = true;
return result;
}
},
{"quote", args => args[0].Quote(this) },
{"quasiquote", Quasiquote },
{"unquote", args => Trampoline(args[0].Eval(this)) },
{"unquote-splicing", args => Trampoline(args[0].Eval(this)) },
{"lambda", args => new Closure(this, args[0],
new Expression(new [] { new Symbol(new SymbolValue("begin")) }.
Concat(args.Skip(1)).ToArray())) },
{"when", args => Trampoline(args[0].Eval(this)).To<bool>()
? (Value) new Closure(this, null, new Expression(new [] { new Symbol(new SymbolValue("begin")) }.
Concat(args.Skip(1)).ToArray()), true)
: (Value) Cons.Empty },
{"unless", args => !Trampoline(args[0].Eval(this)).To<bool>()
? (Value) new Closure(this, null, new Expression(new [] { new Symbol(new SymbolValue("begin")) }.
Concat(args.Skip(1)).ToArray()), true)
: (Value) Cons.Empty },
{
"cond", args =>
{
var clauses = args.Cast<Expression>().ToArray();
foreach (var clause in clauses.Take(args.Count() - 1))
{
var condition = Trampoline(clause.Head.Eval(this));
if (condition.To<bool>())
{
return InvokeCondClause(clause, condition);
}
}
var lastClause = clauses.Last();
var head = lastClause.Head.Quote(this);
if (head is SymbolValue && head.To<string>() == "else")
{
return InvokeCondClause(lastClause);
}
var lastCondition = Trampoline(lastClause.Head.Eval(this));
if (lastCondition.To<bool>())
{
return InvokeCondClause(lastClause, lastCondition);
}
return Cons.Empty;
}
},
{
"if", args =>
{
var condition = Trampoline(args[0].Eval(this)).To<bool>();
if (condition)
{
return new Closure(this, null, args[1], true);
}
if (args.Length > 2)
{
return new Closure(this, null, args[2], true);
}
return Cons.Empty;
}
},
{"let", Let},
{"let*", LetSequential},
{"set!", Set},
{
"begin", args =>
{
foreach (var arg in args.Take(args.Count() - 1))
{
Trampoline(arg.Eval(this));
}
return new Closure(this, null, args.Last(), true);
}
},
{"do", Do},
{"import", Import},
{"and", And},
{"or", Or},
// TODO for jit-compiler letrec and letrec* will have different implementations
{"letrec", Let},
{"letrec*", LetSequential},
};
_globalFrame = new Frame();
_callStack.Push(_globalFrame);
CurrentFrame.Push();
}
private Value Quasiquote(Node[] args)
{
var expression = args[0] as Expression;
if (expression == null)
{
return args[0].Quote(this);
}
return new Cons(expression.Nodes.SelectMany(node =>
{
bool isNested = false;
var expressionNode = node as Expression;
if (expressionNode != null)
{
var value = expressionNode.Head.Quote(this);
if (value is SymbolValue)
{
var call = value.To<string>();
if (call == "unquote")
{
return new[] { expressionNode.Eval(this).ToExpression() };
}
if (call == "unquote-splicing")
{
var innerNode = expressionNode.Eval(this).ToExpression();
var innerExpressionNode = innerNode as Expression;
return innerExpressionNode != null ? innerExpressionNode.Nodes : new[] { innerNode };
}
if (call == "quasiquote")
{
isNested = true;
}
}
if (isNested)
{
return new[] { expressionNode.Quote(this).ToExpression() };
}
return new[] { Quasiquote(new Node[] { expressionNode }).ToExpression() };
}
return new[] { node };
}).Select(node => node.Quote(this)).ToArray());
}
private Value Set(Node[] args)
{
var name = args[0].Quote(this).To<string>();
var value = Trampoline(args[1].Eval(this));
CurrentFrame.Set(name, value);
return Cons.Empty;
}
private Value Or(Node[] args)
{
foreach (var arg in args)
{
var value = Trampoline(arg.Eval(this));
if (value.To<bool>())
{
return value;
}
}
return new Bool(false);
}
private Value And(Node[] args)
{
Value value = new Bool(true);
foreach (var arg in args)
{
value = Trampoline(arg.Eval(this));
if (!value.To<bool>())
{
return new Bool(false);
}
}
return value;
}
private Value Import(Node[] args)
{
var alias = args[0].Eval(this).To<string>();
var module = ModuleAttribute.Find(alias);
module.Import(_parser, this);
return Cons.Empty;
}
private Value Do(Node[] args)
{
var variableClauses = args[0].Quote(this).To<IEnumerable<Value>>().Select(v => v.ToExpression()).Cast<Expression>().ToArray();
var testClause = (Expression)args[1];
var body = new Expression(new[] { new Symbol(new SymbolValue("begin")) }.
Concat(args.Skip(2)).ToArray());
CurrentFrame.Push();
try
{
foreach (var clause in variableClauses)
{
CurrentFrame.Bind(clause.Head.Quote(this).To<string>(), Trampoline(clause.Tail.First().Eval(this)));
}
while (!Trampoline(testClause.Head.Eval(this)).To<bool>())
{
Trampoline(body.Eval(this));
foreach (var clause in variableClauses)
{
if (clause.Tail.Count() > 1)
{
CurrentFrame.Set(clause.Head.Quote(this).To<string>(), Trampoline(clause.Tail.Skip(1).First().Eval(this)));
}
}
}
return new Closure(this, null, new Expression(new[] { new Symbol(new SymbolValue("begin")) }.
Concat(testClause.Tail).ToArray()), true);
}
finally
{
CurrentFrame.Pop();
}
}
private Value Let(Node[] args)
{
var frameArgs = new List<string>();
var frameValues = new List<Value>();
var argNodes = new List<Node>();
var name = string.Empty;
if (args[0] is Symbol)
{
name = args[0].Quote(this).To<string>();
args = args.Skip(1).ToArray();
}
foreach (var clause in args[0].Quote(this).To<IEnumerable<Value>>().Select(v => v.ToExpression()).Cast<Expression>())
{
frameArgs.Add(clause.Head.Quote(this).To<string>());
frameValues.Add(Trampoline(clause.Tail.Single().Eval(this)));
argNodes.Add(clause.Head);
}
CurrentFrame.Push(frameArgs, frameValues);
try
{
if (!string.IsNullOrEmpty(name))
{
CurrentFrame.Bind(name, new Closure(this,
new Expression(argNodes),
new Expression(new[] { new Symbol(new SymbolValue("begin")) }.
Concat(args.Skip(1)).ToArray()), false));
}
var result = new Closure(this, null, new Expression(new[] { new Symbol(new SymbolValue("begin")) }.
Concat(args.Skip(1)).ToArray()), true);
return result;
}
finally
{
CurrentFrame.Pop();
}
}
private Value LetSequential(Node[] args)
{
var name = string.Empty;
var argNodes = new List<Node>();
if (args[0] is Symbol)
{
name = args[0].Quote(this).To<string>();
args = args.Skip(1).ToArray();
}
CurrentFrame.Push();
try
{
foreach (var clause in args[0].Quote(this).To<IEnumerable<Value>>().Select(v => v.ToExpression()).Cast<Expression>())
{
argNodes.Add(clause.Head);
CurrentFrame.Bind(clause.Head.Quote(this).To<string>(), Trampoline(clause.Tail.Single().Eval(this)));
}
if (!string.IsNullOrEmpty(name))
{
CurrentFrame.Bind(name, new Closure(this,
new Expression(argNodes),
new Expression(new[] { new Symbol(new SymbolValue("begin")) }.
Concat(args.Skip(1)).ToArray()), false));
}
var result = new Closure(this, null, new Expression(new[] { new Symbol(new SymbolValue("begin")) }.
Concat(args.Skip(1)).ToArray()), true);
return result;
}
finally
{
CurrentFrame.Pop();
}
}
public void Push(Frame frame)
{
_callStack.Push(frame);
}
public void Push()
{
_callStack.Push(new Frame(_globalFrame));
}
public void Pop()
{
_callStack.Pop();
}
public Value Lookup(string name)
{
return CurrentFrame.Lookup(name);
}
public Value Trampoline(Value value)
{
var tailCall = value as Closure;
while (tailCall != null && tailCall.IsTailCall)
{
value = InvokeClosure(tailCall, new Node[0]);
tailCall = value as Closure;
}
return value;
}
public Value Invoke(Node head, IEnumerable<Node> args = null)
{
Value call;
call = Trampoline(head.Eval(this));
if (call is Undefined)
{
if (head is Symbol)
{
call = head.Quote(this);
}
else
{
return Undefined.Value;
}
}
if (call is SymbolValue)
{
var name = call.To<string>();
if (_specialForms.ContainsKey(name))
{
var value = _specialForms[name].Invoke(args != null ? args.ToArray() : new Node[] { });
if (CurrentFrame.IsGlobal)
{
value = Trampoline(value);
}
return value;
}
}
else
{
var lambda = call as Closure;
if (lambda != null)
{
var value = InvokeClosure(lambda, args != null ? args.ToArray() : new Node[] { });
if (CurrentFrame.IsGlobal)
{
value = Trampoline(value);
}
return value;
}
}
return Undefined.Value;
}
public Value Define(Node definition, Node body)
{
if (definition is Expression)
{
var values = definition.Quote(this).To<IEnumerable<Value>>().ToArray();
var name = values.First().To<string>();
var args = new Expression(values.Skip(1).Select(v => v.ToExpression()));
CurrentFrame.Bind(name, new Closure(this, args, body));
}
else
{
var name = definition.Quote(this).To<string>();
CurrentFrame.Bind(name, body.Eval(this));
}
return Cons.Empty;
}
public Value DefineMacro(string name, Node args, Node body)
{
CurrentFrame.Bind(name, new Closure(this, args, body, false, true));
return Cons.Empty;
}
public Value InvokeClosure(Closure closure, Node[] values)
{
var calculatedValues = closure.IsMacro
? values.Select(value => value.Quote(this)).ToArray()
: values.Select(value => Trampoline(value.Eval(this))).ToArray();
var arguments = closure.HasRestArg
? calculatedValues.Take(closure.Args.Count() - 1).Concat(new[]
{
new Cons(calculatedValues.Skip(closure.Args.Count() - 1).ToArray())
}).ToArray()
: calculatedValues;
if (!closure.IsMacro)
{
Push();
CurrentFrame.Import(closure.Scopes);
}
CurrentFrame.Push(closure.Args, arguments);
try
{
Value result;
if (!closure.IsMacro)
{
result = !closure.IsTailCall
? new Closure(this, null, closure.Body, true)
: closure.Body.Eval(this);
}
else
{
result = Trampoline(closure.Body.Eval(this));
}
return !(closure.IsMacro && _evalMacro) ? result : result.ToExpression().Eval(this);
}
finally
{
CurrentFrame.Pop();
if (!closure.IsMacro)
{
if (closure.Scopes != null)
{
for (var i = 0; i < closure.Scopes.Count(); i++)
{
CurrentFrame.Pop();
}
}
Pop();
}
}
}
}
}
| |
namespace android.widget
{
[global::MonoJavaBridge.JavaClass(typeof(global::android.widget.CursorTreeAdapter_))]
public abstract partial class CursorTreeAdapter : android.widget.BaseExpandableListAdapter, Filterable
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static CursorTreeAdapter()
{
InitJNI();
}
protected CursorTreeAdapter(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _getGroupId11128;
public override long getGroupId(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallLongMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter._getGroupId11128, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter.staticClass, global::android.widget.CursorTreeAdapter._getGroupId11128, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getFilter11129;
public virtual global::android.widget.Filter getFilter()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter._getFilter11129)) as android.widget.Filter;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter.staticClass, global::android.widget.CursorTreeAdapter._getFilter11129)) as android.widget.Filter;
}
internal static global::MonoJavaBridge.MethodId _hasStableIds11130;
public override bool hasStableIds()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter._hasStableIds11130);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter.staticClass, global::android.widget.CursorTreeAdapter._hasStableIds11130);
}
internal static global::MonoJavaBridge.MethodId _getGroupCount11131;
public override int getGroupCount()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter._getGroupCount11131);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter.staticClass, global::android.widget.CursorTreeAdapter._getGroupCount11131);
}
internal static global::MonoJavaBridge.MethodId _getChildrenCount11132;
public override int getChildrenCount(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter._getChildrenCount11132, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter.staticClass, global::android.widget.CursorTreeAdapter._getChildrenCount11132, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getGroup11133;
public override global::java.lang.Object getGroup(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter._getGroup11133, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Object;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter.staticClass, global::android.widget.CursorTreeAdapter._getGroup11133, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Object;
}
internal static global::MonoJavaBridge.MethodId _getChild11134;
public override global::java.lang.Object getChild(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter._getChild11134, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.Object;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter.staticClass, global::android.widget.CursorTreeAdapter._getChild11134, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.Object;
}
internal static global::MonoJavaBridge.MethodId _getChildId11135;
public override long getChildId(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallLongMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter._getChildId11135, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter.staticClass, global::android.widget.CursorTreeAdapter._getChildId11135, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _getGroupView11136;
public override global::android.view.View getGroupView(int arg0, bool arg1, android.view.View arg2, android.view.ViewGroup arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter._getGroupView11136, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as android.view.View;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter.staticClass, global::android.widget.CursorTreeAdapter._getGroupView11136, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as android.view.View;
}
internal static global::MonoJavaBridge.MethodId _getChildView11137;
public override global::android.view.View getChildView(int arg0, int arg1, bool arg2, android.view.View arg3, android.view.ViewGroup arg4)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter._getChildView11137, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4))) as android.view.View;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter.staticClass, global::android.widget.CursorTreeAdapter._getChildView11137, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4))) as android.view.View;
}
internal static global::MonoJavaBridge.MethodId _isChildSelectable11138;
public override bool isChildSelectable(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter._isChildSelectable11138, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter.staticClass, global::android.widget.CursorTreeAdapter._isChildSelectable11138, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _onGroupCollapsed11139;
public override void onGroupCollapsed(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter._onGroupCollapsed11139, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter.staticClass, global::android.widget.CursorTreeAdapter._onGroupCollapsed11139, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getCursor11140;
public virtual global::android.database.Cursor getCursor()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.database.Cursor>(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter._getCursor11140)) as android.database.Cursor;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.database.Cursor>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter.staticClass, global::android.widget.CursorTreeAdapter._getCursor11140)) as android.database.Cursor;
}
internal static global::MonoJavaBridge.MethodId _notifyDataSetChanged11141;
public virtual void notifyDataSetChanged(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter._notifyDataSetChanged11141, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter.staticClass, global::android.widget.CursorTreeAdapter._notifyDataSetChanged11141, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _notifyDataSetChanged11142;
public override void notifyDataSetChanged()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter._notifyDataSetChanged11142);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter.staticClass, global::android.widget.CursorTreeAdapter._notifyDataSetChanged11142);
}
internal static global::MonoJavaBridge.MethodId _notifyDataSetInvalidated11143;
public override void notifyDataSetInvalidated()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter._notifyDataSetInvalidated11143);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter.staticClass, global::android.widget.CursorTreeAdapter._notifyDataSetInvalidated11143);
}
internal static global::MonoJavaBridge.MethodId _changeCursor11144;
public virtual void changeCursor(android.database.Cursor arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter._changeCursor11144, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter.staticClass, global::android.widget.CursorTreeAdapter._changeCursor11144, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _convertToString11145;
public virtual global::java.lang.String convertToString(android.database.Cursor arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter._convertToString11145, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter.staticClass, global::android.widget.CursorTreeAdapter._convertToString11145, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _runQueryOnBackgroundThread11146;
public virtual global::android.database.Cursor runQueryOnBackgroundThread(java.lang.CharSequence arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.database.Cursor>(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter._runQueryOnBackgroundThread11146, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.database.Cursor;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.database.Cursor>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter.staticClass, global::android.widget.CursorTreeAdapter._runQueryOnBackgroundThread11146, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.database.Cursor;
}
public android.database.Cursor runQueryOnBackgroundThread(string arg0)
{
return runQueryOnBackgroundThread((global::java.lang.CharSequence)(global::java.lang.String)arg0);
}
internal static global::MonoJavaBridge.MethodId _getFilterQueryProvider11147;
public virtual global::android.widget.FilterQueryProvider getFilterQueryProvider()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.widget.FilterQueryProvider>(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter._getFilterQueryProvider11147)) as android.widget.FilterQueryProvider;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.widget.FilterQueryProvider>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter.staticClass, global::android.widget.CursorTreeAdapter._getFilterQueryProvider11147)) as android.widget.FilterQueryProvider;
}
internal static global::MonoJavaBridge.MethodId _setFilterQueryProvider11148;
public virtual void setFilterQueryProvider(android.widget.FilterQueryProvider arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter._setFilterQueryProvider11148, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter.staticClass, global::android.widget.CursorTreeAdapter._setFilterQueryProvider11148, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getChildrenCursor11149;
protected abstract global::android.database.Cursor getChildrenCursor(android.database.Cursor arg0);
internal static global::MonoJavaBridge.MethodId _setGroupCursor11150;
public virtual void setGroupCursor(android.database.Cursor arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter._setGroupCursor11150, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter.staticClass, global::android.widget.CursorTreeAdapter._setGroupCursor11150, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setChildrenCursor11151;
public virtual void setChildrenCursor(int arg0, android.database.Cursor arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter._setChildrenCursor11151, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter.staticClass, global::android.widget.CursorTreeAdapter._setChildrenCursor11151, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _newGroupView11152;
protected abstract global::android.view.View newGroupView(android.content.Context arg0, android.database.Cursor arg1, bool arg2, android.view.ViewGroup arg3);
internal static global::MonoJavaBridge.MethodId _bindGroupView11153;
protected abstract void bindGroupView(android.view.View arg0, android.content.Context arg1, android.database.Cursor arg2, bool arg3);
internal static global::MonoJavaBridge.MethodId _newChildView11154;
protected abstract global::android.view.View newChildView(android.content.Context arg0, android.database.Cursor arg1, bool arg2, android.view.ViewGroup arg3);
internal static global::MonoJavaBridge.MethodId _bindChildView11155;
protected abstract void bindChildView(android.view.View arg0, android.content.Context arg1, android.database.Cursor arg2, bool arg3);
internal static global::MonoJavaBridge.MethodId _CursorTreeAdapter11156;
public CursorTreeAdapter(android.database.Cursor arg0, android.content.Context arg1, bool arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.CursorTreeAdapter.staticClass, global::android.widget.CursorTreeAdapter._CursorTreeAdapter11156, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _CursorTreeAdapter11157;
public CursorTreeAdapter(android.database.Cursor arg0, android.content.Context arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.CursorTreeAdapter.staticClass, global::android.widget.CursorTreeAdapter._CursorTreeAdapter11157, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.CursorTreeAdapter.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/CursorTreeAdapter"));
global::android.widget.CursorTreeAdapter._getGroupId11128 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter.staticClass, "getGroupId", "(I)J");
global::android.widget.CursorTreeAdapter._getFilter11129 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter.staticClass, "getFilter", "()Landroid/widget/Filter;");
global::android.widget.CursorTreeAdapter._hasStableIds11130 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter.staticClass, "hasStableIds", "()Z");
global::android.widget.CursorTreeAdapter._getGroupCount11131 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter.staticClass, "getGroupCount", "()I");
global::android.widget.CursorTreeAdapter._getChildrenCount11132 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter.staticClass, "getChildrenCount", "(I)I");
global::android.widget.CursorTreeAdapter._getGroup11133 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter.staticClass, "getGroup", "(I)Ljava/lang/Object;");
global::android.widget.CursorTreeAdapter._getChild11134 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter.staticClass, "getChild", "(II)Ljava/lang/Object;");
global::android.widget.CursorTreeAdapter._getChildId11135 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter.staticClass, "getChildId", "(II)J");
global::android.widget.CursorTreeAdapter._getGroupView11136 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter.staticClass, "getGroupView", "(IZLandroid/view/View;Landroid/view/ViewGroup;)Landroid/view/View;");
global::android.widget.CursorTreeAdapter._getChildView11137 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter.staticClass, "getChildView", "(IIZLandroid/view/View;Landroid/view/ViewGroup;)Landroid/view/View;");
global::android.widget.CursorTreeAdapter._isChildSelectable11138 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter.staticClass, "isChildSelectable", "(II)Z");
global::android.widget.CursorTreeAdapter._onGroupCollapsed11139 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter.staticClass, "onGroupCollapsed", "(I)V");
global::android.widget.CursorTreeAdapter._getCursor11140 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter.staticClass, "getCursor", "()Landroid/database/Cursor;");
global::android.widget.CursorTreeAdapter._notifyDataSetChanged11141 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter.staticClass, "notifyDataSetChanged", "(Z)V");
global::android.widget.CursorTreeAdapter._notifyDataSetChanged11142 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter.staticClass, "notifyDataSetChanged", "()V");
global::android.widget.CursorTreeAdapter._notifyDataSetInvalidated11143 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter.staticClass, "notifyDataSetInvalidated", "()V");
global::android.widget.CursorTreeAdapter._changeCursor11144 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter.staticClass, "changeCursor", "(Landroid/database/Cursor;)V");
global::android.widget.CursorTreeAdapter._convertToString11145 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter.staticClass, "convertToString", "(Landroid/database/Cursor;)Ljava/lang/String;");
global::android.widget.CursorTreeAdapter._runQueryOnBackgroundThread11146 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter.staticClass, "runQueryOnBackgroundThread", "(Ljava/lang/CharSequence;)Landroid/database/Cursor;");
global::android.widget.CursorTreeAdapter._getFilterQueryProvider11147 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter.staticClass, "getFilterQueryProvider", "()Landroid/widget/FilterQueryProvider;");
global::android.widget.CursorTreeAdapter._setFilterQueryProvider11148 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter.staticClass, "setFilterQueryProvider", "(Landroid/widget/FilterQueryProvider;)V");
global::android.widget.CursorTreeAdapter._getChildrenCursor11149 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter.staticClass, "getChildrenCursor", "(Landroid/database/Cursor;)Landroid/database/Cursor;");
global::android.widget.CursorTreeAdapter._setGroupCursor11150 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter.staticClass, "setGroupCursor", "(Landroid/database/Cursor;)V");
global::android.widget.CursorTreeAdapter._setChildrenCursor11151 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter.staticClass, "setChildrenCursor", "(ILandroid/database/Cursor;)V");
global::android.widget.CursorTreeAdapter._newGroupView11152 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter.staticClass, "newGroupView", "(Landroid/content/Context;Landroid/database/Cursor;ZLandroid/view/ViewGroup;)Landroid/view/View;");
global::android.widget.CursorTreeAdapter._bindGroupView11153 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter.staticClass, "bindGroupView", "(Landroid/view/View;Landroid/content/Context;Landroid/database/Cursor;Z)V");
global::android.widget.CursorTreeAdapter._newChildView11154 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter.staticClass, "newChildView", "(Landroid/content/Context;Landroid/database/Cursor;ZLandroid/view/ViewGroup;)Landroid/view/View;");
global::android.widget.CursorTreeAdapter._bindChildView11155 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter.staticClass, "bindChildView", "(Landroid/view/View;Landroid/content/Context;Landroid/database/Cursor;Z)V");
global::android.widget.CursorTreeAdapter._CursorTreeAdapter11156 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter.staticClass, "<init>", "(Landroid/database/Cursor;Landroid/content/Context;Z)V");
global::android.widget.CursorTreeAdapter._CursorTreeAdapter11157 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter.staticClass, "<init>", "(Landroid/database/Cursor;Landroid/content/Context;)V");
}
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.CursorTreeAdapter))]
public sealed partial class CursorTreeAdapter_ : android.widget.CursorTreeAdapter
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static CursorTreeAdapter_()
{
InitJNI();
}
internal CursorTreeAdapter_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _getChildrenCursor11158;
protected override global::android.database.Cursor getChildrenCursor(android.database.Cursor arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.database.Cursor>(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter_._getChildrenCursor11158, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.database.Cursor;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.database.Cursor>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter_.staticClass, global::android.widget.CursorTreeAdapter_._getChildrenCursor11158, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.database.Cursor;
}
internal static global::MonoJavaBridge.MethodId _newGroupView11159;
protected override global::android.view.View newGroupView(android.content.Context arg0, android.database.Cursor arg1, bool arg2, android.view.ViewGroup arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter_._newGroupView11159, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as android.view.View;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter_.staticClass, global::android.widget.CursorTreeAdapter_._newGroupView11159, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as android.view.View;
}
internal static global::MonoJavaBridge.MethodId _bindGroupView11160;
protected override void bindGroupView(android.view.View arg0, android.content.Context arg1, android.database.Cursor arg2, bool arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter_._bindGroupView11160, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter_.staticClass, global::android.widget.CursorTreeAdapter_._bindGroupView11160, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _newChildView11161;
protected override global::android.view.View newChildView(android.content.Context arg0, android.database.Cursor arg1, bool arg2, android.view.ViewGroup arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter_._newChildView11161, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as android.view.View;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter_.staticClass, global::android.widget.CursorTreeAdapter_._newChildView11161, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as android.view.View;
}
internal static global::MonoJavaBridge.MethodId _bindChildView11162;
protected override void bindChildView(android.view.View arg0, android.content.Context arg1, android.database.Cursor arg2, bool arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter_._bindChildView11162, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.CursorTreeAdapter_.staticClass, global::android.widget.CursorTreeAdapter_._bindChildView11162, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.CursorTreeAdapter_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/CursorTreeAdapter"));
global::android.widget.CursorTreeAdapter_._getChildrenCursor11158 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter_.staticClass, "getChildrenCursor", "(Landroid/database/Cursor;)Landroid/database/Cursor;");
global::android.widget.CursorTreeAdapter_._newGroupView11159 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter_.staticClass, "newGroupView", "(Landroid/content/Context;Landroid/database/Cursor;ZLandroid/view/ViewGroup;)Landroid/view/View;");
global::android.widget.CursorTreeAdapter_._bindGroupView11160 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter_.staticClass, "bindGroupView", "(Landroid/view/View;Landroid/content/Context;Landroid/database/Cursor;Z)V");
global::android.widget.CursorTreeAdapter_._newChildView11161 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter_.staticClass, "newChildView", "(Landroid/content/Context;Landroid/database/Cursor;ZLandroid/view/ViewGroup;)Landroid/view/View;");
global::android.widget.CursorTreeAdapter_._bindChildView11162 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter_.staticClass, "bindChildView", "(Landroid/view/View;Landroid/content/Context;Landroid/database/Cursor;Z)V");
}
}
}
| |
//! \file ImageMCG.cs
//! \date Mon Jul 13 17:58:33 2015
//! \brief F&C Co. image format.
//
// Copyright (C) 2015 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.IO;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using GameRes.Formats.Strings;
namespace GameRes.Formats.FC01
{
internal class McgMetaData : ImageMetaData
{
public int DataOffset;
public int PackedSize;
public int Version;
public int ChannelsCount;
}
internal class McgOptions : ResourceOptions
{
public byte Key;
}
[Serializable]
public class McgScheme : ResourceScheme
{
public Dictionary<string, byte> KnownKeys;
}
[Export(typeof(ImageFormat))]
public class McgFormat : ImageFormat
{
public override string Tag { get { return "MCG"; } }
public override string Description { get { return "F&C Co. image format"; } }
public override uint Signature { get { return 0x2047434D; } } // 'MCG'
internal static Dictionary<string, byte> KnownKeys { get { return DefaultScheme.KnownKeys; } }
static McgScheme DefaultScheme = new McgScheme { KnownKeys = new Dictionary<string, byte>() };
public override ResourceScheme Scheme
{
get { return DefaultScheme; }
set { DefaultScheme = (McgScheme)value; }
}
public override ImageMetaData ReadMetaData (IBinaryStream stream)
{
var header = stream.ReadHeader (0x40);
if (header[5] != '.')
return null;
int version = header[4] * 100 + header[6] * 10 + header[7] - 0x14D0;
if (version != 200 && version != 101 && version != 100)
throw new NotSupportedException ("Not supported MCG format version");
int header_size = header.ToInt32 (0x10);
if (header_size < 0x40)
return null;
int bpp = header.ToInt32 (0x24);
if (24 != bpp && 8 != bpp && 16 != bpp)
throw new NotSupportedException ("Not supported MCG image bitdepth");
int packed_size = header.ToInt32 (0x38);
return new McgMetaData
{
Width = header.ToUInt32 (0x1c),
Height = header.ToUInt32 (0x20),
OffsetX = header.ToInt32 (0x14),
OffsetY = header.ToInt32 (0x18),
BPP = bpp,
DataOffset = header_size,
PackedSize = packed_size,
Version = version,
ChannelsCount = header.ToInt32 (0x34),
};
}
// cache key value so that dialog does not pop up on every file accessed.
byte? LastKey = null;
public override ImageData Read (IBinaryStream stream, ImageMetaData info)
{
var meta = (McgMetaData)info;
byte key = 0;
if (101 == meta.Version || 100 == meta.Version)
{
if (null == LastKey)
{
var options = Query<McgOptions> (arcStrings.ArcImageEncrypted);
key = options.Key;
}
else
key = LastKey.Value;
}
var reader = new McgDecoder (stream, meta, key);
reader.Unpack();
if (reader.Key != 0)
LastKey = reader.Key;
return ImageData.Create (info, reader.Format, reader.Palette, reader.Data, reader.Stride);
}
public override void Write (Stream file, ImageData image)
{
throw new System.NotImplementedException ("McgFormat.Write not implemented");
}
public override ResourceOptions GetDefaultOptions ()
{
return new McgOptions { Key = Properties.Settings.Default.MCGLastKey };
}
public override ResourceOptions GetOptions (object widget)
{
var w = widget as GUI.WidgetMCG;
if (null != w)
Properties.Settings.Default.MCGLastKey = w.GetKey ();
return GetDefaultOptions();
}
public override object GetAccessWidget ()
{
return new GUI.WidgetMCG();
}
}
// mcg decompression // graphic.unt @ 100047B0
internal class McgDecoder
{
byte[] m_input;
byte[] m_output;
int m_width;
int m_height;
int m_pixels;
byte m_key;
IBinaryStream m_file;
McgMetaData m_info;
public byte Key { get { return m_key; } }
public byte[] Data { get { return m_output; } }
public int Stride { get; private set; }
public PixelFormat Format { get; private set; }
public BitmapPalette Palette { get; private set; }
public McgDecoder (IBinaryStream input, McgMetaData info, byte key)
{
m_file = input;
m_info = info;
m_width = (int)info.Width;
m_height = (int)info.Height;
m_pixels = m_width*m_height;
m_key = key;
Stride = m_width * m_info.BPP / 8;
if (m_info.Version <= 101)
Stride = (Stride + 3) & -4;
if (24 == m_info.BPP)
Format = PixelFormats.Bgr24;
else if (16 == m_info.BPP)
Format = PixelFormats.Bgr555;
else if (8 == m_info.BPP)
Format = PixelFormats.Indexed8;
else
throw new InvalidFormatException();
}
static readonly byte[] ChannelOrder = { 1, 0, 2 };
public void Unpack ()
{
m_file.Position = m_info.DataOffset;
int input_size = m_info.PackedSize;
if (0 == input_size)
input_size = (int)m_file.Length;
input_size -= m_info.DataOffset;
if (8 == m_info.BPP)
{
Palette = ImageFormat.ReadPalette (m_file.AsStream);
input_size -= 0x400;
}
else if (m_info.ChannelsCount > 0)
{
var masks = new int[m_info.ChannelsCount];
for (int i = 0; i < masks.Length; ++i)
masks[i] = m_file.ReadInt32();
if (16 == m_info.BPP && 3 == m_info.ChannelsCount)
{
if (0x7E0 == masks[1])
Format = PixelFormats.Bgr565;
}
input_size -= m_info.ChannelsCount * 4;
}
m_input = m_file.ReadBytes (input_size);
if (m_input.Length != input_size)
throw new InvalidFormatException ("Unexpected end of file");
if (200 == m_info.Version)
UnpackV200();
else
UnpackV101();
}
void UnpackV101 ()
{
if (m_key != 0)
{
MrgOpener.Decrypt (m_input, 0, m_input.Length-1, m_key);
}
#if DEBUG
else if (101 == m_info.Version) // bruteforce key *in debug build only*
{
var copy = new byte[m_input.Length];
for (int key = 1; key < 256; ++key)
{
Buffer.BlockCopy (m_input, 0, copy, 0, m_input.Length);
MrgOpener.Decrypt (copy, 0, copy.Length-1, (byte)key);
using (var input = new BinMemoryStream (copy))
using (var lzss = new MrgLzssReader (input, copy.Length, Stride * m_height))
{
lzss.Unpack();
if (input.Length - input.Position <= 1)
{
Trace.WriteLine (string.Format ("Found matching key {0:X2}", key), "[MCG]");
m_output = lzss.Data;
m_key = (byte)key;
return;
}
}
}
}
#endif
using (var input = new BinMemoryStream (m_input))
using (var lzss = new MrgLzssReader (input, m_input.Length, Stride * m_height))
{
lzss.Unpack();
// data remaining within input stream indicates invalid encryption key
if (input.Length - input.Position > 1)
{
m_key = 0;
}
m_output = lzss.Data;
}
}
void UnpackV200 ()
{
m_output = new byte[m_pixels*3];
var reader = new MrgDecoder (m_input, 0, (uint)m_pixels);
do
{
reader.ResetKey (m_key);
try
{
for (int i = 0; i < 3; ++i)
{
reader.Unpack();
var plane = reader.Data;
int src = 0;
for (int j = ChannelOrder[i]; j < m_output.Length; j += 3)
{
m_output[j] = plane[src++];
}
}
// Trace.WriteLine (string.Format ("Found matching key {0:X2}", key), "[MCG]");
}
catch (InvalidFormatException)
{
m_key++;
continue;
}
Transform();
Properties.Settings.Default.MCGLastKey = m_key;
return;
}
while (m_key != Properties.Settings.Default.MCGLastKey);
throw new UnknownEncryptionScheme();
}
void Transform ()
{
int dst = 0;
for (int y = m_height-1; y > 0; --y) // @@1a
{
for (int x = Stride-3; x > 0; --x) // @@1b
{
int p0 = m_output[dst];
int py = m_output[dst+Stride] - p0;
int px = m_output[dst+3] - p0;
p0 = Math.Abs (px + py);
py = Math.Abs (py);
px = Math.Abs (px);
byte pv;
if (p0 >= px && py >= px)
pv = m_output[dst+Stride];
else if (p0 < py)
pv = m_output[dst];
else
pv = m_output[dst+3];
m_output[dst+Stride+3] += (byte)(pv + 0x80);
++dst;
}
dst += 3;
}
dst = 0;
for (uint i = 0; i < m_pixels; ++i)
{
sbyte b = -128;
sbyte r = -128;
b += (sbyte)m_output[dst];
r += (sbyte)m_output[dst+2];
int g = m_output[dst+1] - ((b + r) >> 2);
m_output[dst++] = (byte)(b + g);
m_output[dst++] = (byte)g;
m_output[dst++] = (byte)(r + g);
}
}
}
}
| |
// 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.Tracing;
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
using Microsoft.Diagnostics.Tracing.Session;
#endif
using Xunit;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace BasicEventSourceTests
{
/// <summary>
/// A listener can represent an out of process ETW listener (real time or not) or an EventListener
/// </summary>
public abstract class Listener : IDisposable
{
public Action<Event> OnEvent; // Called when you get events.
public abstract void Dispose();
/// <summary>
/// Send a command to an eventSource. Be careful this is async. You may wish to do a WaitForEnable
/// </summary>
public abstract void EventSourceCommand(string eventSourceName, EventCommand command, FilteringOptions options = null);
public void EventSourceSynchronousEnable(EventSource eventSource, FilteringOptions options = null)
{
EventSourceCommand(eventSource.Name, EventCommand.Enable, options);
WaitForEnable(eventSource);
}
public void WaitForEnable(EventSource logger)
{
if (!SpinWait.SpinUntil(() => logger.IsEnabled(), TimeSpan.FromSeconds(10)))
{
throw new InvalidOperationException("EventSource not enabled after 5 seconds");
}
}
internal void EnableTimer(EventSource eventSource, int pollingTime)
{
FilteringOptions options = new FilteringOptions();
options.Args = new Dictionary<string, string>();
options.Args.Add("EventCounterIntervalSec", pollingTime.ToString());
EventSourceCommand(eventSource.Name, EventCommand.Enable, options);
}
}
/// <summary>
/// Used to control what options the harness sends to the EventSource when turning it on. If not given
/// it turns on all keywords, Verbose level, and no args.
/// </summary>
public class FilteringOptions
{
public FilteringOptions() { Keywords = EventKeywords.All; Level = EventLevel.Verbose; }
public EventKeywords Keywords;
public EventLevel Level;
public IDictionary<string, string> Args;
public override string ToString()
{
return string.Format("<Options Keywords='{0}' Level'{1}' ArgsCount='{2}'",
((ulong)Keywords).ToString("x"), Level, Args.Count);
}
}
/// <summary>
/// Because events can be written to a EventListener as well as to ETW, we abstract what the result
/// of an event coming out of the pipe. Basically there are properties that fetch the name
/// and the payload values, and we subclass this for the ETW case and for the EventListener case.
/// </summary>
public abstract class Event
{
public virtual bool IsEtw { get { return false; } }
public virtual bool IsEventListener { get { return false; } }
public abstract string ProviderName { get; }
public abstract string EventName { get; }
public abstract object PayloadValue(int propertyIndex, string propertyName);
public abstract int PayloadCount { get; }
public virtual string PayloadString(int propertyIndex, string propertyName)
{
return PayloadValue(propertyIndex, propertyName).ToString();
}
public abstract IEnumerable<string> PayloadNames { get; }
#if DEBUG
/// <summary>
/// This is a convenience function for the debugger. It is not used typically
/// </summary>
public List<object> PayloadValues
{
get
{
var ret = new List<object>();
for (int i = 0; i < PayloadCount; i++)
ret.Add(PayloadValue(i, null));
return ret;
}
}
#endif
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append(ProviderName).Append('/').Append(EventName).Append('(');
for (int i = 0; i < PayloadCount; i++)
{
if (i != 0)
sb.Append(',');
sb.Append(PayloadString(i, null));
}
sb.Append(')');
return sb.ToString();
}
}
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
/**************************************************************************/
/* Concrete implementation of the Listener abstraction */
/// <summary>
/// Implementation of the Listener abstraction for ETW.
/// </summary>
public class EtwListener : Listener
{
internal static void EnsureStopped()
{
using (var session = new TraceEventSession("EventSourceTestSession", "EventSourceTestData.etl"))
session.Stop();
}
public EtwListener(string dataFileName = "EventSourceTestData.etl", string sessionName = "EventSourceTestSession")
{
_dataFileName = dataFileName;
// Today you have to be Admin to turn on ETW events (anyone can write ETW events).
if (TraceEventSession.IsElevated() != true)
{
throw new ApplicationException("Need to be elevated to run. ");
}
if (dataFileName == null)
{
Debug.WriteLine("Creating a real time session " + sessionName);
Task.Factory.StartNew(delegate ()
{
var session = new TraceEventSession(sessionName, dataFileName);
session.Source.AllEvents += OnEventHelper;
Debug.WriteLine("Listening for real time events");
_session = session; // Indicate that we are alive.
_session.Source.Process();
Debug.WriteLine("Real time listening stopping.");
});
SpinWait.SpinUntil(() => _session != null); // Wait for real time thread to wake up.
}
else
{
// Normalize to a full path name.
dataFileName = Path.GetFullPath(dataFileName);
Debug.WriteLine("Creating ETW data file " + Path.GetFullPath(dataFileName));
_session = new TraceEventSession(sessionName, dataFileName);
}
}
public override void EventSourceCommand(string eventSourceName, EventCommand command, FilteringOptions options = null)
{
if (command == EventCommand.Enable)
{
if (options == null)
options = new FilteringOptions();
_session.EnableProvider(eventSourceName, (TraceEventLevel)options.Level, (ulong)options.Keywords,
new TraceEventProviderOptions() { Arguments = options.Args });
}
else if (command == EventCommand.Disable)
{
_session.DisableProvider(TraceEventProviders.GetEventSourceGuidFromName(eventSourceName));
}
else
throw new NotImplementedException();
Thread.Sleep(200); // Calls are async, give them time to work.
}
public override void Dispose()
{
_session.Flush();
Thread.Sleep(1010); // Let it drain.
_session.Dispose(); // This also will kill the real time thread
if (_dataFileName != null)
{
using (var traceEventSource = new ETWTraceEventSource(_dataFileName))
{
Debug.WriteLine("Processing data file " + Path.GetFullPath(_dataFileName));
// Parse all the events as as best we can, and also send unhandled events there as well.
traceEventSource.Registered.All += OnEventHelper;
traceEventSource.Dynamic.All += OnEventHelper;
traceEventSource.UnhandledEvents += OnEventHelper;
// Process all the events in the file.
traceEventSource.Process();
Debug.WriteLine("Done processing data file " + Path.GetFullPath(_dataFileName));
}
}
}
#region private
private void OnEventHelper(TraceEvent data)
{
// Ignore manifest events.
if ((int)data.ID == 0xFFFE)
return;
this.OnEvent(new EtwEvent(data));
}
/// <summary>
/// EtwEvent implements the 'Event' abstraction for ETW events (it has a TraceEvent in it)
/// </summary>
internal class EtwEvent : Event
{
public override bool IsEtw { get { return true; } }
public override string ProviderName { get { return _data.ProviderName; } }
public override string EventName { get { return _data.EventName; } }
public override object PayloadValue(int propertyIndex, string propertyName)
{
if (propertyName != null)
Assert.Equal(propertyName, _data.PayloadNames[propertyIndex]);
return _data.PayloadValue(propertyIndex);
}
public override string PayloadString(int propertyIndex, string propertyName)
{
Assert.Equal(propertyName, _data.PayloadNames[propertyIndex]);
return _data.PayloadString(propertyIndex);
}
public override int PayloadCount { get { return _data.PayloadNames.Length; } }
public override IEnumerable<string> PayloadNames { get { return _data.PayloadNames; } }
#region private
internal EtwEvent(TraceEvent data) { _data = data.Clone(); }
private TraceEvent _data;
#endregion
}
private string _dataFileName;
private volatile TraceEventSession _session;
#endregion
}
#endif //USE_ETW
public class EventListenerListener : Listener
{
#if false // TODO: Enable when we ship the events. GitHub issue #4865
public event EventHandler<EventSourceCreatedEventArgs> EventSourceCreated
{
add
{
if(this.m_listener != null)
{
this.m_listener.EventSourceCreated += value;
}
}
remove
{
if (this.m_listener != null)
{
this.m_listener.EventSourceCreated -= value;
}
}
}
public event EventHandler<EventWrittenEventArgs> EventWritten
{
add
{
if (this.m_listener != null)
{
this.m_listener.EventWritten += value;
}
}
remove
{
if (this.m_listener != null)
{
this.m_listener.EventWritten -= value;
}
}
}
#endif // false
public EventListenerListener(bool useEventsToListen = false)
{
#if false // TODO: enable when we ship the events. GitHub issue #4865
if (useEventsToListen)
{
m_listener = new HelperEventListener(null);
m_listener.EventSourceCreated += mListenerEventSourceCreated;
m_listener.EventWritten += mListenerEventWritten;
}
else
#endif // false
{
_listener = new HelperEventListener(this);
}
}
private void mListenerEventWritten(object sender, EventWrittenEventArgs eventData)
{
OnEvent(new EventListenerEvent(eventData));
}
#if false // TODO: enable when we ship the events. GitHub issue #4865
private void mListenerEventSourceCreated(object sender, EventSourceCreatedEventArgs eventSource)
{
if(_onEventSourceCreated != null)
{
_onEventSourceCreated(eventSource.EventSource);
}
}
#endif // false
public override void EventSourceCommand(string eventSourceName, EventCommand command, FilteringOptions options = null)
{
if (options == null)
options = new FilteringOptions();
foreach (EventSource source in EventSource.GetSources())
{
if (source.Name == eventSourceName)
{
DoCommand(source, command, options);
return;
}
}
_onEventSourceCreated += delegate (EventSource sourceBeingCreated)
{
if (eventSourceName != null && eventSourceName == sourceBeingCreated.Name)
{
DoCommand(sourceBeingCreated, command, options);
eventSourceName = null; // so we only do it once.
}
};
}
public override void Dispose()
{
_listener.Dispose();
}
#region private
private void DoCommand(EventSource source, EventCommand command, FilteringOptions options)
{
if (command == EventCommand.Enable)
_listener.EnableEvents(source, options.Level, options.Keywords, options.Args);
else if (command == EventCommand.Disable)
_listener.DisableEvents(source);
else
throw new NotImplementedException();
}
private class HelperEventListener : EventListener
{
public HelperEventListener(EventListenerListener forwardTo) { _forwardTo = forwardTo; }
protected override void OnEventWritten(EventWrittenEventArgs eventData)
{
#if false // TODO: EventListener events are not enabled in coreclr. GitHub issue #4865
base.OnEventWritten(eventData);
#endif // false
if (_forwardTo != null && _forwardTo.OnEvent != null)
{
_forwardTo.OnEvent(new EventListenerEvent(eventData));
}
}
protected override void OnEventSourceCreated(EventSource eventSource)
{
base.OnEventSourceCreated(eventSource);
if (_forwardTo != null && _forwardTo._onEventSourceCreated != null)
_forwardTo._onEventSourceCreated(eventSource);
}
private EventListenerListener _forwardTo;
}
/// <summary>
/// EtwEvent implements the 'Event' abstraction for TraceListene events (it has a EventWrittenEventArgs in it)
/// </summary>
internal class EventListenerEvent : Event
{
public override bool IsEventListener { get { return true; } }
public override string ProviderName { get { return _data.EventSource.Name; } }
public override string EventName { get { return _data.EventName; } }
public override object PayloadValue(int propertyIndex, string propertyName)
{
if (propertyName != null)
Assert.Equal(propertyName, _data.PayloadNames[propertyIndex]);
return _data.Payload[propertyIndex];
}
public override int PayloadCount
{
get
{
if (_data.Payload == null)
return 0;
return _data.Payload.Count;
}
}
public override IEnumerable<string> PayloadNames { get { return _data.PayloadNames; } }
#region private
internal EventListenerEvent(EventWrittenEventArgs data) { _data = data; }
private EventWrittenEventArgs _data;
#endregion
}
private EventListener _listener;
private Action<EventSource> _onEventSourceCreated;
#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.Dynamic.Utils;
using System.Reflection;
namespace System.Linq.Expressions.Interpreter
{
internal abstract class AddInstruction : Instruction
{
private static Instruction s_int16, s_int32, s_int64, s_UInt16, s_UInt32, s_UInt64, s_single, s_double;
public override int ConsumedStack { get { return 2; } }
public override int ProducedStack { get { return 1; } }
public override string InstructionName
{
get { return "Add"; }
}
private AddInstruction()
{
}
internal sealed class AddInt32 : AddInstruction
{
public override int Run(InterpretedFrame frame)
{
object l = frame.Data[frame.StackIndex - 2];
object r = frame.Data[frame.StackIndex - 1];
if (l == null || r == null)
{
frame.Data[frame.StackIndex - 2] = null;
}
else
{
frame.Data[frame.StackIndex - 2] = ScriptingRuntimeHelpers.Int32ToObject(unchecked((Int32)l + (Int32)r));
}
frame.StackIndex--;
return +1;
}
}
internal sealed class AddInt16 : AddInstruction
{
public override int Run(InterpretedFrame frame)
{
object l = frame.Data[frame.StackIndex - 2];
object r = frame.Data[frame.StackIndex - 1];
if (l == null || r == null)
{
frame.Data[frame.StackIndex - 2] = null;
}
else
{
frame.Data[frame.StackIndex - 2] = unchecked((Int16)((Int16)l + (Int16)r));
}
frame.StackIndex--;
return +1;
}
}
internal sealed class AddInt64 : AddInstruction
{
public override int Run(InterpretedFrame frame)
{
object l = frame.Data[frame.StackIndex - 2];
object r = frame.Data[frame.StackIndex - 1];
if (l == null || r == null)
{
frame.Data[frame.StackIndex - 2] = null;
}
else
{
frame.Data[frame.StackIndex - 2] = unchecked((Int64)((Int64)l + (Int64)r));
}
frame.StackIndex--;
return +1;
}
}
internal sealed class AddUInt16 : AddInstruction
{
public override int Run(InterpretedFrame frame)
{
object l = frame.Data[frame.StackIndex - 2];
object r = frame.Data[frame.StackIndex - 1];
if (l == null || r == null)
{
frame.Data[frame.StackIndex - 2] = null;
}
else
{
frame.Data[frame.StackIndex - 2] = unchecked((UInt16)((UInt16)l + (UInt16)r));
}
frame.StackIndex--;
return +1;
}
}
internal sealed class AddUInt32 : AddInstruction
{
public override int Run(InterpretedFrame frame)
{
object l = frame.Data[frame.StackIndex - 2];
object r = frame.Data[frame.StackIndex - 1];
if (l == null || r == null)
{
frame.Data[frame.StackIndex - 2] = null;
}
else
{
frame.Data[frame.StackIndex - 2] = unchecked((UInt32)((UInt32)l + (UInt32)r));
}
frame.StackIndex--;
return +1;
}
}
internal sealed class AddUInt64 : AddInstruction
{
public override int Run(InterpretedFrame frame)
{
object l = frame.Data[frame.StackIndex - 2];
object r = frame.Data[frame.StackIndex - 1];
if (l == null || r == null)
{
frame.Data[frame.StackIndex - 2] = null;
}
else
{
frame.Data[frame.StackIndex - 2] = unchecked((UInt64)((UInt64)l + (UInt64)r));
}
frame.StackIndex--;
return +1;
}
}
internal sealed class AddSingle : AddInstruction
{
public override int Run(InterpretedFrame frame)
{
object l = frame.Data[frame.StackIndex - 2];
object r = frame.Data[frame.StackIndex - 1];
if (l == null || r == null)
{
frame.Data[frame.StackIndex - 2] = null;
}
else
{
frame.Data[frame.StackIndex - 2] = (Single)((Single)l + (Single)r);
}
frame.StackIndex--;
return +1;
}
}
internal sealed class AddDouble : AddInstruction
{
public override int Run(InterpretedFrame frame)
{
object l = frame.Data[frame.StackIndex - 2];
object r = frame.Data[frame.StackIndex - 1];
if (l == null || r == null)
{
frame.Data[frame.StackIndex - 2] = null;
}
else
{
frame.Data[frame.StackIndex - 2] = (Double)l + (Double)r;
}
frame.StackIndex--;
return +1;
}
}
public static Instruction Create(Type type)
{
Debug.Assert(TypeUtils.IsArithmetic(type));
switch (System.Dynamic.Utils.TypeExtensions.GetTypeCode(TypeUtils.GetNonNullableType(type)))
{
case TypeCode.Int16: return s_int16 ?? (s_int16 = new AddInt16());
case TypeCode.Int32: return s_int32 ?? (s_int32 = new AddInt32());
case TypeCode.Int64: return s_int64 ?? (s_int64 = new AddInt64());
case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new AddUInt16());
case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new AddUInt32());
case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new AddUInt64());
case TypeCode.Single: return s_single ?? (s_single = new AddSingle());
case TypeCode.Double: return s_double ?? (s_double = new AddDouble());
default:
throw ContractUtils.Unreachable;
}
}
}
internal abstract class AddOvfInstruction : Instruction
{
private static Instruction s_int16, s_int32, s_int64, s_UInt16, s_UInt32, s_UInt64;
public override int ConsumedStack { get { return 2; } }
public override int ProducedStack { get { return 1; } }
public override string InstructionName
{
get { return "AddOvf"; }
}
private AddOvfInstruction()
{
}
internal sealed class AddOvfInt32 : AddOvfInstruction
{
public override int Run(InterpretedFrame frame)
{
object l = frame.Data[frame.StackIndex - 2];
object r = frame.Data[frame.StackIndex - 1];
if (l == null || r == null)
{
frame.Data[frame.StackIndex - 2] = null;
}
else
{
frame.Data[frame.StackIndex - 2] = ScriptingRuntimeHelpers.Int32ToObject(checked((Int32)l + (Int32)r));
}
frame.StackIndex--;
return +1;
}
}
internal sealed class AddOvfInt16 : AddOvfInstruction
{
public override int Run(InterpretedFrame frame)
{
object l = frame.Data[frame.StackIndex - 2];
object r = frame.Data[frame.StackIndex - 1];
if (l == null || r == null)
{
frame.Data[frame.StackIndex - 2] = null;
}
else
{
frame.Data[frame.StackIndex - 2] = checked((Int16)((Int16)l + (Int16)r));
}
frame.StackIndex--;
return +1;
}
}
internal sealed class AddOvfInt64 : AddOvfInstruction
{
public override int Run(InterpretedFrame frame)
{
object l = frame.Data[frame.StackIndex - 2];
object r = frame.Data[frame.StackIndex - 1];
if (l == null || r == null)
{
frame.Data[frame.StackIndex - 2] = null;
}
else
{
frame.Data[frame.StackIndex - 2] = checked((Int64)((Int64)l + (Int64)r));
}
frame.StackIndex--;
return +1;
}
}
internal sealed class AddOvfUInt16 : AddOvfInstruction
{
public override int Run(InterpretedFrame frame)
{
object l = frame.Data[frame.StackIndex - 2];
object r = frame.Data[frame.StackIndex - 1];
if (l == null || r == null)
{
frame.Data[frame.StackIndex - 2] = null;
}
else
{
frame.Data[frame.StackIndex - 2] = checked((UInt16)((UInt16)l + (UInt16)r));
}
frame.StackIndex--;
return +1;
}
}
internal sealed class AddOvfUInt32 : AddOvfInstruction
{
public override int Run(InterpretedFrame frame)
{
object l = frame.Data[frame.StackIndex - 2];
object r = frame.Data[frame.StackIndex - 1];
if (l == null || r == null)
{
frame.Data[frame.StackIndex - 2] = null;
}
else
{
frame.Data[frame.StackIndex - 2] = checked((UInt32)((UInt32)l + (UInt32)r));
}
frame.StackIndex--;
return +1;
}
}
internal sealed class AddOvfUInt64 : AddOvfInstruction
{
public override int Run(InterpretedFrame frame)
{
object l = frame.Data[frame.StackIndex - 2];
object r = frame.Data[frame.StackIndex - 1];
if (l == null || r == null)
{
frame.Data[frame.StackIndex - 2] = null;
}
else
{
frame.Data[frame.StackIndex - 2] = checked((UInt64)((UInt64)l + (UInt64)r));
}
frame.StackIndex--;
return +1;
}
}
public static Instruction Create(Type type)
{
Debug.Assert(TypeUtils.IsArithmetic(type));
switch (System.Dynamic.Utils.TypeExtensions.GetTypeCode(TypeUtils.GetNonNullableType(type)))
{
case TypeCode.Int16: return s_int16 ?? (s_int16 = new AddOvfInt16());
case TypeCode.Int32: return s_int32 ?? (s_int32 = new AddOvfInt32());
case TypeCode.Int64: return s_int64 ?? (s_int64 = new AddOvfInt64());
case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new AddOvfUInt16());
case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new AddOvfUInt32());
case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new AddOvfUInt64());
default:
return AddInstruction.Create(type);
}
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[AddComponentMenu("RPG and MMO UI/Spell Slot")]
public class RnMUI_SpellSlot : RnMUI_IconSlot
{
public static RnMUI_SpellSlot current;
public RnMUI_SlotCooldown cooldownHandle;
private UISpellInfo spellInfo;
/// <summary>
/// Assign event listener.
/// </summary>
public List<EventDelegate> onAssign = new List<EventDelegate>();
/// <summary>
/// Unassign event listener.
/// </summary>
public List<EventDelegate> onUnassign = new List<EventDelegate>();
public override void OnStart()
{
// Try finding the cooldown handler
if (this.cooldownHandle == null) this.cooldownHandle = this.GetComponent<RnMUI_SlotCooldown>();
if (this.cooldownHandle == null) this.cooldownHandle = this.GetComponentInChildren<RnMUI_SlotCooldown>();
}
/// <summary>
/// Gets the spell info of the spell assigned to this slot.
/// </summary>
/// <returns>The spell info.</returns>
public UISpellInfo GetSpellInfo()
{
return spellInfo;
}
/// <summary>
/// Determines whether this slot is assigned.
/// </summary>
/// <returns><c>true</c> if this instance is assigned; otherwise, <c>false</c>.</returns>
public override bool IsAssigned()
{
return (this.spellInfo != null);
}
/// <summary>
/// Assign the slot by spell info.
/// </summary>
/// <param name="spellInfo">Spell info.</param>
public bool Assign(UISpellInfo spellInfo)
{
if (spellInfo == null)
return false;
// Use the base class assign
if (this.Assign(spellInfo.Icon))
{
// Set the spell info
this.spellInfo = spellInfo;
// Check if we have a cooldown handler
if (this.cooldownHandle != null)
this.cooldownHandle.OnAssignSpell(spellInfo);
// Execute the assign event listener
this.ExecuteOnAssign();
// Success
return true;
}
return false;
}
/// <summary>
/// Executes the on assign event listener.
/// </summary>
protected virtual void ExecuteOnAssign()
{
current = this;
EventDelegate.Execute(this.onAssign);
current = null;
}
/// <summary>
/// Assign the slot by the passed source slot.
/// </summary>
/// <param name="source">Source.</param>
public override bool Assign(Object source)
{
if (source is RnMUI_SpellSlot)
{
RnMUI_SpellSlot sourceSlot = source as RnMUI_SpellSlot;
if (sourceSlot != null)
return this.Assign(sourceSlot.GetSpellInfo());
}
// Default
return false;
}
/// <summary>
/// Unassign this slot.
/// </summary>
public override void Unassign()
{
// Remove the icon
base.Unassign();
// Clear the spell info
this.spellInfo = null;
// Check if we have a cooldown handler
if (this.cooldownHandle != null)
this.cooldownHandle.OnUnassign();
// Execute the unassign event listener
this.ExecuteOnUnassign();
}
/// <summary>
/// Executes the on unassign event listener.
/// </summary>
protected virtual void ExecuteOnUnassign()
{
current = this;
EventDelegate.Execute(this.onUnassign);
current = null;
}
/// <summary>
/// Determines whether this slot can swap with the specified target slot.
/// </summary>
/// <returns><c>true</c> if this instance can swap with the specified target; otherwise, <c>false</c>.</returns>
/// <param name="target">Target.</param>
public override bool CanSwapWith(Object target)
{
return (target is RnMUI_SpellSlot);
}
/// <summary>
/// Raises the click event.
/// </summary>
public override void OnClick()
{
if (!this.IsAssigned())
return;
// Check if the slot is on cooldown
if (this.cooldownHandle != null)
{
if (this.cooldownHandle.IsOnCooldown)
return;
this.cooldownHandle.StartCooldown(this.spellInfo.Cooldown);
}
}
/// <summary>
/// Raises the tooltip event.
/// </summary>
/// <param name="show">If set to <c>true</c> show.</param>
public override void OnTooltip(bool show)
{
if (show && this.IsAssigned())
{
// Set the title and description
RnMUI_Tooltip.SetTitle(this.spellInfo.Name);
RnMUI_Tooltip.SetDescription(this.spellInfo.Description);
if (this.spellInfo.Flags.Has(UISpellInfo_Flags.Passive))
{
RnMUI_Tooltip.AddAttribute("Passive", "");
}
else
{
// Power consumption
if (this.spellInfo.PowerCost > 0f)
{
if (this.spellInfo.Flags.Has(UISpellInfo_Flags.PowerCostInPct))
RnMUI_Tooltip.AddAttribute(this.spellInfo.PowerCost.ToString("0") + "%", " Energy");
else
RnMUI_Tooltip.AddAttribute(this.spellInfo.PowerCost.ToString("0"), " Energy");
}
// Range
if (this.spellInfo.Range > 0f)
{
if (this.spellInfo.Range == 1f)
RnMUI_Tooltip.AddAttribute("Melee range", "");
else
RnMUI_Tooltip.AddAttribute(this.spellInfo.Range.ToString("0"), " yd range");
}
// Cast time
if (this.spellInfo.CastTime == 0f)
RnMUI_Tooltip.AddAttribute("Instant", "");
else
RnMUI_Tooltip.AddAttribute(this.spellInfo.CastTime.ToString("0.0"), " sec cast");
// Cooldown
if (this.spellInfo.Cooldown > 0f)
RnMUI_Tooltip.AddAttribute(this.spellInfo.Cooldown.ToString("0.0"), " sec cooldown");
}
// Set the tooltip position
RnMUI_Tooltip.SetPosition(this.iconSprite as UIWidget);
// Show the tooltip
RnMUI_Tooltip.Show();
// Prevent hide
return;
}
// Default hide
RnMUI_Tooltip.Hide();
}
}
| |
using System;
using System.Collections.Generic;
using System.Xml.Linq;
using ALinq.Mapping;
using System.Globalization;
using System.IO;
using System.Text;
using ALinq.SqlClient;
namespace ALinq.MySQL
{
internal static class MySqlBuilder
{
// Methods
internal static void BuildFieldDeclarations(MetaTable table, StringBuilder sb)
{
int num = 0;
var memberNameToMappedName = new Dictionary<object, string>();
foreach (MetaType type in table.RowType.InheritanceTypes)
{
num += BuildFieldDeclarations(type, memberNameToMappedName, sb);
}
if (num == 0)
{
throw SqlClient.Error.CreateDatabaseFailedBecauseOfClassWithNoMembers(table.RowType.Type);
}
}
private static int BuildFieldDeclarations(MetaType type, IDictionary<object, string> memberNameToMappedName, StringBuilder sb)
{
int num = 0;
foreach (var member in type.DataMembers)
{
string str;
if ((!member.IsDeclaredBy(type) || member.IsAssociation) || !member.IsPersistent)
{
continue;
}
object key = InheritanceRules.DistinguishedMemberName(member.Member);
if (memberNameToMappedName.TryGetValue(key, out str))
{
if (!(str == member.MappedName))
{
goto Label_0075;
}
continue;
}
memberNameToMappedName.Add(key, member.MappedName);
Label_0075:
if (sb.Length > 0)
{
sb.Append(", ");
}
sb.AppendLine();
sb.Append(string.Format(CultureInfo.InvariantCulture, " {0} ",
new object[] { MySqlIdentifier.QuoteCompoundIdentifier(member.MappedName) }));
if (!string.IsNullOrEmpty(member.Expression))
{
sb.Append("AS " + member.Expression);
}
else
{
sb.Append(GetDbType(member));
}
num++;
}
return num;
}
private static string BuildKey(IEnumerable<MetaDataMember> members)
{
var builder = new StringBuilder();
foreach (MetaDataMember member in members)
{
if (builder.Length > 0)
{
builder.Append(", ");
}
builder.Append(MySqlIdentifier.QuoteIdentifier(member.MappedName));
}
return builder.ToString();
}
private static void BuildPrimaryKey(MetaTable table, StringBuilder sb)
{
foreach (MetaDataMember member in table.RowType.IdentityMembers)
{
if (sb.Length > 0)
{
sb.Append(", ");
}
sb.Append(MySqlIdentifier.QuoteIdentifier(member.MappedName));
}
}
public static string GetCreateDatabaseCommand(string catalog, string dataFilename, string logFilename)
{
var builder = new StringBuilder();
builder.AppendFormat("CREATE DATABASE {0};", MySqlIdentifier.QuoteIdentifier(catalog));
//if (dataFilename != null)
//{
// builder.AppendFormat(" ON PRIMARY (NAME='{0}', FILENAME='{1}')", Path.GetFileName(dataFilename), dataFilename);
// builder.AppendFormat(" LOG ON (NAME='{0}', FILENAME='{1}')", Path.GetFileName(logFilename), logFilename);
//}
builder.AppendLine();
builder.AppendFormat("Use {0};", catalog);
return builder.ToString();
}
public static IEnumerable<string> GetCreateForeignKeyCommands(MetaTable table)
{
foreach (var metaType in table.RowType.InheritanceTypes)
{
foreach (var command in GetCreateForeignKeyCommands(metaType))
{
yield return command;
}
}
}
private static IEnumerable<string> GetCreateForeignKeyCommands(MetaType metaType)
{
foreach (var member in metaType.DataMembers)
{
if (member.IsDeclaredBy(metaType) && member.IsAssociation)
{
MetaAssociation association = member.Association;
if (association.IsForeignKey)
{
var stringBuilder = new StringBuilder();
var thisKey = BuildKey(association.ThisKey);
var otherKey = BuildKey(association.OtherKey);
var otherTable = association.OtherType.Table.TableName;
var mappedName = member.MappedName;
if (mappedName == member.Name)
{
mappedName = string.Format(CultureInfo.InvariantCulture, "FK_{0}_{1}",
new object[] { MySqlIdentifier.QuoteIdentifier(metaType.Table.TableName), MySqlIdentifier.QuoteIdentifier(member.Name) });
}
var command = "ALTER TABLE {0}" + Environment.NewLine + " ADD CONSTRAINT {1} FOREIGN KEY ({2}) REFERENCES {3}({4})";
var otherMember = association.OtherMember;
if (otherMember != null)
{
string deleteRule = association.DeleteRule;
if (deleteRule != null)
{
command += Environment.NewLine + " ON DELETE " + deleteRule;
}
}
yield return stringBuilder.AppendFormat(command, new object[]
{
metaType.Table.TableName,
mappedName,
thisKey,
otherTable,
otherKey
}).ToString();
}
}
}
}
public static string GetCreateTableCommand(MetaTable table)
{
var builder = new StringBuilder();
var sb = new StringBuilder();
BuildFieldDeclarations(table, sb);
builder.AppendFormat("CREATE TABLE {0}", MySqlIdentifier.QuoteIdentifier(table.TableName));
builder.Append("(");
builder.Append(sb.ToString());
sb = new StringBuilder();
BuildPrimaryKey(table, sb);
if (sb.Length > 0)
{
string s = string.Format(CultureInfo.InvariantCulture, "PK_{0}",
new object[] { table.TableName });
builder.Append(", ");
builder.AppendLine();
builder.AppendFormat(" CONSTRAINT {0} PRIMARY KEY ({1})", s, sb);
}
builder.AppendLine();
builder.Append(" )");
return builder.ToString();
}
private static string GetDbType(MetaDataMember mm)
{
string dbType = mm.DbType;
if (dbType != null)
{
if (dbType.StartsWith("N", StringComparison.CurrentCultureIgnoreCase))
return dbType.Substring(1);
if (dbType.Equals("Image", StringComparison.CurrentCultureIgnoreCase))
return "BLOB";
return dbType;
}
var builder = new StringBuilder();
Type type = mm.Type;
bool canBeNull = mm.CanBeNull;
if (type.IsValueType && IsNullable(type))
{
type = type.GetGenericArguments()[0];
}
if (mm.IsVersion)
{
builder.Append("Timestamp");
}
else if (mm.IsPrimaryKey && mm.IsDbGenerated)
{
switch (Type.GetTypeCode(type))
{
case TypeCode.Object:
if (type != typeof(Guid))
{
throw SqlClient.Error.CouldNotDetermineDbGeneratedSqlType(type);
}
builder.Append("TINYBLOB");
goto Label_02AD;
case TypeCode.DBNull:
case TypeCode.Boolean:
case TypeCode.Char:
case TypeCode.Single:
case TypeCode.Double:
goto Label_02AD;
case TypeCode.SByte:
case TypeCode.Int16:
builder.Append("SmallInt");
goto Label_02AD;
case TypeCode.Byte:
builder.Append("TinyInt");
goto Label_02AD;
case TypeCode.UInt16:
case TypeCode.Int32:
builder.Append("Int");
goto Label_02AD;
case TypeCode.UInt32:
case TypeCode.Int64:
builder.Append("BigInt");
goto Label_02AD;
case TypeCode.UInt64:
case TypeCode.Decimal:
builder.Append("Real");
goto Label_02AD;
}
}
else
{
switch (Type.GetTypeCode(type))
{
case TypeCode.Object:
if (type == typeof(Guid))
{
builder.Append("TINYBLOB");
}
else if (type == typeof(byte[]))
{
builder.Append("LONGBLOB");
}
else if (type == typeof(char[]))
{
builder.Append("VarChar(4000)");
}
else if (type == typeof(XDocument) || type == typeof(XElement))
{
builder.Append("VarChar(4000)");
}
else if (type == typeof(ALinq.Binary))
{
builder.Append("LONGBLOB");
}
else
{
throw SqlClient.Error.CouldNotDetermineSqlType(type);
}
goto Label_02AD;
case TypeCode.DBNull:
goto Label_02AD;
case TypeCode.Boolean:
builder.Append("BIT");
goto Label_02AD;
case TypeCode.Char:
builder.Append("CHAR(1)");
goto Label_02AD;
case TypeCode.SByte:
case TypeCode.Int16:
builder.Append("SmallInt");
goto Label_02AD;
case TypeCode.Byte:
builder.Append("TinyInt");
goto Label_02AD;
case TypeCode.UInt16:
case TypeCode.Int32:
builder.Append("Int");
goto Label_02AD;
case TypeCode.UInt32:
case TypeCode.Int64:
builder.Append("BigInt");
goto Label_02AD;
case TypeCode.UInt64:
builder.Append("Decimal(20)");
goto Label_02AD;
case TypeCode.Single:
builder.Append("Real");
goto Label_02AD;
case TypeCode.Double:
builder.Append("Float");
goto Label_02AD;
case TypeCode.Decimal:
builder.Append("Real");
goto Label_02AD;
case TypeCode.DateTime:
builder.Append("DateTime");
goto Label_02AD;
case TypeCode.String:
builder.Append("TEXT");
goto Label_02AD;
}
}
Label_02AD:
if (!canBeNull)
{
builder.Append(" NOT NULL");
}
if (mm.IsPrimaryKey && mm.IsDbGenerated)
{
if (type == typeof(Guid))
{
builder.Append(" DEFAULT NEWID()");
}
else
{
builder.Append(" AUTO_INCREMENT");
}
}
return builder.ToString();
}
internal static string GetDropDatabaseCommand(string catalog)
{
var builder = new StringBuilder();
builder.AppendFormat("DROP DATABASE {0}", MySqlIdentifier.QuoteIdentifier(catalog));
return builder.ToString();
}
internal static bool IsNullable(Type type)
{
return (type.IsGenericType && typeof(Nullable<>).IsAssignableFrom(type.GetGenericTypeDefinition()));
}
// Nested Types
}
}
| |
// ***********************************************************************
// Copyright (c) 2008 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Linq;
using NUnit.Framework.Constraints;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.TestData;
using NUnit.TestUtilities;
#if ASYNC
using System.Threading.Tasks;
#endif
#if NET40
using Task = System.Threading.Tasks.TaskEx;
#endif
namespace NUnit.Framework.Assertions
{
[TestFixture]
public class WarningTests
{
[TestCase("WarnUnless_Passes_Boolean")]
[TestCase("WarnIf_Passes_Boolean")]
[TestCase("WarnUnless_Passes_BooleanWithMessage")]
[TestCase("WarnIf_Passes_BooleanWithMessage")]
[TestCase("WarnUnless_Passes_BooleanWithMessageAndArgs")]
[TestCase("WarnIf_Passes_BooleanWithMessageAndArgs")]
#if !NET20
[TestCase("WarnUnless_Passes_BooleanWithMessageStringFunc")]
[TestCase("WarnIf_Passes_BooleanWithMessageStringFunc")]
[TestCase("WarnUnless_Passes_BooleanLambda")]
[TestCase("WarnIf_Passes_BooleanLambda")]
[TestCase("WarnUnless_Passes_BooleanLambdaWithMessage")]
[TestCase("WarnIf_Passes_BooleanLambdaWithMessage")]
[TestCase("WarnUnless_Passes_BooleanLambdaWithMessageAndArgs")]
[TestCase("WarnIf_Passes_BooleanLambdaWithMessageAndArgs")]
[TestCase("WarnUnless_Passes_BooleanLambdaWithWithMessageStringFunc")]
[TestCase("WarnIf_Passes_BooleanLambdaWithWithMessageStringFunc")]
#endif
[TestCase("WarnUnless_Passes_ActualAndConstraint")]
[TestCase("WarnIf_Passes_ActualAndConstraint")]
[TestCase("WarnUnless_Passes_ActualAndConstraintWithMessage")]
[TestCase("WarnIf_Passes_ActualAndConstraintWithMessage")]
[TestCase("WarnUnless_Passes_ActualAndConstraintWithMessageAndArgs")]
[TestCase("WarnIf_Passes_ActualAndConstraintWithMessageAndArgs")]
#if !NET20
[TestCase("WarnUnless_Passes_ActualAndConstraintWithMessageStringFunc")]
[TestCase("WarnIf_Passes_ActualAndConstraintWithMessageStringFunc")]
[TestCase("WarnUnless_Passes_ActualLambdaAndConstraint")]
[TestCase("WarnIf_Passes_ActualLambdaAndConstraint")]
[TestCase("WarnUnless_Passes_ActualLambdaAndConstraintWithMessage")]
[TestCase("WarnIf_Passes_ActualLambdaAndConstraintWithMessage")]
[TestCase("WarnUnless_Passes_ActualLambdaAndConstraintWithMessageAndArgs")]
[TestCase("WarnIf_Passes_ActualLambdaAndConstraintWithMessageAndArgs")]
[TestCase("WarnUnless_Passes_ActualLambdaAndConstraintWithMessageStringFunc")]
[TestCase("WarnIf_Passes_ActualLambdaAndConstraintWithMessageStringFunc")]
#endif
[TestCase("WarnUnless_Passes_DelegateAndConstraint")]
[TestCase("WarnIf_Passes_DelegateAndConstraint")]
[TestCase("WarnUnless_Passes_DelegateAndConstraintWithMessage")]
[TestCase("WarnIf_Passes_DelegateAndConstraintWithMessage")]
[TestCase("WarnUnless_Passes_DelegateAndConstraintWithMessageAndArgs")]
[TestCase("WarnIf_Passes_DelegateAndConstraintWithMessageAndArgs")]
#if !NET20
[TestCase("WarnUnless_Passes_DelegateAndConstraintWithMessageStringFunc")]
[TestCase("WarnIf_Passes_DelegateAndConstraintWithMessageStringFunc")]
#endif
#if ASYNC
[TestCase("WarnUnless_Passes_Async")]
[TestCase("WarnIf_Passes_Async")]
#endif
public void WarningPasses(string methodName)
{
var result = TestBuilder.RunTestCase(typeof(WarningFixture), methodName);
Assert.That(result.ResultState, Is.EqualTo(ResultState.Success));
Assert.That(result.AssertCount, Is.EqualTo(1), "Incorrect AssertCount");
Assert.That(result.AssertionResults.Count, Is.EqualTo(0), "There should be no AssertionResults");
}
[TestCase("WarnUnless_Fails_Boolean", null)]
[TestCase("WarnIf_Fails_Boolean", null)]
[TestCase("WarnUnless_Fails_BooleanWithMessage", "message")]
[TestCase("WarnIf_Fails_BooleanWithMessage", "message")]
[TestCase("WarnUnless_Fails_BooleanWithMessageAndArgs", "got 5")]
[TestCase("WarnIf_Fails_BooleanWithMessageAndArgs", "got 5")]
#if !NET20
[TestCase("WarnUnless_Fails_BooleanWithMessageStringFunc", "got 5")]
[TestCase("WarnIf_Fails_BooleanWithMessageStringFunc", "got 5")]
[TestCase("WarnUnless_Fails_BooleanLambda", null)]
[TestCase("WarnIf_Fails_BooleanLambda", null)]
[TestCase("WarnUnless_Fails_BooleanLambdaWithMessage", "message")]
[TestCase("WarnIf_Fails_BooleanLambdaWithMessage", "message")]
[TestCase("WarnUnless_Fails_BooleanLambdaWithMessageAndArgs", "got 5")]
[TestCase("WarnIf_Fails_BooleanLambdaWithMessageAndArgs", "got 5")]
[TestCase("WarnUnless_Fails_BooleanLambdaWithMessageStringFunc", "got 5")]
[TestCase("WarnIf_Fails_BooleanLambdaWithMessageStringFunc", "got 5")]
#endif
[TestCase("WarnUnless_Fails_ActualAndConstraint", null)]
[TestCase("WarnIf_Fails_ActualAndConstraint", null)]
[TestCase("WarnUnless_Fails_ActualAndConstraintWithMessage", "Error")]
[TestCase("WarnIf_Fails_ActualAndConstraintWithMessage", "Error")]
[TestCase("WarnUnless_Fails_ActualAndConstraintWithMessageAndArgs", "Should be 5")]
[TestCase("WarnIf_Fails_ActualAndConstraintWithMessageAndArgs", "Should be 5")]
#if !NET20
[TestCase("WarnUnless_Fails_ActualAndConstraintWithMessageStringFunc", "Should be 5")]
[TestCase("WarnIf_Fails_ActualAndConstraintWithMessageStringFunc", "Should be 5")]
[TestCase("WarnUnless_Fails_ActualLambdaAndConstraint", null)]
[TestCase("WarnIf_Fails_ActualLambdaAndConstraint", null)]
[TestCase("WarnUnless_Fails_ActualLambdaAndConstraintWithMessage", "Error")]
[TestCase("WarnIf_Fails_ActualLambdaAndConstraintWithMessage", "Error")]
[TestCase("WarnUnless_Fails_ActualLambdaAndConstraintWithMessageAndArgs", "Should be 5")]
[TestCase("WarnIf_Fails_ActualLambdaAndConstraintWithMessageAndArgs", "Should be 5")]
[TestCase("WarnUnless_Fails_ActualLambdaAndConstraintWithMessageStringFunc", "Should be 5")]
[TestCase("WarnIf_Fails_ActualLambdaAndConstraintWithMessageStringFunc", "Should be 5")]
#endif
[TestCase("WarnUnless_Fails_DelegateAndConstraint", null)]
[TestCase("WarnIf_Fails_DelegateAndConstraint", null)]
[TestCase("WarnUnless_Fails_DelegateAndConstraintWithMessage", "Error")]
[TestCase("WarnIf_Fails_DelegateAndConstraintWithMessage", "Error")]
[TestCase("WarnUnless_Fails_DelegateAndConstraintWithMessageAndArgs", "Should be 4")]
[TestCase("WarnIf_Fails_DelegateAndConstraintWithMessageAndArgs", "Should be 4")]
#if !NET20
[TestCase("WarnUnless_Fails_DelegateAndConstraintWithMessageStringFunc", "Should be 4")]
[TestCase("WarnIf_Fails_DelegateAndConstraintWithMessageStringFunc", "Should be 4")]
#endif
#if ASYNC
[TestCase("WarnUnless_Fails_Async", null)]
[TestCase("WarnIf_Fails_Async", null)]
#endif
public void WarningFails(string methodName, string expectedMessage)
{
var result = TestBuilder.RunTestCase(typeof(WarningFixture), methodName);
Assert.That(result.ResultState, Is.EqualTo(ResultState.Warning));
Assert.That(result.AssertCount, Is.EqualTo(1), "Incorrect AssertCount");
Assert.That(result.AssertionResults.Count, Is.EqualTo(1), "Incorrect number of AssertionResults");
Assert.That(result.AssertionResults[0].Status, Is.EqualTo(AssertionStatus.Warning));
Assert.That(result.AssertionResults[0].Message, Is.Not.Null, "Assertion Message should not be null");
Assert.That(result.Message, Is.Not.Null, "Result Message should not be null");
Assert.That(result.Message, Contains.Substring(result.AssertionResults[0].Message), "Result message should contain assertion message");
Assert.That(result.AssertionResults[0].StackTrace, Does.Contain("WarningFixture"));
Assert.That(result.AssertionResults[0].StackTrace.Split(new char[] { '\n' }).Length, Is.LessThan(3));
if (expectedMessage != null)
{
Assert.That(result.Message, Does.Contain(expectedMessage));
Assert.That(result.AssertionResults[0].Message, Does.Contain(expectedMessage));
}
}
#if !NET20
[Test]
public void PassingAssertion_DoesNotCallExceptionStringFunc()
{
// Arrange
var funcWasCalled = false;
Func<string> getExceptionMessage = () =>
{
funcWasCalled = true;
return "Func was called";
};
// Act
using (new TestExecutionContext.IsolatedContext())
Warn.Unless(0 + 1 == 1, getExceptionMessage);
// Assert
Assert.That(!funcWasCalled, "The getExceptionMessage function was called when it should not have been.");
}
[Test]
public void FailingWarning_CallsExceptionStringFunc()
{
// Arrange
var funcWasCalled = false;
Func<string> getExceptionMessage = () =>
{
funcWasCalled = true;
return "Func was called";
};
// Act
using (new TestExecutionContext.IsolatedContext())
Warn.Unless(1 + 1 == 1, getExceptionMessage);
// Assert
Assert.That(funcWasCalled, "The getExceptionMessage function was not called when it should have been.");
}
#endif
#if ASYNC
[Test]
public void WarnUnless_Async_Error()
{
#if !NET40
var exception =
#endif
Assert.Throws<InvalidOperationException>(() =>
Warn.Unless(async () => await ThrowExceptionGenericTask(), Is.EqualTo(1)));
#if !NET40
Assert.That(exception.StackTrace, Does.Contain("ThrowExceptionGenericTask"));
#endif
}
[Test]
public void WarnIf_Async_Error()
{
#if !NET40
var exception =
#endif
Assert.Throws<InvalidOperationException>(() =>
Warn.If(async () => await ThrowExceptionGenericTask(), Is.Not.EqualTo(1)));
#if !NET40
Assert.That(exception.StackTrace, Does.Contain("ThrowExceptionGenericTask"));
#endif
}
private static Task<int> One()
{
return Task.Run(() => 1);
}
private static async Task<int> ThrowExceptionGenericTask()
{
await One();
throw new InvalidOperationException();
}
#endif
// We decided to trim ExecutionContext and below because ten lines per warning adds up
// and makes it hard to read build logs.
// See https://github.com/nunit/nunit/pull/2431#issuecomment-328404432.
[TestCase(nameof(WarningFixture.WarningSynchronous), 1)]
[TestCase(nameof(WarningFixture.WarningInThreadStart), 2)]
#if !PLATFORM_DETECTION
[TestCase(nameof(WarningFixture.WarningInBeginInvoke), 4)]
#else
[TestCase(nameof(WarningFixture.WarningInBeginInvoke), 4, ExcludePlatform = "mono", Reason = "Warning has no effect inside BeginInvoke on Mono")]
#endif
[TestCase(nameof(WarningFixture.WarningInThreadPoolQueueUserWorkItem), 2)]
#if ASYNC
[TestCase(nameof(WarningFixture.WarningInTaskRun), 4)]
[TestCase(nameof(WarningFixture.WarningAfterAwaitTaskDelay), 5)]
#endif
public static void StackTracesAreFiltered(string methodName, int maxLineCount)
{
var result = TestBuilder.RunTestCase(typeof(WarningFixture), methodName);
if (result.FailCount != 0 && result.Message.StartsWith(typeof(PlatformNotSupportedException).FullName))
{
return; // BeginInvoke causes PlatformNotSupportedException on .NET Core
}
if (result.AssertionResults.Count != 1 || result.AssertionResults[0].Status != AssertionStatus.Warning)
{
Assert.Fail("Expected a single warning assertion. Message: " + result.Message);
}
var warningStackTrace = result.AssertionResults[0].StackTrace;
var lines = warningStackTrace.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
if (maxLineCount < lines.Length)
{
Assert.Fail(
$"Expected the number of lines to be no more than {maxLineCount}, but it was {lines.Length}:" + Environment.NewLine
+ Environment.NewLine
+ string.Concat(lines.Select((line, i) => $" {i + 1}. {line.Trim()}" + Environment.NewLine))
+ "(end)");
// ^ Most of that is to differentiate it from the current method's stack trace
// reported directly underneath at the same level of indentation.
}
}
}
}
| |
/*
Copyright (c) 2004-2009 Krzysztof Ostrowski. All rights reserved.
Redistribution and use in source and binary forms,
with or without modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
THIS SOFTWARE IS PROVIDED "AS IS" BY THE ABOVE COPYRIGHT HOLDER(S)
AND ALL OTHER CONTRIBUTORS 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 ABOVE COPYRIGHT HOLDER(S) OR ANY OTHER
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
namespace QS.Fx.Base
{
[QS.Fx.Reflection.ValueClass(QS.Fx.Reflection.ValueClasses.UINT64)]
[QS.Fx.Printing.Printable(QS.Fx.Printing.PrintingStyle.Native)]
[QS.Fx.Serialization.ClassID(QS.ClassID.Fx_Base_Unsigned_64)]
[XmlType(TypeName = "UINT64")]
public sealed class UINT64 : QS.Fx.Serialization.ISerializable, IComparable<UINT64>, IComparable, IEquatable<UINT64>, QS.Fx.Serialization.IStringSerializable
{
#region Constructor
public UINT64(ulong number)
{
this.number = number;
}
public UINT64(string number)
{
this.String = number;
}
public UINT64()
{
}
#endregion
#region Fields
private ulong number;
#endregion
#region Accessors
[XmlIgnore]
public ulong Number
{
get { return this.number; }
set { this.number = value; }
}
[XmlAttribute("value")]
public string String
{
get { return this.number.ToString(); }
set { this.number = Convert.ToUInt64(value); }
}
#endregion
#region Casting
public static explicit operator ulong(UINT64 u)
{
return u.number;
}
public static explicit operator UINT64(ulong number)
{
return new UINT64(number);
}
public static explicit operator UINT64(string number)
{
return new UINT64(number);
}
public static explicit operator string(UINT64 number)
{
return number.String;
}
#endregion
#region Overridden from System.Object
public override string ToString()
{
return this.number.ToString("x");
}
public override bool Equals(object obj)
{
return (obj is UINT64) && (((UINT64) obj).number == this.number);
}
public override int GetHashCode()
{
return this.number.GetHashCode();
}
#endregion
#region IComparable<Incarnation> Members
public int CompareTo(UINT64 other)
{
return this.number.CompareTo(other.number);
}
#endregion
#region ISerializable Members
public unsafe QS.Fx.Serialization.SerializableInfo SerializableInfo
{
get { return new QS.Fx.Serialization.SerializableInfo((ushort)QS.ClassID.Fx_Base_Unsigned_64, sizeof(ulong), sizeof(ulong), 0); }
}
public unsafe void SerializeTo(ref QS.Fx.Base.ConsumableBlock header, ref IList<QS.Fx.Base.Block> data)
{
fixed (byte* bufferptr = header.Array)
{
*((ulong*)(bufferptr + header.Offset)) = this.number;
}
header.consume(sizeof(ulong));
}
public unsafe void DeserializeFrom(ref QS.Fx.Base.ConsumableBlock header, ref QS.Fx.Base.ConsumableBlock data)
{
fixed (byte* bufferptr = header.Array)
{
this.number = *((ulong*)(bufferptr + header.Offset));
}
header.consume(sizeof(ulong));
}
#endregion
#region IComparable Members
int IComparable.CompareTo(object other)
{
if (other is UINT64)
return this.number.CompareTo(((UINT64) other).number);
else
throw new Exception("Cannot compare with an object that is not an Unsigned_64.");
}
#endregion
#region IEquatable<Incarnation> Members
bool IEquatable<UINT64>.Equals(UINT64 other)
{
return other.number == this.number;
}
#endregion
#region IStringSerializable Members
ushort QS.Fx.Serialization.IStringSerializable.ClassID
{
get { return (ushort) QS.ClassID.Fx_Base_Unsigned_64; }
}
string QS.Fx.Serialization.IStringSerializable.AsString
{
get { return this.String; }
set { this.String = value; }
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Drawing;
using System.Linq;
using System.Text;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using MyCompany.Visitors.Client.iOS.ViewController;
using MyCompany.Visitors.Client.iOS.Views;
using MyCompany.Visitors.Client.Model;
namespace MyCompany.Visitors.Client
{
class VisitorPickerViewController: UICollectionViewController
{
public Action<Visitor> Selected { get; set; }
public Action CreateNew { get; set; }
readonly Source source;
int columns = 1;
public VisitorPickerViewController()
: base(new UICollectionViewFlowLayout())
{
this.NavigationItem.RightBarButtonItem = new UIBarButtonItem(UIBarButtonSystemItem.Add,(sender,args)=>
{
//if (CreateNew != null) CreateNew();
var visitVc = new EditVisitorViewController()
{
Visitor = new VMVisitor()
{
Visitor = new Visitor(),
},
Selected = (visit) =>
{
if (Selected != null)
Selected(visit);
}
};
this.NavigationController.PushViewController(visitVc,true);
});
CollectionView.RegisterClassForCell(typeof(Source.VisitCell), Source.VisitCell.Identifier);
CollectionView.Source = source = new Source();
CollectionView.BackgroundColor = View.BackgroundColor = UIColor.FromRGB(239, 239, 244);
CollectionView.ContentInset = new UIEdgeInsets(10,20,0,20);
Title = "Who is visiting?";
}
public ObservableCollection<VMVisitor> Visits
{
get { return source.Visits; }
set
{
try
{
if (source.Visits != null)
source.Visits.CollectionChanged -= VisitsOnCollectionChanged;
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
source.Visits = value;
source.Visits.CollectionChanged += VisitsOnCollectionChanged;
CollectionView.ReloadData();
}
}
public int Columns
{
get { return columns; }
set
{
if (columns == value)
return;
columns = value;
SetLayout();
}
}
void VisitsOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs args)
{
if (args.Action == NotifyCollectionChangedAction.Add || args.Action == NotifyCollectionChangedAction.Remove)
BeginInvokeOnMainThread(() =>
{
if (args.NewItems != null)
{
var indexPaths = new List<NSIndexPath>();
for (int i = 0; i < args.NewItems.Count; i++)
indexPaths.Add(NSIndexPath.FromRowSection(args.NewStartingIndex + i, 0));
CollectionView.InsertItems(indexPaths.ToArray());
}
if (args.OldItems != null)
{
var indexPaths = new List<NSIndexPath>();
for (int i = 0; i < args.OldItems.Count; i++)
indexPaths.Add(NSIndexPath.FromRowSection(args.OldStartingIndex + i, 0));
CollectionView.DeleteItems(indexPaths.ToArray());
}
});
}
public override void ViewWillAppear(bool animated)
{
source.Parent = this;
base.ViewWillAppear(animated);
//CollectionView.ContentInset = new UIEdgeInsets(0,10, 0, 10);
SetLayout();
}
public override void ViewWillDisappear(bool animated)
{
base.ViewWillDisappear(animated);
source.Parent = null;
}
public override void DidRotate(UIInterfaceOrientation fromInterfaceOrientation)
{
base.DidRotate(fromInterfaceOrientation);
SetLayout();
}
void SetLayout()
{
var width = View.Bounds.Width/3 - 45;
CollectionView.SetCollectionViewLayout(new UICollectionViewFlowLayout
{
ItemSize = new SizeF(width, width * 1.2f),
//MinimumInteritemSpacing = 20,
ScrollDirection = UICollectionViewScrollDirection.Vertical
}, true);
}
class Source : UICollectionViewSource
{
public VisitorPickerViewController Parent;
public override void ItemSelected(UICollectionView collectionView, NSIndexPath indexPath)
{
Parent.Selected(Visits[indexPath.Row].Visitor);
}
public ObservableCollection<VMVisitor> Visits { get; set; }
public override int GetItemsCount(UICollectionView collectionView, int section)
{
return Visits == null ? 0 : Visits.Count;
}
public override int NumberOfSections(UICollectionView collectionView)
{
return 1;
}
public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath)
{
var cell = collectionView.DequeueReusableCell(VisitCell.Identifier, indexPath) as VisitCell;
cell.Visit = Visits[indexPath.Row];
return cell;
}
public class VisitCell : UICollectionViewCell
{
public static readonly NSString Identifier = (NSString) "VisitCell";
readonly SmallVisitorView visitorView;
[Export("initWithFrame:")]
public VisitCell(RectangleF frame)
: base(frame)
{
//this.BackgroundColor = UIColor.Red;
visitorView = new SmallVisitorView();
visitorView.AddParallax(-20, 20);
ContentView.AddSubview(visitorView);
}
public VMVisitor Visit
{
get { return visitorView.Visitor; }
set { visitorView.Visitor = value; }
}
public override void LayoutSubviews()
{
base.LayoutSubviews();
visitorView.Frame = ContentView.Bounds;
}
}
}
}
}
| |
#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
using System.Text;
using System.IO;
using System.Collections;
using Ctrip.Log4.Util;
using Ctrip.Log4.Repository;
namespace Ctrip.Log4.Util
{
/// <summary>
/// Abstract class that provides the formatting functionality that
/// derived classes need.
/// </summary>
/// <remarks>
/// <para>
/// Conversion specifiers in a conversion patterns are parsed to
/// individual PatternConverters. Each of which is responsible for
/// converting a logging event in a converter specific manner.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public abstract class PatternConverter
{
#region Protected Instance Constructors
/// <summary>
/// Protected constructor
/// </summary>
/// <remarks>
/// <para>
/// Initializes a new instance of the <see cref="PatternConverter" /> class.
/// </para>
/// </remarks>
protected PatternConverter()
{
}
#endregion Protected Instance Constructors
#region Public Instance Properties
/// <summary>
/// Get the next pattern converter in the chain
/// </summary>
/// <value>
/// the next pattern converter in the chain
/// </value>
/// <remarks>
/// <para>
/// Get the next pattern converter in the chain
/// </para>
/// </remarks>
public virtual PatternConverter Next
{
get { return m_next; }
}
/// <summary>
/// Gets or sets the formatting info for this converter
/// </summary>
/// <value>
/// The formatting info for this converter
/// </value>
/// <remarks>
/// <para>
/// Gets or sets the formatting info for this converter
/// </para>
/// </remarks>
public virtual FormattingInfo FormattingInfo
{
get { return new FormattingInfo(m_min, m_max, m_leftAlign); }
set
{
m_min = value.Min;
m_max = value.Max;
m_leftAlign = value.LeftAlign;
}
}
/// <summary>
/// Gets or sets the option value for this converter
/// </summary>
/// <summary>
/// The option for this converter
/// </summary>
/// <remarks>
/// <para>
/// Gets or sets the option value for this converter
/// </para>
/// </remarks>
public virtual string Option
{
get { return m_option; }
set { m_option = value; }
}
#endregion Public Instance Properties
#region Protected Abstract Methods
/// <summary>
/// Evaluate this pattern converter and write the output to a writer.
/// </summary>
/// <param name="writer"><see cref="TextWriter" /> that will receive the formatted result.</param>
/// <param name="state">The state object on which the pattern converter should be executed.</param>
/// <remarks>
/// <para>
/// Derived pattern converters must override this method in order to
/// convert conversion specifiers in the appropriate way.
/// </para>
/// </remarks>
abstract protected void Convert(TextWriter writer, object state);
#endregion Protected Abstract Methods
#region Public Instance Methods
/// <summary>
/// Set the next pattern converter in the chains
/// </summary>
/// <param name="patternConverter">the pattern converter that should follow this converter in the chain</param>
/// <returns>the next converter</returns>
/// <remarks>
/// <para>
/// The PatternConverter can merge with its neighbor during this method (or a sub class).
/// Therefore the return value may or may not be the value of the argument passed in.
/// </para>
/// </remarks>
public virtual PatternConverter SetNext(PatternConverter patternConverter)
{
m_next = patternConverter;
return m_next;
}
/// <summary>
/// Write the pattern converter to the writer with appropriate formatting
/// </summary>
/// <param name="writer"><see cref="TextWriter" /> that will receive the formatted result.</param>
/// <param name="state">The state object on which the pattern converter should be executed.</param>
/// <remarks>
/// <para>
/// This method calls <see cref="Convert"/> to allow the subclass to perform
/// appropriate conversion of the pattern converter. If formatting options have
/// been specified via the <see cref="FormattingInfo"/> then this method will
/// apply those formattings before writing the output.
/// </para>
/// </remarks>
virtual public void Format(TextWriter writer, object state)
{
if (m_min < 0 && m_max == int.MaxValue)
{
// Formatting options are not in use
Convert(writer, state);
}
else
{
string msg = null;
int len;
lock (m_formatWriter)
{
m_formatWriter.Reset(c_renderBufferMaxCapacity, c_renderBufferSize);
Convert(m_formatWriter, state);
StringBuilder buf = m_formatWriter.GetStringBuilder();
len = buf.Length;
if (len > m_max)
{
msg = buf.ToString(len - m_max, m_max);
len = m_max;
}
else
{
msg = buf.ToString();
}
}
if (len < m_min)
{
if (m_leftAlign)
{
writer.Write(msg);
SpacePad(writer, m_min - len);
}
else
{
SpacePad(writer, m_min - len);
writer.Write(msg);
}
}
else
{
writer.Write(msg);
}
}
}
private static readonly string[] SPACES = { " ", " ", " ", " ", // 1,2,4,8 spaces
" ", // 16 spaces
" " }; // 32 spaces
/// <summary>
/// Fast space padding method.
/// </summary>
/// <param name="writer"><see cref="TextWriter" /> to which the spaces will be appended.</param>
/// <param name="length">The number of spaces to be padded.</param>
/// <remarks>
/// <para>
/// Fast space padding method.
/// </para>
/// </remarks>
protected static void SpacePad(TextWriter writer, int length)
{
while(length >= 32)
{
writer.Write(SPACES[5]);
length -= 32;
}
for(int i = 4; i >= 0; i--)
{
if ((length & (1<<i)) != 0)
{
writer.Write(SPACES[i]);
}
}
}
#endregion Public Instance Methods
#region Private Instance Fields
private PatternConverter m_next;
private int m_min = -1;
private int m_max = int.MaxValue;
private bool m_leftAlign = false;
/// <summary>
/// The option string to the converter
/// </summary>
private string m_option = null;
private ReusableStringWriter m_formatWriter = new ReusableStringWriter(System.Globalization.CultureInfo.InvariantCulture);
#endregion Private Instance Fields
#region Constants
/// <summary>
/// Initial buffer size
/// </summary>
private const int c_renderBufferSize = 256;
/// <summary>
/// Maximum buffer size before it is recycled
/// </summary>
private const int c_renderBufferMaxCapacity = 1024;
#endregion
#region Static Methods
/// <summary>
/// Write an dictionary to a <see cref="TextWriter"/>
/// </summary>
/// <param name="writer">the writer to write to</param>
/// <param name="repository">a <see cref="ILoggerRepository"/> to use for object conversion</param>
/// <param name="value">the value to write to the writer</param>
/// <remarks>
/// <para>
/// Writes the <see cref="IDictionary"/> to a writer in the form:
/// </para>
/// <code>
/// {key1=value1, key2=value2, key3=value3}
/// </code>
/// <para>
/// If the <see cref="ILoggerRepository"/> specified
/// is not null then it is used to render the key and value to text, otherwise
/// the object's ToString method is called.
/// </para>
/// </remarks>
protected static void WriteDictionary(TextWriter writer, ILoggerRepository repository, IDictionary value)
{
WriteDictionary(writer, repository, value.GetEnumerator());
}
/// <summary>
/// Write an dictionary to a <see cref="TextWriter"/>
/// </summary>
/// <param name="writer">the writer to write to</param>
/// <param name="repository">a <see cref="ILoggerRepository"/> to use for object conversion</param>
/// <param name="value">the value to write to the writer</param>
/// <remarks>
/// <para>
/// Writes the <see cref="IDictionaryEnumerator"/> to a writer in the form:
/// </para>
/// <code>
/// {key1=value1, key2=value2, key3=value3}
/// </code>
/// <para>
/// If the <see cref="ILoggerRepository"/> specified
/// is not null then it is used to render the key and value to text, otherwise
/// the object's ToString method is called.
/// </para>
/// </remarks>
protected static void WriteDictionary(TextWriter writer, ILoggerRepository repository, IDictionaryEnumerator value)
{
writer.Write("{");
bool first = true;
// Write out all the dictionary key value pairs
while (value.MoveNext())
{
if (first)
{
first = false;
}
else
{
writer.Write(", ");
}
WriteObject(writer, repository, value.Key);
writer.Write("=");
WriteObject(writer, repository, value.Value);
}
writer.Write("}");
}
/// <summary>
/// Write an object to a <see cref="TextWriter"/>
/// </summary>
/// <param name="writer">the writer to write to</param>
/// <param name="repository">a <see cref="ILoggerRepository"/> to use for object conversion</param>
/// <param name="value">the value to write to the writer</param>
/// <remarks>
/// <para>
/// Writes the Object to a writer. If the <see cref="ILoggerRepository"/> specified
/// is not null then it is used to render the object to text, otherwise
/// the object's ToString method is called.
/// </para>
/// </remarks>
protected static void WriteObject(TextWriter writer, ILoggerRepository repository, object value)
{
if (repository != null)
{
repository.RendererMap.FindAndRender(value, writer);
}
else
{
// Don't have a repository to render with so just have to rely on ToString
if (value == null)
{
writer.Write( SystemInfo.NullText );
}
else
{
writer.Write( value.ToString() );
}
}
}
#endregion
private PropertiesDictionary properties;
/// <summary>
///
/// </summary>
public PropertiesDictionary Properties
{
get { return properties; }
set { properties = value; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Compression.Tests
{
public class GZipStreamTests
{
static string gzTestFile(string fileName) { return Path.Combine("GZTestData", fileName); }
[Fact]
public void BaseStream1()
{
var writeStream = new MemoryStream();
var zip = new GZipStream(writeStream, CompressionMode.Compress);
Assert.Same(zip.BaseStream, writeStream);
writeStream.Dispose();
}
[Fact]
public void BaseStream2()
{
var ms = new MemoryStream();
var zip = new GZipStream(ms, CompressionMode.Decompress);
Assert.Same(zip.BaseStream, ms);
ms.Dispose();
}
[Fact]
public async Task ModifyBaseStream()
{
var ms = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.txt.gz"));
var zip = new GZipStream(ms, CompressionMode.Decompress);
int size = 1024;
byte[] bytes = new byte[size];
zip.BaseStream.Read(bytes, 0, size); // This will throw if the underlying stream is not writable as expected
}
[Fact]
public void DecompressCanRead()
{
var ms = new MemoryStream();
var zip = new GZipStream(ms, CompressionMode.Decompress);
Assert.True(zip.CanRead, "GZipStream not CanRead in Decompress");
zip.Dispose();
Assert.False(zip.CanRead, "GZipStream CanRead after dispose in Decompress");
}
[Fact]
public void CompressCanWrite()
{
var ms = new MemoryStream();
var zip = new GZipStream(ms, CompressionMode.Compress);
Assert.True(zip.CanWrite, "GZipStream not CanWrite with CompressionMode.Compress");
zip.Dispose();
Assert.False(zip.CanWrite, "GZipStream CanWrite after dispose");
}
[Fact]
public void CanDisposeBaseStream()
{
var ms = new MemoryStream();
var zip = new GZipStream(ms, CompressionMode.Compress);
ms.Dispose(); // This would throw if this was invalid
}
[Fact]
public void CanDisposeGZipStream()
{
var ms = new MemoryStream();
var zip = new GZipStream(ms, CompressionMode.Compress);
zip.Dispose();
Assert.Null(zip.BaseStream);
zip.Dispose(); // Should be a no-op
}
[Fact]
public async Task CanReadBaseStreamAfterDispose()
{
var ms = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.txt.gz"));
var zip = new GZipStream(ms, CompressionMode.Decompress, leaveOpen: true);
var baseStream = zip.BaseStream;
zip.Dispose();
int size = 1024;
byte[] bytes = new byte[size];
baseStream.Read(bytes, 0, size); // This will throw if the underlying stream is not writable as expected
}
[Fact]
public async Task DecompressWorks()
{
var compareStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.txt"));
var gzStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.txt.gz"));
await DecompressAsync(compareStream, gzStream);
}
[Fact]
public async Task DecompressWorksWithDoc()
{
var compareStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.doc"));
var gzStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.doc.gz"));
await DecompressAsync(compareStream, gzStream);
}
[Fact]
public async Task DecompressWorksWithDocx()
{
var compareStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.docx"));
var gzStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.docx.gz"));
await DecompressAsync(compareStream, gzStream);
}
[Fact]
public async Task DecompressWorksWithPdf()
{
var compareStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.pdf"));
var gzStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.pdf.gz"));
await DecompressAsync(compareStream, gzStream);
}
// Making this async since regular read/write are tested below
private static async Task DecompressAsync(MemoryStream compareStream, MemoryStream gzStream)
{
var ms = new MemoryStream();
var zip = new GZipStream(gzStream, CompressionMode.Decompress);
var GZipStream = new MemoryStream();
await zip.CopyToAsync(GZipStream);
GZipStream.Position = 0;
compareStream.Position = 0;
byte[] compareArray = compareStream.ToArray();
byte[] writtenArray = GZipStream.ToArray();
Assert.Equal(compareArray.Length, writtenArray.Length);
for (int i = 0; i < compareArray.Length; i++)
{
Assert.Equal(compareArray[i], writtenArray[i]);
}
}
[Fact]
public void NullBaseStreamThrows()
{
Assert.Throws<ArgumentNullException>(() =>
{
var deflate = new GZipStream(null, CompressionMode.Decompress);
});
Assert.Throws<ArgumentNullException>(() =>
{
var deflate = new GZipStream(null, CompressionMode.Compress);
});
}
[Fact]
public void DisposedBaseStreamThrows()
{
var ms = new MemoryStream();
ms.Dispose();
AssertExtensions.Throws<ArgumentException>("stream", () =>
{
var deflate = new GZipStream(ms, CompressionMode.Decompress);
});
AssertExtensions.Throws<ArgumentException>("stream", () =>
{
var deflate = new GZipStream(ms, CompressionMode.Compress);
});
}
[Fact]
public void ReadOnlyStreamThrowsOnCompress()
{
var ms = new LocalMemoryStream();
ms.SetCanWrite(false);
AssertExtensions.Throws<ArgumentException>("stream", () =>
{
var gzip = new GZipStream(ms, CompressionMode.Compress);
});
}
[Fact]
public void WriteOnlyStreamThrowsOnDecompress()
{
var ms = new LocalMemoryStream();
ms.SetCanRead(false);
AssertExtensions.Throws<ArgumentException>("stream", () =>
{
var gzip = new GZipStream(ms, CompressionMode.Decompress);
});
}
[Fact]
public void CopyToAsyncArgumentValidation()
{
using (GZipStream gs = new GZipStream(new MemoryStream(), CompressionMode.Decompress))
{
AssertExtensions.Throws<ArgumentNullException>("destination", () => { gs.CopyToAsync(null); });
AssertExtensions.Throws<ArgumentOutOfRangeException>("bufferSize", () => { gs.CopyToAsync(new MemoryStream(), 0); });
Assert.Throws<NotSupportedException>(() => { gs.CopyToAsync(new MemoryStream(new byte[1], writable: false)); });
gs.Dispose();
Assert.Throws<ObjectDisposedException>(() => { gs.CopyToAsync(new MemoryStream()); });
}
using (GZipStream gs = new GZipStream(new MemoryStream(), CompressionMode.Compress))
{
Assert.Throws<NotSupportedException>(() => { gs.CopyToAsync(new MemoryStream()); });
}
}
[Fact]
public void TestCtors()
{
CompressionLevel[] legalValues = new CompressionLevel[] { CompressionLevel.Optimal, CompressionLevel.Fastest, CompressionLevel.NoCompression };
foreach (CompressionLevel level in legalValues)
{
bool[] boolValues = new bool[] { true, false };
foreach (bool remainsOpen in boolValues)
{
TestCtor(level, remainsOpen);
}
}
}
[Fact]
public void TestLevelOptimial()
{
TestCtor(CompressionLevel.Optimal);
}
[Fact]
public void TestLevelNoCompression()
{
TestCtor(CompressionLevel.NoCompression);
}
[Fact]
public void TestLevelFastest()
{
TestCtor(CompressionLevel.Fastest);
}
private static void TestCtor(CompressionLevel level, bool? leaveOpen = null)
{
//Create the GZipStream
int _bufferSize = 1024;
var bytes = new byte[_bufferSize];
var baseStream = new MemoryStream(bytes, writable: true);
GZipStream ds;
if (leaveOpen == null)
{
ds = new GZipStream(baseStream, level);
}
else
{
ds = new GZipStream(baseStream, level, leaveOpen ?? false);
}
//Write some data and Close the stream
string strData = "Test Data";
var encoding = Encoding.UTF8;
byte[] data = encoding.GetBytes(strData);
ds.Write(data, 0, data.Length);
ds.Flush();
ds.Dispose();
if (leaveOpen != true)
{
//Check that Close has really closed the underlying stream
Assert.Throws<ObjectDisposedException>(() => { baseStream.Write(bytes, 0, bytes.Length); });
}
//Read the data
byte[] data2 = new byte[_bufferSize];
baseStream = new MemoryStream(bytes, writable: false);
ds = new GZipStream(baseStream, CompressionMode.Decompress);
int size = ds.Read(data2, 0, _bufferSize - 5);
//Verify the data roundtripped
for (int i = 0; i < size + 5; i++)
{
if (i < data.Length)
{
Assert.Equal(data[i], data2[i]);
}
else
{
Assert.Equal(data2[i], (byte)0);
}
}
}
[Fact]
public async Task Flush()
{
var ms = new MemoryStream();
var ds = new GZipStream(ms, CompressionMode.Compress);
ds.Flush();
await ds.FlushAsync();
// Just ensuring Flush doesn't throw
}
[Fact]
public void FlushFailsAfterDispose()
{
var ms = new MemoryStream();
var ds = new GZipStream(ms, CompressionMode.Compress);
ds.Dispose();
Assert.Throws<ObjectDisposedException>(() => { ds.Flush(); });
}
[Fact]
public async Task FlushAsyncFailsAfterDispose()
{
var ms = new MemoryStream();
var ds = new GZipStream(ms, CompressionMode.Compress);
ds.Dispose();
await Assert.ThrowsAsync<ObjectDisposedException>(async () =>
{
await ds.FlushAsync();
});
}
[Fact]
public void TestSeekMethodsDecompress()
{
var ms = new MemoryStream();
var zip = new GZipStream(ms, CompressionMode.Decompress);
Assert.False(zip.CanSeek);
Assert.Throws<NotSupportedException>(delegate { long value = zip.Length; });
Assert.Throws<NotSupportedException>(delegate { long value = zip.Position; });
Assert.Throws<NotSupportedException>(delegate { zip.Position = 100L; });
Assert.Throws<NotSupportedException>(delegate { zip.SetLength(100L); });
Assert.Throws<NotSupportedException>(delegate { zip.Seek(100L, SeekOrigin.Begin); });
zip.Dispose();
Assert.False(zip.CanSeek);
}
[Fact]
public void TestSeekMethodsCompress()
{
var ms = new MemoryStream();
var zip = new GZipStream(ms, CompressionMode.Compress);
Assert.False(zip.CanSeek);
Assert.Throws<NotSupportedException>(delegate { long value = zip.Length; });
Assert.Throws<NotSupportedException>(delegate { long value = zip.Position; });
Assert.Throws<NotSupportedException>(delegate { zip.Position = 100L; });
Assert.Throws<NotSupportedException>(delegate { zip.SetLength(100L); });
Assert.Throws<NotSupportedException>(delegate { zip.Seek(100L, SeekOrigin.Begin); });
zip.Dispose();
Assert.False(zip.CanSeek);
}
}
}
| |
// 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.Text;
using System.IO;
using System.Threading;
using System.Diagnostics;
using Xunit;
namespace System.Data.SqlClient.ManualTesting.Tests
{
public class RandomStressTest
{
private static readonly TimeSpan TimeLimitDefault = new TimeSpan(0, 0, 10);
private const int ThreadCountDefault = 4;
private const int IterationsPerTableDefault = 50;
private const int MaxColumns = 5000;
private const int MaxRows = 100;
private const int MaxTotal = MaxColumns * 10;
private string[] _connectionStrings;
private string _operationCanceledErrorMessage;
private string _severeErrorMessage;
private SqlRandomTypeInfoCollection _katmaiTypes;
private ManualResetEvent _endEvent;
private int _runningThreads;
private long _totalValues;
private long _totalTables;
private long _totalIterations;
private long _totalTicks;
private RandomizerPool _randPool;
[Fact]
public void TestMain()
{
_operationCanceledErrorMessage = SystemDataResourceManager.Instance.SQL_OperationCancelled;
_severeErrorMessage = SystemDataResourceManager.Instance.SQL_SevereError;
// pure random
_randPool = new RandomizerPool();
SqlConnectionStringBuilder regularConnectionString = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr);
regularConnectionString.MultipleActiveResultSets = false;
List<string> connStrings = new List<string>();
connStrings.Add(regularConnectionString.ToString());
connStrings.Add(regularConnectionString.ToString());
regularConnectionString.MultipleActiveResultSets = true;
connStrings.Add(regularConnectionString.ToString());
_connectionStrings = connStrings.ToArray();
_katmaiTypes = SqlRandomTypeInfoCollection.CreateSql2008Collection();
_endEvent = new ManualResetEvent(false);
if (_randPool.ReproMode)
{
_runningThreads = 1;
TestThread();
}
else
{
for (int tcount = 0; tcount < ThreadCountDefault; tcount++)
{
Thread t = new Thread(TestThread);
t.Start();
}
}
}
private void NextConnection(ref SqlConnection con, Randomizer rand)
{
if (con != null)
{
con.Close();
}
string connString = _connectionStrings[rand.Next(_connectionStrings.Length)];
con = new SqlConnection(connString);
con.Open();
}
private void TestThread()
{
try
{
using (var rootScope = _randPool.RootScope<SqlRandomizer>())
{
Stopwatch watch = new Stopwatch();
SqlConnection con = null;
try
{
NextConnection(ref con, rootScope.Current);
if (_randPool.ReproMode)
{
using (var testScope = rootScope.NewScope<SqlRandomizer>())
{
// run only once if repro file is provided
RunTest(con, testScope, _katmaiTypes, watch);
}
}
else
{
while (watch.Elapsed < TimeLimitDefault)
{
using (var testScope = rootScope.NewScope<SqlRandomizer>())
{
RunTest(con, testScope, _katmaiTypes, watch);
}
if (rootScope.Current.Next(100) == 0)
{
// replace the connection
NextConnection(ref con, rootScope.Current);
}
}
}
}
finally
{
if (con != null)
{
con.Close();
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
finally
{
if (Interlocked.Decrement(ref _runningThreads) == 0)
_endEvent.Set();
}
}
private void RunTest(SqlConnection con, RandomizerPool.Scope<SqlRandomizer> testScope, SqlRandomTypeInfoCollection types, Stopwatch watch)
{
Exception pendingException = null;
string tempTableName = null;
try
{
// select number of columns to use and null bitmap to test
int columnsCount, rowsCount;
testScope.Current.NextTableDimentions(MaxRows, MaxColumns, MaxTotal, out rowsCount, out columnsCount);
SqlRandomTable table = SqlRandomTable.Create(testScope.Current, types, columnsCount, rowsCount, createPrimaryKeyColumn: true);
long total = (long)rowsCount * columnsCount;
Interlocked.Add(ref _totalValues, total);
Interlocked.Increment(ref _totalTables);
tempTableName = SqlRandomizer.GenerateUniqueTempTableNameForSqlServer();
table.GenerateTableOnServer(con, tempTableName);
long prevTicks = watch.ElapsedTicks;
watch.Start();
if (_randPool.ReproMode)
{
// perform one iteration only
using (var iterationScope = testScope.NewScope<SqlRandomizer>())
{
RunTestIteration(con, iterationScope.Current, table, tempTableName);
Interlocked.Increment(ref _totalIterations);
}
}
else
{
// continue with normal loop
for (int i = 0; i < IterationsPerTableDefault && watch.Elapsed < TimeLimitDefault; i++)
{
using (var iterationScope = testScope.NewScope<SqlRandomizer>())
{
RunTestIteration(con, iterationScope.Current, table, tempTableName);
Interlocked.Increment(ref _totalIterations);
}
}
}
watch.Stop();
Interlocked.Add(ref _totalTicks, watch.ElapsedTicks - prevTicks);
}
catch (Exception e)
{
pendingException = e;
throw;
}
finally
{
// keep the temp table for troubleshooting if debugger is attached
// the thread is going down anyway and connection will be closed
if (pendingException == null && tempTableName != null)
{
// destroy the temp table to free resources on the server
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "DROP TABLE " + tempTableName;
try
{
cmd.ExecuteNonQuery();
}
catch
{
}
}
}
}
private void RunTestIteration(SqlConnection con, SqlRandomizer rand, SqlRandomTable table, string tableName)
{
// random list of columns
int columnCount = table.Columns.Count;
int[] columnIndices = rand.NextIndices(columnCount);
int selectedCount = rand.NextIntInclusive(1, maxValueInclusive: columnCount);
StringBuilder selectBuilder = new StringBuilder();
table.GenerateSelectFromTableTSql(tableName, selectBuilder, columnIndices, 0, selectedCount);
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = selectBuilder.ToString();
bool cancel = rand.Next(100) == 0; // in 1% of the cases, call Cancel
if (cancel)
{
int cancelAfterMilliseconds = rand.Next(5);
int cancelAfterSpinCount = rand.Next(1000);
ThreadPool.QueueUserWorkItem((object state) =>
{
for (int i = 0; cancel && i < cancelAfterMilliseconds; i++)
{
Thread.Sleep(1);
}
if (cancel && cancelAfterSpinCount > 0)
{
SpinWait.SpinUntil(() => false, new TimeSpan(cancelAfterSpinCount));
}
if (cancel)
{
cmd.Cancel();
}
});
}
int readerRand = rand.NextIntInclusive(0, maxValueInclusive: 256);
CommandBehavior readerBehavior = CommandBehavior.Default;
if (readerRand % 10 == 0)
readerBehavior = CommandBehavior.SequentialAccess;
try
{
using (SqlDataReader reader = cmd.ExecuteReader(readerBehavior))
{
int row = 0;
while (reader.Read())
{
int rowRand = rand.NextIntInclusive();
if (rowRand % 1000 == 0)
{
// abandon this reader
break;
}
else if (rowRand % 25 == 0)
{
// skip the row
row++;
continue;
}
IList<object> expectedRow = table[row];
for (int c = 0; c < reader.FieldCount; c++)
{
if (rand.NextIntInclusive(0, maxValueInclusive: 10) == 0)
{
// skip the column
continue;
}
int expectedTableColumn = columnIndices[c];
object expectedValue = expectedRow[expectedTableColumn];
if (table.Columns[expectedTableColumn].CanCompareValues)
{
Assert.True(expectedValue != null, "FAILED: Null is expected with CanCompareValues");
// read the value same way it was written
object actualValue = table.Columns[expectedTableColumn].Read(reader, c, expectedValue.GetType());
Assert.True(table.Columns[expectedTableColumn].CompareValues(expectedValue, actualValue),
string.Format("FAILED: Data Comparison Failure:\n{0}", table.Columns[expectedTableColumn].BuildErrorMessage(expectedValue, actualValue)));
}
}
row++;
}
}
// keep last - this will stop the cancel task, if it is still active
cancel = false;
}
catch (SqlException e)
{
if (!cancel)
throw;
bool expected = false;
foreach (SqlError error in e.Errors)
{
if (error.Message == _operationCanceledErrorMessage)
{
// ignore this one - expected if canceled
expected = true;
break;
}
else if (error.Message == _severeErrorMessage)
{
// A severe error occurred on the current command. The results, if any, should be discarded.
expected = true;
break;
}
}
if (!expected)
{
// rethrow to the user
foreach (SqlError error in e.Errors)
{
Console.WriteLine("{0} {1}", error.Number, error.Message);
}
throw;
}
}
catch (InvalidOperationException e)
{
bool expected = false;
if (e.Message == _operationCanceledErrorMessage)
{
// "Operation canceled" exception is raised as a SqlException (as one of SqlError objects) and as InvalidOperationException
expected = true;
}
if (!expected)
{
throw;
}
}
}
}
}
| |
// <copyright file="PlayerManager.cs" company="Google Inc.">
// Copyright (C) 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
#if UNITY_ANDROID
namespace GooglePlayGames.Native.PInvoke
{
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using GooglePlayGames.BasicApi.Multiplayer;
using GooglePlayGames.OurUtils;
using C = GooglePlayGames.Native.Cwrapper.PlayerManager;
using Types = GooglePlayGames.Native.Cwrapper.Types;
using Status = GooglePlayGames.Native.Cwrapper.CommonErrorStatus;
internal class PlayerManager
{
private readonly GameServices mGameServices;
internal PlayerManager(GameServices services)
{
mGameServices = Misc.CheckNotNull(services);
}
internal void FetchSelf(Action<FetchSelfResponse> callback)
{
C.PlayerManager_FetchSelf(mGameServices.AsHandle(), Types.DataSource.CACHE_OR_NETWORK,
InternalFetchSelfCallback, Callbacks.ToIntPtr(callback, FetchSelfResponse.FromPointer));
}
[AOT.MonoPInvokeCallback(typeof(C.FetchSelfCallback))]
private static void InternalFetchSelfCallback(IntPtr response, IntPtr data)
{
Callbacks.PerformInternalCallback("PlayerManager#InternalFetchSelfCallback",
Callbacks.Type.Temporary, response, data);
}
internal void FetchList(string[] userIds, Action<NativePlayer[]> callback)
{
FetchResponseCollector coll = new FetchResponseCollector();
coll.pendingCount = userIds.Length;
coll.callback = callback;
foreach(string id in userIds)
{
C.PlayerManager_Fetch(mGameServices.AsHandle(),
Types.DataSource.CACHE_OR_NETWORK,
id,
InternalFetchCallback,
Callbacks.ToIntPtr<FetchResponse>(
(rsp) => HandleFetchResponse(coll, rsp),
FetchResponse.FromPointer)
);
}
}
[AOT.MonoPInvokeCallback(typeof(C.FetchCallback))]
private static void InternalFetchCallback(IntPtr response, IntPtr data)
{
Callbacks.PerformInternalCallback("PlayerManager#InternalFetchCallback",
Callbacks.Type.Temporary, response, data);
}
internal void HandleFetchResponse(FetchResponseCollector collector,
FetchResponse resp)
{
if (resp.Status() == Status.ResponseStatus.VALID ||
resp.Status() == Status.ResponseStatus.VALID_BUT_STALE)
{
NativePlayer player = resp.GetPlayer();
collector.results.Add(player);
}
collector.pendingCount--;
if (collector.pendingCount == 0)
{
collector.callback(collector.results.ToArray());
}
}
internal void FetchFriends(Action<BasicApi.ResponseStatus, List<Player>> callback)
{
C.PlayerManager_FetchConnected(mGameServices.AsHandle(),
Types.DataSource.CACHE_OR_NETWORK,
InternalFetchConnectedCallback,
Callbacks.ToIntPtr<FetchListResponse>(
(rsp) => HandleFetchCollected(rsp, callback),
FetchListResponse.FromPointer)
);
}
[AOT.MonoPInvokeCallback(typeof(C.FetchListCallback))]
private static void InternalFetchConnectedCallback(IntPtr response, IntPtr data)
{
Callbacks.PerformInternalCallback("PlayerManager#InternalFetchConnectedCallback",
Callbacks.Type.Temporary, response, data);
}
internal void HandleFetchCollected(FetchListResponse rsp,
Action<GooglePlayGames.BasicApi.ResponseStatus, List<Player>> callback)
{
List<Player> players = new List<Player>();
if (rsp.Status() == Status.ResponseStatus.VALID ||
rsp.Status() == Status.ResponseStatus.VALID_BUT_STALE)
{
Logger.d("Got " + rsp.Length().ToUInt64() + " players");
foreach (NativePlayer p in rsp)
{
players.Add(p.AsPlayer());
}
}
callback((BasicApi.ResponseStatus)rsp.Status(), players);
}
internal class FetchListResponse : BaseReferenceHolder, IEnumerable<NativePlayer>
{
internal FetchListResponse(IntPtr selfPointer) : base(selfPointer)
{
}
protected override void CallDispose(HandleRef selfPointer)
{
C.PlayerManager_FetchListResponse_Dispose(SelfPtr());
}
internal Status.ResponseStatus Status()
{
return C.PlayerManager_FetchListResponse_GetStatus(SelfPtr());
}
#region IEnumerable implementation
public IEnumerator<NativePlayer> GetEnumerator()
{
return PInvokeUtilities.ToEnumerator<NativePlayer>(Length(),
(index) => GetElement(index));
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
internal UIntPtr Length()
{
return C.PlayerManager_FetchListResponse_GetData_Length(SelfPtr());
}
internal NativePlayer GetElement(UIntPtr index)
{
if (index.ToUInt64() >= Length().ToUInt64())
{
throw new ArgumentOutOfRangeException();
}
return new NativePlayer(
C.PlayerManager_FetchListResponse_GetData_GetElement(SelfPtr(), index));
}
internal static FetchListResponse FromPointer(IntPtr selfPointer)
{
if (PInvokeUtilities.IsNull(selfPointer))
{
return null;
}
return new FetchListResponse(selfPointer);
}
}
internal class FetchResponseCollector
{
internal int pendingCount;
internal List<NativePlayer> results = new List<NativePlayer>();
internal Action<NativePlayer[]> callback;
}
internal class FetchResponse : BaseReferenceHolder
{
internal FetchResponse(IntPtr selfPointer) : base(selfPointer)
{
}
protected override void CallDispose(HandleRef selfPointer)
{
C.PlayerManager_FetchResponse_Dispose(SelfPtr());
}
internal NativePlayer GetPlayer()
{
return new NativePlayer(
C.PlayerManager_FetchResponse_GetData(SelfPtr())
);
}
internal Status.ResponseStatus Status()
{
return C.PlayerManager_FetchResponse_GetStatus(SelfPtr());
}
internal static FetchResponse FromPointer(IntPtr selfPointer)
{
if (PInvokeUtilities.IsNull(selfPointer))
{
return null;
}
return new FetchResponse(selfPointer);
}
}
internal class FetchSelfResponse : BaseReferenceHolder
{
internal FetchSelfResponse(IntPtr selfPointer)
: base(selfPointer)
{
}
internal Status.ResponseStatus Status()
{
return C.PlayerManager_FetchSelfResponse_GetStatus(SelfPtr());
}
internal NativePlayer Self()
{
return new NativePlayer(C.PlayerManager_FetchSelfResponse_GetData(SelfPtr()));
}
protected override void CallDispose(HandleRef selfPointer)
{
C.PlayerManager_FetchSelfResponse_Dispose(SelfPtr());
}
internal static FetchSelfResponse FromPointer(IntPtr selfPointer)
{
if (PInvokeUtilities.IsNull(selfPointer))
{
return null;
}
return new FetchSelfResponse(selfPointer);
}
}
}
}
#endif
| |
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// ReSharper disable InconsistentNaming
// ReSharper disable MemberCanBePrivate.Global
namespace Sodium.Interop
{
internal static class SodiumLibrary
{
private const string Name = SodiumRuntimeConfig.LibraryName;
static SodiumLibrary()
{
RuntimeShim.PinDllImportLibrary(Name);
sodium_init();
}
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern void sodium_init();
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern void randombytes_buf(byte[] buffer, int size);
//randombytes_uniform
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int randombytes_uniform(int upperBound);
//sodium_increment
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern void sodium_increment(byte[] buffer, long length);
//sodium_compare
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sodium_compare(byte[] a, byte[] b, long length);
//sodium_version_string
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr sodium_version_string();
//crypto_hash
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_hash(byte[] buffer, byte[] message, long length);
//crypto_hash_sha512
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_hash_sha512(byte[] buffer, byte[] message, long length);
//crypto_hash_sha256
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_hash_sha256(byte[] buffer, byte[] message, long length);
//crypto_generichash
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_generichash(byte[] buffer, int bufferLength, byte[] message, long messageLength, byte[] key, int keyLength);
//crypto_generichash_blake2b_salt_personal
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_generichash_blake2b_salt_personal(byte[] buffer, int bufferLength, byte[] message, long messageLength, byte[] key, int keyLength, byte[] salt, byte[] personal);
//crypto_onetimeauth
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_onetimeauth(byte[] buffer, byte[] message, long messageLength, byte[] key);
//crypto_onetimeauth_verify
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_onetimeauth_verify(byte[] signature, byte[] message, long messageLength, byte[] key);
//crypto_pwhash_str
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_pwhash_str(byte[] buffer, byte[] password, long passwordLen, long opsLimit, int memLimit);
//crypto_pwhash_str_verify
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_pwhash_str_verify(byte[] buffer, byte[] password, long passLength);
//crypto_pwhash
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_pwhash(byte[] buffer, long bufferLen, byte[] password, long passwordLen, byte[] salt, long opsLimit, int memLimit, int alg);
//crypto_pwhash_scryptsalsa208sha256_str
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_pwhash_scryptsalsa208sha256_str(byte[] buffer, byte[] password, long passwordLen, long opsLimit, int memLimit);
//crypto_pwhash_scryptsalsa208sha256
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_pwhash_scryptsalsa208sha256(byte[] buffer, long bufferLen, byte[] password, long passwordLen, byte[] salt, long opsLimit, int memLimit);
//crypto_pwhash_scryptsalsa208sha256_str_verify
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_pwhash_scryptsalsa208sha256_str_verify(byte[] buffer, byte[] password, long passLength);
//crypto_sign_keypair
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_sign_keypair(byte[] publicKey, byte[] secretKey);
//crypto_sign_seed_keypair
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_sign_seed_keypair(byte[] publicKey, byte[] secretKey, byte[] seed);
//crypto_sign
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_sign(byte[] buffer, ref long bufferLength, byte[] message, long messageLength, byte[] key);
//crypto_sign_open
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_sign_open(byte[] buffer, ref long bufferLength, byte[] signedMessage, long signedMessageLength, byte[] key);
//crypto_sign_detached
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_sign_detached(byte[] signature, ref long signatureLength, byte[] message, long messageLength, byte[] key);
//crypto_sign_verify_detached
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_sign_verify_detached(byte[] signature, byte[] message, long messageLength, byte[] key);
//crypto_sign_ed25519_sk_to_seed
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_sign_ed25519_sk_to_seed(byte[] seed, byte[] secretKey);
//crypto_sign_ed25519_sk_to_pk
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_sign_ed25519_sk_to_pk(byte[] publicKey, byte[] secretKey);
//crypto_sign_ed25519_pk_to_curve25519
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_sign_ed25519_pk_to_curve25519(byte[] curve25519Pk, byte[] ed25519Pk);
//crypto_sign_ed25519_sk_to_curve25519
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_sign_ed25519_sk_to_curve25519(byte[] curve25519Sk, byte[] ed25519Sk);
//crypto_box_keypair
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_box_keypair(byte[] publicKey, byte[] secretKey);
//crypto_box_easy
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_box_easy(byte[] buffer, byte[] message, long messageLength, byte[] nonce, byte[] publicKey, byte[] secretKey);
//crypto_box_open_easy
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_box_open_easy(byte[] buffer, byte[] cipherText, long cipherTextLength, byte[] nonce, byte[] publicKey, byte[] secretKey);
//crypto_box_detached
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_box_detached(byte[] cipher, byte[] mac, byte[] message, long messageLength, byte[] nonce, byte[] pk, byte[] sk);
//crypto_box_open_detached
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_box_open_detached(byte[] buffer, byte[] cipherText, byte[] mac, long cipherTextLength, byte[] nonce, byte[] pk, byte[] sk);
//crypto_scalarmult_bytes
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_scalarmult_bytes();
//crypto_scalarmult_scalarbytes
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_scalarmult_scalarbytes();
//crypto_scalarmult_primitive
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern byte crypto_scalarmult_primitive();
//crypto_scalarmult_base
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_scalarmult_base(byte[] q, byte[] n);
//crypto_scalarmult
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_scalarmult(byte[] q, byte[] n, byte[] p);
//crypto_box_seal
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_box_seal(byte[] buffer, byte[] message, long messageLength, byte[] pk);
//crypto_box_seal_open
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_box_seal_open(byte[] buffer, byte[] cipherText, long cipherTextLength, byte[] pk, byte[] sk);
//crypto_secretbox_easy
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_secretbox_easy(byte[] buffer, byte[] message, long messageLength, byte[] nonce, byte[] key);
//crypto_secretbox_open_easy
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_secretbox_open_easy(byte[] buffer, byte[] cipherText, long cipherTextLength, byte[] nonce, byte[] key);
//crypto_secretbox_detached
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_secretbox_detached(byte[] cipher, byte[] mac, byte[] message, long messageLength, byte[] nonce, byte[] key);
//crypto_secretbox_open_detached
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_secretbox_open_detached(byte[] buffer, byte[] cipherText, byte[] mac, long cipherTextLength, byte[] nonce, byte[] key);
//crypto_auth
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_auth(byte[] buffer, byte[] message, long messageLength, byte[] key);
//crypto_auth_verify
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_auth_verify(byte[] signature, byte[] message, long messageLength, byte[] key);
//crypto_auth_hmacsha256
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_auth_hmacsha256(byte[] buffer, byte[] message, long messageLength, byte[] key);
//crypto_auth_hmacsha256_verify
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_auth_hmacsha256_verify(byte[] signature, byte[] message, long messageLength, byte[] key);
//crypto_auth_hmacsha512
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_auth_hmacsha512(byte[] signature, byte[] message, long messageLength, byte[] key);
//crypto_auth_hmacsha512_verify
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_auth_hmacsha512_verify(byte[] signature, byte[] message, long messageLength, byte[] key);
//crypto_shorthash
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_shorthash(byte[] buffer, byte[] message, long messageLength, byte[] key);
//crypto_stream_xor
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_stream_xor(byte[] buffer, byte[] message, long messageLength, byte[] nonce, byte[] key);
//crypto_stream_chacha20_xor
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_stream_chacha20_xor(byte[] buffer, byte[] message, long messageLength, byte[] nonce, byte[] key);
//sodium_bin2hex
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr sodium_bin2hex(byte[] hex, int hexMaxlen, byte[] bin, int binLen);
//sodium_hex2bin
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sodium_hex2bin(IntPtr bin, int binMaxlen, string hex, int hexLen, string ignore, out int binLen, string hexEnd);
//crypto_aead_chacha20poly1305_encrypt
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_aead_chacha20poly1305_encrypt(
IntPtr cipher, out long cipherLength, byte[] message, long messageLength, byte[] additionalData,
long additionalDataLength, byte[] nsec, byte[] nonce, byte[] key);
//crypto_aead_chacha20poly1305_decrypt
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_aead_chacha20poly1305_decrypt(
IntPtr message, out long messageLength, byte[] nsec, byte[] cipher, long cipherLength, byte[] additionalData,
long additionalDataLength, byte[] nonce, byte[] key);
//crypto_aead_aes256gcm_is_available
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_aead_aes256gcm_is_available();
//crypto_aead_aes256gcm_encrypt
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_aead_aes256gcm_encrypt(
IntPtr cipher, out long cipherLength, byte[] message, long messageLength, byte[] additionalData,
long additionalDataLength, byte[] nsec, byte[] nonce, byte[] key);
//crypto_aead_aes256gcm_decrypt
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_aead_aes256gcm_decrypt(
IntPtr message, out long messageLength, byte[] nsec, byte[] cipher, long cipherLength, byte[] additionalData,
long additionalDataLength, byte[] nonce, byte[] key);
//crypto_generichash_state
[StructLayout(LayoutKind.Sequential, Size = 384)]
[SuppressMessage("ReSharper", "FieldCanBeMadeReadOnly.Global")]
internal struct _HashState
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
public ulong[] h;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
public ulong[] t;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
public ulong[] f;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
public byte[] buf;
public uint buflen;
public byte last_node;
}
//crypto_generichash_init
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_generichash_init(IntPtr state, byte[] key, int keySize, int hashSize);
//crypto_generichash_update
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_generichash_update(IntPtr state, byte[] message, long messageLength);
//crypto_generichash_final
[DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_generichash_final(IntPtr state, byte[] buffer, int bufferLength);
}
}
| |
// 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 TestZInt32()
{
var test = new BooleanBinaryOpTest__TestZInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
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 BooleanBinaryOpTest__TestZInt32
{
private const int VectorSize = 32;
private const int Op1ElementCount = VectorSize / sizeof(Int32);
private const int Op2ElementCount = VectorSize / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector256<Int32> _clsVar1;
private static Vector256<Int32> _clsVar2;
private Vector256<Int32> _fld1;
private Vector256<Int32> _fld2;
private BooleanBinaryOpTest__DataTable<Int32, Int32> _dataTable;
static BooleanBinaryOpTest__TestZInt32()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize);
}
public BooleanBinaryOpTest__TestZInt32()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
_dataTable = new BooleanBinaryOpTest__DataTable<Int32, Int32>(_data1, _data2, VectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx.TestZ(
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
var result = Avx.TestZ(
Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx.TestZ(
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
var method = typeof(Avx).GetMethod(nameof(Avx.TestZ), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunReflectionScenario_Load()
{
var method = typeof(Avx).GetMethod(nameof(Avx.TestZ), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunReflectionScenario_LoadAligned()
{
var method = typeof(Avx).GetMethod(nameof(Avx.TestZ), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunClsVarScenario()
{
var result = Avx.TestZ(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr);
var result = Avx.TestZ(left, right);
ValidateResult(left, right, result);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr));
var result = Avx.TestZ(left, right);
ValidateResult(left, right, result);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr));
var result = Avx.TestZ(left, right);
ValidateResult(left, right, result);
}
public void RunLclFldScenario()
{
var test = new BooleanBinaryOpTest__TestZInt32();
var result = Avx.TestZ(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunFldScenario()
{
var result = Avx.TestZ(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<Int32> left, Vector256<Int32> right, bool result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* left, void* right, bool result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Int32[] left, Int32[] right, bool result, [CallerMemberName] string method = "")
{
var expectedResult = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult &= ((left[i] & right[i]) == 0);
}
if (expectedResult != result)
{
Succeeded = false;
Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.TestZ)}<Int32>(Vector256<Int32>, Vector256<Int32>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: primitive/contact_information.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace HOLMS.Types.Primitive {
/// <summary>Holder for reflection information generated from primitive/contact_information.proto</summary>
public static partial class ContactInformationReflection {
#region Descriptor
/// <summary>File descriptor for primitive/contact_information.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ContactInformationReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiNwcmltaXRpdmUvY29udGFjdF9pbmZvcm1hdGlvbi5wcm90bxIVaG9sbXMu",
"dHlwZXMucHJpbWl0aXZlItQDChJDb250YWN0SW5mb3JtYXRpb24SEgoKZ2l2",
"ZW5fbmFtZRgBIAEoCRIUCgxnaXZlbl9uYW1lXzIYAiABKAkSEwoLZmFtaWx5",
"X25hbWUYAyABKAkSDQoFZW1haWwYBCABKAkSEgoKaG9tZV9waG9uZRgFIAEo",
"CRIUCgxtb2JpbGVfcGhvbmUYBiABKAkSEgoKZmF4X251bWJlchgHIAEoCRIU",
"CgxvZmZpY2VfcGhvbmUYCCABKAkSGAoQb2ZmaWNlX2FkZHJlc3NfMRgJIAEo",
"CRIYChBvZmZpY2VfYWRkcmVzc18yGAogASgJEhMKC29mZmljZV9jaXR5GAsg",
"ASgJEhQKDG9mZmljZV9zdGF0ZRgMIAEoCRISCgpvZmZpY2VfemlwGA0gASgJ",
"EhUKDW9mZmljZV9uYXRpb24YDiABKAkSFgoOaG9tZV9hZGRyZXNzXzEYDyAB",
"KAkSFgoOaG9tZV9hZGRyZXNzXzIYECABKAkSEQoJaG9tZV9jaXR5GBEgASgJ",
"EhIKCmhvbWVfc3RhdGUYEiABKAkSEAoIaG9tZV96aXAYEyABKAkSEwoLaG9t",
"ZV9uYXRpb24YFCABKAkSFAoMY29tcGFueV9uYW1lGBUgASgJQiNaCXByaW1p",
"dGl2ZaoCFUhPTE1TLlR5cGVzLlByaW1pdGl2ZWIGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Primitive.ContactInformation), global::HOLMS.Types.Primitive.ContactInformation.Parser, new[]{ "GivenName", "GivenName2", "FamilyName", "Email", "HomePhone", "MobilePhone", "FaxNumber", "OfficePhone", "OfficeAddress1", "OfficeAddress2", "OfficeCity", "OfficeState", "OfficeZip", "OfficeNation", "HomeAddress1", "HomeAddress2", "HomeCity", "HomeState", "HomeZip", "HomeNation", "CompanyName" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class ContactInformation : pb::IMessage<ContactInformation> {
private static readonly pb::MessageParser<ContactInformation> _parser = new pb::MessageParser<ContactInformation>(() => new ContactInformation());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ContactInformation> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Primitive.ContactInformationReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ContactInformation() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ContactInformation(ContactInformation other) : this() {
givenName_ = other.givenName_;
givenName2_ = other.givenName2_;
familyName_ = other.familyName_;
email_ = other.email_;
homePhone_ = other.homePhone_;
mobilePhone_ = other.mobilePhone_;
faxNumber_ = other.faxNumber_;
officePhone_ = other.officePhone_;
officeAddress1_ = other.officeAddress1_;
officeAddress2_ = other.officeAddress2_;
officeCity_ = other.officeCity_;
officeState_ = other.officeState_;
officeZip_ = other.officeZip_;
officeNation_ = other.officeNation_;
homeAddress1_ = other.homeAddress1_;
homeAddress2_ = other.homeAddress2_;
homeCity_ = other.homeCity_;
homeState_ = other.homeState_;
homeZip_ = other.homeZip_;
homeNation_ = other.homeNation_;
companyName_ = other.companyName_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ContactInformation Clone() {
return new ContactInformation(this);
}
/// <summary>Field number for the "given_name" field.</summary>
public const int GivenNameFieldNumber = 1;
private string givenName_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string GivenName {
get { return givenName_; }
set {
givenName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "given_name_2" field.</summary>
public const int GivenName2FieldNumber = 2;
private string givenName2_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string GivenName2 {
get { return givenName2_; }
set {
givenName2_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "family_name" field.</summary>
public const int FamilyNameFieldNumber = 3;
private string familyName_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string FamilyName {
get { return familyName_; }
set {
familyName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "email" field.</summary>
public const int EmailFieldNumber = 4;
private string email_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Email {
get { return email_; }
set {
email_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "home_phone" field.</summary>
public const int HomePhoneFieldNumber = 5;
private string homePhone_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string HomePhone {
get { return homePhone_; }
set {
homePhone_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "mobile_phone" field.</summary>
public const int MobilePhoneFieldNumber = 6;
private string mobilePhone_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string MobilePhone {
get { return mobilePhone_; }
set {
mobilePhone_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "fax_number" field.</summary>
public const int FaxNumberFieldNumber = 7;
private string faxNumber_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string FaxNumber {
get { return faxNumber_; }
set {
faxNumber_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "office_phone" field.</summary>
public const int OfficePhoneFieldNumber = 8;
private string officePhone_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string OfficePhone {
get { return officePhone_; }
set {
officePhone_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "office_address_1" field.</summary>
public const int OfficeAddress1FieldNumber = 9;
private string officeAddress1_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string OfficeAddress1 {
get { return officeAddress1_; }
set {
officeAddress1_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "office_address_2" field.</summary>
public const int OfficeAddress2FieldNumber = 10;
private string officeAddress2_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string OfficeAddress2 {
get { return officeAddress2_; }
set {
officeAddress2_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "office_city" field.</summary>
public const int OfficeCityFieldNumber = 11;
private string officeCity_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string OfficeCity {
get { return officeCity_; }
set {
officeCity_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "office_state" field.</summary>
public const int OfficeStateFieldNumber = 12;
private string officeState_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string OfficeState {
get { return officeState_; }
set {
officeState_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "office_zip" field.</summary>
public const int OfficeZipFieldNumber = 13;
private string officeZip_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string OfficeZip {
get { return officeZip_; }
set {
officeZip_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "office_nation" field.</summary>
public const int OfficeNationFieldNumber = 14;
private string officeNation_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string OfficeNation {
get { return officeNation_; }
set {
officeNation_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "home_address_1" field.</summary>
public const int HomeAddress1FieldNumber = 15;
private string homeAddress1_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string HomeAddress1 {
get { return homeAddress1_; }
set {
homeAddress1_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "home_address_2" field.</summary>
public const int HomeAddress2FieldNumber = 16;
private string homeAddress2_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string HomeAddress2 {
get { return homeAddress2_; }
set {
homeAddress2_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "home_city" field.</summary>
public const int HomeCityFieldNumber = 17;
private string homeCity_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string HomeCity {
get { return homeCity_; }
set {
homeCity_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "home_state" field.</summary>
public const int HomeStateFieldNumber = 18;
private string homeState_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string HomeState {
get { return homeState_; }
set {
homeState_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "home_zip" field.</summary>
public const int HomeZipFieldNumber = 19;
private string homeZip_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string HomeZip {
get { return homeZip_; }
set {
homeZip_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "home_nation" field.</summary>
public const int HomeNationFieldNumber = 20;
private string homeNation_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string HomeNation {
get { return homeNation_; }
set {
homeNation_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "company_name" field.</summary>
public const int CompanyNameFieldNumber = 21;
private string companyName_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string CompanyName {
get { return companyName_; }
set {
companyName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ContactInformation);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ContactInformation other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (GivenName != other.GivenName) return false;
if (GivenName2 != other.GivenName2) return false;
if (FamilyName != other.FamilyName) return false;
if (Email != other.Email) return false;
if (HomePhone != other.HomePhone) return false;
if (MobilePhone != other.MobilePhone) return false;
if (FaxNumber != other.FaxNumber) return false;
if (OfficePhone != other.OfficePhone) return false;
if (OfficeAddress1 != other.OfficeAddress1) return false;
if (OfficeAddress2 != other.OfficeAddress2) return false;
if (OfficeCity != other.OfficeCity) return false;
if (OfficeState != other.OfficeState) return false;
if (OfficeZip != other.OfficeZip) return false;
if (OfficeNation != other.OfficeNation) return false;
if (HomeAddress1 != other.HomeAddress1) return false;
if (HomeAddress2 != other.HomeAddress2) return false;
if (HomeCity != other.HomeCity) return false;
if (HomeState != other.HomeState) return false;
if (HomeZip != other.HomeZip) return false;
if (HomeNation != other.HomeNation) return false;
if (CompanyName != other.CompanyName) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (GivenName.Length != 0) hash ^= GivenName.GetHashCode();
if (GivenName2.Length != 0) hash ^= GivenName2.GetHashCode();
if (FamilyName.Length != 0) hash ^= FamilyName.GetHashCode();
if (Email.Length != 0) hash ^= Email.GetHashCode();
if (HomePhone.Length != 0) hash ^= HomePhone.GetHashCode();
if (MobilePhone.Length != 0) hash ^= MobilePhone.GetHashCode();
if (FaxNumber.Length != 0) hash ^= FaxNumber.GetHashCode();
if (OfficePhone.Length != 0) hash ^= OfficePhone.GetHashCode();
if (OfficeAddress1.Length != 0) hash ^= OfficeAddress1.GetHashCode();
if (OfficeAddress2.Length != 0) hash ^= OfficeAddress2.GetHashCode();
if (OfficeCity.Length != 0) hash ^= OfficeCity.GetHashCode();
if (OfficeState.Length != 0) hash ^= OfficeState.GetHashCode();
if (OfficeZip.Length != 0) hash ^= OfficeZip.GetHashCode();
if (OfficeNation.Length != 0) hash ^= OfficeNation.GetHashCode();
if (HomeAddress1.Length != 0) hash ^= HomeAddress1.GetHashCode();
if (HomeAddress2.Length != 0) hash ^= HomeAddress2.GetHashCode();
if (HomeCity.Length != 0) hash ^= HomeCity.GetHashCode();
if (HomeState.Length != 0) hash ^= HomeState.GetHashCode();
if (HomeZip.Length != 0) hash ^= HomeZip.GetHashCode();
if (HomeNation.Length != 0) hash ^= HomeNation.GetHashCode();
if (CompanyName.Length != 0) hash ^= CompanyName.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (GivenName.Length != 0) {
output.WriteRawTag(10);
output.WriteString(GivenName);
}
if (GivenName2.Length != 0) {
output.WriteRawTag(18);
output.WriteString(GivenName2);
}
if (FamilyName.Length != 0) {
output.WriteRawTag(26);
output.WriteString(FamilyName);
}
if (Email.Length != 0) {
output.WriteRawTag(34);
output.WriteString(Email);
}
if (HomePhone.Length != 0) {
output.WriteRawTag(42);
output.WriteString(HomePhone);
}
if (MobilePhone.Length != 0) {
output.WriteRawTag(50);
output.WriteString(MobilePhone);
}
if (FaxNumber.Length != 0) {
output.WriteRawTag(58);
output.WriteString(FaxNumber);
}
if (OfficePhone.Length != 0) {
output.WriteRawTag(66);
output.WriteString(OfficePhone);
}
if (OfficeAddress1.Length != 0) {
output.WriteRawTag(74);
output.WriteString(OfficeAddress1);
}
if (OfficeAddress2.Length != 0) {
output.WriteRawTag(82);
output.WriteString(OfficeAddress2);
}
if (OfficeCity.Length != 0) {
output.WriteRawTag(90);
output.WriteString(OfficeCity);
}
if (OfficeState.Length != 0) {
output.WriteRawTag(98);
output.WriteString(OfficeState);
}
if (OfficeZip.Length != 0) {
output.WriteRawTag(106);
output.WriteString(OfficeZip);
}
if (OfficeNation.Length != 0) {
output.WriteRawTag(114);
output.WriteString(OfficeNation);
}
if (HomeAddress1.Length != 0) {
output.WriteRawTag(122);
output.WriteString(HomeAddress1);
}
if (HomeAddress2.Length != 0) {
output.WriteRawTag(130, 1);
output.WriteString(HomeAddress2);
}
if (HomeCity.Length != 0) {
output.WriteRawTag(138, 1);
output.WriteString(HomeCity);
}
if (HomeState.Length != 0) {
output.WriteRawTag(146, 1);
output.WriteString(HomeState);
}
if (HomeZip.Length != 0) {
output.WriteRawTag(154, 1);
output.WriteString(HomeZip);
}
if (HomeNation.Length != 0) {
output.WriteRawTag(162, 1);
output.WriteString(HomeNation);
}
if (CompanyName.Length != 0) {
output.WriteRawTag(170, 1);
output.WriteString(CompanyName);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (GivenName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(GivenName);
}
if (GivenName2.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(GivenName2);
}
if (FamilyName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(FamilyName);
}
if (Email.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Email);
}
if (HomePhone.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(HomePhone);
}
if (MobilePhone.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(MobilePhone);
}
if (FaxNumber.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(FaxNumber);
}
if (OfficePhone.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(OfficePhone);
}
if (OfficeAddress1.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(OfficeAddress1);
}
if (OfficeAddress2.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(OfficeAddress2);
}
if (OfficeCity.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(OfficeCity);
}
if (OfficeState.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(OfficeState);
}
if (OfficeZip.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(OfficeZip);
}
if (OfficeNation.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(OfficeNation);
}
if (HomeAddress1.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(HomeAddress1);
}
if (HomeAddress2.Length != 0) {
size += 2 + pb::CodedOutputStream.ComputeStringSize(HomeAddress2);
}
if (HomeCity.Length != 0) {
size += 2 + pb::CodedOutputStream.ComputeStringSize(HomeCity);
}
if (HomeState.Length != 0) {
size += 2 + pb::CodedOutputStream.ComputeStringSize(HomeState);
}
if (HomeZip.Length != 0) {
size += 2 + pb::CodedOutputStream.ComputeStringSize(HomeZip);
}
if (HomeNation.Length != 0) {
size += 2 + pb::CodedOutputStream.ComputeStringSize(HomeNation);
}
if (CompanyName.Length != 0) {
size += 2 + pb::CodedOutputStream.ComputeStringSize(CompanyName);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ContactInformation other) {
if (other == null) {
return;
}
if (other.GivenName.Length != 0) {
GivenName = other.GivenName;
}
if (other.GivenName2.Length != 0) {
GivenName2 = other.GivenName2;
}
if (other.FamilyName.Length != 0) {
FamilyName = other.FamilyName;
}
if (other.Email.Length != 0) {
Email = other.Email;
}
if (other.HomePhone.Length != 0) {
HomePhone = other.HomePhone;
}
if (other.MobilePhone.Length != 0) {
MobilePhone = other.MobilePhone;
}
if (other.FaxNumber.Length != 0) {
FaxNumber = other.FaxNumber;
}
if (other.OfficePhone.Length != 0) {
OfficePhone = other.OfficePhone;
}
if (other.OfficeAddress1.Length != 0) {
OfficeAddress1 = other.OfficeAddress1;
}
if (other.OfficeAddress2.Length != 0) {
OfficeAddress2 = other.OfficeAddress2;
}
if (other.OfficeCity.Length != 0) {
OfficeCity = other.OfficeCity;
}
if (other.OfficeState.Length != 0) {
OfficeState = other.OfficeState;
}
if (other.OfficeZip.Length != 0) {
OfficeZip = other.OfficeZip;
}
if (other.OfficeNation.Length != 0) {
OfficeNation = other.OfficeNation;
}
if (other.HomeAddress1.Length != 0) {
HomeAddress1 = other.HomeAddress1;
}
if (other.HomeAddress2.Length != 0) {
HomeAddress2 = other.HomeAddress2;
}
if (other.HomeCity.Length != 0) {
HomeCity = other.HomeCity;
}
if (other.HomeState.Length != 0) {
HomeState = other.HomeState;
}
if (other.HomeZip.Length != 0) {
HomeZip = other.HomeZip;
}
if (other.HomeNation.Length != 0) {
HomeNation = other.HomeNation;
}
if (other.CompanyName.Length != 0) {
CompanyName = other.CompanyName;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
GivenName = input.ReadString();
break;
}
case 18: {
GivenName2 = input.ReadString();
break;
}
case 26: {
FamilyName = input.ReadString();
break;
}
case 34: {
Email = input.ReadString();
break;
}
case 42: {
HomePhone = input.ReadString();
break;
}
case 50: {
MobilePhone = input.ReadString();
break;
}
case 58: {
FaxNumber = input.ReadString();
break;
}
case 66: {
OfficePhone = input.ReadString();
break;
}
case 74: {
OfficeAddress1 = input.ReadString();
break;
}
case 82: {
OfficeAddress2 = input.ReadString();
break;
}
case 90: {
OfficeCity = input.ReadString();
break;
}
case 98: {
OfficeState = input.ReadString();
break;
}
case 106: {
OfficeZip = input.ReadString();
break;
}
case 114: {
OfficeNation = input.ReadString();
break;
}
case 122: {
HomeAddress1 = input.ReadString();
break;
}
case 130: {
HomeAddress2 = input.ReadString();
break;
}
case 138: {
HomeCity = input.ReadString();
break;
}
case 146: {
HomeState = input.ReadString();
break;
}
case 154: {
HomeZip = input.ReadString();
break;
}
case 162: {
HomeNation = input.ReadString();
break;
}
case 170: {
CompanyName = input.ReadString();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
namespace Boxed.AspNetCore.TagHelpers.OpenGraph
{
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Razor.TagHelpers;
/// <summary>
/// This object type represents a product. This includes both virtual and physical products, but it typically
/// represents items that are available in an online store. This object type is not part of the Open Graph standard
/// but is used by Facebook.
/// See https://developers.facebook.com/docs/reference/opengraph/object-type/product/.
/// </summary>
[HtmlTargetElement(
"open-graph-product",
Attributes = TitleAttributeName + "," + MainImageAttributeName,
TagStructure = TagStructure.WithoutEndTag)]
public class OpenGraphProduct : OpenGraphMetadata
{
private const string AgeGroupAttributeName = "age-group";
private const string AvailabilityAttributeName = "availability";
private const string BrandAttributeName = "brand";
private const string CategoryAttributeName = "category";
private const string ColourAttributeName = "colour";
private const string ConditionAttributeName = "condition";
private const string EANAttributeName = "ean";
private const string ExpirationTimeAttributeName = "expiration-time";
private const string IsShareableAttributeName = "shareable";
private const string ISBNAttributeName = "isbn";
private const string ManufacturerPartNumberAttributeName = "manufacturer-part-number";
private const string MaterialAttributeName = "material";
private const string OriginalPricesAttributeName = "original-prices";
private const string PatternAttributeName = "pattern";
private const string PluralTitleAttributeName = "plural-title";
private const string PretaxPricesAttributeName = "pretax-prices";
private const string PricesAttributeName = "prices";
private const string ProductLinkUrlAttributeName = "product-link-url";
private const string PurchaseLimitAttributeName = "purchase-limit";
private const string RetailerUrlAttributeName = "retailer-url";
private const string RetailerCategoryAttributeName = "retailer-category";
private const string RetailerPartNumberAttributeName = "retailer-part-number";
private const string RetailerTitleAttributeName = "retailer-title";
private const string SalePriceAttributeName = "sale-price";
private const string SalePriceDatesAttributeName = "sale-price-dates";
private const string ShippingCostAttributeName = "shipping-cost";
private const string ShippingWeightAttributeName = "shipping-weight";
private const string SizeAttributeName = "size";
private const string TargetGenderAttributeName = "target-gender";
private const string WeightAttributeName = "weight";
/// <summary>
/// Gets or sets the target age group of the product, one of 'kids' or 'adult'.
/// </summary>
[HtmlAttributeName(AgeGroupAttributeName)]
public OpenGraphAgeGroup? AgeGroup { get; set; }
/// <summary>
/// Gets or sets the availability of the product, one of 'instock', 'oos', or 'pending'.
/// </summary>
[HtmlAttributeName(AvailabilityAttributeName)]
public OpenGraphAvailability? Availability { get; set; }
/// <summary>
/// Gets or sets the brand of the product or its original manufacturer.
/// </summary>
[HtmlAttributeName(BrandAttributeName)]
public string Brand { get; set; }
/// <summary>
/// Gets or sets the category for the product.
/// </summary>
[HtmlAttributeName(CategoryAttributeName)]
public string Category { get; set; }
/// <summary>
/// Gets or sets the colour of the product.
/// </summary>
[HtmlAttributeName(ColourAttributeName)]
public string Colour { get; set; }
/// <summary>
/// Gets or sets the condition of the item, one of 'new', 'refurbished', or 'used'.
/// </summary>
[HtmlAttributeName(ConditionAttributeName)]
public OpenGraphCondition? Condition { get; set; }
/// <summary>
/// Gets or sets an International Article Number, or European Article Number (EAN), for the product.
/// </summary>
[HtmlAttributeName(EANAttributeName)]
public string EAN { get; set; }
/// <summary>
/// Gets or sets a time representing when the product expired (or will expire).
/// </summary>
[HtmlAttributeName(ExpirationTimeAttributeName)]
public DateTime? ExpirationTime { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the associated story has a share button on it.
/// </summary>
[HtmlAttributeName(IsShareableAttributeName)]
public bool? IsShareable { get; set; }
/// <summary>
/// Gets or sets a International Standard Book Number (ISBN) for the product, intended for when it is a book.
/// </summary>
[HtmlAttributeName(ISBNAttributeName)]
public string ISBN { get; set; }
/// <summary>
/// Gets or sets the manufacturers part number for the product.
/// </summary>
[HtmlAttributeName(ManufacturerPartNumberAttributeName)]
public string ManufacturerPartNumber { get; set; }
/// <summary>
/// Gets or sets a description of the material used to make the product.
/// </summary>
[HtmlAttributeName(MaterialAttributeName)]
public string Material { get; set; }
/// <summary>
/// Gets the namespace of this open graph type.
/// </summary>
public override string Namespace => "product: http://ogp.me/ns/product#";
/// <summary>
/// Gets or sets the original prices of the product.
/// </summary>
[HtmlAttributeName(OriginalPricesAttributeName)]
public IEnumerable<OpenGraphCurrency> OriginalPrices { get; set; }
/// <summary>
/// Gets or sets a description of the pattern used on the product.
/// </summary>
[HtmlAttributeName(PatternAttributeName)]
public string Pattern { get; set; }
/// <summary>
/// Gets or sets a title to be used to describe multiple items of this product.
/// </summary>
[HtmlAttributeName(PluralTitleAttributeName)]
public string PluralTitle { get; set; }
/// <summary>
/// Gets or sets the pre-tax prices of the product.
/// </summary>
[HtmlAttributeName(PretaxPricesAttributeName)]
public IEnumerable<OpenGraphCurrency> PretaxPrices { get; set; }
/// <summary>
/// Gets or sets the prices of the product.
/// </summary>
[HtmlAttributeName(PricesAttributeName)]
public IEnumerable<OpenGraphCurrency> Prices { get; set; }
/// <summary>
/// Gets or sets a URL link to find out more about the product.
/// </summary>
[HtmlAttributeName(ProductLinkUrlAttributeName)]
public Uri ProductLinkUrl { get; set; }
/// <summary>
/// Gets or sets the maximum number of times a person can purchase the product.
/// </summary>
[HtmlAttributeName(PurchaseLimitAttributeName)]
public int PurchaseLimit { get; set; }
/// <summary>
/// Gets or sets the URL to the page about the retailer of the product. This URL must contain profile meta tags <see cref="OpenGraphProfile"/>.
/// </summary>
[HtmlAttributeName(RetailerUrlAttributeName)]
public Uri RetailerUrl { get; set; }
/// <summary>
/// Gets or sets the retailer's category for the product.
/// </summary>
[HtmlAttributeName(RetailerCategoryAttributeName)]
public string RetailerCategory { get; set; }
/// <summary>
/// Gets or sets the retailer's part number for the product.
/// </summary>
[HtmlAttributeName(RetailerPartNumberAttributeName)]
public string RetailerPartNumber { get; set; }
/// <summary>
/// Gets or sets the name of the retailer of the product.
/// </summary>
[HtmlAttributeName(RetailerTitleAttributeName)]
public string RetailerTitle { get; set; }
/// <summary>
/// Gets or sets the sale price of the product.
/// </summary>
[HtmlAttributeName(SalePriceAttributeName)]
public OpenGraphCurrency SalePrice { get; set; }
/// <summary>
/// Gets or sets the date range for which the sale price is valid.
/// </summary>
[HtmlAttributeName(SalePriceDatesAttributeName)]
public OpenGraphDateTimeRange SalePriceDates { get; set; }
/// <summary>
/// Gets or sets the shipping cost of the product.
/// </summary>
[HtmlAttributeName(ShippingCostAttributeName)]
public IEnumerable<OpenGraphCurrency> ShippingCost { get; set; }
/// <summary>
/// Gets or sets the shipping weight of the product.
/// </summary>
[HtmlAttributeName(ShippingWeightAttributeName)]
public OpenGraphQuantity ShippingWeight { get; set; }
/// <summary>
/// Gets or sets a size describing the product(such as 'S', 'M', 'L').
/// </summary>
[HtmlAttributeName(SizeAttributeName)]
public string Size { get; set; }
/// <summary>
/// Gets or sets the target gender for the product.
/// </summary>
[HtmlAttributeName(TargetGenderAttributeName)]
public OpenGraphTargetGender? TargetGender { get; set; }
/// <summary>
/// Gets the type of your object. Depending on the type you specify, other properties may also be required.
/// </summary>
public override OpenGraphType Type => OpenGraphType.Product;
/// <summary>
/// Gets or sets a Universal Product Code(UPC) for the product.
/// </summary>
[HtmlAttributeName(TargetGenderAttributeName)]
public string UPC { get; set; }
/// <summary>
/// Gets or sets the weight of the product.
/// </summary>
[HtmlAttributeName(WeightAttributeName)]
public OpenGraphQuantity Weight { get; set; }
/// <summary>
/// Appends a HTML-encoded string representing this instance to the <paramref name="stringBuilder"/> containing the Open Graph meta tags.
/// </summary>
/// <param name="stringBuilder">The string builder.</param>
public override void ToString(StringBuilder stringBuilder)
{
if (stringBuilder == null)
{
throw new ArgumentNullException(nameof(stringBuilder));
}
base.ToString(stringBuilder);
if (this.AgeGroup.HasValue)
{
stringBuilder.AppendMetaPropertyContent("product:age_group", this.AgeGroup.Value.ToLowercaseString());
}
if (this.Availability.HasValue)
{
stringBuilder.AppendMetaPropertyContent("product:availability", this.Availability.Value.ToLowercaseString());
}
stringBuilder.AppendMetaPropertyContentIfNotNull("product:brand", this.Brand);
stringBuilder.AppendMetaPropertyContentIfNotNull("product:category", this.Category);
stringBuilder.AppendMetaPropertyContentIfNotNull("product:color", this.Colour);
if (this.Condition.HasValue)
{
stringBuilder.AppendMetaPropertyContent("product:condition", this.Condition.Value.ToLowercaseString());
}
stringBuilder.AppendMetaPropertyContentIfNotNull("product:ean", this.EAN);
stringBuilder.AppendMetaPropertyContentIfNotNull("product:expiration_time", this.ExpirationTime);
stringBuilder.AppendMetaPropertyContentIfNotNull("product:is_product_shareable", this.IsShareable);
stringBuilder.AppendMetaPropertyContentIfNotNull("product:isbn", this.ISBN);
stringBuilder.AppendMetaPropertyContentIfNotNull("product:material", this.Material);
stringBuilder.AppendMetaPropertyContentIfNotNull("product:mfr_part_no", this.ManufacturerPartNumber);
if (this.OriginalPrices != null)
{
foreach (var originalPrice in this.OriginalPrices)
{
stringBuilder.AppendMetaPropertyContent("product:original_price:amount", originalPrice.Amount);
stringBuilder.AppendMetaPropertyContent("product:original_price:currency", originalPrice.Currency);
}
}
stringBuilder.AppendMetaPropertyContentIfNotNull("product:pattern", this.Pattern);
stringBuilder.AppendMetaPropertyContentIfNotNull("product:plural_title", this.PluralTitle);
if (this.PretaxPrices != null)
{
foreach (var pretaxPrice in this.PretaxPrices)
{
stringBuilder.AppendMetaPropertyContent("product:pretax_price:amount", pretaxPrice.Amount);
stringBuilder.AppendMetaPropertyContent("product:pretax_price:currency", pretaxPrice.Currency);
}
}
if (this.Prices != null)
{
foreach (var price in this.Prices)
{
stringBuilder.AppendMetaPropertyContent("product:price:amount", price.Amount);
stringBuilder.AppendMetaPropertyContent("product:price:currency", price.Currency);
}
}
stringBuilder.AppendMetaPropertyContentIfNotNull("product:product_link", this.ProductLinkUrl);
stringBuilder.AppendMetaPropertyContentIfNotNull("product:purchase_limit", this.PurchaseLimit);
stringBuilder.AppendMetaPropertyContentIfNotNull("product:retailer", this.RetailerUrl);
stringBuilder.AppendMetaPropertyContentIfNotNull("product:retailer_category", this.RetailerCategory);
stringBuilder.AppendMetaPropertyContentIfNotNull("product:retailer_part_no", this.RetailerPartNumber);
stringBuilder.AppendMetaPropertyContentIfNotNull("product:retailer_title", this.RetailerTitle);
if (this.SalePrice != null)
{
stringBuilder.AppendMetaPropertyContent("product:sale_price:amount", this.SalePrice.Amount);
stringBuilder.AppendMetaPropertyContent("product:sale_price:currency", this.SalePrice.Currency);
}
if (this.SalePriceDates != null)
{
stringBuilder.AppendMetaPropertyContent("product:sale_price_dates:start", this.SalePriceDates.Start);
stringBuilder.AppendMetaPropertyContent("product:sale_price_dates:end", this.SalePriceDates.End);
}
if (this.ShippingCost != null)
{
foreach (var shippingCost in this.ShippingCost)
{
stringBuilder.AppendMetaPropertyContent("product:shipping_cost:amount", shippingCost.Amount);
stringBuilder.AppendMetaPropertyContent("product:shipping_cost:currency", shippingCost.Currency);
}
}
if (this.ShippingWeight != null)
{
stringBuilder.AppendMetaPropertyContent("product:shipping_weight:value", this.ShippingWeight.Value);
stringBuilder.AppendMetaPropertyContent("product:shipping_weight:units", this.ShippingWeight.Units);
}
stringBuilder.AppendMetaPropertyContentIfNotNull("product:size", this.Size);
if (this.TargetGender.HasValue)
{
stringBuilder.AppendMetaPropertyContent("product:target_gender", this.TargetGender.Value.ToLowercaseString());
}
stringBuilder.AppendMetaPropertyContentIfNotNull("product:upc", this.UPC);
if (this.Weight != null)
{
stringBuilder.AppendMetaPropertyContent("product:weight:value", this.Weight.Value);
stringBuilder.AppendMetaPropertyContent("product:weight:units", this.Weight.Units);
}
}
}
}
| |
using System.Linq;
using System.Threading.Tasks;
using AspNetCoreSpa.Server.Entities;
using AspNetCoreSpa.Server.Extensions;
using AspNetCoreSpa.Server.Services.Abstract;
using AspNetCoreSpa.Server.ViewModels.AccountViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Logging;
namespace AspNetCoreSpa.Server.Controllers.api
{
[Authorize]
[Route("api/[controller]")]
public class AccountController : BaseController
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ISmsSender _smsSender;
private readonly ILogger _logger;
public AccountController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender,
ISmsSender smsSender,
ILoggerFactory loggerFactory)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_smsSender = smsSender;
_logger = loggerFactory.CreateLogger<AccountController>();
}
[HttpPost("login")]
[AllowAnonymous]
public async Task<IActionResult> Login([FromBody]LoginViewModel model)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
var user = await _userManager.FindByEmailAsync(model.Email);
var roles = await _userManager.GetRolesAsync(user);
_logger.LogInformation(1, "User logged in.");
return AppUtils.SignIn(user, roles);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(SendCode), new { RememberMe = model.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning(2, "User account locked out.");
return BadRequest("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return BadRequest(ModelState.GetModelErrors());
}
}
[HttpPost("register")]
[AllowAnonymous]
public async Task<IActionResult> Register([FromBody]RegisterViewModel model, string returnUrl = null)
{
var currentUser = new ApplicationUser
{
UserName = model.Email,
Email = model.Email,
FirstName = model.Firstname,
LastName = model.Lastname
};
var result = await _userManager.CreateAsync(currentUser, model.Password);
if (result.Succeeded)
{
// Add to roles
var roleAddResult = await _userManager.AddToRoleAsync(currentUser, "User");
if (roleAddResult.Succeeded)
{
var code = await _userManager.GenerateEmailConfirmationTokenAsync(currentUser);
var host = Request.Scheme + "://" + Request.Host;
var callbackUrl = host + "?userId=" + currentUser.Id + "&emailConfirmCode=" + code;
var confirmationLink = "<a class='btn-primary' href=\"" + callbackUrl + "\">Confirm email address</a>";
_logger.LogInformation(3, "User created a new account with password.");
//await _emailSender.SendEmailAsync(MailType.Register, new EmailModel { To = model.Email }, confirmationLink);
return Json(new { });
}
}
AddErrors(result);
// If we got this far, something failed, redisplay form
return BadRequest(ModelState.GetModelErrors());
}
[HttpPost("logout")]
public async Task<IActionResult> LogOff()
{
await _signInManager.SignOutAsync();
_logger.LogInformation(4, "User logged out.");
return Ok();
}
[HttpGet("ExternalLogin")]
[AllowAnonymous]
public IActionResult ExternalLogin(string provider, string returnUrl = null)
{
// Request a redirect to the external login provider.
var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl });
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return Challenge(properties, provider);
}
[HttpGet("ExternalLoginCallback")]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
if (remoteError != null)
{
return Render(ExternalLoginStatus.Error);
}
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return Render(ExternalLoginStatus.Invalid);
}
// Sign in the user with this external login provider if the user already has a login.
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
if (result.Succeeded)
{
_logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider);
return Render(ExternalLoginStatus.Ok); // Everything Ok, login user
}
if (result.RequiresTwoFactor)
{
return Render(ExternalLoginStatus.TwoFactor);
}
if (result.IsLockedOut)
{
return Render(ExternalLoginStatus.Lockout);
}
else
{
// If the user does not have an account, then ask the user to create an account.
// ViewData["ReturnUrl"] = returnUrl;
// ViewData["LoginProvider"] = info.LoginProvider;
// var email = info.Principal.FindFirstValue(ClaimTypes.Email);
// return RedirectToAction("Index", "Home", new ExternalLoginCreateAccountViewModel { Email = email });
return Render(ExternalLoginStatus.CreateAccount);
}
}
[HttpPost("ExternalLoginCreateAccount")]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ExternalLoginCreateAccount([FromBody]ExternalLoginConfirmationViewModel model, string returnUrl = null)
{
// Get the information about the user from the external login provider
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return BadRequest("External login information cannot be accessed, try again.");
}
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user);
if (result.Succeeded)
{
result = await _userManager.AddLoginAsync(user, info);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider);
return Ok(); // Everything ok
}
}
return BadRequest(new[] { "Email already exists" });
}
[HttpGet("ConfirmEmail")]
[AllowAnonymous]
public async Task<IActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return View("Error");
}
var result = await _userManager.ConfirmEmailAsync(user, code);
return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
[HttpGet("ForgotPassword")]
[AllowAnonymous]
public IActionResult ForgotPassword()
{
return View();
}
[HttpPost("ForgotPassword")]
[AllowAnonymous]
public async Task<IActionResult> ForgotPassword([FromBody]ForgotPasswordViewModel model)
{
var currentUser = await _userManager.FindByNameAsync(model.Email);
if (currentUser == null || !(await _userManager.IsEmailConfirmedAsync(currentUser)))
{
// Don't reveal that the user does not exist or is not confirmed
return View("ForgotPasswordConfirmation");
}
// For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
var code = await _userManager.GeneratePasswordResetTokenAsync(currentUser);
var host = Request.Scheme + "://" + Request.Host;
var callbackUrl = host + "?userId=" + currentUser.Id + "&passwordResetCode=" + code;
var confirmationLink = "<a class='btn-primary' href=\"" + callbackUrl + "\">Reset your password</a>";
await _emailSender.SendEmailAsync(MailType.ForgetPassword, new EmailModel { To = model.Email }, confirmationLink);
return Json(new { });
}
[HttpPost("resetpassword")]
[AllowAnonymous]
public async Task<IActionResult> ResetPassword([FromBody]ResetPasswordViewModel model)
{
var user = await _userManager.FindByNameAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return Ok("Reset confirmed");
}
var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password);
if (result.Succeeded)
{
return Ok("Reset confirmed"); ;
}
AddErrors(result);
return BadRequest(ModelState.GetModelErrors());
}
[HttpGet("SendCode")]
[AllowAnonymous]
public async Task<ActionResult> SendCode(string returnUrl = null, bool rememberMe = false)
{
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return BadRequest("Error");
}
var userFactors = await _userManager.GetValidTwoFactorProvidersAsync(user);
var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
[HttpPost("SendCode")]
[AllowAnonymous]
public async Task<IActionResult> SendCode([FromBody]SendCodeViewModel model)
{
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return BadRequest("Error");
}
// Generate the token and send it
var code = await _userManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider);
if (string.IsNullOrWhiteSpace(code))
{
return BadRequest("Error");
}
var message = "Your security code is: " + code;
if (model.SelectedProvider == "Email")
{
await _emailSender.SendEmailAsync(MailType.SecurityCode, new EmailModel { }, null);
//await _emailSender.SendEmailAsync(Email, await _userManager.GetEmailAsync(user), "Security Code", message);
}
else if (model.SelectedProvider == "Phone")
{
await _smsSender.SendSmsTwillioAsync(await _userManager.GetPhoneNumberAsync(user), message);
}
return RedirectToAction(nameof(VerifyCode), new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
}
[HttpGet("VerifyCode")]
[AllowAnonymous]
public async Task<IActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null)
{
// Require that the user has already logged in via username/password or external login
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return BadRequest("Error");
}
return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
[HttpPost("VerifyCode")]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyCode(VerifyCodeViewModel model)
{
// The following code protects for brute force attacks against the two factor codes.
// If a user enters incorrect codes for a specified amount of time then the user account
// will be locked out for a specified amount of time.
var result = await _signInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser);
if (result.Succeeded)
{
return RedirectToLocal(model.ReturnUrl);
}
if (result.IsLockedOut)
{
_logger.LogWarning(7, "User account locked out.");
return View("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid code.");
return View(model);
}
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
private Task<ApplicationUser> GetCurrentUserAsync()
{
return _userManager.GetUserAsync(HttpContext.User);
}
private IActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction(nameof(HomeController.Index), "Home");
}
}
private IActionResult Render(ExternalLoginStatus status)
{
return RedirectToAction("Index", "Home", new { externalLoginStatus = (int)status });
}
#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;
internal class TestApp
{
private static unsafe long test_6(ref B b)
{
fixed (B* pb = &b)
{
return pb->m_bval;
}
}
private static unsafe long test_13(B* pb)
{
return (--pb)->m_bval;
}
private static unsafe long test_20(B* pb, long i)
{
return (&pb[-(i << (int)i)])->m_bval;
}
private static unsafe long test_27(AA* px)
{
return AA.get_pb(px)->m_bval;
}
private static unsafe long test_34(long pb)
{
return ((B*)checked((long)pb))->m_bval;
}
private static unsafe long test_41(B* pb)
{
return (pb++)[0].m_bval;
}
private static unsafe long test_48(B[,] ab, long i, long j)
{
fixed (B* pb = &ab[i, j])
{
return pb[0].m_bval;
}
}
private static unsafe long test_55(B* pb1)
{
B* pb;
return (pb = pb1 - 8)[0].m_bval;
}
private static unsafe long test_62(B* pb, B* pb1, B* pb2)
{
return (pb = pb + (pb2 - pb1))[0].m_bval;
}
private static unsafe long test_69(B* pb1, bool trig)
{
fixed (B* pb = &AA.s_x.m_b)
{
return (trig ? pb : pb1)[0].m_bval;
}
}
private static unsafe long test_76(byte* pb)
{
return ((B*)(pb + 7))[0].m_bval;
}
private static unsafe long test_83(B b)
{
return AA.get_bv1((&b));
}
private static unsafe long test_90()
{
fixed (B* pb = &AA.s_x.m_b)
{
return AA.get_bv1(pb);
}
}
private static unsafe long test_97(B* pb, long i)
{
return AA.get_bv1((&pb[i * 2]));
}
private static unsafe long test_104(B* pb1, B* pb2)
{
return AA.get_bv1((pb1 >= pb2 ? pb1 : null));
}
private static unsafe long test_111(long pb)
{
return AA.get_bv1(((B*)pb));
}
private static unsafe long test_118(B* pb)
{
return AA.get_bv2(*pb);
}
private static unsafe long test_125(B[] ab, long i)
{
fixed (B* pb = &ab[i])
{
return AA.get_bv2(*pb);
}
}
private static unsafe long test_132(B* pb)
{
return AA.get_bv2(*(pb += 6));
}
private static unsafe long test_139(B* pb, long[,,] i, long ii)
{
return AA.get_bv2(*(&pb[++i[--ii, 0, 0]]));
}
private static unsafe long test_146(AA* px)
{
return AA.get_bv2(*((B*)AA.get_pb_i(px)));
}
private static unsafe long test_153(byte diff, A* pa)
{
return AA.get_bv2(*((B*)(((byte*)pa) + diff)));
}
private static unsafe long test_160()
{
AA loc_x = new AA(0, 100);
return AA.get_bv3(ref *(&loc_x.m_b));
}
private static unsafe long test_167(B[][] ab, long i, long j)
{
fixed (B* pb = &ab[i][j])
{
return AA.get_bv3(ref *pb);
}
}
private static unsafe long test_174(B* pb1, long i)
{
B* pb;
return AA.get_bv3(ref *(pb = (B*)(((byte*)pb1) + i * sizeof(B))));
}
private static unsafe long test_181(B* pb, long[,,] i, long ii, byte jj)
{
return AA.get_bv3(ref *(&pb[i[ii - jj, 0, ii - jj] = ii - 1]));
}
private static unsafe long test_188(ulong ub, byte lb)
{
return AA.get_bv3(ref *((B*)(ub | lb)));
}
private static unsafe long test_195(long p, long s)
{
return AA.get_bv3(ref *((B*)((p >> 4) | s)));
}
private static unsafe long test_202(B[] ab)
{
fixed (B* pb = &ab[0])
{
return pb->m_bval == 100 ? 100 : 101;
}
}
private static unsafe long test_209(B* pb)
{
return (++pb)->m_bval == 100 ? 100 : 101;
}
private static unsafe long test_216(B* pb, long[] i, long ii)
{
return (&pb[i[ii]])->m_bval == 100 ? 100 : 101;
}
private static unsafe long test_223(AA* px)
{
return (AA.get_pb_1(px) + 1)->m_bval == 100 ? 100 : 101;
}
private static unsafe long test_230(long pb)
{
return ((B*)checked(((long)pb) + 1))->m_bval == 100 ? 100 : 101;
}
private static unsafe long test_237(B* pb)
{
return AA.get_i1(&(pb--)->m_bval);
}
private static unsafe long test_244(AA[,] ab, long i)
{
long j = 0;
fixed (B* pb = &ab[--i, ++j].m_b)
{
return AA.get_i1(&pb->m_bval);
}
}
private static unsafe long test_251(B* pb1, long i)
{
B* pb;
return AA.get_i1(&(pb = pb1 + i)->m_bval);
}
private static unsafe long test_258(B* pb1, B* pb2)
{
return AA.get_i1(&(pb1 > pb2 ? pb2 : null)->m_bval);
}
private static unsafe long test_265(long pb)
{
return AA.get_i1(&((B*)pb)->m_bval);
}
private static unsafe long test_272(double* pb, long i)
{
return AA.get_i1(&((B*)(pb + i))->m_bval);
}
private static unsafe long test_279(ref B b)
{
fixed (B* pb = &b)
{
return AA.get_i2(pb->m_bval);
}
}
private static unsafe long test_286(B* pb)
{
return AA.get_i2((--pb)->m_bval);
}
private static unsafe long test_293(B* pb, long i)
{
return AA.get_i2((&pb[-(i << (int)i)])->m_bval);
}
private static unsafe long test_300(AA* px)
{
return AA.get_i2(AA.get_pb(px)->m_bval);
}
private static unsafe long test_307(long pb)
{
return AA.get_i2(((B*)checked((long)pb))->m_bval);
}
private static unsafe long test_314(B* pb)
{
return AA.get_i3(ref (pb++)->m_bval);
}
private static unsafe long test_321(B[,] ab, long i, long j)
{
fixed (B* pb = &ab[i, j])
{
return AA.get_i3(ref pb->m_bval);
}
}
private static unsafe long test_328(B* pb1)
{
B* pb;
return AA.get_i3(ref (pb = pb1 - 8)->m_bval);
}
private static unsafe long test_335(B* pb, B* pb1, B* pb2)
{
return AA.get_i3(ref (pb = pb + (pb2 - pb1))->m_bval);
}
private static unsafe long test_342(B* pb1, bool trig)
{
fixed (B* pb = &AA.s_x.m_b)
{
return AA.get_i3(ref (trig ? pb : pb1)->m_bval);
}
}
private static unsafe long test_349(byte* pb)
{
return AA.get_i3(ref ((B*)(pb + 7))->m_bval);
}
private static unsafe long test_356(B b)
{
return AA.get_bv1((&b)) != 100 ? 99 : 100;
}
private static unsafe long test_363()
{
fixed (B* pb = &AA.s_x.m_b)
{
return AA.get_bv1(pb) != 100 ? 99 : 100;
}
}
private static unsafe long test_370(B* pb, long i)
{
return AA.get_bv1((&pb[i * 2])) != 100 ? 99 : 100;
}
private static unsafe long test_377(B* pb1, B* pb2)
{
return AA.get_bv1((pb1 >= pb2 ? pb1 : null)) != 100 ? 99 : 100;
}
private static unsafe long test_384(long pb)
{
return AA.get_bv1(((B*)pb)) != 100 ? 99 : 100;
}
private static unsafe long test_391(B* pb)
{
long[] e = { 100, 101 };
return e[pb + 1 > pb ? 0 : 1];
}
private static unsafe int Main()
{
AA loc_x = new AA(0, 100);
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_6(ref loc_x.m_b) != 100)
{
Console.WriteLine("test_6() failed.");
return 106;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_13(&loc_x.m_b + 1) != 100)
{
Console.WriteLine("test_13() failed.");
return 113;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_20(&loc_x.m_b + 2, 1) != 100)
{
Console.WriteLine("test_20() failed.");
return 120;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_27(&loc_x) != 100)
{
Console.WriteLine("test_27() failed.");
return 127;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_34((long)(long)&loc_x.m_b) != 100)
{
Console.WriteLine("test_34() failed.");
return 134;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_41(&loc_x.m_b) != 100)
{
Console.WriteLine("test_41() failed.");
return 141;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_48(new B[,] { { new B(), new B() }, { new B(), loc_x.m_b } }, 1, 1) != 100)
{
Console.WriteLine("test_48() failed.");
return 148;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_55(&loc_x.m_b + 8) != 100)
{
Console.WriteLine("test_55() failed.");
return 155;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_62(&loc_x.m_b - 2, &loc_x.m_b - 1, &loc_x.m_b + 1) != 100)
{
Console.WriteLine("test_62() failed.");
return 162;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_69(&loc_x.m_b, true) != 100)
{
Console.WriteLine("test_69() failed.");
return 169;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_76(((byte*)(&loc_x.m_b)) - 7) != 100)
{
Console.WriteLine("test_76() failed.");
return 176;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_83(loc_x.m_b) != 100)
{
Console.WriteLine("test_83() failed.");
return 183;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_90() != 100)
{
Console.WriteLine("test_90() failed.");
return 190;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_97(&loc_x.m_b - 2, 1) != 100)
{
Console.WriteLine("test_97() failed.");
return 197;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_104(&loc_x.m_b, &loc_x.m_b) != 100)
{
Console.WriteLine("test_104() failed.");
return 204;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_111((long)&loc_x.m_b) != 100)
{
Console.WriteLine("test_111() failed.");
return 211;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_118(&loc_x.m_b) != 100)
{
Console.WriteLine("test_118() failed.");
return 218;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_125(new B[] { new B(), new B(), loc_x.m_b }, 2) != 100)
{
Console.WriteLine("test_125() failed.");
return 225;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_132(&loc_x.m_b - 6) != 100)
{
Console.WriteLine("test_132() failed.");
return 232;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_139(&loc_x.m_b - 1, new long[,,] { { { 0 } }, { { 0 } } }, 2) != 100)
{
Console.WriteLine("test_139() failed.");
return 239;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_146(&loc_x) != 100)
{
Console.WriteLine("test_146() failed.");
return 246;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_153((byte)(((long)&loc_x.m_b) - ((long)&loc_x.m_a)), &loc_x.m_a) != 100)
{
Console.WriteLine("test_153() failed.");
return 253;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_160() != 100)
{
Console.WriteLine("test_160() failed.");
return 260;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_167(new B[][] { new B[] { new B(), new B() }, new B[] { new B(), loc_x.m_b } }, 1, 1) != 100)
{
Console.WriteLine("test_167() failed.");
return 267;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_174(&loc_x.m_b - 8, 8) != 100)
{
Console.WriteLine("test_174() failed.");
return 274;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_181(&loc_x.m_b - 1, new long[,,] { { { 0 } }, { { 0 } } }, 2, 2) != 100)
{
Console.WriteLine("test_181() failed.");
return 281;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_188(((ulong)&loc_x.m_b) & (~(ulong)0xff), unchecked((byte)&loc_x.m_b)) != 100)
{
Console.WriteLine("test_188() failed.");
return 288;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_195(((long)(&loc_x.m_b)) << 4, ((long)(&loc_x.m_b)) & 0xff000000) != 100)
{
Console.WriteLine("test_195() failed.");
return 295;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_202(new B[] { loc_x.m_b }) != 100)
{
Console.WriteLine("test_202() failed.");
return 302;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_209(&loc_x.m_b - 1) != 100)
{
Console.WriteLine("test_209() failed.");
return 309;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_216(&loc_x.m_b - 1, new long[] { 0, 1 }, 1) != 100)
{
Console.WriteLine("test_216() failed.");
return 316;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_223(&loc_x) != 100)
{
Console.WriteLine("test_223() failed.");
return 323;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_230((long)(((long)&loc_x.m_b) - 1)) != 100)
{
Console.WriteLine("test_230() failed.");
return 330;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_237(&loc_x.m_b) != 100)
{
Console.WriteLine("test_237() failed.");
return 337;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_244(new AA[,] { { new AA(), new AA() }, { new AA(), loc_x } }, 2) != 100)
{
Console.WriteLine("test_244() failed.");
return 344;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_251(&loc_x.m_b - 8, 8) != 100)
{
Console.WriteLine("test_251() failed.");
return 351;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_258(&loc_x.m_b + 1, &loc_x.m_b) != 100)
{
Console.WriteLine("test_258() failed.");
return 358;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_265((long)&loc_x.m_b) != 100)
{
Console.WriteLine("test_265() failed.");
return 365;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_272(((double*)(&loc_x.m_b)) - 4, 4) != 100)
{
Console.WriteLine("test_272() failed.");
return 372;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_279(ref loc_x.m_b) != 100)
{
Console.WriteLine("test_279() failed.");
return 379;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_286(&loc_x.m_b + 1) != 100)
{
Console.WriteLine("test_286() failed.");
return 386;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_293(&loc_x.m_b + 2, 1) != 100)
{
Console.WriteLine("test_293() failed.");
return 393;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_300(&loc_x) != 100)
{
Console.WriteLine("test_300() failed.");
return 400;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_307((long)(long)&loc_x.m_b) != 100)
{
Console.WriteLine("test_307() failed.");
return 407;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_314(&loc_x.m_b) != 100)
{
Console.WriteLine("test_314() failed.");
return 414;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_321(new B[,] { { new B(), new B() }, { new B(), loc_x.m_b } }, 1, 1) != 100)
{
Console.WriteLine("test_321() failed.");
return 421;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_328(&loc_x.m_b + 8) != 100)
{
Console.WriteLine("test_328() failed.");
return 428;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_335(&loc_x.m_b - 2, &loc_x.m_b - 1, &loc_x.m_b + 1) != 100)
{
Console.WriteLine("test_335() failed.");
return 435;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_342(&loc_x.m_b, true) != 100)
{
Console.WriteLine("test_342() failed.");
return 442;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_349(((byte*)(&loc_x.m_b)) - 7) != 100)
{
Console.WriteLine("test_349() failed.");
return 449;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_356(loc_x.m_b) != 100)
{
Console.WriteLine("test_356() failed.");
return 456;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_363() != 100)
{
Console.WriteLine("test_363() failed.");
return 463;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_370(&loc_x.m_b - 2, 1) != 100)
{
Console.WriteLine("test_370() failed.");
return 470;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_377(&loc_x.m_b, &loc_x.m_b) != 100)
{
Console.WriteLine("test_377() failed.");
return 477;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_384((long)&loc_x.m_b) != 100)
{
Console.WriteLine("test_384() failed.");
return 484;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_391((B*)1) != 100)
{
Console.WriteLine("test_391() failed.");
return 491;
}
Console.WriteLine("All tests passed.");
return 100;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// System.Net.HttpConnection
//
// Author:
// Gonzalo Paniagua Javier (gonzalo.mono@gmail.com)
//
// Copyright (c) 2005-2009 Novell, Inc. (http://www.novell.com)
// Copyright (c) 2012 Xamarin, Inc. (http://xamarin.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.IO;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
namespace System.Net
{
internal sealed class HttpConnection
{
private static AsyncCallback s_onreadCallback = new AsyncCallback(OnRead);
private const int BufferSize = 8192;
private Socket _socket;
private Stream _stream;
private HttpEndPointListener _epl;
private MemoryStream _memoryStream;
private byte[] _buffer;
private HttpListenerContext _context;
private StringBuilder _currentLine;
private ListenerPrefix _prefix;
private HttpRequestStream _requestStream;
private HttpResponseStream _responseStream;
private bool _chunked;
private int _reuses;
private bool _contextBound;
private bool _secure;
private X509Certificate _cert;
private int _timeout = 90000; // 90k ms for first request, 15k ms from then on
private Timer _timer;
private IPEndPoint _localEndPoint;
private HttpListener _lastListener;
private int[] _clientCertErrors;
private X509Certificate2 _clientCert;
private SslStream _sslStream;
private InputState _inputState = InputState.RequestLine;
private LineState _lineState = LineState.None;
private int _position;
public HttpConnection(Socket sock, HttpEndPointListener epl, bool secure, X509Certificate cert)
{
_socket = sock;
_epl = epl;
_secure = secure;
_cert = cert;
if (secure == false)
{
_stream = new NetworkStream(sock, false);
}
else
{
#pragma warning disable CA5359
_sslStream = epl.Listener.CreateSslStream(new NetworkStream(sock, false), false, (t, c, ch, e) =>
{
if (c == null)
{
return true;
}
var c2 = c as X509Certificate2;
if (c2 == null)
{
c2 = new X509Certificate2(c.GetRawCertData());
}
_clientCert = c2;
_clientCertErrors = new int[] { (int)e };
return true;
});
#pragma warning restore CA5359
_stream = _sslStream;
}
_timer = new Timer(OnTimeout, null, Timeout.Infinite, Timeout.Infinite);
if (_sslStream != null) {
_sslStream.AuthenticateAsServer (_cert, true, (SslProtocols)ServicePointManager.SecurityProtocol, false);
}
Init();
}
internal int[] ClientCertificateErrors
{
get { return _clientCertErrors; }
}
internal X509Certificate2 ClientCertificate
{
get { return _clientCert; }
}
internal SslStream SslStream
{
get { return _sslStream; }
}
private void Init()
{
_contextBound = false;
_requestStream = null;
_responseStream = null;
_prefix = null;
_chunked = false;
_memoryStream = new MemoryStream();
_position = 0;
_inputState = InputState.RequestLine;
_lineState = LineState.None;
_context = new HttpListenerContext(this);
}
public Stream ConnectedStream => _stream;
public bool IsClosed
{
get { return (_socket == null); }
}
public int Reuses
{
get { return _reuses; }
}
public IPEndPoint LocalEndPoint
{
get
{
if (_localEndPoint != null)
return _localEndPoint;
_localEndPoint = (IPEndPoint)_socket.LocalEndPoint;
return _localEndPoint;
}
}
public IPEndPoint RemoteEndPoint
{
get { return (IPEndPoint)_socket.RemoteEndPoint; }
}
public bool IsSecure
{
get { return _secure; }
}
public ListenerPrefix Prefix
{
get { return _prefix; }
set { _prefix = value; }
}
private void OnTimeout(object unused)
{
CloseSocket();
Unbind();
}
public void BeginReadRequest()
{
if (_buffer == null)
_buffer = new byte[BufferSize];
try
{
if (_reuses == 1)
_timeout = 15000;
_timer.Change(_timeout, Timeout.Infinite);
_stream.BeginRead(_buffer, 0, BufferSize, s_onreadCallback, this);
}
catch
{
_timer.Change(Timeout.Infinite, Timeout.Infinite);
CloseSocket();
Unbind();
}
}
public HttpRequestStream GetRequestStream(bool chunked, long contentlength)
{
if (_requestStream == null)
{
byte[] buffer = _memoryStream.GetBuffer();
int length = (int)_memoryStream.Length;
_memoryStream = null;
if (chunked)
{
_chunked = true;
_context.Response.SendChunked = true;
_requestStream = new ChunkedInputStream(_context, _stream, buffer, _position, length - _position);
}
else
{
_requestStream = new HttpRequestStream(_stream, buffer, _position, length - _position, contentlength);
}
}
return _requestStream;
}
public HttpResponseStream GetResponseStream()
{
if (_responseStream == null)
{
HttpListener listener = _context._listener;
if (listener == null)
return new HttpResponseStream(_stream, _context.Response, true);
_responseStream = new HttpResponseStream(_stream, _context.Response, listener.IgnoreWriteExceptions);
}
return _responseStream;
}
private static void OnRead(IAsyncResult ares)
{
HttpConnection cnc = (HttpConnection)ares.AsyncState;
cnc.OnReadInternal(ares);
}
private void OnReadInternal(IAsyncResult ares)
{
_timer.Change(Timeout.Infinite, Timeout.Infinite);
int nread = -1;
try
{
nread = _stream.EndRead(ares);
_memoryStream.Write(_buffer, 0, nread);
if (_memoryStream.Length > 32768)
{
SendError(HttpStatusDescription.Get(400), 400);
Close(true);
return;
}
}
catch
{
if (_memoryStream != null && _memoryStream.Length > 0)
SendError();
if (_socket != null)
{
CloseSocket();
Unbind();
}
return;
}
if (nread == 0)
{
CloseSocket();
Unbind();
return;
}
if (ProcessInput(_memoryStream))
{
if (!_context.HaveError)
_context.Request.FinishInitialization();
if (_context.HaveError)
{
SendError();
Close(true);
return;
}
if (!_epl.BindContext(_context))
{
const int NotFoundErrorCode = 404;
SendError(HttpStatusDescription.Get(NotFoundErrorCode), NotFoundErrorCode);
Close(true);
return;
}
HttpListener listener = _context._listener;
if (_lastListener != listener)
{
RemoveConnection();
listener.AddConnection(this);
_lastListener = listener;
}
_contextBound = true;
listener.RegisterContext(_context);
return;
}
_stream.BeginRead(_buffer, 0, BufferSize, s_onreadCallback, this);
}
private void RemoveConnection()
{
if (_lastListener == null)
_epl.RemoveConnection(this);
else
_lastListener.RemoveConnection(this);
}
private enum InputState
{
RequestLine,
Headers
}
private enum LineState
{
None,
CR,
LF
}
// true -> done processing
// false -> need more input
private bool ProcessInput(MemoryStream ms)
{
byte[] buffer = ms.GetBuffer();
int len = (int)ms.Length;
int used = 0;
string line;
while (true)
{
if (_context.HaveError)
return true;
if (_position >= len)
break;
try
{
line = ReadLine(buffer, _position, len - _position, ref used);
_position += used;
}
catch
{
_context.ErrorMessage = HttpStatusDescription.Get(400);
_context.ErrorStatus = 400;
return true;
}
if (line == null)
break;
if (line == "")
{
if (_inputState == InputState.RequestLine)
continue;
_currentLine = null;
ms = null;
return true;
}
if (_inputState == InputState.RequestLine)
{
_context.Request.SetRequestLine(line);
_inputState = InputState.Headers;
}
else
{
try
{
_context.Request.AddHeader(line);
}
catch (Exception e)
{
_context.ErrorMessage = e.Message;
_context.ErrorStatus = 400;
return true;
}
}
}
if (used == len)
{
ms.SetLength(0);
_position = 0;
}
return false;
}
private string ReadLine(byte[] buffer, int offset, int len, ref int used)
{
if (_currentLine == null)
_currentLine = new StringBuilder(128);
int last = offset + len;
used = 0;
for (int i = offset; i < last && _lineState != LineState.LF; i++)
{
used++;
byte b = buffer[i];
if (b == 13)
{
_lineState = LineState.CR;
}
else if (b == 10)
{
_lineState = LineState.LF;
}
else
{
_currentLine.Append((char)b);
}
}
string result = null;
if (_lineState == LineState.LF)
{
_lineState = LineState.None;
result = _currentLine.ToString();
_currentLine.Length = 0;
}
return result;
}
public void SendError(string msg, int status)
{
try
{
HttpListenerResponse response = _context.Response;
response.StatusCode = status;
response.ContentType = "text/html";
string description = HttpStatusDescription.Get(status);
string str;
if (msg != null)
str = string.Format("<h1>{0} ({1})</h1>", description, msg);
else
str = string.Format("<h1>{0}</h1>", description);
byte[] error = Encoding.Default.GetBytes(str);
response.Close(error, false);
}
catch
{
// response was already closed
}
}
public void SendError()
{
SendError(_context.ErrorMessage, _context.ErrorStatus);
}
private void Unbind()
{
if (_contextBound)
{
_epl.UnbindContext(_context);
_contextBound = false;
}
}
public void Close()
{
Close(false);
}
private void CloseSocket()
{
if (_socket == null)
return;
try
{
_socket.Close();
}
catch { }
finally
{
_socket = null;
}
RemoveConnection();
}
internal void Close(bool force)
{
if (_socket != null)
{
Stream st = GetResponseStream();
if (st != null)
st.Close();
_responseStream = null;
}
if (_socket != null)
{
force |= !_context.Request.KeepAlive;
if (!force)
force = (_context.Response.Headers[HttpKnownHeaderNames.Connection] == HttpHeaderStrings.Close);
if (!force && _context.Request.FlushInput())
{
if (_chunked && _context.Response.ForceCloseChunked == false)
{
// Don't close. Keep working.
_reuses++;
Unbind();
Init();
BeginReadRequest();
return;
}
_reuses++;
Unbind();
Init();
BeginReadRequest();
return;
}
Socket s = _socket;
_socket = null;
try
{
if (s != null)
s.Shutdown(SocketShutdown.Both);
}
catch
{
}
finally
{
if (s != null)
s.Close();
}
Unbind();
RemoveConnection();
return;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using log4net;
#if !LATE_BIND
using HSVCALCULATELib;
#endif
using HFMCONSTANTSLib;
using Command;
using HFMCmd;
namespace HFM
{
public enum EConsolidationType : short
{
All = tagCONSOLIDATIONTYPE.CONSOLIDATE_ALL,
AllWithData = tagCONSOLIDATIONTYPE.CONSOLIDATE_ALLWITHDATA,
EntityOnly = tagCONSOLIDATIONTYPE.CONSOLIDATE_ENTITYONLY,
ForceEntityOnly = tagCONSOLIDATIONTYPE.CONSOLIDATE_FORCEENTITYONLY,
Impacted = tagCONSOLIDATIONTYPE.CONSOLIDATE_IMPACTED
}
/// <summary>
/// Wraps the HsvCalculate module, exposing its functionality for performing
/// calculations, allocations, translations, consolidations etc.
/// </summary>
public class Calculate
{
// Reference to class logger
protected static readonly ILog _log = LogManager.GetLogger(
System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Reference to the Session object
private readonly Session _session;
// Reference to a Metadata object
private readonly Metadata _metadata;
// Reference to HFM HsvCalculate COM object
#if LATE_BIND
private readonly dynamic _hsvCalculate;
#else
private readonly HsvCalculate _hsvCalculate;
#endif
public Calculate(Session session)
{
_log.Trace("Constructing Calculate object");
_session = session;
_metadata = session.Metadata;
#if LATE_BIND
_hsvCalculate = session.HsvSession.Calculate;
#else
_hsvCalculate = (HsvCalculate)session.HsvSession.Calculate;
#endif
}
[Command("Performs an allocation")]
public void Allocate(
[Parameter("The scenario(s) in which to perform the allocation",
Alias = "Scenario")]
IEnumerable<string> scenarios,
[Parameter("The year(s) for which to perform the allocation",
Alias = "Year")]
IEnumerable<string> years,
[Parameter("The period(s) over which the allocation should be performed",
Alias = "Period")]
IEnumerable<string> periods,
[Parameter("The entity member(s) for which the allocation should be performed",
Alias = "Entity")]
IEnumerable<string> entities,
[Parameter("The value member(s) for which the allocation should be peformed",
Alias = "Value")]
IEnumerable<string> values,
IOutput output)
{
var ops = _metadata.DoSubcubeOp("Allocating", scenarios, years, periods, entities, values, output,
(pov) => _hsvCalculate.Allocate(pov.Scenario.Id, pov.Year.Id, pov.Period.Id,
pov.Entity.Id, pov.Entity.ParentId, pov.Value.Id));
_log.InfoFormat("Allocate completed: {0} performed", ops);
}
[Command("Performs a calculation", Name = "Calculate")]
public void ChartLogic(
[Parameter("The scenario(s) in which to perform the calculation",
Alias = "Scenario")]
IEnumerable<string> scenarios,
[Parameter("The year(s) for which to perform the calculation",
Alias = "Year")]
IEnumerable<string> years,
[Parameter("The period(s) over which the calculation should be performed",
Alias = "Period")]
IEnumerable<string> periods,
[Parameter("The entities for which the calculation should be performed",
Alias = "Entity")]
IEnumerable<string> entities,
[Parameter("The value member(s) for which the calculation should be peformed",
Alias = "Value")]
IEnumerable<string> values,
[Parameter("Flag indicating whether to force a calculation when not needed",
DefaultValue = false)]
bool force,
IOutput output)
{
var ops = _metadata.DoSubcubeOp("Caclulating", scenarios, years, periods, entities, values, output,
(pov) => _hsvCalculate.ChartLogic(pov.Scenario.Id, pov.Year.Id, pov.Period.Id,
pov.Entity.Id, pov.Entity.ParentId, pov.Value.Id, force));
_log.InfoFormat("Calculate completed: {0} performed", ops);
}
[Command("Performs a translation")]
public void Translate(
[Parameter("The scenario(s) in which to perform the translation",
Alias = "Scenario")]
IEnumerable<string> scenarios,
[Parameter("The year(s) for which to perform the translation",
Alias = "Year")]
IEnumerable<string> years,
[Parameter("The period(s) over which the translation should be performed",
Alias = "Period")]
IEnumerable<string> periods,
[Parameter("The entities for which the translation should be performed",
Alias = "Entity")]
IEnumerable<string> entities,
[Parameter("The value member(s) for which the translation should be peformed",
Alias = "Value")]
IEnumerable<string> values,
[Parameter("Flag indicating whether to force a translation when not needed",
DefaultValue = false)]
bool force,
IOutput output)
{
var ops = _metadata.DoSubcubeOp("Translating", scenarios, years, periods, entities, values, output,
(pov) => _hsvCalculate.Translate(pov.Scenario.Id, pov.Year.Id, pov.Period.Id,
pov.Entity.Id, pov.Entity.ParentId, pov.Value.Id, force, true));
_log.InfoFormat("Translate completed: {0} performed", ops);
}
[Command("Performs a consolidation")]
public void Consolidate(
[Parameter("The scenario(s) in which to perform the consolidation",
Alias = "Scenario")]
IEnumerable<string> scenarios,
[Parameter("The year(s) for which to perform the consolidation",
Alias = "Year")]
IEnumerable<string> years,
[Parameter("The period(s) over which the consolidation should be performed",
Alias = "Period")]
IEnumerable<string> periods,
[Parameter("The entities for which the consolidation should be performed",
Alias = "Entity")]
IEnumerable<string> entities,
[Parameter("The type of consolidation to perform",
DefaultValue = EConsolidationType.Impacted)]
EConsolidationType consolidationType,
IOutput output)
{
int consols = 0, skipped = 0;
var slice = new Slice(_metadata);
slice[EDimension.Scenario] = scenarios;
slice[EDimension.Year] = years;
slice[EDimension.Period] = periods;
slice[EDimension.Entity] = entities;
// Calculate number of iterations, and measure progress
var POVs = slice.Combos;
output.InitProgress("Consolidating", POVs.Length);
foreach(var pov in POVs) {
if(output.Cancelled) {
break;
}
if(ConsolidatePOV(pov, consolidationType, output)) { consols++; }
else { skipped++; }
}
output.EndProgress();
if(consolidationType == EConsolidationType.Impacted) {
_log.InfoFormat("Consolidation completed: {0} performed, {1} not needed",
consols, skipped);
}
else {
_log.InfoFormat("Consolidation completed: {0} performed", consols);
}
}
#if HFM_11_1_2_2
[Command("Performs an Equity Pick-up adjustment calculation",
Since = "11.1.2.2")]
public void CalculateEPU(
[Parameter("The scenario in which to perform the equity pick-up",
Alias = "Scenario")]
IEnumerable<string> scenarios,
[Parameter("The year for which to perform the equity pick-up",
Alias = "Year")]
IEnumerable<string> years,
[Parameter("The period(s) over which the equity pick-up should be performed",
Alias = "Period")]
IEnumerable<string> periods,
[Parameter("Flag indicating whether to recalculate equity pick-up for all owner-owned pairs, " +
"or only those pairs that have been impacted",
DefaultValue = false)]
bool force,
IOutput output)
{
int ops = 0;
var slice = new Slice(_metadata);
slice[EDimension.Scenario] = scenarios;
slice[EDimension.Year] = years;
slice[EDimension.Period] = periods;
// Calculate number of iterations, and measure progress
var POVs = slice.Combos;
output.InitProgress("Equity Pick-Up", POVs.Length);
foreach(var pov in POVs) {
_log.FineFormat("Equity Pick-Up for {0}", pov);
HFM.Try(() => _hsvCalculate.CalcEPU(pov.Scenario.Id, pov.Year.Id, pov.Period.Id, force));
ops++;
if(output.IterationComplete()) {
break;
}
}
output.EndProgress();
_log.InfoFormat("Equity Pick-Up completed: {0} performed", ops);
}
#endif
/// Calculates a Scenario/Year/Period/Entity combination specified in
/// the POV
internal void CalculatePOV(POV pov, bool force)
{
_log.FineFormat("Calculating {0}", pov);
HFM.Try(() => _hsvCalculate.ChartLogic(pov.Scenario.Id, pov.Year.Id, pov.Period.Id,
pov.Entity.Id, pov.Entity.ParentId, pov.Value.Id,
force));
}
/// Consolidates a Scenario/Year/Period/Entity combination specified in
/// the POV
internal bool ConsolidatePOV(POV pov, EConsolidationType consolidationType, IOutput output)
{
var si = _session.SystemInfo;
if(consolidationType != EConsolidationType.Impacted ||
ECalcStatus.NeedsConsolidation.IsSet(_session.Data.GetCalcStatus(pov))) {
_log.FineFormat("Consolidating {0}", pov);
si.MonitorBlockingTask(output);
HFM.Try(() => _hsvCalculate.Consolidate(pov.Scenario.Id, pov.Year.Id, pov.Period.Id,
pov.Entity.Id, pov.Entity.ParentId,
(short)consolidationType));
si.BlockingTaskComplete();
return true;
}
else {
_log.FineFormat("Consolidation not needed for {0}", pov);
return false;
}
}
}
}
| |
#if !MONO
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using NUnit.Framework;
using Palaso.Code;
using Palaso.Reporting;
using Palaso.UI.WindowsForms.Keyboarding;
using Palaso.UI.WindowsForms.Keyboarding.Windows;
using Palaso.WritingSystems;
namespace PalasoUIWindowsForms.Tests.Keyboarding
{
[TestFixture]
[Category("SkipOnTeamCity")] // TeamCity builds don't seem to be able to see any installed keyboards.
public class WindowsKeyboardControllerTests
{
private Form _window;
[TestFixtureSetUp]
public void FixtureSetup()
{
KeyboardController.Initialize();
}
[TestFixtureTearDown]
public void FixtureTearDown()
{
KeyboardController.Shutdown();
}
[SetUp]
public void Setup()
{
ErrorReport.IsOkToInteractWithUser = false;
}
private void RequiresWindow()
{
_window = new Form();
var box = new TextBox();
box.Dock = DockStyle.Fill;
_window.Controls.Add(box);
_window.Show();
box.Select();
Application.DoEvents();
}
[TearDown]
public void Teardown()
{
if (_window != null)
{
_window.Close();
_window.Dispose();
}
}
[Test]
[Category("Windows IME")]
public void GetAllKeyboards_GivesSeveral()
{
var keyboards = Keyboard.Controller.AllAvailableKeyboards;
Assert.Greater(keyboards.Count(), 1, "This test requires that the Windows IME has at least two languages installed.");
}
[Test]
public void ActivateKeyboard_BogusName_RaisesMessageBox()
{
Assert.Throws<ErrorReport.ProblemNotificationSentToUserException>(
() => Keyboard.Controller.SetKeyboard("foobar")
);
}
[Test]
public void ActivateKeyboard_BogusName_SecondTimeNoLongerRaisesMessageBox()
{
// the keyboardName for this test and above need to be different
const string keyboardName = "This should never be the same as the name of an installed keyboard";
try
{
Keyboard.Controller.SetKeyboard(keyboardName);
Assert.Fail("Should have thrown exception but didn't.");
}
catch (ErrorReport.ProblemNotificationSentToUserException)
{
}
Assert.DoesNotThrow(() => Keyboard.Controller.SetKeyboard(keyboardName));
}
[Test]
public void ActivateKeyboard_BogusNameWithLocale_DoesntThrow()
{
// REVIEW: Should this show an error?
Assert.DoesNotThrow(
() => Keyboard.Controller.SetKeyboard("foobar", "en-US")
);
}
IKeyboardDefinition FirstInactiveKeyboard
{
get
{
var keyboards = Keyboard.Controller.AllAvailableKeyboards.Where(x => x.Type == KeyboardType.System);
Assert.Greater(keyboards.Count(), 0, "This test requires that the Windows IME has at least one language installed.");
var d = keyboards.FirstOrDefault(x => x != Keyboard.Controller.ActiveKeyboard);
if (d == null)
return keyboards.First(); // Some tests have some value even if it is an active keyboard.
return d;
}
}
[Test]
[Category("Windows IME")]
public void WindowsIME_ActivateKeyboardUsingId_ReportsItWasActivated()
{
var d = FirstInactiveKeyboard;
Keyboard.Controller.SetKeyboard(d.Id);
Assert.AreEqual(d, Keyboard.Controller.ActiveKeyboard);
}
[Test]
[Category("Windows IME")]
public void WindowsIME_ActivateKeyboardUsingLayoutAndLocale_ReportsItWasActivated()
{
var d = FirstInactiveKeyboard;
Keyboard.Controller.SetKeyboard(d.Layout, d.Locale);
Assert.AreEqual(d, Keyboard.Controller.ActiveKeyboard);
}
[Test]
[Category("Windows IME")]
public void WindowsIME_ActivateKeyboardUsingKeyboard_ReportsItWasActivated()
{
var d = FirstInactiveKeyboard;
Keyboard.Controller.SetKeyboard(d);
Assert.AreEqual(d, Keyboard.Controller.ActiveKeyboard);
}
[Test]
[Category("Windows IME")]
public void WindowsIME_DeActivateKeyboard_RevertsToDefault()
{
var keyboards = Keyboard.Controller.AllAvailableKeyboards.Where(x => x.Type == KeyboardType.System);
Assert.Greater(keyboards.Count(), 1, "This test requires that the Windows IME has at least two languages installed.");
var d = GetNonDefaultKeyboard(keyboards.ToList());
d.Activate();
Assert.AreEqual(d, Keyboard.Controller.ActiveKeyboard);
Keyboard.Controller.ActivateDefaultKeyboard();
Assert.AreNotEqual(d, Keyboard.Controller.ActiveKeyboard);
}
private static IKeyboardDefinition GetNonDefaultKeyboard(IList<IKeyboardDefinition> keyboards)
{
// The default language is not necessarily the first one, so we have to make sure
// that we don't select the default one.
var defaultKeyboard =
Keyboard.Controller.GetKeyboard(InputLanguage.DefaultInputLanguage.LayoutName,
InputLanguage.DefaultInputLanguage.Culture.Name);
int index = keyboards.Count - 1;
while (index >= 0)
{
if (!keyboards[index].Equals(defaultKeyboard))
break;
index--;
}
if (index < 0)
Assert.Fail("Could not find a non-default keyboard !?");
return keyboards[index];
}
[Test]
[Category("Windows IME")]
public void WindowsIME_GetKeyboards_GivesSeveralButOnlyWindowsOnes()
{
var keyboards = Keyboard.Controller.AllAvailableKeyboards.Where(x => x.Type == KeyboardType.System);
Assert.Greater(keyboards.Count(), 1, "This test requires that the Windows IME has at least two languages installed.");
Assert.That(keyboards.Select(keyboard => ((KeyboardDescription)keyboard).Engine), Is.All.TypeOf<WinKeyboardAdaptor>());
}
[Test]
public void CheckWindowsAssumptions()
{
// For Windows we expect to have exactly one keyboard adaptor. If we implement
// additional ones, e.g. for Keyman, we might need to change some methods, e.g.
// ActivateDefaultKeyboard, DefaultForWritingSystem and CreateKeyboardDefinition.
Assert.That(KeyboardController.Adaptors.Length, Is.EqualTo(1));
Assert.That(KeyboardController.Adaptors.Select(adaptor => adaptor.Type),
Has.All.EqualTo(KeyboardType.System));
}
[Test]
public void ActivateDefaultKeyboard_ActivatesDefaultInputLanguage()
{
Keyboard.Controller.ActivateDefaultKeyboard();
Assert.That(WinKeyboardAdaptor.GetInputLanguage(Keyboard.Controller.ActiveKeyboard),
Is.EqualTo(InputLanguage.DefaultInputLanguage));
}
[Test]
public void CreateKeyboardDefinition_NewKeyboard_ReturnsNewObject()
{
var keyboard = Keyboard.Controller.CreateKeyboardDefinition("foo", "en-US");
Assert.That(keyboard, Is.Not.Null);
Assert.That(keyboard, Is.TypeOf<WinKeyboardDescription>());
Assert.That((keyboard as KeyboardDescription).InputLanguage, Is.Not.Null);
}
// TODO: Remove or implement
#if WANT_PORT
[Test]
[Category("Keyman6")]
[Platform(Exclude = "Linux", Reason = "Keyman not supported on Linux")]
public void Keyman6_GetKeyboards_GivesAtLeastOneAndOnlyKeyman6Ones()
{
RequiresKeyman6();
List<KeyboardController.KeyboardDescriptor> keyboards = KeyboardController.GetAvailableKeyboards(KeyboardController.Engines.Keyman6);
Assert.Greater(keyboards.Count, 0);
foreach (KeyboardController.KeyboardDescriptor keyboard in keyboards)
{
Assert.AreEqual(KeyboardController.Engines.Keyman6, keyboard.engine);
}
}
[Test]
[Category("Keyman6")]
[Platform(Exclude = "Linux", Reason = "Doesn't need to run on Linux")]
public void Keyman6_ActivateKeyboard_ReportsItWasActivated()
{
RequiresKeyman6();
RequiresWindow();
KeyboardController.KeyboardDescriptor d = KeyboardController.GetAvailableKeyboards(KeyboardController.Engines.Keyman6)[0];
Application.DoEvents(); //required
Keyboard.Controller.SetKeyboard(d.ShortName);
Application.DoEvents(); //required
Assert.AreEqual(d.ShortName, KeyboardController.GetActiveKeyboard());
}
[Test]
[Category("Keyman6")]
[Platform(Exclude = "Linux", Reason = "Doesn't need to run on Linux")]
public void Keyman6_DeActivateKeyboard_RevertsToDefault()
{
RequiresKeyman6();
var d = KeyboardController.GetAvailableKeyboards(KeyboardController.Engines.Keyman6)[0];
Keyboard.Controller.SetKeyboard(d.ShortName);
Application.DoEvents();//required
KeyboardController.DeactivateKeyboard();
Application.DoEvents();//required
Assert.AreNotEqual(d.ShortName, KeyboardController.GetActiveKeyboard());
}
[Test]
[Category("Keyman7")]
[Platform(Exclude = "Linux", Reason = "Doesn't need to run on Linux")]
public void Keyman7_ActivateKeyboard_ReportsItWasActivated()
{
RequiresKeyman7();
KeyboardController.KeyboardDescriptor d = KeyboardController.GetAvailableKeyboards(KeyboardController.Engines.Keyman7)[0];
Keyboard.Controller.SetKeyboard(d.ShortName);
Application.DoEvents();//required
Assert.AreEqual(d.ShortName, KeyboardController.GetActiveKeyboard());
}
[Test]
[Category("Keyman7")]
[Platform(Exclude = "Linux", Reason = "Doesn't need to run on Linux")]
public void Keyman7_DeActivateKeyboard_RevertsToDefault()
{
RequiresKeyman7();
KeyboardController.KeyboardDescriptor d = KeyboardController.GetAvailableKeyboards(KeyboardController.Engines.Keyman7)[0];
Keyboard.Controller.SetKeyboard(d.ShortName);
Application.DoEvents();//required
KeyboardController.DeactivateKeyboard();
Application.DoEvents();//required
Assert.AreNotEqual(d.ShortName, KeyboardController.GetActiveKeyboard());
}
[Test]
[Category("Keyman7")]
[Platform(Exclude = "Linux", Reason = "Doesn't need to run on Linux")]
public void Keyman7_GetKeyboards_GivesAtLeastOneAndOnlyKeyman7Ones()
{
RequiresKeyman7();
List<KeyboardController.KeyboardDescriptor> keyboards = KeyboardController.GetAvailableKeyboards(KeyboardController.Engines.Keyman7);
Assert.Greater(keyboards.Count, 0);
foreach (KeyboardController.KeyboardDescriptor keyboard in keyboards)
{
Assert.AreEqual(KeyboardController.Engines.Keyman7, keyboard.engine);
}
}
/// <summary>
/// The main thing here is that it doesn't crash doing a LoadLibrary()
/// </summary>
[Test]
public void NoKeyman7_GetKeyboards_DoesNotCrash()
{
KeyboardController.GetAvailableKeyboards(KeyboardController.Engines.Keyman7);
}
private static void RequiresKeyman6()
{
Assert.IsTrue(KeyboardController.EngineAvailable(KeyboardController.Engines.Keyman6),
"Keyman 6 Not available");
}
private static void RequiresKeyman7()
{
Assert.IsTrue(KeyboardController.EngineAvailable(KeyboardController.Engines.Keyman7),
"Keyman 7 Not available");
}
#endif
}
}
#endif
| |
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.ComponentModel;
using WeifenLuo.WinFormsUI.Docking;
namespace ATABBI.TexE.Customization
{
internal class VS2003DockPaneStrip : DockPaneStripBase
{
private class TabVS2003 : Tab
{
internal TabVS2003(IDockContent content)
: base(content)
{
}
private int m_tabX;
protected internal int TabX
{
get { return m_tabX; }
set { m_tabX = value; }
}
private int m_tabWidth;
protected internal int TabWidth
{
get { return m_tabWidth; }
set { m_tabWidth = value; }
}
private int m_maxWidth;
protected internal int MaxWidth
{
get { return m_maxWidth; }
set { m_maxWidth = value; }
}
private bool m_flag;
protected internal bool Flag
{
get { return m_flag; }
set { m_flag = value; }
}
}
protected override DockPaneStripBase.Tab CreateTab(IDockContent content)
{
return new TabVS2003(content);
}
private class DocumentButton : Label
{
public DocumentButton(Image image)
{
Image = image;
}
}
#region consts
private const int _ToolWindowStripGapLeft = 4;
private const int _ToolWindowStripGapRight = 3;
private const int _ToolWindowImageHeight = 16;
private const int _ToolWindowImageWidth = 16;
private const int _ToolWindowImageGapTop = 3;
private const int _ToolWindowImageGapBottom = 1;
private const int _ToolWindowImageGapLeft = 3;
private const int _ToolWindowImageGapRight = 2;
private const int _ToolWindowTextGapRight = 1;
private const int _ToolWindowTabSeperatorGapTop = 3;
private const int _ToolWindowTabSeperatorGapBottom = 3;
private const int _DocumentTabMaxWidth = 200;
private const int _DocumentButtonGapTop = 5;
private const int _DocumentButtonGapBottom = 5;
private const int _DocumentButtonGapBetween = 0;
private const int _DocumentButtonGapRight = 3;
private const int _DocumentTabGapTop = 3;
private const int _DocumentTabGapLeft = 3;
private const int _DocumentTabGapRight = 3;
private const int _DocumentIconGapLeft = 6;
private const int _DocumentIconHeight = 16;
private const int _DocumentIconWidth = 16;
#endregion
private InertButton m_buttonClose, m_buttonScrollLeft, m_buttonScrollRight;
private IContainer m_components;
private ToolTip m_toolTip;
/// <exclude/>
protected IContainer Components
{
get { return m_components; }
}
private int m_offsetX = 0;
private int OffsetX
{
get { return m_offsetX; }
set
{
m_offsetX = value;
#if DEBUG
if (m_offsetX > 0)
throw new InvalidOperationException();
#endif
}
}
#region Customizable Properties
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowStripGapLeft"]/*'/>
protected virtual int ToolWindowStripGapLeft
{
get { return _ToolWindowStripGapLeft; }
}
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowStripGapRight"]/*'/>
protected virtual int ToolWindowStripGapRight
{
get { return _ToolWindowStripGapRight; }
}
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowImageHeight"]/*'/>
protected virtual int ToolWindowImageHeight
{
get { return _ToolWindowImageHeight; }
}
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowImageWidth"]/*'/>
protected virtual int ToolWindowImageWidth
{
get { return _ToolWindowImageWidth; }
}
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowImageGapTop"]/*'/>
protected virtual int ToolWindowImageGapTop
{
get { return _ToolWindowImageGapTop; }
}
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowImageGapBottom"]/*'/>
protected virtual int ToolWindowImageGapBottom
{
get { return _ToolWindowImageGapBottom; }
}
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowImageGapLeft"]/*'/>
protected virtual int ToolWindowImageGapLeft
{
get { return _ToolWindowImageGapLeft; }
}
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowImageGapRight"]/*'/>
protected virtual int ToolWindowImageGapRight
{
get { return _ToolWindowImageGapRight; }
}
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowTextGapRight"]/*'/>
protected virtual int ToolWindowTextGapRight
{
get { return _ToolWindowTextGapRight; }
}
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowSeperatorGaptop"]/*'/>
protected virtual int ToolWindowTabSeperatorGapTop
{
get { return _ToolWindowTabSeperatorGapTop; }
}
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowSeperatorGapBottom"]/*'/>
protected virtual int ToolWindowTabSeperatorGapBottom
{
get { return _ToolWindowTabSeperatorGapBottom; }
}
private static Image _imageCloseEnabled = null;
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ImageCloseEnabled"]/*'/>
protected virtual Image ImageCloseEnabled
{
get
{
if (_imageCloseEnabled == null)
_imageCloseEnabled = Resources.DockPaneStrip_CloseEnabled;
return _imageCloseEnabled;
}
}
private static Image _imageCloseDisabled = null;
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ImageCloseDisabled"]/*'/>
protected virtual Image ImageCloseDisabled
{
get
{
if (_imageCloseDisabled == null)
_imageCloseDisabled = Resources.DockPaneStrip_CloseDisabled;
return _imageCloseDisabled;
}
}
private static Image _imageScrollLeftEnabled = null;
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ImageScrollLeftEnabled"]/*'/>
protected virtual Image ImageScrollLeftEnabled
{
get
{
if (_imageScrollLeftEnabled == null)
_imageScrollLeftEnabled = Resources.DockPaneStrip_ScrollLeftEnabled;
return _imageScrollLeftEnabled;
}
}
private static Image _imageScrollLeftDisabled = null;
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ImageScrollLeftDisabled"]/*'/>
protected virtual Image ImageScrollLeftDisabled
{
get
{
if (_imageScrollLeftDisabled == null)
_imageScrollLeftDisabled = Resources.DockPaneStrip_ScrollLeftDisabled;
return _imageScrollLeftDisabled;
}
}
private static Image _imageScrollRightEnabled = null;
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ImageScrollRightEnabled"]/*'/>
protected virtual Image ImageScrollRightEnabled
{
get
{
if (_imageScrollRightEnabled == null)
_imageScrollRightEnabled = Resources.DockPaneStrip_ScrollRightEnabled;
return _imageScrollRightEnabled;
}
}
private static Image _imageScrollRightDisabled = null;
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ImageScrollRightDisabled"]/*'/>
protected virtual Image ImageScrollRightDisabled
{
get
{
if (_imageScrollRightDisabled == null)
_imageScrollRightDisabled = Resources.DockPaneStrip_ScrollRightDisabled;
return _imageScrollRightDisabled;
}
}
private static string _toolTipClose = null;
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolTipClose"]/*'/>
protected virtual string ToolTipClose
{
get
{
if (_toolTipClose == null)
_toolTipClose = Strings.DockPaneStrip_ToolTipClose;
return _toolTipClose;
}
}
private static string _toolTipScrollLeft = null;
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolTipScrollLeft"]/*'/>
protected virtual string ToolTipScrollLeft
{
get
{
if (_toolTipScrollLeft == null)
_toolTipScrollLeft = Strings.DockPaneStrip_ToolTipScrollLeft;
return _toolTipScrollLeft;
}
}
private static string _toolTipScrollRight = null;
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolTipScrollRight"]/*'/>
protected virtual string ToolTipScrollRight
{
get
{
if (_toolTipScrollRight == null)
_toolTipScrollRight = Strings.DockPaneStrip_ToolTipScrollRight;
return _toolTipScrollRight;
}
}
private static TextFormatFlags _toolWindowTextFormat =
TextFormatFlags.EndEllipsis |
TextFormatFlags.HorizontalCenter |
TextFormatFlags.SingleLine |
TextFormatFlags.VerticalCenter;
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowTextStringFormat"]/*'/>
protected virtual TextFormatFlags ToolWindowTextFormat
{
get { return _toolWindowTextFormat; }
}
private static TextFormatFlags _documentTextFormat =
TextFormatFlags.PathEllipsis |
TextFormatFlags.SingleLine |
TextFormatFlags.VerticalCenter;
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentTextStringFormat"]/*'/>
public static TextFormatFlags DocumentTextFormat
{
get { return _documentTextFormat; }
}
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentTabMaxWidth"]/*'/>
protected virtual int DocumentTabMaxWidth
{
get { return _DocumentTabMaxWidth; }
}
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentButtonGapTop"]/*'/>
protected virtual int DocumentButtonGapTop
{
get { return _DocumentButtonGapTop; }
}
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentButtonGapBottom"]/*'/>
protected virtual int DocumentButtonGapBottom
{
get { return _DocumentButtonGapBottom; }
}
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentButtonGapBetween"]/*'/>
protected virtual int DocumentButtonGapBetween
{
get { return _DocumentButtonGapBetween; }
}
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentButtonGapRight"]/*'/>
protected virtual int DocumentButtonGapRight
{
get { return _DocumentButtonGapRight; }
}
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentTabGapTop"]/*'/>
protected virtual int DocumentTabGapTop
{
get { return _DocumentTabGapTop; }
}
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentTabGapLeft"]/*'/>
protected virtual int DocumentTabGapLeft
{
get { return _DocumentTabGapLeft; }
}
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentTabGapRight"]/*'/>
protected virtual int DocumentTabGapRight
{
get { return _DocumentTabGapRight; }
}
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentIconGapLeft"]/*'/>
protected virtual int DocumentIconGapLeft
{
get { return _DocumentIconGapLeft; }
}
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentIconWidth"]/*'/>
protected virtual int DocumentIconWidth
{
get { return _DocumentIconWidth; }
}
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentIconHeight"]/*'/>
protected virtual int DocumentIconHeight
{
get { return _DocumentIconHeight; }
}
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="OutlineInnerPen"]/*'/>
protected virtual Pen OutlineInnerPen
{
get { return SystemPens.ControlText; }
}
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="OutlineOuterPen"]/*'/>
protected virtual Pen OutlineOuterPen
{
get { return SystemPens.ActiveCaptionText; }
}
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ActiveBackBrush"]/*'/>
protected virtual Brush ActiveBackBrush
{
get { return SystemBrushes.Control; }
}
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ActiveTextBrush"]/*'/>
protected virtual Color ActiveTextColor
{
get { return SystemColors.ControlText; }
}
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="TabSeperatorPen"]/*'/>
protected virtual Pen TabSeperatorPen
{
get { return SystemPens.GrayText; }
}
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="InactiveTextBrush"]/*'/>
protected virtual Color InactiveTextColor
{
get { return SystemColors.ControlDarkDark; }
}
#endregion
public VS2003DockPaneStrip(DockPane pane) : base(pane)
{
SetStyle(ControlStyles.ResizeRedraw, true);
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SuspendLayout();
Font = SystemInformation.MenuFont;
BackColor = Color.WhiteSmoke;
m_components = new Container();
m_toolTip = new ToolTip(Components);
m_buttonClose = new InertButton(ImageCloseEnabled, ImageCloseDisabled);
m_buttonScrollLeft = new InertButton(ImageScrollLeftEnabled, ImageScrollLeftDisabled);
m_buttonScrollRight = new InertButton(ImageScrollRightEnabled, ImageScrollRightDisabled);
m_buttonClose.ToolTipText = ToolTipClose;
m_buttonClose.Anchor = AnchorStyles.Top | AnchorStyles.Right;
m_buttonClose.Click += new EventHandler(Close_Click);
m_buttonScrollLeft.Enabled = false;
m_buttonScrollLeft.RepeatClick = true;
m_buttonScrollLeft.ToolTipText = ToolTipScrollLeft;
m_buttonScrollLeft.Anchor = AnchorStyles.Top | AnchorStyles.Right;
m_buttonScrollLeft.Click += new EventHandler(ScrollLeft_Click);
m_buttonScrollRight.Enabled = false;
m_buttonScrollRight.RepeatClick = true;
m_buttonScrollRight.ToolTipText = ToolTipScrollRight;
m_buttonScrollRight.Anchor = AnchorStyles.Top | AnchorStyles.Right;
m_buttonScrollRight.Click += new EventHandler(ScrollRight_Click);
Controls.AddRange(new Control[] { m_buttonClose,
m_buttonScrollLeft,
m_buttonScrollRight });
ResumeLayout();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
Components.Dispose();
}
base.Dispose (disposing);
}
protected override int MeasureHeight()
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return MeasureHeight_ToolWindow();
else
return MeasureHeight_Document();
}
private int MeasureHeight_ToolWindow()
{
if (DockPane.IsAutoHide || Tabs.Count <= 1)
return 0;
int height = Math.Max(Font.Height, ToolWindowImageHeight)
+ ToolWindowImageGapTop + ToolWindowImageGapBottom;
return height;
}
private int MeasureHeight_Document()
{
int height = Math.Max(Font.Height + DocumentTabGapTop,
ImageCloseEnabled.Height + DocumentButtonGapTop + DocumentButtonGapBottom);
return height;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint (e);
CalculateTabs();
DrawTabStrip(e.Graphics);
}
protected override void OnRefreshChanges()
{
CalculateTabs();
SetInertButtons();
Invalidate();
}
protected override GraphicsPath GetOutline(int index)
{
Point[] pts = new Point[8];
if (Appearance == DockPane.AppearanceStyle.Document)
{
Rectangle rectTab = GetTabRectangle(index);
rectTab.Intersect(TabsRectangle);
int y = DockPane.PointToClient(PointToScreen(new Point(0, rectTab.Bottom))).Y;
Rectangle rectPaneClient = DockPane.ClientRectangle;
pts[0] = DockPane.PointToScreen(new Point(rectPaneClient.Left, y));
pts[1] = PointToScreen(new Point(rectTab.Left, rectTab.Bottom));
pts[2] = PointToScreen(new Point(rectTab.Left, rectTab.Top));
pts[3] = PointToScreen(new Point(rectTab.Right, rectTab.Top));
pts[4] = PointToScreen(new Point(rectTab.Right, rectTab.Bottom));
pts[5] = DockPane.PointToScreen(new Point(rectPaneClient.Right, y));
pts[6] = DockPane.PointToScreen(new Point(rectPaneClient.Right, rectPaneClient.Bottom));
pts[7] = DockPane.PointToScreen(new Point(rectPaneClient.Left, rectPaneClient.Bottom));
}
else
{
Rectangle rectTab = GetTabRectangle(index);
rectTab.Intersect(TabsRectangle);
int y = DockPane.PointToClient(PointToScreen(new Point(0, rectTab.Top))).Y;
Rectangle rectPaneClient = DockPane.ClientRectangle;
pts[0] = DockPane.PointToScreen(new Point(rectPaneClient.Left, rectPaneClient.Top));
pts[1] = DockPane.PointToScreen(new Point(rectPaneClient.Right, rectPaneClient.Top));
pts[2] = DockPane.PointToScreen(new Point(rectPaneClient.Right, y));
pts[3] = PointToScreen(new Point(rectTab.Right, rectTab.Top));
pts[4] = PointToScreen(new Point(rectTab.Right, rectTab.Bottom));
pts[5] = PointToScreen(new Point(rectTab.Left, rectTab.Bottom));
pts[6] = PointToScreen(new Point(rectTab.Left, rectTab.Top));
pts[7] = DockPane.PointToScreen(new Point(rectPaneClient.Left, y));
}
GraphicsPath path = new GraphicsPath();
path.AddLines(pts);
return path;
}
private void CalculateTabs()
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
CalculateTabs_ToolWindow();
else
CalculateTabs_Document();
}
private void CalculateTabs_ToolWindow()
{
if (Tabs.Count <= 1 || DockPane.IsAutoHide)
return;
Rectangle rectTabStrip = ClientRectangle;
// Calculate tab widths
int countTabs = Tabs.Count;
foreach (TabVS2003 tab in Tabs)
{
tab.MaxWidth = GetTabOriginalWidth(Tabs.IndexOf(tab));
tab.Flag = false;
}
// Set tab whose max width less than average width
bool anyWidthWithinAverage = true;
int totalWidth = rectTabStrip.Width - ToolWindowStripGapLeft - ToolWindowStripGapRight;
int totalAllocatedWidth = 0;
int averageWidth = totalWidth / countTabs;
int remainedTabs = countTabs;
for (anyWidthWithinAverage=true; anyWidthWithinAverage && remainedTabs>0;)
{
anyWidthWithinAverage = false;
foreach (TabVS2003 tab in Tabs)
{
if (tab.Flag)
continue;
if (tab.MaxWidth <= averageWidth)
{
tab.Flag = true;
tab.TabWidth = tab.MaxWidth;
totalAllocatedWidth += tab.TabWidth;
anyWidthWithinAverage = true;
remainedTabs--;
}
}
if (remainedTabs != 0)
averageWidth = (totalWidth - totalAllocatedWidth) / remainedTabs;
}
// If any tab width not set yet, set it to the average width
if (remainedTabs > 0)
{
int roundUpWidth = (totalWidth - totalAllocatedWidth) - (averageWidth * remainedTabs);
foreach (TabVS2003 tab in Tabs)
{
if (tab.Flag)
continue;
tab.Flag = true;
if (roundUpWidth > 0)
{
tab.TabWidth = averageWidth + 1;
roundUpWidth --;
}
else
tab.TabWidth = averageWidth;
}
}
// Set the X position of the tabs
int x = rectTabStrip.X + ToolWindowStripGapLeft;
foreach (TabVS2003 tab in Tabs)
{
tab.TabX = x;
x += tab.TabWidth;
}
}
private void CalculateTabs_Document()
{
Rectangle rectTabStrip = TabsRectangle;
int totalWidth = 0;
foreach (TabVS2003 tab in Tabs)
{
tab.TabWidth = Math.Min(GetTabOriginalWidth(Tabs.IndexOf(tab)), DocumentTabMaxWidth);
totalWidth += tab.TabWidth;
}
if (totalWidth + OffsetX < rectTabStrip.Width && OffsetX < 0)
OffsetX = Math.Min(0, rectTabStrip.Width - totalWidth);
int x = rectTabStrip.X + OffsetX;
foreach (TabVS2003 tab in Tabs)
{
tab.TabX = x;
x += tab.TabWidth;
}
}
protected override void EnsureTabVisible(IDockContent content)
{
if (Appearance != DockPane.AppearanceStyle.Document || !Tabs.Contains(content))
return;
Rectangle rectTabStrip = TabsRectangle;
Rectangle rectTab = GetTabRectangle(Tabs.IndexOf(content));
if (rectTab.Right > rectTabStrip.Right)
{
OffsetX -= rectTab.Right - rectTabStrip.Right;
rectTab.X -= rectTab.Right - rectTabStrip.Right;
}
if (rectTab.Left < rectTabStrip.Left)
OffsetX += rectTabStrip.Left - rectTab.Left;
OnRefreshChanges();
}
private int GetTabOriginalWidth(int index)
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return GetTabOriginalWidth_ToolWindow(index);
else
return GetTabOriginalWidth_Document(index);
}
private int GetTabOriginalWidth_ToolWindow(int index)
{
IDockContent content = Tabs[index].Content;
using (Graphics g = CreateGraphics())
{
Size sizeString = TextRenderer.MeasureText(g, content.DockHandler.TabText, Font);
return ToolWindowImageWidth + sizeString.Width + ToolWindowImageGapLeft
+ ToolWindowImageGapRight + ToolWindowTextGapRight;
}
}
private int GetTabOriginalWidth_Document(int index)
{
IDockContent content = Tabs[index].Content;
int height = GetTabRectangle_Document(index).Height;
using (Graphics g = CreateGraphics())
{
Size sizeText;
if (content == DockPane.ActiveContent && DockPane.IsActiveDocumentPane)
{
using (Font boldFont = new Font(this.Font, FontStyle.Bold))
{
sizeText = TextRenderer.MeasureText(g, content.DockHandler.TabText, boldFont, new Size(DocumentTabMaxWidth, height), DocumentTextFormat);
}
}
else
sizeText = TextRenderer.MeasureText(content.DockHandler.TabText, Font, new Size(DocumentTabMaxWidth, height), DocumentTextFormat);
if (DockPane.DockPanel.ShowDocumentIcon)
return sizeText.Width + DocumentIconWidth + DocumentIconGapLeft;
else
return sizeText.Width;
}
}
private void DrawTabStrip(Graphics g)
{
OnBeginDrawTabStrip();
if (Appearance == DockPane.AppearanceStyle.Document)
DrawTabStrip_Document(g);
else
DrawTabStrip_ToolWindow(g);
OnEndDrawTabStrip();
}
private void DrawTabStrip_Document(Graphics g)
{
int count = Tabs.Count;
if (count == 0)
return;
Rectangle rectTabStrip = ClientRectangle;
g.DrawLine(OutlineOuterPen, rectTabStrip.Left, rectTabStrip.Bottom - 1,
rectTabStrip.Right, rectTabStrip.Bottom - 1);
// Draw the tabs
Rectangle rectTabOnly = TabsRectangle;
Rectangle rectTab = Rectangle.Empty;
g.SetClip(rectTabOnly);
for (int i=0; i<count; i++)
{
rectTab = GetTabRectangle(i);
if (rectTab.IntersectsWith(rectTabOnly))
DrawTab(g, Tabs[i] as TabVS2003, rectTab);
}
}
private void DrawTabStrip_ToolWindow(Graphics g)
{
Rectangle rectTabStrip = ClientRectangle;
g.DrawLine(OutlineInnerPen, rectTabStrip.Left, rectTabStrip.Top,
rectTabStrip.Right, rectTabStrip.Top);
for (int i=0; i<Tabs.Count; i++)
DrawTab(g, Tabs[i] as TabVS2003, GetTabRectangle(i));
}
private Rectangle GetTabRectangle(int index)
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return GetTabRectangle_ToolWindow(index);
else
return GetTabRectangle_Document(index);
}
private Rectangle GetTabRectangle_ToolWindow(int index)
{
Rectangle rectTabStrip = ClientRectangle;
TabVS2003 tab = (TabVS2003)(Tabs[index]);
return new Rectangle(tab.TabX, rectTabStrip.Y, tab.TabWidth, rectTabStrip.Height);
}
private Rectangle GetTabRectangle_Document(int index)
{
Rectangle rectTabStrip = ClientRectangle;
TabVS2003 tab = (TabVS2003)Tabs[index];
return new Rectangle(tab.TabX, rectTabStrip.Y + DocumentTabGapTop, tab.TabWidth, rectTabStrip.Height - DocumentTabGapTop);
}
private void DrawTab(Graphics g, TabVS2003 tab, Rectangle rect)
{
OnBeginDrawTab(tab);
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
DrawTab_ToolWindow(g, tab, rect);
else
DrawTab_Document(g, tab, rect);
OnEndDrawTab(tab);
}
private void DrawTab_ToolWindow(Graphics g, TabVS2003 tab, Rectangle rect)
{
Rectangle rectIcon = new Rectangle(
rect.X + ToolWindowImageGapLeft,
rect.Y + rect.Height - 1 - ToolWindowImageGapBottom - ToolWindowImageHeight,
ToolWindowImageWidth, ToolWindowImageHeight);
Rectangle rectText = rectIcon;
rectText.X += rectIcon.Width + ToolWindowImageGapRight;
rectText.Width = rect.Width - rectIcon.Width - ToolWindowImageGapLeft -
ToolWindowImageGapRight - ToolWindowTextGapRight;
if (DockPane.ActiveContent == tab.Content)
{
g.FillRectangle(ActiveBackBrush, rect);
g.DrawLine(OutlineOuterPen,
rect.X, rect.Y, rect.X, rect.Y + rect.Height - 1);
g.DrawLine(OutlineInnerPen,
rect.X, rect.Y + rect.Height - 1, rect.X + rect.Width - 1, rect.Y + rect.Height - 1);
g.DrawLine(OutlineInnerPen,
rect.X + rect.Width - 1, rect.Y, rect.X + rect.Width - 1, rect.Y + rect.Height - 1);
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, Font, rectText, ActiveTextColor, ToolWindowTextFormat);
}
else
{
if (Tabs.IndexOf(DockPane.ActiveContent) != Tabs.IndexOf(tab) + 1)
g.DrawLine(TabSeperatorPen,
rect.X + rect.Width - 1,
rect.Y + ToolWindowTabSeperatorGapTop,
rect.X + rect.Width - 1,
rect.Y + rect.Height - 1 - ToolWindowTabSeperatorGapBottom);
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, Font, rectText, InactiveTextColor, ToolWindowTextFormat);
}
if (rect.Contains(rectIcon))
g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon);
}
private void DrawTab_Document(Graphics g, TabVS2003 tab, Rectangle rect)
{
Rectangle rectText = rect;
if (DockPane.DockPanel.ShowDocumentIcon)
{
rectText.X += DocumentIconWidth + DocumentIconGapLeft;
rectText.Width -= DocumentIconWidth + DocumentIconGapLeft;
}
if (DockPane.ActiveContent == tab.Content)
{
g.FillRectangle(ActiveBackBrush, rect);
g.DrawLine(OutlineOuterPen, rect.X, rect.Y, rect.X, rect.Y + rect.Height);
g.DrawLine(OutlineOuterPen, rect.X, rect.Y, rect.X + rect.Width - 1, rect.Y);
g.DrawLine(OutlineInnerPen,
rect.X + rect.Width - 1, rect.Y,
rect.X + rect.Width - 1, rect.Y + rect.Height - 1);
if (DockPane.DockPanel.ShowDocumentIcon)
{
Icon icon = (tab.Content as Form).Icon;
Rectangle rectIcon = new Rectangle(
rect.X + DocumentIconGapLeft,
rect.Y + (rect.Height - DocumentIconHeight) / 2,
DocumentIconWidth, DocumentIconHeight);
g.DrawIcon(tab.ContentForm.Icon, rectIcon);
}
if (DockPane.IsActiveDocumentPane)
{
using (Font boldFont = new Font(this.Font, FontStyle.Bold))
{
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, boldFont, rectText, ActiveTextColor, DocumentTextFormat);
}
}
else
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, Font, rectText, InactiveTextColor, DocumentTextFormat);
}
else
{
if (Tabs.IndexOf(DockPane.ActiveContent) != Tabs.IndexOf(tab) + 1)
g.DrawLine(TabSeperatorPen,
rect.X + rect.Width - 1, rect.Y,
rect.X + rect.Width - 1, rect.Y + rect.Height - 1 - DocumentTabGapTop);
if (DockPane.DockPanel.ShowDocumentIcon)
{
Icon icon = tab.ContentForm.Icon;
Rectangle rectIcon = new Rectangle(
rect.X + DocumentIconGapLeft,
rect.Y + (rect.Height - DocumentIconHeight) / 2,
DocumentIconWidth, DocumentIconHeight);
g.DrawIcon(tab.ContentForm.Icon, rectIcon);
}
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, Font, rectText, InactiveTextColor, DocumentTextFormat);
}
}
private Rectangle TabsRectangle
{
get
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return ClientRectangle;
Rectangle rectWindow = ClientRectangle;
int x = rectWindow.X;
int y = rectWindow.Y;
int width = rectWindow.Width;
int height = rectWindow.Height;
x += DocumentTabGapLeft;
width -= DocumentTabGapLeft +
DocumentTabGapRight +
DocumentButtonGapRight +
m_buttonClose.Width +
m_buttonScrollRight.Width +
m_buttonScrollLeft.Width +
2 * DocumentButtonGapBetween;
return new Rectangle(x, y, width, height);
}
}
private void ScrollLeft_Click(object sender, EventArgs e)
{
Rectangle rectTabStrip = TabsRectangle;
int index;
for (index=0; index<Tabs.Count; index++)
if (GetTabRectangle(index).IntersectsWith(rectTabStrip))
break;
Rectangle rectTab = GetTabRectangle(index);
if (rectTab.Left < rectTabStrip.Left)
OffsetX += rectTabStrip.Left - rectTab.Left;
else if (index == 0)
OffsetX = 0;
else
OffsetX += rectTabStrip.Left - GetTabRectangle(index - 1).Left;
OnRefreshChanges();
}
private void ScrollRight_Click(object sender, EventArgs e)
{
Rectangle rectTabStrip = TabsRectangle;
int index;
int count = Tabs.Count;
for (index=0; index<count; index++)
if (GetTabRectangle(index).IntersectsWith(rectTabStrip))
break;
if (index + 1 < count)
{
OffsetX -= GetTabRectangle(index + 1).Left - rectTabStrip.Left;
CalculateTabs();
}
Rectangle rectLastTab = GetTabRectangle(count - 1);
if (rectLastTab.Right < rectTabStrip.Right)
OffsetX += rectTabStrip.Right - rectLastTab.Right;
OnRefreshChanges();
}
private void SetInertButtons()
{
// Set the visibility of the inert buttons
m_buttonScrollLeft.Visible = m_buttonScrollRight.Visible = m_buttonClose.Visible = (DockPane.DockState == DockState.Document);
m_buttonClose.ForeColor = m_buttonScrollRight.ForeColor = m_buttonScrollLeft.ForeColor = SystemColors.ControlDarkDark;
m_buttonClose.BorderColor = m_buttonScrollRight.BorderColor = m_buttonScrollLeft.BorderColor = SystemColors.ControlDarkDark;
// Enable/disable scroll buttons
int count = Tabs.Count;
Rectangle rectTabOnly = TabsRectangle;
Rectangle rectTab = (count == 0) ? Rectangle.Empty : GetTabRectangle(count - 1);
m_buttonScrollLeft.Enabled = (OffsetX < 0);
m_buttonScrollRight.Enabled = rectTab.Right > rectTabOnly.Right;
// show/hide close button
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
m_buttonClose.Visible = false;
else
{
bool showCloseButton = DockPane.ActiveContent == null ? true : DockPane.ActiveContent.DockHandler.CloseButton;
if (m_buttonClose.Visible != showCloseButton)
{
m_buttonClose.Visible = showCloseButton;
PerformLayout();
}
}
}
/// <exclude/>
protected override void OnLayout(LayoutEventArgs levent)
{
Rectangle rectTabStrip = ClientRectangle;
// Set position and size of the buttons
int buttonWidth = ImageCloseEnabled.Width;
int buttonHeight = ImageCloseEnabled.Height;
int height = rectTabStrip.Height - DocumentButtonGapTop - DocumentButtonGapBottom;
if (buttonHeight < height)
{
buttonWidth = buttonWidth * (height / buttonHeight);
buttonHeight = height;
}
Size buttonSize = new Size(buttonWidth, buttonHeight);
m_buttonClose.Size = m_buttonScrollLeft.Size = m_buttonScrollRight.Size = buttonSize;
int x = rectTabStrip.X + rectTabStrip.Width - DocumentTabGapLeft
- DocumentButtonGapRight - buttonWidth;
int y = rectTabStrip.Y + DocumentButtonGapTop;
m_buttonClose.Location = new Point(x, y);
Point point = m_buttonClose.Location;
bool showCloseButton = DockPane.ActiveContent == null ? true : DockPane.ActiveContent.DockHandler.CloseButton;
if (showCloseButton)
point.Offset(-(DocumentButtonGapBetween + buttonWidth), 0);
m_buttonScrollRight.Location = point;
point.Offset(-(DocumentButtonGapBetween + buttonWidth), 0);
m_buttonScrollLeft.Location = point;
OnRefreshChanges();
base.OnLayout (levent);
}
private void Close_Click(object sender, EventArgs e)
{
DockPane.CloseActiveContent();
}
/// <exclude/>
protected override int HitTest(Point ptMouse)
{
Rectangle rectTabStrip = TabsRectangle;
for (int i=0; i<Tabs.Count; i++)
{
Rectangle rectTab = GetTabRectangle(i);
rectTab.Intersect(rectTabStrip);
if (rectTab.Contains(ptMouse))
return i;
}
return -1;
}
/// <exclude/>
protected override void OnMouseMove(MouseEventArgs e)
{
int index = HitTest(PointToClient(Control.MousePosition));
string toolTip = string.Empty;
base.OnMouseMove(e);
if (index != -1)
{
Rectangle rectTab = GetTabRectangle(index);
if (Tabs[index].Content.DockHandler.ToolTipText != null)
toolTip = Tabs[index].Content.DockHandler.ToolTipText;
else if (rectTab.Width < GetTabOriginalWidth(index))
toolTip = Tabs[index].Content.DockHandler.TabText;
}
if (m_toolTip.GetToolTip(this) != toolTip)
{
m_toolTip.Active = false;
m_toolTip.SetToolTip(this, toolTip);
m_toolTip.Active = true;
}
}
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Method[@name="OnBeginDrawTabStrip()"]/*'/>
protected virtual void OnBeginDrawTabStrip()
{
}
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Method[@name="OnEndDrawTabStrip()"]/*'/>
protected virtual void OnEndDrawTabStrip()
{
}
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Method[@name="OnBeginDrawTab(DockPaneTab)"]/*'/>
protected virtual void OnBeginDrawTab(Tab tab)
{
}
/// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Method[@name="OnEndDrawTab(DockPaneTab)"]/*'/>
protected virtual void OnEndDrawTab(Tab tab)
{
}
}
}
| |
// code taken from http://www.codeproject.com/KB/GDI-plus/ExtendedGraphics.aspx
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
// A simple extension to the Graphics class for extended
// graphic routines, such,
// as for creating rounded rectangles.
// Because, Graphics class is an abstract class,
// that is why it can not be inherited. Although,
// I have provided a simple constructor
// that builds the ExtendedGraphics object around a
// previously created Graphics object.
// Please contact: aaronreginald@yahoo.com for the most
// recent implementations of
// this class.
namespace System.Drawing.Extended
{
/// <SUMMARY>
/// Inherited child for the class Graphics encapsulating
/// additional functionality for curves and rounded rectangles.
/// </SUMMARY>
public class ExtendedGraphics
{
private Graphics mGraphics;
public Graphics Graphics
{
get{ return this.mGraphics; }
set{ this.mGraphics = value; }
}
public ExtendedGraphics(Graphics graphics)
{
this.Graphics = graphics;
}
#region Fills a Rounded Rectangle with integers.
public void FillRoundRectangle(System.Drawing.Brush brush,
int x, int y,
int width, int height, int radius)
{
float fx = Convert.ToSingle(x);
float fy = Convert.ToSingle(y);
float fwidth = Convert.ToSingle(width);
float fheight = Convert.ToSingle(height);
float fradius = Convert.ToSingle(radius);
this.FillRoundRectangle(brush, fx, fy,
fwidth, fheight, fradius);
}
#endregion
#region Fills a Rounded Rectangle with continuous numbers.
public void FillRoundRectangle(System.Drawing.Brush brush,
float x, float y,
float width, float height, float radius)
{
RectangleF rectangle = new RectangleF(x, y, width, height);
GraphicsPath path = this.GetRoundedRect(rectangle, radius);
this.Graphics.FillPath(brush, path);
}
#endregion
#region Draws a Rounded Rectangle border with integers.
public void DrawRoundRectangle(System.Drawing.Pen pen, int x, int y,
int width, int height, int radius)
{
float fx = Convert.ToSingle(x);
float fy = Convert.ToSingle(y);
float fwidth = Convert.ToSingle(width);
float fheight = Convert.ToSingle(height);
float fradius = Convert.ToSingle(radius);
this.DrawRoundRectangle(pen, fx, fy, fwidth, fheight, fradius);
}
#endregion
#region Draws a Rounded Rectangle border with continuous numbers.
public void DrawRoundRectangle(System.Drawing.Pen pen,
float x, float y,
float width, float height, float radius)
{
RectangleF rectangle = new RectangleF(x, y, width, height);
GraphicsPath path = this.GetRoundedRect(rectangle, radius);
this.Graphics.DrawPath(pen, path);
}
#endregion
#region Get the desired Rounded Rectangle path.
private GraphicsPath GetRoundedRect(RectangleF baseRect,
float radius)
{
// if corner radius is less than or equal to zero,
// return the original rectangle
if( radius<=0.0F )
{
GraphicsPath mPath = new GraphicsPath();
mPath.AddRectangle(baseRect);
mPath.CloseFigure();
return mPath;
}
// if the corner radius is greater than or equal to
// half the width, or height (whichever is shorter)
// then return a capsule instead of a lozenge
if( radius>=(Math.Min(baseRect.Width, baseRect.Height))/2.0)
return GetCapsule( baseRect );
// create the arc for the rectangle sides and declare
// a graphics path object for the drawing
float diameter = radius * 2.0F;
SizeF sizeF = new SizeF( diameter, diameter );
RectangleF arc = new RectangleF( baseRect.Location, sizeF );
GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath();
// top left arc
path.AddArc( arc, 180, 90 );
// top right arc
arc.X = baseRect.Right-diameter;
path.AddArc( arc, 270, 90 );
// bottom right arc
arc.Y = baseRect.Bottom-diameter;
path.AddArc( arc, 0, 90 );
// bottom left arc
arc.X = baseRect.Left;
path.AddArc( arc, 90, 90 );
path.CloseFigure();
return path;
}
#endregion
#region Gets the desired Capsular path.
private GraphicsPath GetCapsule( RectangleF baseRect )
{
float diameter;
RectangleF arc;
GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath();
try
{
if( baseRect.Width>baseRect.Height )
{
// return horizontal capsule
diameter = baseRect.Height;
SizeF sizeF = new SizeF(diameter, diameter);
arc = new RectangleF( baseRect.Location, sizeF );
path.AddArc( arc, 90, 180);
arc.X = baseRect.Right-diameter;
path.AddArc( arc, 270, 180);
}
else if( baseRect.Width < baseRect.Height )
{
// return vertical capsule
diameter = baseRect.Width;
SizeF sizeF = new SizeF(diameter, diameter);
arc = new RectangleF( baseRect.Location, sizeF );
path.AddArc( arc, 180, 180 );
arc.Y = baseRect.Bottom-diameter;
path.AddArc( arc, 0, 180 );
}
else
{
// return circle
path.AddEllipse( baseRect );
}
}
catch
{
path.AddEllipse( baseRect );
}
finally
{
path.CloseFigure();
}
return path;
}
#endregion
}
}
| |
//---------------------------------------------------------------------------
//
// File: HtmlSchema.cs
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// Description: Static information about HTML structure
//
//---------------------------------------------------------------------------
namespace HTMLConverter
{
using System.Diagnostics;
using System.Collections;
/// <summary>
/// HtmlSchema class
/// maintains static information about HTML structure
/// can be used by HtmlParser to check conditions under which an element starts or ends, etc.
/// </summary>
internal class HtmlSchema
{
// ---------------------------------------------------------------------
//
// Constructors
//
// ---------------------------------------------------------------------
#region Constructors
/// <summary>
/// static constructor, initializes the ArrayLists
/// that hold the elements in various sub-components of the schema
/// e.g _htmlEmptyElements, etc.
/// </summary>
static HtmlSchema()
{
// initializes the list of all html elements
InitializeInlineElements();
InitializeBlockElements();
InitializeOtherOpenableElements();
// initialize empty elements list
InitializeEmptyElements();
// initialize list of elements closing on the outer element end
InitializeElementsClosingOnParentElementEnd();
// initalize list of elements that close when a new element starts
InitializeElementsClosingOnNewElementStart();
// Initialize character entities
InitializeHtmlCharacterEntities();
}
#endregion Constructors;
// ---------------------------------------------------------------------
//
// Internal Methods
//
// ---------------------------------------------------------------------
#region Internal Methods
/// <summary>
/// returns true when xmlElementName corresponds to empty element
/// </summary>
/// <param name="xmlElementName">
/// string representing name to test
/// </param>
internal static bool IsEmptyElement(string xmlElementName)
{
// convert to lowercase before we check
// because element names are not case sensitive
return _htmlEmptyElements.Contains(xmlElementName.ToLower());
}
/// <summary>
/// returns true if xmlElementName represents a block formattinng element.
/// It used in an algorithm of transferring inline elements over block elements
/// in HtmlParser
/// </summary>
/// <param name="xmlElementName"></param>
/// <returns></returns>
internal static bool IsBlockElement(string xmlElementName)
{
return _htmlBlockElements.Contains(xmlElementName);
}
/// <summary>
/// returns true if the xmlElementName represents an inline formatting element
/// </summary>
/// <param name="xmlElementName"></param>
/// <returns></returns>
internal static bool IsInlineElement(string xmlElementName)
{
return _htmlInlineElements.Contains(xmlElementName);
}
/// <summary>
/// It is a list of known html elements which we
/// want to allow to produce bt HTML parser,
/// but don'tt want to act as inline, block or no-scope.
/// Presence in this list will allow to open
/// elements during html parsing, and adding the
/// to a tree produced by html parser.
/// </summary>
internal static bool IsKnownOpenableElement(string xmlElementName)
{
return _htmlOtherOpenableElements.Contains(xmlElementName);
}
/// <summary>
/// returns true when xmlElementName closes when the outer element closes
/// this is true of elements with optional start tags
/// </summary>
/// <param name="xmlElementName">
/// string representing name to test
/// </param>
internal static bool ClosesOnParentElementEnd(string xmlElementName)
{
// convert to lowercase when testing
return _htmlElementsClosingOnParentElementEnd.Contains(xmlElementName.ToLower());
}
/// <summary>
/// returns true if the current element closes when the new element, whose name has just been read, starts
/// </summary>
/// <param name="currentElementName">
/// string representing current element name
/// </param>
/// <param name="elementName"></param>
/// string representing name of the next element that will start
internal static bool ClosesOnNextElementStart(string currentElementName, string nextElementName)
{
Debug.Assert(currentElementName == currentElementName.ToLower());
switch (currentElementName)
{
case "colgroup":
return _htmlElementsClosingColgroup.Contains(nextElementName) && HtmlSchema.IsBlockElement(nextElementName);
case "dd":
return _htmlElementsClosingDD.Contains(nextElementName) && HtmlSchema.IsBlockElement(nextElementName);
case "dt":
return _htmlElementsClosingDT.Contains(nextElementName) && HtmlSchema.IsBlockElement(nextElementName);
case "li":
return _htmlElementsClosingLI.Contains(nextElementName);
case "p":
return HtmlSchema.IsBlockElement(nextElementName);
case "tbody":
return _htmlElementsClosingTbody.Contains(nextElementName);
case "tfoot":
return _htmlElementsClosingTfoot.Contains(nextElementName);
case "thead":
return _htmlElementsClosingThead.Contains(nextElementName);
case "tr":
return _htmlElementsClosingTR.Contains(nextElementName);
case "td":
return _htmlElementsClosingTD.Contains(nextElementName);
case "th":
return _htmlElementsClosingTH.Contains(nextElementName);
}
return false;
}
/// <summary>
/// returns true if the string passed as argument is an Html entity name
/// </summary>
/// <param name="entityName">
/// string to be tested for Html entity name
/// </param>
internal static bool IsEntity(string entityName)
{
// we do not convert entity strings to lowercase because these names are case-sensitive
if (_htmlCharacterEntities.Contains(entityName))
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// returns the character represented by the entity name string which is passed as an argument, if the string is an entity name
/// as specified in _htmlCharacterEntities, returns the character value of 0 otherwise
/// </summary>
/// <param name="entityName">
/// string representing entity name whose character value is desired
/// </param>
internal static char EntityCharacterValue(string entityName)
{
if (_htmlCharacterEntities.Contains(entityName))
{
return (char) _htmlCharacterEntities[entityName];
}
else
{
return (char)0;
}
}
#endregion Internal Methods
// ---------------------------------------------------------------------
//
// Internal Properties
//
// ---------------------------------------------------------------------
#region Internal Properties
#endregion Internal Indexers
// ---------------------------------------------------------------------
//
// Private Methods
//
// ---------------------------------------------------------------------
#region Private Methods
private static void InitializeInlineElements()
{
_htmlInlineElements = new ArrayList();
_htmlInlineElements.Add("a");
_htmlInlineElements.Add("abbr");
_htmlInlineElements.Add("acronym");
_htmlInlineElements.Add("address");
_htmlInlineElements.Add("b");
_htmlInlineElements.Add("bdo"); // ???
_htmlInlineElements.Add("big");
_htmlInlineElements.Add("button");
_htmlInlineElements.Add("code");
_htmlInlineElements.Add("del"); // deleted text
_htmlInlineElements.Add("dfn");
_htmlInlineElements.Add("em");
_htmlInlineElements.Add("font");
_htmlInlineElements.Add("i");
_htmlInlineElements.Add("ins"); // inserted text
_htmlInlineElements.Add("kbd"); // text to entered by a user
_htmlInlineElements.Add("label");
_htmlInlineElements.Add("legend"); // ???
_htmlInlineElements.Add("q"); // short inline quotation
_htmlInlineElements.Add("s"); // strike-through text style
_htmlInlineElements.Add("samp"); // Specifies a code sample
_htmlInlineElements.Add("small");
_htmlInlineElements.Add("span");
_htmlInlineElements.Add("strike");
_htmlInlineElements.Add("strong");
_htmlInlineElements.Add("sub");
_htmlInlineElements.Add("sup");
_htmlInlineElements.Add("u");
_htmlInlineElements.Add("var"); // indicates an instance of a program variable
}
private static void InitializeBlockElements()
{
_htmlBlockElements = new ArrayList();
_htmlBlockElements.Add("blockquote");
_htmlBlockElements.Add("body");
_htmlBlockElements.Add("caption");
_htmlBlockElements.Add("center");
_htmlBlockElements.Add("cite");
_htmlBlockElements.Add("dd");
_htmlBlockElements.Add("dir"); // treat as UL element
_htmlBlockElements.Add("div");
_htmlBlockElements.Add("dl");
_htmlBlockElements.Add("dt");
_htmlBlockElements.Add("form"); // Not a block according to XHTML spec
_htmlBlockElements.Add("h1");
_htmlBlockElements.Add("h2");
_htmlBlockElements.Add("h3");
_htmlBlockElements.Add("h4");
_htmlBlockElements.Add("h5");
_htmlBlockElements.Add("h6");
_htmlBlockElements.Add("html");
_htmlBlockElements.Add("li");
_htmlBlockElements.Add("menu"); // treat as UL element
_htmlBlockElements.Add("ol");
_htmlBlockElements.Add("p");
_htmlBlockElements.Add("pre"); // Renders text in a fixed-width font
_htmlBlockElements.Add("table");
_htmlBlockElements.Add("tbody");
_htmlBlockElements.Add("td");
_htmlBlockElements.Add("textarea");
_htmlBlockElements.Add("tfoot");
_htmlBlockElements.Add("th");
_htmlBlockElements.Add("thead");
_htmlBlockElements.Add("tr");
_htmlBlockElements.Add("tt");
_htmlBlockElements.Add("ul");
}
/// <summary>
/// initializes _htmlEmptyElements with empty elements in HTML 4 spec at
/// http://www.w3.org/TR/REC-html40/index/elements.html
/// </summary>
private static void InitializeEmptyElements()
{
// Build a list of empty (no-scope) elements
// (element not requiring closing tags, and not accepting any content)
_htmlEmptyElements = new ArrayList();
_htmlEmptyElements.Add("area");
_htmlEmptyElements.Add("base");
_htmlEmptyElements.Add("basefont");
_htmlEmptyElements.Add("br");
_htmlEmptyElements.Add("col");
_htmlEmptyElements.Add("frame");
_htmlEmptyElements.Add("hr");
_htmlEmptyElements.Add("img");
_htmlEmptyElements.Add("input");
_htmlEmptyElements.Add("isindex");
_htmlEmptyElements.Add("link");
_htmlEmptyElements.Add("meta");
_htmlEmptyElements.Add("param");
}
private static void InitializeOtherOpenableElements()
{
// It is a list of known html elements which we
// want to allow to produce bt HTML parser,
// but don'tt want to act as inline, block or no-scope.
// Presence in this list will allow to open
// elements during html parsing, and adding the
// to a tree produced by html parser.
_htmlOtherOpenableElements = new ArrayList();
_htmlOtherOpenableElements.Add("applet");
_htmlOtherOpenableElements.Add("base");
_htmlOtherOpenableElements.Add("basefont");
_htmlOtherOpenableElements.Add("colgroup");
_htmlOtherOpenableElements.Add("fieldset");
//_htmlOtherOpenableElements.Add("form"); --> treated as block
_htmlOtherOpenableElements.Add("frameset");
_htmlOtherOpenableElements.Add("head");
_htmlOtherOpenableElements.Add("iframe");
_htmlOtherOpenableElements.Add("map");
_htmlOtherOpenableElements.Add("noframes");
_htmlOtherOpenableElements.Add("noscript");
_htmlOtherOpenableElements.Add("object");
_htmlOtherOpenableElements.Add("optgroup");
_htmlOtherOpenableElements.Add("option");
_htmlOtherOpenableElements.Add("script");
_htmlOtherOpenableElements.Add("select");
_htmlOtherOpenableElements.Add("style");
_htmlOtherOpenableElements.Add("title");
}
/// <summary>
/// initializes _htmlElementsClosingOnParentElementEnd with the list of HTML 4 elements for which closing tags are optional
/// we assume that for any element for which closing tags are optional, the element closes when it's outer element
/// (in which it is nested) does
/// </summary>
private static void InitializeElementsClosingOnParentElementEnd()
{
_htmlElementsClosingOnParentElementEnd = new ArrayList();
_htmlElementsClosingOnParentElementEnd.Add("body");
_htmlElementsClosingOnParentElementEnd.Add("colgroup");
_htmlElementsClosingOnParentElementEnd.Add("dd");
_htmlElementsClosingOnParentElementEnd.Add("dt");
_htmlElementsClosingOnParentElementEnd.Add("head");
_htmlElementsClosingOnParentElementEnd.Add("html");
_htmlElementsClosingOnParentElementEnd.Add("li");
_htmlElementsClosingOnParentElementEnd.Add("p");
_htmlElementsClosingOnParentElementEnd.Add("tbody");
_htmlElementsClosingOnParentElementEnd.Add("td");
_htmlElementsClosingOnParentElementEnd.Add("tfoot");
_htmlElementsClosingOnParentElementEnd.Add("thead");
_htmlElementsClosingOnParentElementEnd.Add("th");
_htmlElementsClosingOnParentElementEnd.Add("tr");
}
private static void InitializeElementsClosingOnNewElementStart()
{
_htmlElementsClosingColgroup = new ArrayList();
_htmlElementsClosingColgroup.Add("colgroup");
_htmlElementsClosingColgroup.Add("tr");
_htmlElementsClosingColgroup.Add("thead");
_htmlElementsClosingColgroup.Add("tfoot");
_htmlElementsClosingColgroup.Add("tbody");
_htmlElementsClosingDD = new ArrayList();
_htmlElementsClosingDD.Add("dd");
_htmlElementsClosingDD.Add("dt");
// TODO: dd may end in other cases as well - if a new "p" starts, etc.
// TODO: these are the basic "legal" cases but there may be more recovery
_htmlElementsClosingDT = new ArrayList();
_htmlElementsClosingDD.Add("dd");
_htmlElementsClosingDD.Add("dt");
// TODO: dd may end in other cases as well - if a new "p" starts, etc.
// TODO: these are the basic "legal" cases but there may be more recovery
_htmlElementsClosingLI = new ArrayList();
_htmlElementsClosingLI.Add("li");
// TODO: more complex recovery
_htmlElementsClosingTbody = new ArrayList();
_htmlElementsClosingTbody.Add("tbody");
_htmlElementsClosingTbody.Add("thead");
_htmlElementsClosingTbody.Add("tfoot");
// TODO: more complex recovery
_htmlElementsClosingTR = new ArrayList();
// NOTE: tr should not really close on a new thead
// because if there are rows before a thead, it is assumed to be in tbody, whose start tag is optional
// and thead can't come after tbody
// however, if we do encounter this, it's probably best to end the row and ignore the thead or treat
// it as part of the table
_htmlElementsClosingTR.Add("thead");
_htmlElementsClosingTR.Add("tfoot");
_htmlElementsClosingTR.Add("tbody");
_htmlElementsClosingTR.Add("tr");
// TODO: more complex recovery
_htmlElementsClosingTD = new ArrayList();
_htmlElementsClosingTD.Add("td");
_htmlElementsClosingTD.Add("th");
_htmlElementsClosingTD.Add("tr");
_htmlElementsClosingTD.Add("tbody");
_htmlElementsClosingTD.Add("tfoot");
_htmlElementsClosingTD.Add("thead");
// TODO: more complex recovery
_htmlElementsClosingTH = new ArrayList();
_htmlElementsClosingTH.Add("td");
_htmlElementsClosingTH.Add("th");
_htmlElementsClosingTH.Add("tr");
_htmlElementsClosingTH.Add("tbody");
_htmlElementsClosingTH.Add("tfoot");
_htmlElementsClosingTH.Add("thead");
// TODO: more complex recovery
_htmlElementsClosingThead = new ArrayList();
_htmlElementsClosingThead.Add("tbody");
_htmlElementsClosingThead.Add("tfoot");
// TODO: more complex recovery
_htmlElementsClosingTfoot = new ArrayList();
_htmlElementsClosingTfoot.Add("tbody");
// although thead comes before tfoot, we add it because if it is found the tfoot should close
// and some recovery processing be done on the thead
_htmlElementsClosingTfoot.Add("thead");
// TODO: more complex recovery
}
/// <summary>
/// initializes _htmlCharacterEntities hashtable with the character corresponding to entity names
/// </summary>
private static void InitializeHtmlCharacterEntities()
{
_htmlCharacterEntities = new Hashtable();
_htmlCharacterEntities["Aacute"] = (char)193;
_htmlCharacterEntities["aacute"] = (char)225;
_htmlCharacterEntities["Acirc"] = (char)194;
_htmlCharacterEntities["acirc"] = (char)226;
_htmlCharacterEntities["acute"] = (char)180;
_htmlCharacterEntities["AElig"] = (char)198;
_htmlCharacterEntities["aelig"] = (char)230;
_htmlCharacterEntities["Agrave"] = (char)192;
_htmlCharacterEntities["agrave"] = (char)224;
_htmlCharacterEntities["alefsym"] = (char)8501;
_htmlCharacterEntities["Alpha"] = (char)913;
_htmlCharacterEntities["alpha"] = (char)945;
_htmlCharacterEntities["amp"] = (char)38;
_htmlCharacterEntities["and"] = (char)8743;
_htmlCharacterEntities["ang"] = (char)8736;
_htmlCharacterEntities["Aring"] = (char)197;
_htmlCharacterEntities["aring"] = (char)229;
_htmlCharacterEntities["asymp"] = (char)8776;
_htmlCharacterEntities["Atilde"] = (char)195;
_htmlCharacterEntities["atilde"] = (char)227;
_htmlCharacterEntities["Auml"] = (char)196;
_htmlCharacterEntities["auml"] = (char)228;
_htmlCharacterEntities["bdquo"] = (char)8222;
_htmlCharacterEntities["Beta"] = (char)914;
_htmlCharacterEntities["beta"] = (char)946;
_htmlCharacterEntities["brvbar"] = (char)166;
_htmlCharacterEntities["bull"] = (char)8226;
_htmlCharacterEntities["cap"] = (char)8745;
_htmlCharacterEntities["Ccedil"] = (char)199;
_htmlCharacterEntities["ccedil"] = (char)231;
_htmlCharacterEntities["cent"] = (char)162;
_htmlCharacterEntities["Chi"] = (char)935;
_htmlCharacterEntities["chi"] = (char)967;
_htmlCharacterEntities["circ"] = (char)710;
_htmlCharacterEntities["clubs"] = (char)9827;
_htmlCharacterEntities["cong"] = (char)8773;
_htmlCharacterEntities["copy"] = (char)169;
_htmlCharacterEntities["crarr"] = (char)8629;
_htmlCharacterEntities["cup"] = (char)8746;
_htmlCharacterEntities["curren"] = (char)164;
_htmlCharacterEntities["dagger"] = (char)8224;
_htmlCharacterEntities["Dagger"] = (char)8225;
_htmlCharacterEntities["darr"] = (char)8595;
_htmlCharacterEntities["dArr"] = (char)8659;
_htmlCharacterEntities["deg"] = (char)176;
_htmlCharacterEntities["Delta"] = (char)916;
_htmlCharacterEntities["delta"] = (char)948;
_htmlCharacterEntities["diams"] = (char)9830;
_htmlCharacterEntities["divide"] = (char)247;
_htmlCharacterEntities["Eacute"] = (char)201;
_htmlCharacterEntities["eacute"] = (char)233;
_htmlCharacterEntities["Ecirc"] = (char)202;
_htmlCharacterEntities["ecirc"] = (char)234;
_htmlCharacterEntities["Egrave"] = (char)200;
_htmlCharacterEntities["egrave"] = (char)232;
_htmlCharacterEntities["empty"] = (char)8709;
_htmlCharacterEntities["emsp"] = (char)8195;
_htmlCharacterEntities["ensp"] = (char)8194;
_htmlCharacterEntities["Epsilon"] = (char)917;
_htmlCharacterEntities["epsilon"] = (char)949;
_htmlCharacterEntities["equiv"] = (char)8801;
_htmlCharacterEntities["Eta"] = (char)919;
_htmlCharacterEntities["eta"] = (char)951;
_htmlCharacterEntities["ETH"] = (char)208;
_htmlCharacterEntities["eth"] = (char)240;
_htmlCharacterEntities["Euml"] = (char)203;
_htmlCharacterEntities["euml"] = (char)235;
_htmlCharacterEntities["euro"] = (char)8364;
_htmlCharacterEntities["exist"] = (char)8707;
_htmlCharacterEntities["fnof"] = (char)402;
_htmlCharacterEntities["forall"] = (char)8704;
_htmlCharacterEntities["frac12"] = (char)189;
_htmlCharacterEntities["frac14"] = (char)188;
_htmlCharacterEntities["frac34"] = (char)190;
_htmlCharacterEntities["frasl"] = (char)8260;
_htmlCharacterEntities["Gamma"] = (char)915;
_htmlCharacterEntities["gamma"] = (char)947;
_htmlCharacterEntities["ge"] = (char)8805;
_htmlCharacterEntities["gt"] = (char)62;
_htmlCharacterEntities["harr"] = (char)8596;
_htmlCharacterEntities["hArr"] = (char)8660;
_htmlCharacterEntities["hearts"] = (char)9829;
_htmlCharacterEntities["hellip"] = (char)8230;
_htmlCharacterEntities["Iacute"] = (char)205;
_htmlCharacterEntities["iacute"] = (char)237;
_htmlCharacterEntities["Icirc"] = (char)206;
_htmlCharacterEntities["icirc"] = (char)238;
_htmlCharacterEntities["iexcl"] = (char)161;
_htmlCharacterEntities["Igrave"] = (char)204;
_htmlCharacterEntities["igrave"] = (char)236;
_htmlCharacterEntities["image"] = (char)8465;
_htmlCharacterEntities["infin"] = (char)8734;
_htmlCharacterEntities["int"] = (char)8747;
_htmlCharacterEntities["Iota"] = (char)921;
_htmlCharacterEntities["iota"] = (char)953;
_htmlCharacterEntities["iquest"] = (char)191;
_htmlCharacterEntities["isin"] = (char)8712;
_htmlCharacterEntities["Iuml"] = (char)207;
_htmlCharacterEntities["iuml"] = (char)239;
_htmlCharacterEntities["Kappa"] = (char)922;
_htmlCharacterEntities["kappa"] = (char)954;
_htmlCharacterEntities["Lambda"] = (char)923;
_htmlCharacterEntities["lambda"] = (char)955;
_htmlCharacterEntities["lang"] = (char)9001;
_htmlCharacterEntities["laquo"] = (char)171;
_htmlCharacterEntities["larr"] = (char)8592;
_htmlCharacterEntities["lArr"] = (char)8656;
_htmlCharacterEntities["lceil"] = (char)8968;
_htmlCharacterEntities["ldquo"] = (char)8220;
_htmlCharacterEntities["le"] = (char)8804;
_htmlCharacterEntities["lfloor"] = (char)8970;
_htmlCharacterEntities["lowast"] = (char)8727;
_htmlCharacterEntities["loz"] = (char)9674;
_htmlCharacterEntities["lrm"] = (char)8206;
_htmlCharacterEntities["lsaquo"] = (char)8249;
_htmlCharacterEntities["lsquo"] = (char)8216;
_htmlCharacterEntities["lt"] = (char)60;
_htmlCharacterEntities["macr"] = (char)175;
_htmlCharacterEntities["mdash"] = (char)8212;
_htmlCharacterEntities["micro"] = (char)181;
_htmlCharacterEntities["middot"] = (char)183;
_htmlCharacterEntities["minus"] = (char)8722;
_htmlCharacterEntities["Mu"] = (char)924;
_htmlCharacterEntities["mu"] = (char)956;
_htmlCharacterEntities["nabla"] = (char)8711;
_htmlCharacterEntities["nbsp"] = (char)160;
_htmlCharacterEntities["ndash"] = (char)8211;
_htmlCharacterEntities["ne"] = (char)8800;
_htmlCharacterEntities["ni"] = (char)8715;
_htmlCharacterEntities["not"] = (char)172;
_htmlCharacterEntities["notin"] = (char)8713;
_htmlCharacterEntities["nsub"] = (char)8836;
_htmlCharacterEntities["Ntilde"] = (char)209;
_htmlCharacterEntities["ntilde"] = (char)241;
_htmlCharacterEntities["Nu"] = (char)925;
_htmlCharacterEntities["nu"] = (char)957;
_htmlCharacterEntities["Oacute"] = (char)211;
_htmlCharacterEntities["ocirc"] = (char)244;
_htmlCharacterEntities["OElig"] = (char)338;
_htmlCharacterEntities["oelig"] = (char)339;
_htmlCharacterEntities["Ograve"] = (char)210;
_htmlCharacterEntities["ograve"] = (char)242;
_htmlCharacterEntities["oline"] = (char)8254;
_htmlCharacterEntities["Omega"] = (char)937;
_htmlCharacterEntities["omega"] = (char)969;
_htmlCharacterEntities["Omicron"] = (char)927;
_htmlCharacterEntities["omicron"] = (char)959;
_htmlCharacterEntities["oplus"] = (char)8853;
_htmlCharacterEntities["or"] = (char)8744;
_htmlCharacterEntities["ordf"] = (char)170;
_htmlCharacterEntities["ordm"] = (char)186;
_htmlCharacterEntities["Oslash"] = (char)216;
_htmlCharacterEntities["oslash"] = (char)248;
_htmlCharacterEntities["Otilde"] = (char)213;
_htmlCharacterEntities["otilde"] = (char)245;
_htmlCharacterEntities["otimes"] = (char)8855;
_htmlCharacterEntities["Ouml"] = (char)214;
_htmlCharacterEntities["ouml"] = (char)246;
_htmlCharacterEntities["para"] = (char)182;
_htmlCharacterEntities["part"] = (char)8706;
_htmlCharacterEntities["permil"] = (char)8240;
_htmlCharacterEntities["perp"] = (char)8869;
_htmlCharacterEntities["Phi"] = (char)934;
_htmlCharacterEntities["phi"] = (char)966;
_htmlCharacterEntities["pi"] = (char)960;
_htmlCharacterEntities["piv"] = (char)982;
_htmlCharacterEntities["plusmn"] = (char)177;
_htmlCharacterEntities["pound"] = (char)163;
_htmlCharacterEntities["prime"] = (char)8242;
_htmlCharacterEntities["Prime"] = (char)8243;
_htmlCharacterEntities["prod"] = (char)8719;
_htmlCharacterEntities["prop"] = (char)8733;
_htmlCharacterEntities["Psi"] = (char)936;
_htmlCharacterEntities["psi"] = (char)968;
_htmlCharacterEntities["quot"] = (char)34;
_htmlCharacterEntities["radic"] = (char)8730;
_htmlCharacterEntities["rang"] = (char)9002;
_htmlCharacterEntities["raquo"] = (char)187;
_htmlCharacterEntities["rarr"] = (char)8594;
_htmlCharacterEntities["rArr"] = (char)8658;
_htmlCharacterEntities["rceil"] = (char)8969;
_htmlCharacterEntities["rdquo"] = (char)8221;
_htmlCharacterEntities["real"] = (char)8476;
_htmlCharacterEntities["reg"] = (char)174;
_htmlCharacterEntities["rfloor"] = (char)8971;
_htmlCharacterEntities["Rho"] = (char)929;
_htmlCharacterEntities["rho"] = (char)961;
_htmlCharacterEntities["rlm"] = (char)8207;
_htmlCharacterEntities["rsaquo"] = (char)8250;
_htmlCharacterEntities["rsquo"] = (char)8217;
_htmlCharacterEntities["sbquo"] = (char)8218;
_htmlCharacterEntities["Scaron"] = (char)352;
_htmlCharacterEntities["scaron"] = (char)353;
_htmlCharacterEntities["sdot"] = (char)8901;
_htmlCharacterEntities["sect"] = (char)167;
_htmlCharacterEntities["shy"] = (char)173;
_htmlCharacterEntities["Sigma"] = (char)931;
_htmlCharacterEntities["sigma"] = (char)963;
_htmlCharacterEntities["sigmaf"] = (char)962;
_htmlCharacterEntities["sim"] = (char)8764;
_htmlCharacterEntities["spades"] = (char)9824;
_htmlCharacterEntities["sub"] = (char)8834;
_htmlCharacterEntities["sube"] = (char)8838;
_htmlCharacterEntities["sum"] = (char)8721;
_htmlCharacterEntities["sup"] = (char)8835;
_htmlCharacterEntities["sup1"] = (char)185;
_htmlCharacterEntities["sup2"] = (char)178;
_htmlCharacterEntities["sup3"] = (char)179;
_htmlCharacterEntities["supe"] = (char)8839;
_htmlCharacterEntities["szlig"] = (char)223;
_htmlCharacterEntities["Tau"] = (char)932;
_htmlCharacterEntities["tau"] = (char)964;
_htmlCharacterEntities["there4"] = (char)8756;
_htmlCharacterEntities["Theta"] = (char)920;
_htmlCharacterEntities["theta"] = (char)952;
_htmlCharacterEntities["thetasym"] = (char)977;
_htmlCharacterEntities["thinsp"] = (char)8201;
_htmlCharacterEntities["THORN"] = (char)222;
_htmlCharacterEntities["thorn"] = (char)254;
_htmlCharacterEntities["tilde"] = (char)732;
_htmlCharacterEntities["times"] = (char)215;
_htmlCharacterEntities["trade"] = (char)8482;
_htmlCharacterEntities["Uacute"] = (char)218;
_htmlCharacterEntities["uacute"] = (char)250;
_htmlCharacterEntities["uarr"] = (char)8593;
_htmlCharacterEntities["uArr"] = (char)8657;
_htmlCharacterEntities["Ucirc"] = (char)219;
_htmlCharacterEntities["ucirc"] = (char)251;
_htmlCharacterEntities["Ugrave"] = (char)217;
_htmlCharacterEntities["ugrave"] = (char)249;
_htmlCharacterEntities["uml"] = (char)168;
_htmlCharacterEntities["upsih"] = (char)978;
_htmlCharacterEntities["Upsilon"] = (char)933;
_htmlCharacterEntities["upsilon"] = (char)965;
_htmlCharacterEntities["Uuml"] = (char)220;
_htmlCharacterEntities["uuml"] = (char)252;
_htmlCharacterEntities["weierp"] = (char)8472;
_htmlCharacterEntities["Xi"] = (char)926;
_htmlCharacterEntities["xi"] = (char)958;
_htmlCharacterEntities["Yacute"] = (char)221;
_htmlCharacterEntities["yacute"] = (char)253;
_htmlCharacterEntities["yen"] = (char)165;
_htmlCharacterEntities["Yuml"] = (char)376;
_htmlCharacterEntities["yuml"] = (char)255;
_htmlCharacterEntities["Zeta"] = (char)918;
_htmlCharacterEntities["zeta"] = (char)950;
_htmlCharacterEntities["zwj"] = (char)8205;
_htmlCharacterEntities["zwnj"] = (char)8204;
}
#endregion Private Methods
// ---------------------------------------------------------------------
//
// Private Fields
//
// ---------------------------------------------------------------------
#region Private Fields
// html element names
// this is an array list now, but we may want to make it a hashtable later for better performance
private static ArrayList _htmlInlineElements;
private static ArrayList _htmlBlockElements;
private static ArrayList _htmlOtherOpenableElements;
// list of html empty element names
private static ArrayList _htmlEmptyElements;
// names of html elements for which closing tags are optional, and close when the outer nested element closes
private static ArrayList _htmlElementsClosingOnParentElementEnd;
// names of elements that close certain optional closing tag elements when they start
// names of elements closing the colgroup element
private static ArrayList _htmlElementsClosingColgroup;
// names of elements closing the dd element
private static ArrayList _htmlElementsClosingDD;
// names of elements closing the dt element
private static ArrayList _htmlElementsClosingDT;
// names of elements closing the li element
private static ArrayList _htmlElementsClosingLI;
// names of elements closing the tbody element
private static ArrayList _htmlElementsClosingTbody;
// names of elements closing the td element
private static ArrayList _htmlElementsClosingTD;
// names of elements closing the tfoot element
private static ArrayList _htmlElementsClosingTfoot;
// names of elements closing the thead element
private static ArrayList _htmlElementsClosingThead;
// names of elements closing the th element
private static ArrayList _htmlElementsClosingTH;
// names of elements closing the tr element
private static ArrayList _htmlElementsClosingTR;
// html character entities hashtable
private static Hashtable _htmlCharacterEntities;
#endregion Private Fields
}
}
| |
// ***********************************************************************
// Copyright (c) 2009-2018 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.TestData;
using NUnit.TestUtilities;
namespace NUnit.Framework.Attributes
{
public partial class RangeAttributeTests
{
#region Shared specs
public static IEnumerable<Type> TestedParameterTypes() => new[]
{
typeof(sbyte),
typeof(byte),
typeof(short),
typeof(ushort),
typeof(int),
typeof(uint),
typeof(long),
typeof(ulong),
typeof(float),
typeof(double),
typeof(decimal)
};
// See XML docs for the ParamAttributeTypeConversions class.
private static readonly Type[] Int32RangeConvertibleToParameterTypes = { typeof(int), typeof(sbyte), typeof(byte), typeof(short), typeof(decimal) };
private static readonly Type[] UInt32RangeConvertibleToParameterTypes = { typeof(uint) };
private static readonly Type[] Int64RangeConvertibleToParameterTypes = { typeof(long) };
private static readonly Type[] UInt64RangeConvertibleToParameterTypes = { typeof(ulong) };
private static readonly Type[] SingleRangeConvertibleToParameterTypes = { typeof(float) };
private static readonly Type[] DoubleRangeConvertibleToParameterTypes = { typeof(double), typeof(decimal) };
#endregion
[Test]
public void MultipleAttributes()
{
Test test = TestBuilder.MakeParameterizedMethodSuite(typeof(RangeTestFixture), nameof(RangeTestFixture.MethodWithMultipleRanges));
var arguments = from testCase in test.Tests select testCase.Arguments[0];
Assert.That(arguments, Is.EquivalentTo(new[] { 1, 2, 3, 10, 11, 12 }));
}
#region Forward
public static IEnumerable<RangeWithExpectedConversions> ForwardRangeCases => new[]
{
new RangeWithExpectedConversions(new RangeAttribute(11, 15), Int32RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11u, 15u), UInt32RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11L, 15L), Int64RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11UL, 15UL), UInt64RangeConvertibleToParameterTypes)
};
[Test]
public static void ForwardRange(
[ValueSource(nameof(ForwardRangeCases))] RangeWithExpectedConversions rangeWithExpectedConversions,
[ValueSource(nameof(TestedParameterTypes))] Type parameterType)
{
rangeWithExpectedConversions.AssertCoercionErrorOrMatchingSequence(
parameterType, new[] { 11, 12, 13, 14, 15 });
}
#endregion
#region Backward
public static IEnumerable<RangeWithExpectedConversions> BackwardRangeCases => new[]
{
new RangeWithExpectedConversions(new RangeAttribute(15, 11), Int32RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(15L, 11L), Int64RangeConvertibleToParameterTypes)
};
[Test]
public static void BackwardRange(
[ValueSource(nameof(BackwardRangeCases))] RangeWithExpectedConversions rangeWithExpectedConversions,
[ValueSource(nameof(TestedParameterTypes))] Type parameterType)
{
rangeWithExpectedConversions.AssertCoercionErrorOrMatchingSequence(
parameterType, new[] { 15, 14, 13, 12, 11 });
}
[Test]
public static void BackwardRangeDisallowed_UInt32()
{
Assert.That(() => new RangeAttribute(15u, 11u), Throws.InstanceOf<ArgumentException>());
}
[Test]
public static void BackwardRangeDisallowed_UInt64()
{
Assert.That(() => new RangeAttribute(15UL, 11UL), Throws.InstanceOf<ArgumentException>());
}
#endregion
#region Degenerate
public static IEnumerable<RangeWithExpectedConversions> DegenerateRangeCases => new[]
{
new RangeWithExpectedConversions(new RangeAttribute(11, 11), Int32RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11u, 11u), UInt32RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11L, 11L), Int64RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11UL, 11UL), UInt64RangeConvertibleToParameterTypes)
};
[Test]
public static void DegenerateRange(
[ValueSource(nameof(DegenerateRangeCases))] RangeWithExpectedConversions rangeWithExpectedConversions,
[ValueSource(nameof(TestedParameterTypes))] Type parameterType)
{
rangeWithExpectedConversions.AssertCoercionErrorOrMatchingSequence(
parameterType, new[] { 11 });
}
public static IEnumerable<RangeWithExpectedConversions> DegeneratePositiveStepRangeCases => new[]
{
new RangeWithExpectedConversions(new RangeAttribute(11, 11, 2), Int32RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11u, 11u, 2u), UInt32RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11L, 11L, 2L), Int64RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11UL, 11UL, 2UL), UInt64RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11f, 11f, 2f), SingleRangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11d, 11d, 2d), DoubleRangeConvertibleToParameterTypes)
};
[Test]
public static void DegeneratePositiveStepRangeDisallowed_Int32(
[ValueSource(nameof(DegeneratePositiveStepRangeCases))] RangeWithExpectedConversions rangeWithExpectedConversions,
[ValueSource(nameof(TestedParameterTypes))] Type parameterType)
{
rangeWithExpectedConversions.AssertCoercionErrorOrMatchingSequence(
parameterType, new[] { 11 });
}
public static IEnumerable<RangeWithExpectedConversions> DegenerateNegativeStepRangeCases => new[]
{
new RangeWithExpectedConversions(new RangeAttribute(11, 11, -2), Int32RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11L, 11L, -2L), Int64RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11f, 11f, -2f), SingleRangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11d, 11d, -2d), DoubleRangeConvertibleToParameterTypes)
};
[Test]
public static void DegenerateNegativeStepRange(
[ValueSource(nameof(DegenerateNegativeStepRangeCases))] RangeWithExpectedConversions rangeWithExpectedConversions,
[ValueSource(nameof(TestedParameterTypes))] Type parameterType)
{
rangeWithExpectedConversions.AssertCoercionErrorOrMatchingSequence(
parameterType, new[] { 11 });
}
[Test]
public static void DegenerateZeroStepRangeDisallowed_Int32()
{
Assert.That(() => new RangeAttribute(11, 11, 0), Throws.InstanceOf<ArgumentException>());
}
[Test]
public static void DegenerateZeroStepRangeDisallowed_Int64()
{
Assert.That(() => new RangeAttribute(11L, 11L, 0L), Throws.InstanceOf<ArgumentException>());
}
[Test]
public static void DegenerateZeroStepRangeDisallowed_Single()
{
Assert.That(() => new RangeAttribute(11f, 11f, 0f), Throws.InstanceOf<ArgumentException>());
}
[Test]
public static void DegenerateZeroStepRangeDisallowed_Double()
{
Assert.That(() => new RangeAttribute(11d, 11d, 0d), Throws.InstanceOf<ArgumentException>());
}
#endregion
#region Forward step
public static IEnumerable<RangeWithExpectedConversions> ForwardStepRangeCases => new[]
{
new RangeWithExpectedConversions(new RangeAttribute(11, 15, 2), Int32RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11u, 15u, 2u), UInt32RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11L, 15L, 2L), Int64RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11UL, 15UL, 2UL), UInt64RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11f, 15f, 2f), SingleRangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11d, 15d, 2d), DoubleRangeConvertibleToParameterTypes)
};
[Test]
public static void ForwardStepRange(
[ValueSource(nameof(ForwardStepRangeCases))] RangeWithExpectedConversions rangeWithExpectedConversions,
[ValueSource(nameof(TestedParameterTypes))] Type parameterType)
{
rangeWithExpectedConversions.AssertCoercionErrorOrMatchingSequence(
parameterType, new[] { 11, 13, 15 });
}
#endregion
#region Backward step
public static IEnumerable<RangeWithExpectedConversions> BackwardStepRangeCases => new[]
{
new RangeWithExpectedConversions(new RangeAttribute(15, 11, -2), Int32RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(15L, 11L, -2L), Int64RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(15f, 11f, -2f), SingleRangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(15d, 11d, -2d), DoubleRangeConvertibleToParameterTypes)
};
[Test]
public static void BackwardStepRange(
[ValueSource(nameof(BackwardStepRangeCases))] RangeWithExpectedConversions rangeWithExpectedConversions,
[ValueSource(nameof(TestedParameterTypes))] Type parameterType)
{
rangeWithExpectedConversions.AssertCoercionErrorOrMatchingSequence(
parameterType, new[] { 15, 13, 11 });
}
#endregion
#region Zero step
[Test]
public static void ZeroStepRangeDisallowed_Int32()
{
Assert.That(() => new RangeAttribute(11, 15, 0), Throws.InstanceOf<ArgumentException>());
}
[Test]
public static void ZeroStepRangeDisallowed_UInt32()
{
Assert.That(() => new RangeAttribute(11u, 15u, 0u), Throws.InstanceOf<ArgumentException>());
}
[Test]
public static void ZeroStepRangeDisallowed_Int64()
{
Assert.That(() => new RangeAttribute(11L, 15L, 0L), Throws.InstanceOf<ArgumentException>());
}
[Test]
public static void ZeroStepRangeDisallowed_UInt64()
{
Assert.That(() => new RangeAttribute(11UL, 15UL, 0UL), Throws.InstanceOf<ArgumentException>());
}
[Test]
public static void ZeroStepRangeDisallowed_Single()
{
Assert.That(() => new RangeAttribute(11f, 15f, 0f), Throws.InstanceOf<ArgumentException>());
}
[Test]
public static void ZeroStepRangeDisallowed_Double()
{
Assert.That(() => new RangeAttribute(11d, 15d, 0d), Throws.InstanceOf<ArgumentException>());
}
#endregion
#region Opposing step
[Test]
public static void OpposingStepForwardRangeDisallowed_Int32()
{
Assert.That(() => new RangeAttribute(11, 15, -2), Throws.InstanceOf<ArgumentException>());
}
[Test]
public static void OpposingStepBackwardRangeDisallowed_Int32()
{
Assert.That(() => new RangeAttribute(15, 11, 2), Throws.InstanceOf<ArgumentException>());
}
[Test]
public static void OppositeStepForwardRangeDisallowed_Int64()
{
Assert.That(() => new RangeAttribute(11L, 15L, -2L), Throws.InstanceOf<ArgumentException>());
}
[Test]
public static void OpposingStepBackwardRangeDisallowed_Int64()
{
Assert.That(() => new RangeAttribute(15L, 11L, 2L), Throws.InstanceOf<ArgumentException>());
}
[Test]
public static void OppositeStepForwardRangeDisallowed_Single()
{
Assert.That(() => new RangeAttribute(11f, 15f, -2f), Throws.InstanceOf<ArgumentException>());
}
[Test]
public static void OpposingStepBackwardRangeDisallowed_Single()
{
Assert.That(() => new RangeAttribute(15f, 11f, 2f), Throws.InstanceOf<ArgumentException>());
}
[Test]
public static void OppositeForwardRangeDisallowed_Double()
{
Assert.That(() => new RangeAttribute(11d, 15d, -2d), Throws.InstanceOf<ArgumentException>());
}
[Test]
public static void OpposingStepBackwardRangeDisallowed_Double()
{
Assert.That(() => new RangeAttribute(15d, 11d, 2d), Throws.InstanceOf<ArgumentException>());
}
#endregion
// The smallest distance from MaxValue or MinValue which results in a different number,
// overcoming loss of precision.
// Calculated by hand by flipping bits. Used the round-trip format and double-checked.
private const float SingleExtremaEpsilon = 2.028241E+31f;
private const double DoubleExtremaEpsilon = 1.99584030953472E+292;
private const double LargestDoubleConvertibleToDecimal = 7.9228162514264329E+28;
private const double NextLargestDoubleConvertibleToLowerDecimal = 7.92281625142642E+28;
#region MaxValue
[Test]
public static void MaxValueRange_Int32()
{
Assert.That(
GetData(new RangeAttribute(int.MaxValue - 2, int.MaxValue), typeof(int)),
Is.EqualTo(new[] { int.MaxValue - 2, int.MaxValue - 1, int.MaxValue }));
}
[Test]
public static void MaxValueRange_UInt32()
{
Assert.That(
GetData(new RangeAttribute(uint.MaxValue - 2, uint.MaxValue), typeof(uint)),
Is.EqualTo(new[] { uint.MaxValue - 2, uint.MaxValue - 1, uint.MaxValue }));
}
[Test]
public static void MaxValueRange_Int64()
{
Assert.That(
GetData(new RangeAttribute(long.MaxValue - 2, long.MaxValue), typeof(long)),
Is.EqualTo(new[] { long.MaxValue - 2, long.MaxValue - 1, long.MaxValue }));
}
[Test]
public static void MaxValueRange_UInt64()
{
Assert.That(
GetData(new RangeAttribute(ulong.MaxValue - 2, ulong.MaxValue), typeof(ulong)),
Is.EqualTo(new[] { ulong.MaxValue - 2, ulong.MaxValue - 1, ulong.MaxValue }));
}
[Test]
public static void MaxValueRange_Single()
{
Assert.That(
GetData(new RangeAttribute(float.MaxValue - SingleExtremaEpsilon * 2, float.MaxValue, SingleExtremaEpsilon), typeof(float)),
Is.EqualTo(new[] { float.MaxValue - SingleExtremaEpsilon * 2, float.MaxValue - SingleExtremaEpsilon, float.MaxValue }));
}
[Test]
public static void MaxValueRangeLosingPrecision_Single()
{
Assert.That(() => GetData(new RangeAttribute(float.MaxValue - SingleExtremaEpsilon, float.MaxValue, SingleExtremaEpsilon / 2), typeof(float)),
Throws.InstanceOf<ArithmeticException>());
}
[Test]
public static void MaxValueRange_Double()
{
Assert.That(
GetData(new RangeAttribute(double.MaxValue - DoubleExtremaEpsilon * 2, double.MaxValue, DoubleExtremaEpsilon), typeof(double)),
Is.EqualTo(new[] { double.MaxValue - DoubleExtremaEpsilon * 2, double.MaxValue - DoubleExtremaEpsilon, double.MaxValue }));
}
[Test]
public static void MaxValueRangeLosingPrecision_Double()
{
Assert.That(() => GetData(new RangeAttribute(double.MaxValue - DoubleExtremaEpsilon, double.MaxValue, DoubleExtremaEpsilon / 2), typeof(double)),
Throws.InstanceOf<ArithmeticException>());
}
[Test]
public static void MaxValueRange_Decimal()
{
const decimal fromDecimal = (decimal)NextLargestDoubleConvertibleToLowerDecimal;
const decimal toDecimal = (decimal)LargestDoubleConvertibleToDecimal;
const double step = (double)((toDecimal - fromDecimal) / 2);
Assert.That(
GetData(new RangeAttribute(NextLargestDoubleConvertibleToLowerDecimal, LargestDoubleConvertibleToDecimal, step), typeof(decimal)),
Is.EqualTo(new[]
{
fromDecimal,
fromDecimal + (decimal)step,
fromDecimal + (decimal)step * 2
}));
}
[Test]
public static void MaxValueRangeLosingPrecision_Decimal()
{
Assert.That(() => GetData(new RangeAttribute(NextLargestDoubleConvertibleToLowerDecimal, LargestDoubleConvertibleToDecimal, 0.1), typeof(decimal)),
Throws.InstanceOf<ArithmeticException>());
}
#endregion
#region MinValue
[Test]
public static void MinValueRange_Int32()
{
Assert.That(
GetData(new RangeAttribute(int.MinValue + 2, int.MinValue), typeof(int)),
Is.EqualTo(new[] { int.MinValue + 2, int.MinValue + 1, int.MinValue }));
}
[Test]
public static void MinValueRange_Int64()
{
Assert.That(
GetData(new RangeAttribute(long.MinValue + 2, long.MinValue), typeof(long)),
Is.EqualTo(new[] { long.MinValue + 2, long.MinValue + 1, long.MinValue }));
}
[Test]
public static void MinValueRange_Single()
{
Assert.That(
GetData(new RangeAttribute(float.MinValue + SingleExtremaEpsilon * 2, float.MinValue, -SingleExtremaEpsilon), typeof(float)),
Is.EqualTo(new[] { float.MinValue + SingleExtremaEpsilon * 2, float.MinValue + SingleExtremaEpsilon, float.MinValue }));
}
[Test]
public static void MinValueRangeLosingPrecision_Single()
{
Assert.That(() => GetData(new RangeAttribute(float.MinValue + SingleExtremaEpsilon, float.MinValue, -SingleExtremaEpsilon / 2), typeof(float)),
Throws.InstanceOf<ArithmeticException>());
}
[Test]
public static void MinValueRange_Double()
{
Assert.That(
GetData(new RangeAttribute(double.MinValue + DoubleExtremaEpsilon * 2, double.MinValue, -DoubleExtremaEpsilon), typeof(double)),
Is.EqualTo(new[] { double.MinValue + DoubleExtremaEpsilon * 2, double.MinValue + DoubleExtremaEpsilon, double.MinValue }));
}
[Test]
public static void MinValueRangeLosingPrecision_Double()
{
Assert.That(() => GetData(new RangeAttribute(double.MinValue + DoubleExtremaEpsilon, double.MinValue, -DoubleExtremaEpsilon / 2), typeof(double)),
Throws.InstanceOf<ArithmeticException>());
}
[Test]
public static void MinValueRange_Decimal()
{
const decimal fromDecimal = -(decimal)NextLargestDoubleConvertibleToLowerDecimal;
const decimal toDecimal = -(decimal)LargestDoubleConvertibleToDecimal;
const double step = (double)((toDecimal - fromDecimal) / 2);
Assert.That(
GetData(new RangeAttribute(-NextLargestDoubleConvertibleToLowerDecimal, -LargestDoubleConvertibleToDecimal, step), typeof(decimal)),
Is.EqualTo(new[]
{
fromDecimal,
fromDecimal + (decimal)step,
fromDecimal + (decimal)step * 2
}));
}
[Test]
public static void MinValueRangeLosingPrecision_Decimal()
{
Assert.That(() => GetData(new RangeAttribute(-NextLargestDoubleConvertibleToLowerDecimal, -LargestDoubleConvertibleToDecimal, -0.1), typeof(decimal)),
Throws.InstanceOf<ArithmeticException>());
}
#endregion
private static object[] GetData(RangeAttribute rangeAttribute, Type parameterType)
{
return rangeAttribute.GetData(new StubParameterInfo(parameterType)).Cast<object>().ToArray();
}
private sealed class StubParameterInfo : IParameterInfo
{
public StubParameterInfo(Type parameterType)
{
ParameterType = parameterType;
}
public Type ParameterType { get; }
public bool IsOptional
{
get { throw new NotImplementedException(); }
}
public IMethodInfo Method
{
get { throw new NotImplementedException(); }
}
public ParameterInfo ParameterInfo
{
get { throw new NotImplementedException(); }
}
public T[] GetCustomAttributes<T>(bool inherit) where T : class
{
throw new NotImplementedException();
}
public bool IsDefined<T>(bool inherit) where T : class
{
throw new NotImplementedException();
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using liquicode.AppTools;
using NUnit.Framework;
public class FileSystemTests
{
//---------------------------------------------------------------------
protected FileSystemProvider _FileSystem = new LocalFileSystem( Path.GetTempPath() );
//---------------------------------------------------------------------
protected string GetConfigValue( string ConfigPathname, string ValueName )
{
foreach( string fileline in File.ReadAllLines( ConfigPathname ) )
{
string line = fileline.Trim();
if( !line.StartsWith( ValueName, StringComparison.InvariantCultureIgnoreCase ) ) { continue; }
line = line.Substring( ValueName.Length ).Trim();
if( !line.StartsWith( "=" ) ) { continue; }
line = line.Substring( 1 ).Trim();
return line;
}
return "";
}
//---------------------------------------------------------------------
private string FitString( string Text, int size )
{
if( Text.Length > size ) { Text = Text.Substring( 0, size ); }
if( Text.Length < size ) { Text = Text.PadRight( size ); }
return Text;
}
//---------------------------------------------------------------------
protected void WriteItemSummary( FileSystemItem item )
{
string s = "";
s = " --- ";
s += item.Size.ToString();
s = this.FitString( s, 25 );
if( item.DateLastWrite.HasValue ) { s += item.DateLastWrite; }
s = this.FitString( s, 50 );
if( item.DateLastRead.HasValue ) { s += item.DateLastRead; }
s = this.FitString( s, 75 );
if( item.DateCreated.HasValue ) { s += item.DateCreated; }
s = this.FitString( s, 100 );
Console.Out.WriteLine( s );
if( item.IsLink )
{ Console.Out.WriteLine( " -> " + item.LinkTarget ); }
s = item.Pathname;
if( item.IsFolder ) { s = "[" + s + "]"; }
if( item.IsLink ) { s = "<" + s + ">"; }
Console.Out.WriteLine( s );
return;
}
//---------------------------------------------------------------------
[Test]
public void T01_Settings()
{
Console.Out.WriteLine( "Settings." );
Hashtable settings = this._FileSystem.Settings();
foreach( string sKey in settings.Keys )
{
string sValue = settings[ sKey ].ToString();
Console.WriteLine( sKey + " = " + sValue );
}
return;
}
//---------------------------------------------------------------------
[Test]
public void T11_ListFolders()
{
Commands.ListEntriesCommand ListCommand = new Commands.ListEntriesCommand();
ListCommand.in_Pathname = "";
ListCommand.in_IncludeFolders = true;
ListCommand.in_IncludeLinks = true;
this._FileSystem.List( ListCommand );
Console.Out.WriteLine( "ListFolders for '" + ListCommand.in_Pathname + "' found " + ListCommand.out_ItemList.Count.ToString() + " item(s)." );
foreach( FileSystemItem item in ListCommand.out_ItemList )
{ this.WriteItemSummary( item ); }
return;
}
//---------------------------------------------------------------------
[Test]
public void T12_ListFolderItems()
{
Commands.ListEntriesCommand ListCommand = new Commands.ListEntriesCommand();
ListCommand.in_Pathname = "";
ListCommand.in_IncludeFolders = true;
ListCommand.in_IncludeLinks = true;
this._FileSystem.List( ListCommand );
Console.Out.WriteLine( "ListFolders2 for '" + ListCommand.in_Pathname + "' found " + ListCommand.out_ItemList.Count.ToString() + " item(s)." );
foreach( FileSystemItem item in ListCommand.out_ItemList )
{
Commands.ReadItemCommand ReadCommand = new Commands.ReadItemCommand();
ReadCommand.in_Pathname = item.Pathname;
this._FileSystem.Read( ReadCommand );
this.WriteItemSummary( ReadCommand.out_Item );
}
return;
}
//---------------------------------------------------------------------
[Test]
public void T13_CreateFolder()
{
Commands.CreateItemCommand CreateCommand = new Commands.CreateItemCommand();
CreateCommand.in_Pathname = "TestFolder1";
CreateCommand.in_IsFolder = true;
CreateCommand.in_CreatePath = true;
this._FileSystem.Create( CreateCommand );
Console.Out.WriteLine( "Created '" + CreateCommand.out_Item.Pathname + "'." );
this.WriteItemSummary( CreateCommand.out_Item );
return;
}
//---------------------------------------------------------------------
[Test]
public void T14_ReadFolder()
{
Commands.ReadItemCommand ReadCommand = new Commands.ReadItemCommand();
ReadCommand.in_Pathname = "TestFolder1";
this._FileSystem.Read( ReadCommand );
Console.Out.WriteLine( "Read '" + ReadCommand.out_Item.Pathname + "'." );
this.WriteItemSummary( ReadCommand.out_Item );
return;
}
//---------------------------------------------------------------------
[Test]
public void T15_UpdateFolder()
{
Commands.ReadItemCommand ReadCommand = new Commands.ReadItemCommand();
ReadCommand.in_Pathname = "TestFolder1";
this._FileSystem.Read( ReadCommand );
if( ReadCommand.out_Item == null ) { throw new Exception( "Folder '" + ReadCommand.in_Pathname + "' does not exist.'" ); }
Commands.UpdateItemCommand UpdateCommand = new Commands.UpdateItemCommand();
UpdateCommand.in_Pathname = ReadCommand.out_Item.Pathname;
UpdateCommand.in_Item = ReadCommand.out_Item;
UpdateCommand.in_Item.Name = "RenamedTestFolder1";
this._FileSystem.Update( UpdateCommand );
UpdateCommand.in_Pathname = "RenamedTestFolder1";
UpdateCommand.in_Item = UpdateCommand.out_Item;
UpdateCommand.in_Item.Name = "TestFolder1";
this._FileSystem.Update( UpdateCommand );
Console.Out.WriteLine( "Updated '" + UpdateCommand.out_Item.Pathname + "'." );
this.WriteItemSummary( UpdateCommand.out_Item );
return;
}
//---------------------------------------------------------------------
[Test]
public void T16_DeleteFolder()
{
Commands.DeleteItemCommand DeleteCommand = new Commands.DeleteItemCommand();
DeleteCommand.in_Pathname = "TestFolder1";
DeleteCommand.in_IsFolder = true;
this._FileSystem.Delete( DeleteCommand );
Console.Out.WriteLine( "Deleted '" + DeleteCommand.in_Pathname + "'." );
return;
}
//---------------------------------------------------------------------
[Test]
public void T17_FolderCRUD()
{
Commands.CreateItemCommand CreateCommand = new Commands.CreateItemCommand();
CreateCommand.in_Pathname = "TestFolder1";
CreateCommand.in_IsFolder = true;
CreateCommand.in_CreatePath = true;
this._FileSystem.Create( CreateCommand );
Console.Out.WriteLine( "Created '" + CreateCommand.out_Item.Pathname + "'." );
this.WriteItemSummary( CreateCommand.out_Item );
Commands.ReadItemCommand ReadCommand = new Commands.ReadItemCommand();
ReadCommand.in_Pathname = CreateCommand.out_Item.Pathname;
this._FileSystem.Read( ReadCommand );
Console.Out.WriteLine( "Read '" + ReadCommand.out_Item.Pathname + "'." );
this.WriteItemSummary( ReadCommand.out_Item );
Commands.UpdateItemCommand UpdateCommand = new Commands.UpdateItemCommand();
UpdateCommand.in_Pathname = ReadCommand.out_Item.Pathname;
UpdateCommand.in_Item = ReadCommand.out_Item;
UpdateCommand.in_Item.Name = "RenamedTestFolder1";
this._FileSystem.Update( UpdateCommand );
Console.Out.WriteLine( "Updated '" + UpdateCommand.out_Item.Pathname + "'." );
this.WriteItemSummary( UpdateCommand.out_Item );
Commands.DeleteItemCommand DeleteCommand = new Commands.DeleteItemCommand();
DeleteCommand.in_Pathname = UpdateCommand.out_Item.Pathname;
DeleteCommand.in_IsFolder = true;
this._FileSystem.Delete( DeleteCommand );
Console.Out.WriteLine( "Deleted '" + DeleteCommand.in_Pathname + "'." );
return;
}
//---------------------------------------------------------------------
[Test]
public void T21_ListFiles()
{
Commands.ListEntriesCommand ListCommand = new Commands.ListEntriesCommand();
ListCommand.in_Pathname = "";
ListCommand.in_IncludeFiles = true;
this._FileSystem.List( ListCommand );
Console.Out.WriteLine( "ListFiles for '" + ListCommand.in_Pathname + "' found " + ListCommand.out_ItemList.Count.ToString() + " item(s)." );
foreach( FileSystemItem item in ListCommand.out_ItemList )
{ this.WriteItemSummary( item ); }
return;
}
//---------------------------------------------------------------------
[Test]
public void T22_ListFileItems()
{
Commands.ListEntriesCommand ListCommand = new Commands.ListEntriesCommand();
ListCommand.in_Pathname = "";
ListCommand.in_IncludeFiles = true;
this._FileSystem.List( ListCommand );
Console.Out.WriteLine( "ListFiles2 for '" + ListCommand.in_Pathname + "' found " + ListCommand.out_ItemList.Count.ToString() + " item(s)." );
foreach( FileSystemItem item in ListCommand.out_ItemList )
{
Commands.ReadItemCommand ReadCommand = new Commands.ReadItemCommand();
ReadCommand.in_Pathname = item.Pathname;
this._FileSystem.Read( ReadCommand );
this.WriteItemSummary( ReadCommand.out_Item );
}
return;
}
//---------------------------------------------------------------------
[Test]
public void T23_CreateFile()
{
Commands.CreateItemCommand CreateCommand = new Commands.CreateItemCommand();
CreateCommand.in_Pathname = "TestFile1";
CreateCommand.in_IsFolder = false;
CreateCommand.in_CreatePath = true;
this._FileSystem.Create( CreateCommand );
Console.Out.WriteLine( "Created '" + CreateCommand.out_Item.Pathname + "'." );
this.WriteItemSummary( CreateCommand.out_Item );
return;
}
//---------------------------------------------------------------------
[Test]
public void T24_ReadFile()
{
Commands.ReadItemCommand ReadCommand = new Commands.ReadItemCommand();
ReadCommand.in_Pathname = "TestFile1";
this._FileSystem.Read( ReadCommand );
Console.Out.WriteLine( "Read '" + ReadCommand.out_Item.Pathname + "'." );
this.WriteItemSummary( ReadCommand.out_Item );
return;
}
//---------------------------------------------------------------------
[Test]
public void T25_UpdateFile()
{
Commands.ReadItemCommand ReadCommand = new Commands.ReadItemCommand();
ReadCommand.in_Pathname = "TestFile1";
this._FileSystem.Read( ReadCommand );
if( ReadCommand.out_Item == null ) { throw new Exception( "Folder '" + ReadCommand.in_Pathname + "' does not exist.'" ); }
Commands.UpdateItemCommand UpdateCommand = new Commands.UpdateItemCommand();
UpdateCommand.in_Pathname = ReadCommand.out_Item.Pathname;
UpdateCommand.in_Item = ReadCommand.out_Item;
UpdateCommand.in_Item.Name = "RenamedTestFile1";
this._FileSystem.Update( UpdateCommand );
UpdateCommand.in_Pathname = "RenamedTestFile1";
UpdateCommand.in_Item = UpdateCommand.out_Item;
UpdateCommand.in_Item.Name = "TestFile1";
this._FileSystem.Update( UpdateCommand );
Console.Out.WriteLine( "Updated '" + UpdateCommand.out_Item.Pathname + "'." );
this.WriteItemSummary( UpdateCommand.out_Item );
return;
}
//---------------------------------------------------------------------
[Test]
public void T26_DeleteFile()
{
Commands.DeleteItemCommand DeleteCommand = new Commands.DeleteItemCommand();
DeleteCommand.in_Pathname = "TestFile1";
DeleteCommand.in_IsFolder = false;
this._FileSystem.Delete( DeleteCommand );
Console.Out.WriteLine( "Deleted '" + DeleteCommand.in_Pathname + "'." );
return;
}
//---------------------------------------------------------------------
[Test]
public void T27_FileCRUD()
{
Commands.CreateItemCommand CreateCommand = new Commands.CreateItemCommand();
CreateCommand.in_Pathname = "TestFile1";
CreateCommand.in_IsFolder = false;
CreateCommand.in_CreatePath = true;
this._FileSystem.Create( CreateCommand );
Console.Out.WriteLine( "Created '" + CreateCommand.out_Item.Pathname + "'." );
this.WriteItemSummary( CreateCommand.out_Item );
Commands.ReadItemCommand ReadCommand = new Commands.ReadItemCommand();
ReadCommand.in_Pathname = CreateCommand.out_Item.Pathname;
this._FileSystem.Read( ReadCommand );
Console.Out.WriteLine( "Read '" + ReadCommand.out_Item.Pathname + "'." );
this.WriteItemSummary( ReadCommand.out_Item );
Commands.UpdateItemCommand UpdateCommand = new Commands.UpdateItemCommand();
UpdateCommand.in_Pathname = ReadCommand.out_Item.Pathname;
UpdateCommand.in_Item = ReadCommand.out_Item;
UpdateCommand.in_Item.Name = "RenamedTestFile1";
this._FileSystem.Update( UpdateCommand );
Console.Out.WriteLine( "Updated '" + UpdateCommand.out_Item.Pathname + "'." );
this.WriteItemSummary( UpdateCommand.out_Item );
Commands.DeleteItemCommand DeleteCommand = new Commands.DeleteItemCommand();
DeleteCommand.in_Pathname = UpdateCommand.out_Item.Pathname;
DeleteCommand.in_IsFolder = false;
this._FileSystem.Delete( DeleteCommand );
Console.Out.WriteLine( "Deleted '" + DeleteCommand.in_Pathname + "'." );
return;
}
//---------------------------------------------------------------------
[Test]
public void T31_Compare()
{
FileSystemItem item1 = this._FileSystem.Create( "TestFile1", false, true );
FileSystemItem item2 = this._FileSystem.Create( "TestFile2", false, true );
ComparisonResult comparison = ComparisonResult.Equal;
comparison = FileSystemItem.CompareItems( item1, item2, FileSystemFields.FieldsDateLastWrite );
//Assert.AreEqual( ComparisonResult.Item1IsLesser, comparison, "Item1 is older than Item2." );
Console.Out.WriteLine( "Comparison = " + comparison.ToString() + "." );
Console.Out.WriteLine( "item1.DateLastWrite = item2.DateLastWrite;" );
item1.DateLastWrite = item2.DateLastWrite;
item1 = this._FileSystem.Update( item1.Pathname, item1.IsFolder, item1 );
comparison = FileSystemItem.CompareItems( item1, item2, FileSystemFields.FieldsDateLastWrite );
//Assert.AreEqual( ComparisonResult.Equal, comparison, "Item1 and Item2 are equal." );
Console.Out.WriteLine( "Comparison = " + comparison.ToString() + "." );
this._FileSystem.Delete( "TestFile1", false );
this._FileSystem.Delete( "TestFile2", false );
return;
}
}
| |
using System.Data;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using LambdicSql;
using LambdicSql.feat.Dapper;
using static LambdicSql.SqlServer.Symbol;
using Test.Helper;
using LambdicSql.SqlServer;
namespace Test
{
[TestClass]
public class TestSymbolFuncsMetadata
{
public TestContext TestContext { get; set; }
public IDbConnection _connection;
[TestInitialize]
public void TestInitialize()
{
_connection = TestEnvironment.CreateConnection(TestContext);
_connection.Open();
}
[TestCleanup]
public void TestCleanup() => _connection.Dispose();
[TestMethod]
[Priority(1)]
public void Test_ObjectToParameter_1()
{
var sql = Db<DB>.Sql(db => Select(Object_Id(db.tbl_staff)));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
OBJECT_ID(@p_0)", "tbl_staff");
}
[TestMethod]
[Priority(1)]
public void Test_ObjectToParameter_2()
{
var sql = Db<DB>.Sql(db => Select(Object_Id("tbl_staff")));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
OBJECT_ID(@p_0)", "tbl_staff");
}
[TestMethod]
[Priority(1)]
public void Test_AtAtProcId()
{
var sql = Db<DB>.Sql(db => Select(AtAtProcId()));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
@@PROCID");
}
[TestMethod]
[Priority(1)]
public void Test_AppName()
{
var sql = Db<DB>.Sql(db => Select(App_Name()));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
APP_NAME()");
}
[TestMethod]
[Priority(1)]
public void Test_AssemblyProperty()
{
var sql = Db<DB>.Sql(db => Select(AssemblyProperty("HelloWorld", "PublicKey")));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
ASSEMBLYPROPERTY(@p_0, @p_1)", "HelloWorld", "PublicKey");
}
[TestMethod]
[Priority(1)]
public void Test_Col_Length()
{
var sql = Db<DB>.Sql(db => Select(Col_Length(db.tbl_staff, db.tbl_staff.id)));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
COL_LENGTH(@p_0, @p_1)", "tbl_staff", "id");
}
[TestMethod]
[Priority(1)]
public void Test_Col_Name()
{
var sql = Db<DB>.Sql(db => Select(Col_Name(Object_Id(db.tbl_staff), 1)));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
Assert.AreEqual(sql.Build(_connection.GetType()).Text,
@"SELECT
COL_NAME(OBJECT_ID(@p_0), @p_1)");
}
[TestMethod]
[Priority(1)]
public void Test_ColumnProperty()
{
var sql = Db<DB>.Sql(db => Select(ColumnProperty(Object_Id(db.tbl_staff), db.tbl_staff.id, "PRECISION")));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
COLUMNPROPERTY(OBJECT_ID(@p_0), @p_1, @p_2)", "tbl_staff", "id", "PRECISION");
}
[TestMethod]
[Priority(1)]
public void Test_DataBase_Principal_Id_1()
{
var sql = Db<DB>.Sql(db => Select(DataBase_Principal_Id()));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
DATABASE_PRINCIPAL_ID()");
}
[TestMethod]
[Priority(1)]
public void Test_DataBase_Principal_Id_2()
{
var sql = Db<DB>.Sql(db => Select(DataBase_Principal_Id("db_owner")));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
DATABASE_PRINCIPAL_ID(@p_0)", "db_owner");
}
[TestMethod]
[Priority(1)]
public void Test_DataBasePropertyEx()
{
var sql = Db<DB>.Sql(db => Select(DataBasePropertyEx("LambdicSqlTest", "IsAutoShrink")));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
DATABASEPROPERTYEX(@p_0, @p_1)", "LambdicSqlTest", "IsAutoShrink");
}
[TestMethod]
[Priority(1)]
public void Test_Db_Id()
{
var sql = Db<DB>.Sql(db => Select(Db_Id("LambdicSqlTest")));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
DB_ID(@p_0)", "LambdicSqlTest");
}
[TestMethod]
[Priority(1)]
public void Test_Db_Name()
{
var sql = Db<DB>.Sql(db => Select(Db_Name(Db_Id("LambdicSqlTest"))));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
DB_NAME(DB_ID(@p_0))", "LambdicSqlTest");
}
[TestMethod]
[Priority(1)]
public void Test_File_Id()
{
var sql = Db<DB>.Sql(db => Select(File_Id("LambdicSqlTest")));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
FILE_ID(@p_0)", "LambdicSqlTest");
}
[TestMethod]
[Priority(1)]
public void Test_File_Index()
{
var sql = Db<DB>.Sql(db => Select(File_Idex("LambdicSqlTest")));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
FILE_IDEX(@p_0)", "LambdicSqlTest");
}
[TestMethod]
[Priority(1)]
public void Test_File_Name()
{
var sql = Db<DB>.Sql(db => Select(File_Name(File_Id("LambdicSqlTest"))));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
FILE_NAME(FILE_ID(@p_0))", "LambdicSqlTest");
}
[TestMethod]
[Priority(1)]
public void Test_FileGroup_Id()
{
var sql = Db<DB>.Sql(db => Select(FileGroup_Id("PRIMARY")));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
FILEGROUP_ID(@p_0)", "PRIMARY");
}
[TestMethod]
[Priority(1)]
public void Test_FileGroup_Name()
{
var sql = Db<DB>.Sql(db => Select(FileGroup_Name(FileGroup_Id("PRIMARY"))));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
FILEGROUP_NAME(FILEGROUP_ID(@p_0))", "PRIMARY");
}
[TestMethod]
[Priority(1)]
public void Test_FileGroupProperty()
{
var sql = Db<DB>.Sql(db => Select(FileGroupProperty("PRIMARY", "IsReadOnly")));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
FILEGROUPPROPERTY(@p_0, @p_1)", "PRIMARY", "IsReadOnly");
}
[TestMethod]
[Priority(1)]
public void Test_FileProperty()
{
var sql = Db<DB>.Sql(db => Select(FileProperty("LambdicSqlTest", "IsReadOnly")));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
FILEPROPERTY(@p_0, @p_1)", "LambdicSqlTest", "IsReadOnly");
}
[TestMethod]
[Priority(1)]
public void Test_FullTextCatalogProperty()
{
var sql = Db<DB>.Sql(db => Select(FullTextCatalogProperty("LambdicSqlTest", "IsReadOnly")));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
FULLTEXTCATALOGPROPERTY(@p_0, @p_1)", "LambdicSqlTest", "IsReadOnly");
}
[TestMethod]
[Priority(1)]
public void Test_FullTextServiceProperty()
{
var sql = Db<DB>.Sql(db => Select(FullTextServiceProperty("VerifySignature")));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
FULLTEXTSERVICEPROPERTY(@p_0)", "VerifySignature");
}
[TestMethod]
[Priority(1)]
public void Test_Index_Col()
{
var sql = Db<DB>.Sql(db => Select(Index_Col(db.tbl_staff, 1, 1)));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
INDEX_COL(@p_0, @p_1, @p_2)", "tbl_staff", 1, 1);
}
[TestMethod]
[Priority(1)]
public void Test_IndexKey_Property()
{
var sql = Db<DB>.Sql(db => Select(IndexKey_Property(Object_Id(db.tbl_staff), 1, 1, "ColumnId")));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
INDEXKEY_PROPERTY(OBJECT_ID(@p_0), @p_1, @p_2, @p_3)", "tbl_staff", 1, 1, "ColumnId");
}
[TestMethod]
[Priority(1)]
public void Test_IndexProperty()
{
var sql = Db<DB>.Sql(db => Select(IndexProperty(Object_Id(db.tbl_staff), "id", "IsClustered")));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
INDEXPROPERTY(OBJECT_ID(@p_0), @p_1, @p_2)", "tbl_staff", "id", "IsClustered");
}
[TestMethod]
[Priority(1)]
public void Test_Object_Id_1()
{
var sql = Db<DB>.Sql(db => Select(Object_Id(db.tbl_staff)));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
OBJECT_ID(@p_0)", "tbl_staff");
}
[TestMethod]
[Priority(1)]
public void Test_Object_Id_2()
{
var sql = Db<DB>.Sql(db => Select(Object_Id(db.tbl_staff, "U")));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
OBJECT_ID(@p_0, @p_1)", "tbl_staff", "U");
}
[TestMethod]
[Priority(1)]
public void Test_Object_Definition()
{
var sql = Db<DB>.Sql(db => Select(Object_Definition(Object_Id(db.tbl_staff))));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
OBJECT_DEFINITION(OBJECT_ID(@p_0))", "tbl_staff");
}
[TestMethod]
[Priority(1)]
public void Test_Object_Name_1()
{
var sql = Db<DB>.Sql(db => Select(Object_Name(Object_Id(db.tbl_staff))));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
OBJECT_NAME(OBJECT_ID(@p_0))", "tbl_staff");
}
[TestMethod]
[Priority(1)]
public void Test_Object_Name_2()
{
var sql = Db<DB>.Sql(db => Select(Object_Name(Object_Id(db.tbl_staff), 1)));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
OBJECT_NAME(OBJECT_ID(@p_0), @p_1)", "tbl_staff", 1);
}
[TestMethod]
[Priority(1)]
public void Test_Object_Schema_Name()
{
var sql = Db<DB>.Sql(db => Select(Object_Schema_Name(Object_Id(db.tbl_staff))));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
OBJECT_SCHEMA_NAME(OBJECT_ID(@p_0))", "tbl_staff");
}
[TestMethod]
[Priority(1)]
public void Test_ObjectProperty()
{
var sql = Db<DB>.Sql(db => Select(ObjectProperty(Object_Id(db.tbl_staff), "CnstIsClustKey")));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
OBJECTPROPERTY(OBJECT_ID(@p_0), @p_1)", "tbl_staff", "CnstIsClustKey");
}
[TestMethod]
[Priority(1)]
public void Test_ObjectPropertyEx()
{
var sql = Db<DB>.Sql(db => Select(ObjectPropertyEx(Object_Id(db.tbl_staff), "CnstIsClustKey")));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
OBJECTPROPERTYEX(OBJECT_ID(@p_0), @p_1)", "tbl_staff", "CnstIsClustKey");
}
[TestMethod]
[Priority(1)]
public void Test_Original_Db_Name()
{
var sql = Db<DB>.Sql(db => Select(Original_Db_Name()));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
ORIGINAL_DB_NAME()");
}
[TestMethod]
[Priority(1)]
public void Test_ParseName()
{
var sql = Db<DB>.Sql(db => Select(ParseName(db.tbl_staff.id, 1)));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
PARSENAME(@p_0, @p_1)", "tbl_staff.id",1);
}
[TestMethod]
[Priority(1)]
public void Test_Schema_Id()
{
var sql = Db<DBSchema>.Sql(db => Select(Schema_Id(db.dbo)));
sql.Gen(_connection);
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
SCHEMA_ID(@p_0)", "dbo");
}
[Priority(1)]
[TestMethod]
public void Test_Schema_Name()
{
var sql = Db<DBSchema>.Sql(db => Select(Schema_Name(Schema_Id("dbo"))));
sql.Gen(_connection);
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
SCHEMA_NAME(SCHEMA_ID(@p_0))", "dbo");
}
[Priority(1)]
[TestMethod]
public void Test_Scope_Identity()
{
var sql = Db<DB>.Sql(db => Select(Scope_Identity()));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
SCOPE_IDENTITY()");
}
[TestMethod]
[Priority(1)]
public void Test_ServerProperty()
{
var sql = Db<DB>.Sql(db => Select(ServerProperty("BuildClrVersion")));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
SERVERPROPERTY(@p_0)", "BuildClrVersion");
}
[TestMethod]
[Priority(1)]
public void Test_Stats_Date()
{
var sql = Db<DB>.Sql(db => Select(Stats_Date(0, 0)));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
STATS_DATE(@p_0, @p_1)", 0, 0);
}
[TestMethod]
[Priority(1)]
public void Test_Type_Id_Name()
{
var sql = Db<DB>.Sql(db => Select(Type_Name(Type_Id("int"))));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
TYPE_NAME(TYPE_ID(@p_0))", "int");
}
[TestMethod]
[Priority(1)]
public void Test_TypeProperty()
{
var sql = Db<DB>.Sql(db => Select(TypeProperty(Type_Id("int"), "OwnerId")));
var datas = _connection.Query(sql).ToList();
Assert.IsTrue(0 < datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT
TYPEPROPERTY(TYPE_ID(@p_0), @p_1)", "int", "OwnerId");
}
}
}
| |
#if SILVERLIGHT
using Microsoft.VisualStudio.TestTools.UnitTesting;
#else
using NUnit.Framework;
using System.Text.RegularExpressions;
#endif
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using DevExpress.Mvvm.DataAnnotations;
using DevExpress.Mvvm.Native;
using System.Security;
using System.Globalization;
using System.Collections.Generic;
using System.Collections;
namespace DevExpress.Mvvm.Tests {
[TestFixture]
public class MetadataBuilderTests {
#region validation
[MetadataType(typeof(ValidationEntityMetadata))]
public class ValidationEntity {
public static string StringProperty1_CustomErrorText_Required;
public static string StringProperty1_CustomErrorText_MinLength;
public static string StringProperty1_CustomErrorText_MaxLength;
public static string StringProperty3_CustomErrorText;
public static string PhoneProperty_CustomErrorText;
public static string CreditCardProperty_CustomErrorText;
public static string EmailAddressProperty_CustomErrorText;
public static string UrlProperty_CustomErrorText;
public static string DoubleRange_CustomErrorText;
public static string StringRegExp_CustomErrorText;
public static string CustomString_CustomErrorText;
public string StringProperty0 { get; set; }
public string StringProperty1 { get; set; }
public string StringProperty1_CustomError { get; set; }
public string StringProperty2 { get; set; }
public string StringProperty3 { get; set; }
public string StringProperty3_CustomError { get; set; }
public string PhoneProperty { get; set; }
public string PhoneProperty_CustomError { get; set; }
public string CreditCardProperty { get; set; }
public string CreditCardProperty_CustomError { get; set; }
public string EmailAddressProperty { get; set; }
public string EmailAddressProperty_CustomError { get; set; }
public string UrlProperty { get; set; }
public string UrlProperty_CustomError { get; set; }
public double DoubleRange { get; set; }
public double? DoubleRange_Nullable { get; set; }
public double DoubleRange_CustomError { get; set; }
public int IntRange { get; set; }
public string StringRange { get; set; }
public string StringRegExp { get; set; }
public string StringRegExp_CustomError { get; set; }
public int IntRegExp { get; set; }
public string CustomString_CustomError { get; set; }
public string CustomString_CustomError2 { get; set; }
public string CustomString_CustomError3 { get; set; }
public string CustomString { get; set; }
public string TwoErrorsProperty { get; set; }
}
public class ValidationEntityMetadata : IMetadataProvider<ValidationEntity> {
void IMetadataProvider<ValidationEntity>.BuildMetadata(MetadataBuilder<ValidationEntity> builder) {
builder.Property(x => x.StringProperty1)
.Required()
.MinLength(2)
.MaxLength(5);
builder.Property(x => x.StringProperty1_CustomError)
.Required(() => ValidationEntity.StringProperty1_CustomErrorText_Required)
.MinLength(2, () => ValidationEntity.StringProperty1_CustomErrorText_MinLength)
.MaxLength(5, () => ValidationEntity.StringProperty1_CustomErrorText_MaxLength);
builder.Property(x => x.StringProperty2)
.Required()
.MinLength(2);
builder.Property(x => x.StringProperty3)
.Required(allowEmptyStrings: true);
builder.Property(x => x.StringProperty3_CustomError)
.Required(allowEmptyStrings: true, errorMessageAccessor: () => ValidationEntity.StringProperty3_CustomErrorText);
builder.Property(x => x.PhoneProperty)
.PhoneNumberDataType();
builder.Property(x => x.PhoneProperty_CustomError)
.PhoneNumberDataType(() => ValidationEntity.PhoneProperty_CustomErrorText);
builder.Property(x => x.CreditCardProperty)
.CreditCardDataType();
builder.Property(x => x.CreditCardProperty_CustomError)
.CreditCardDataType(() => ValidationEntity.CreditCardProperty_CustomErrorText);
builder.Property(x => x.EmailAddressProperty)
.EmailAddressDataType();
builder.Property(x => x.EmailAddressProperty_CustomError)
.EmailAddressDataType(() => ValidationEntity.EmailAddressProperty_CustomErrorText);
builder.Property(x => x.UrlProperty)
.UrlDataType();
builder.Property(x => x.UrlProperty_CustomError)
.UrlDataType(() => ValidationEntity.UrlProperty_CustomErrorText);
builder.Property(x => x.DoubleRange)
.InRange(9, 13);
builder.Property(x => x.DoubleRange_Nullable)
.InRange(9, 13);
builder.Property(x => x.DoubleRange_CustomError)
.InRange(9, 13, () => ValidationEntity.DoubleRange_CustomErrorText);
builder.Property(x => x.IntRange)
.InRange(9, 13);
builder.Property(x => x.StringRange)
.InRange("B", "D");
builder.Property(x => x.StringRegExp)
.MatchesRegularExpression(@"^[a-z]{1,2}$");
builder.Property(x => x.StringRegExp_CustomError)
.MatchesRegularExpression(@"^[a-z]{1,2}$", () => ValidationEntity.StringRegExp_CustomErrorText);
builder.Property(x => x.IntRegExp)
.MatchesRegularExpression(@"^[1-2]{1,2}$");
builder.Property(x => x.CustomString)
.MatchesRule(x => x.Length <= 2);
builder.Property(x => x.CustomString_CustomError)
.MatchesRule(x => x.Length <= 2, () => ValidationEntity.CustomString_CustomErrorText);
#pragma warning disable 618
builder.Property(x => x.CustomString_CustomError2)
.MatchesInstanceRule(x => x.CustomString_CustomError2.Length <= 2, () => ValidationEntity.CustomString_CustomErrorText);
#pragma warning restore 618
builder.Property(x => x.CustomString_CustomError3)
.MatchesInstanceRule((value, instance) => instance.CustomString_CustomError2.Length <= 2 || value.Length <= 2, () => ValidationEntity.CustomString_CustomErrorText);
builder.Property(x => x.TwoErrorsProperty)
.MinLength(10)
.MaxLength(1);
}
}
[Test]
public void Validation() {
var entity = new ValidationEntity();
string required = "The StringProperty1 field is required.";
string minLength = "The field StringProperty1 must be a string or array type with a minimum length of '2'.";
string maxLength = "The field StringProperty1 must be a string or array type with a maximum length of '5'.";
var property1Validator = CreateValidator<ValidationEntity, string>(x => x.StringProperty1);
Assert.AreEqual(required, property1Validator.GetErrorText(null, entity));
Assert.AreEqual(minLength, property1Validator.GetErrorText("1", entity));
Assert.AreEqual(maxLength, property1Validator.GetErrorText("123456", entity));
Assert.AreEqual(string.Empty, property1Validator.GetErrorText("123", entity));
var property1Validator_CustomError = CreateValidator<ValidationEntity, string>(x => x.StringProperty1_CustomError);
ValidationEntity.StringProperty1_CustomErrorText_Required = "{0} property required";
Assert.AreEqual("StringProperty1_CustomError property required", property1Validator_CustomError.GetErrorText(null, entity));
ValidationEntity.StringProperty1_CustomErrorText_MinLength = "{0} min";
Assert.AreEqual("StringProperty1_CustomError min", property1Validator_CustomError.GetErrorText("1", entity));
ValidationEntity.StringProperty1_CustomErrorText_MaxLength= "{0} max";
Assert.AreEqual("StringProperty1_CustomError max", property1Validator_CustomError.GetErrorText("123456", entity));
var property2Validator = CreateValidator<ValidationEntity, string>(x => x.StringProperty2);
Assert.AreEqual(required.Replace("StringProperty1", "StringProperty2") + " " + minLength.Replace("StringProperty1", "StringProperty2"), property2Validator.GetErrorText(string.Empty, entity));
var property3Validator = CreateValidator<ValidationEntity, string>(x => x.StringProperty3);
Assert.AreEqual(string.Empty, property3Validator.GetErrorText(string.Empty, entity));
Assert.AreEqual(required.Replace("StringProperty1", "StringProperty3"), property3Validator.GetErrorText(null, entity));
var property3Validator_CustomError = CreateValidator<ValidationEntity, string>(x => x.StringProperty3_CustomError);
ValidationEntity.StringProperty3_CustomErrorText = "{0} property required and doesn't allow empty strings";
Assert.AreEqual("StringProperty3_CustomError property required and doesn't allow empty strings", property3Validator_CustomError.GetErrorText(null, entity));
var phoneValidator = CreateValidator<ValidationEntity, string>(x => x.PhoneProperty);
Assert.AreEqual("The PhoneProperty field is not a valid phone number.", phoneValidator.GetErrorText("abc", entity));
phoneValidator = CreateValidator<ValidationEntity, string>(x => x.PhoneProperty_CustomError);
ValidationEntity.PhoneProperty_CustomErrorText = "{0} phone";
Assert.AreEqual("PhoneProperty_CustomError phone", phoneValidator.GetErrorText("abc", entity));
var creditCardValidator = CreateValidator<ValidationEntity, string>(x => x.CreditCardProperty);
Assert.AreEqual("The CreditCardProperty field is not a valid credit card number.", creditCardValidator.GetErrorText("1234 5678 1234 5678", entity));
Assert.AreEqual(string.Empty, creditCardValidator.GetErrorText("4012888888881881", entity));
Assert.AreEqual(string.Empty, creditCardValidator.GetErrorText("4012 8888 8888 1881", entity));
creditCardValidator = CreateValidator<ValidationEntity, string>(x => x.CreditCardProperty_CustomError);
ValidationEntity.CreditCardProperty_CustomErrorText= "{0} card";
Assert.AreEqual("CreditCardProperty_CustomError card", creditCardValidator.GetErrorText("1234 5678 1234 5678", entity));
var emailAddressPropertyValidator = CreateValidator<ValidationEntity, string>(x => x.EmailAddressProperty);
Assert.AreEqual("The EmailAddressProperty field is not a valid e-mail address.", emailAddressPropertyValidator.GetErrorText("a@", entity));
Assert.AreEqual(string.Empty, emailAddressPropertyValidator.GetErrorText("a@b.c", entity));
emailAddressPropertyValidator = CreateValidator<ValidationEntity, string>(x => x.EmailAddressProperty_CustomError);
ValidationEntity.EmailAddressProperty_CustomErrorText = "{0} mail";
Assert.AreEqual("EmailAddressProperty_CustomError mail", emailAddressPropertyValidator.GetErrorText("a@", entity));
var urlPropertyValidator = CreateValidator<ValidationEntity, string>(x => x.UrlProperty);
Assert.AreEqual(string.Empty, urlPropertyValidator.GetErrorText("https://www.devexpress.com/", entity));
Assert.AreEqual("The UrlProperty field is not a valid fully-qualified http, https, or ftp URL.", urlPropertyValidator.GetErrorText("abc", entity));
urlPropertyValidator = CreateValidator<ValidationEntity, string>(x => x.UrlProperty_CustomError);
ValidationEntity.UrlProperty_CustomErrorText = "{0} url";
Assert.AreEqual("UrlProperty_CustomError url", urlPropertyValidator.GetErrorText("abc", entity));
var doubleRangeValidator = CreateValidator<ValidationEntity, double>(x => x.DoubleRange);
Assert.AreEqual(string.Empty, doubleRangeValidator.GetErrorText(10d, entity));
Assert.AreEqual("The field DoubleRange must be between 9 and 13.", doubleRangeValidator.GetErrorText(8d, entity));
Assert.AreEqual("The field DoubleRange must be between 9 and 13.", doubleRangeValidator.GetErrorText(14d, entity));
doubleRangeValidator = CreateValidator<ValidationEntity, double?>(x => x.DoubleRange_Nullable);
Assert.AreEqual(string.Empty, doubleRangeValidator.GetErrorText(10d, entity));
Assert.AreEqual("The field DoubleRange_Nullable must be between 9 and 13.", doubleRangeValidator.GetErrorText(8d, entity));
Assert.AreEqual("The field DoubleRange_Nullable must be between 9 and 13.", doubleRangeValidator.GetErrorText(14d, entity));
Assert.AreEqual(string.Empty, doubleRangeValidator.GetErrorText(null, entity));
doubleRangeValidator = CreateValidator<ValidationEntity, double>(x => x.DoubleRange_CustomError);
ValidationEntity.DoubleRange_CustomErrorText = "{0} range {1} {2}";
Assert.AreEqual("DoubleRange_CustomError range 9 13", doubleRangeValidator.GetErrorText(8d, entity));
var intRangeValidator = CreateValidator<ValidationEntity, int>(x => x.IntRange);
Assert.AreEqual(string.Empty, intRangeValidator.GetErrorText(10, entity));
Assert.AreEqual("The field IntRange must be between 9 and 13.", intRangeValidator.GetErrorText(8, entity));
Assert.AreEqual("The field IntRange must be between 9 and 13.", intRangeValidator.GetErrorText(14, entity));
var stringRangeValidator = CreateValidator<ValidationEntity, string>(x => x.StringRange);
Assert.AreEqual(string.Empty, stringRangeValidator.GetErrorText("Clown", entity));
Assert.AreEqual(string.Empty, stringRangeValidator.GetErrorText(string.Empty, entity));
Assert.AreEqual("The field StringRange must be between B and D.", stringRangeValidator.GetErrorText("Apple", entity));
Assert.AreEqual("The field StringRange must be between B and D.", stringRangeValidator.GetErrorText("Express", entity));
var stringRegExpValidator = CreateValidator<ValidationEntity, string>(x => x.StringRegExp);
Assert.AreEqual(string.Empty, stringRegExpValidator.GetErrorText("cl", entity));
Assert.AreEqual(@"The field StringRegExp must match the regular expression '^[a-z]{1,2}$'.", stringRegExpValidator.GetErrorText("Apple", entity));
stringRegExpValidator = CreateValidator<ValidationEntity, string>(x => x.StringRegExp_CustomError);
ValidationEntity.StringRegExp_CustomErrorText = "{0} regexp {1}";
Assert.AreEqual(@"StringRegExp_CustomError regexp ^[a-z]{1,2}$", stringRegExpValidator.GetErrorText("Apple", entity));
var intRegExpValidator = CreateValidator<ValidationEntity, int>(x => x.IntRegExp);
Assert.AreEqual(string.Empty, intRegExpValidator.GetErrorText(1, entity));
Assert.AreEqual(@"The field IntRegExp must match the regular expression '^[1-2]{1,2}$'.", intRegExpValidator.GetErrorText(3, entity));
var customStringValidator = CreateValidator<ValidationEntity, string>(x => x.CustomString);
Assert.AreEqual(string.Empty, customStringValidator.GetErrorText("12", entity));
Assert.AreEqual("CustomString is not valid.", customStringValidator.GetErrorText("123", entity));
customStringValidator = CreateValidator<ValidationEntity, string>(x => x.CustomString_CustomError);
ValidationEntity.CustomString_CustomErrorText = "{0} custom";
Assert.AreEqual("CustomString_CustomError custom", customStringValidator.GetErrorText("123", entity));
entity.CustomString_CustomError2 = "123";
customStringValidator = CreateValidator<ValidationEntity, string>(x => x.CustomString_CustomError2);
Assert.AreEqual("CustomString_CustomError2 custom", customStringValidator.GetErrorText(null, entity));
customStringValidator = CreateValidator<ValidationEntity, string>(x => x.CustomString_CustomError3);
Assert.AreEqual(string.Empty, customStringValidator.GetErrorText(string.Empty, entity));
Assert.AreEqual("CustomString_CustomError3 custom", customStringValidator.GetErrorText("123", entity));
var twoErrorsValidator = CreateValidator<ValidationEntity, string>(x => x.TwoErrorsProperty);
Assert.AreEqual("The field TwoErrorsProperty must be a string or array type with a minimum length of '10'. The field TwoErrorsProperty must be a string or array type with a maximum length of '1'.", twoErrorsValidator.GetErrorText("123", entity));
Assert.AreEqual("The field TwoErrorsProperty must be a string or array type with a minimum length of '10'.", twoErrorsValidator.GetErrors("123", entity).ElementAt(0));
Assert.AreEqual("The field TwoErrorsProperty must be a string or array type with a maximum length of '1'.", twoErrorsValidator.GetErrors("123", entity).ElementAt(1));
Assert.AreEqual(2, twoErrorsValidator.GetErrors("123", entity).Count());
}
static PropertyValidator CreateValidator<T, TProperty>(Expression<Func<T, TProperty>> propertyExpression) {
string propertyName = BindableBase.GetPropertyNameFast(propertyExpression);
return PropertyValidator.FromAttributes(MetadataHelper.GetExternalAndFluentAPIAttrbutes(typeof(T), propertyName), propertyName);
}
public class ValidationEntityWithDisplayNameAttributes {
#if !SILVERLIGHT
[DisplayName("_PropertyWithDisplayNameAttribute_")]
#endif
[StringLength(2)]
public string PropertyWithDisplayNameAttribute { get; set; }
[Display(Name = "_PropertyWithDisplayAttribute_", ShortName = "_______")]
#if !SILVERLIGHT
[DisplayName("________")]
#endif
[StringLength(2)]
public string PropertyWithDisplayAttribute { get; set; }
public string PropertyWithDisplayAttribute_Fluent { get; set; }
}
[Test]
public void ValidationEntityWithDisplayNameAttributesTest() {
var entity = new ValidationEntityWithDisplayNameAttributes {
PropertyWithDisplayNameAttribute = "asdf",
PropertyWithDisplayAttribute = "asdf",
PropertyWithDisplayAttribute_Fluent = "asdf",
};
#if !SILVERLIGHT
Assert.AreEqual("The field _PropertyWithDisplayNameAttribute_ must be a string with a maximum length of 2.", IDataErrorInfoHelper.GetErrorText(entity, "PropertyWithDisplayNameAttribute"));
#endif
Assert.AreEqual("The field _PropertyWithDisplayAttribute_ must be a string with a maximum length of 2.", IDataErrorInfoHelper.GetErrorText(entity, "PropertyWithDisplayAttribute"));
}
#if !SILVERLIGHT
[Test]
public void ResourceStringsTest() {
foreach(var property in typeof(DataAnnotationsResources).GetProperties(BindingFlags.Static | BindingFlags.NonPublic).Where(x => x.PropertyType == typeof(string))) {
Assert.AreEqual(DataAnnotationsResourcesResolver.AnnotationsResourceManager.GetString(property.Name), property.GetValue(null, null));
}
}
[Test]
public void RegexTest() {
CheckRegex(typeof(PhoneAttribute), typeof(ValidationAttribute).Assembly.GetType(typeof(ValidationAttribute).Namespace + ".PhoneAttribute"));
CheckRegex(typeof(UrlAttribute), typeof(ValidationAttribute).Assembly.GetType(typeof(ValidationAttribute).Namespace + ".UrlAttribute"));
CheckRegex(typeof(EmailAddressAttribute), typeof(ValidationAttribute).Assembly.GetType(typeof(ValidationAttribute).Namespace + ".EmailAddressAttribute"));
}
static void CheckRegex(Type dxType, Type annotationsType) {
Regex dxRegex = (Regex)dxType.GetField("regex", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null);
Regex regex = (Regex)annotationsType.GetField("_regex", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null);
Assert.AreEqual(GetPatternFromRegex(regex), GetPatternFromRegex(dxRegex));
}
static string GetPatternFromRegex(Regex regex) {
return (string)typeof(Regex).GetField("pattern", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(regex);
}
#endif
#endregion
#region MetadataHelper tests
#region several external metadata
[MetadataType(typeof(BaseMetadata))]
public class BaseClass {
public class BaseMetadata {
[ReadOnly(true)]
public string BaseProperty { get; set; }
}
public string BaseProperty { get; set; }
}
[MetadataType(typeof(Metadata))]
public class Class : BaseClass {
public class Metadata {
[ReadOnly(true)]
public string Property { get; set; }
}
public string Property { get; set; }
}
[Test]
public void SeveralExternalMetadata() {
Assert.IsNotNull(MetadataHelper.GetExternalAndFluentAPIAttrbutes(typeof(Class), "Property").OfType<ReadOnlyAttribute>().Single());
Assert.IsNotNull(MetadataHelper.GetExternalAndFluentAPIAttrbutes(typeof(Class), "BaseProperty").OfType<ReadOnlyAttribute>().Single());
}
#endregion
#region metadata with Fluent API
[MetadataType(typeof(MetadataWithFluentApiMetadata))]
public class MetadataWithFluentApi {
public static void BuildMetadata(MetadataBuilder<MetadataWithFluentApi> builder) {
builder.Property(x => x.Property).Required();
}
public string Property { get; set; }
public string Property2 { get; set; }
public string Property3 { get; set; }
}
public class MetadataWithFluentApiMetadata : IMetadataProvider<MetadataWithFluentApi> {
[Display(Name = "test")]
public string Property2 { get; set; }
void IMetadataProvider<MetadataWithFluentApi>.BuildMetadata(MetadataBuilder<MetadataWithFluentApi> builder) {
builder.Property(x => x.Property3).MaxLength(10);
}
}
[MetadataType(typeof(MetadataWithFluentApi))]
public class MetadataWithFluentApiClient {
public string Property { get; set; }
}
[Test]
public void MetadataWithFluentApiTest() {
Assert.IsNotNull(MetadataHelper.GetExternalAndFluentAPIAttrbutes(typeof(MetadataWithFluentApiClient), "Property").OfType<DXRequiredAttribute>().Single());
Assert.IsNotNull(MetadataHelper.GetExternalAndFluentAPIAttrbutes(typeof(MetadataWithFluentApiClient), "Property2").OfType<DisplayAttribute>().Single());
Assert.IsNotNull(MetadataHelper.GetExternalAndFluentAPIAttrbutes(typeof(MetadataWithFluentApiClient), "Property3").OfType<DXMaxLengthAttribute>().Single());
}
#endregion
#endregion
#region sequrity
[Test]
public void SecuritySafeCriticalClassesHasNoInternalAutogeneratedClassesWhichImplementInterfaces() {
foreach(Type type in Assembly.GetExecutingAssembly().GetTypes()) {
if(type.IsNested || !IsSequritySafeCriticalType(type))
continue;
CheckNestedTypes(type);
}
}
void CheckNestedTypes(Type type) {
foreach(Type nestedType in type.GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic)) {
if(!IsSequritySafeCriticalType(nestedType))
Assert.IsFalse(nestedType.GetInterfaces().Any(), nestedType.FullName + " type is not SequritySafeCritical");
CheckNestedTypes(nestedType);
}
}
static bool IsSequritySafeCriticalType(Type type) {
return type.GetCustomAttributes(false).OfType<SecuritySafeCriticalAttribute>().Any();
}
#endregion
#region MetadataBuilder test
class StrictPropertiesAndMethodExpressionEntity {
public int Prop { get; set; }
public void Method() { }
}
public int StringProperty0 { get; set; }
public void SomeMethod() { }
public bool SomeMethod2() { return false; }
[Test]
public void StrictPropertiesAndMethodExpression() {
var builder = new MetadataBuilder<StrictPropertiesAndMethodExpressionEntity>();
TestHelper.AssertThrows<ArgumentException>(() => builder.Property(x => StringProperty0));
TestHelper.AssertThrows<ArgumentException>(() => builder.CommandFromMethod(x => SomeMethod()));
TestHelper.AssertThrows<ArgumentException>(() => builder.Property(x => x.Prop).OnPropertyChangedCall(x => SomeMethod()));
TestHelper.AssertThrows<ArgumentException>(() => builder.Property(x => x.Prop).OnPropertyChangingCall(x => SomeMethod()));
TestHelper.AssertThrows<ArgumentException>(() => builder.CommandFromMethod(x => x.Method()).CanExecuteMethod(x => SomeMethod2()));
}
#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.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using CryptographicException = System.Security.Cryptography.CryptographicException;
using SafeBCryptKeyHandle = Microsoft.Win32.SafeHandles.SafeBCryptKeyHandle;
using SafeX509ChainHandle = Microsoft.Win32.SafeHandles.SafeX509ChainHandle;
using X509KeyUsageFlags = System.Security.Cryptography.X509Certificates.X509KeyUsageFlags;
using SafeNCryptKeyHandle = Microsoft.Win32.SafeHandles.SafeNCryptKeyHandle;
using Internal.Cryptography;
using Internal.Cryptography.Pal.Native;
internal static partial class Interop
{
public static partial class crypt32
{
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static unsafe extern bool CryptQueryObject(
CertQueryObjectType dwObjectType,
void* pvObject,
ExpectedContentTypeFlags dwExpectedContentTypeFlags,
ExpectedFormatTypeFlags dwExpectedFormatTypeFlags,
int dwFlags, // reserved - always pass 0
out CertEncodingType pdwMsgAndCertEncodingType,
out ContentType pdwContentType,
out FormatType pdwFormatType,
out SafeCertStoreHandle phCertStore,
out SafeCryptMsgHandle phMsg,
out SafeCertContextHandle ppvContext
);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static unsafe extern bool CryptQueryObject(
CertQueryObjectType dwObjectType,
void* pvObject,
ExpectedContentTypeFlags dwExpectedContentTypeFlags,
ExpectedFormatTypeFlags dwExpectedFormatTypeFlags,
int dwFlags, // reserved - always pass 0
IntPtr pdwMsgAndCertEncodingType,
out ContentType pdwContentType,
IntPtr pdwFormatType,
IntPtr phCertStore,
IntPtr phMsg,
IntPtr ppvContext
);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static unsafe extern bool CryptQueryObject(
CertQueryObjectType dwObjectType,
void* pvObject,
ExpectedContentTypeFlags dwExpectedContentTypeFlags,
ExpectedFormatTypeFlags dwExpectedFormatTypeFlags,
int dwFlags, // reserved - always pass 0
IntPtr pdwMsgAndCertEncodingType,
out ContentType pdwContentType,
IntPtr pdwFormatType,
out SafeCertStoreHandle phCertStore,
IntPtr phMsg,
IntPtr ppvContext
);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertGetCertificateContextProperty(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, [Out] byte[] pvData, [In, Out] ref int pcbData);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertGetCertificateContextProperty(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, [Out] out CRYPTOAPI_BLOB pvData, [In, Out] ref int pcbData);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertGetCertificateContextProperty")]
public static extern bool CertGetCertificateContextPropertyString(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, [Out] StringBuilder pvData, [In, Out] ref int pcbData);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe bool CertSetCertificateContextProperty(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, CertSetPropertyFlags dwFlags, [In] CRYPTOAPI_BLOB* pvData);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe bool CertSetCertificateContextProperty(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, CertSetPropertyFlags dwFlags, [In] CRYPT_KEY_PROV_INFO* pvData);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertGetNameStringW")]
public static extern int CertGetNameString(SafeCertContextHandle pCertContext, CertNameType dwType, CertNameFlags dwFlags, [In] ref CertNameStringType pvTypePara, [Out] StringBuilder pszNameString, int cchNameString);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern SafeCertContextHandle CertDuplicateCertificateContext(IntPtr pCertContext);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertDuplicateCertificateContext")]
public static extern SafeCertContextHandleWithKeyContainerDeletion CertDuplicateCertificateContextWithKeyContainerDeletion(IntPtr pCertContext);
public static SafeCertStoreHandle CertOpenStore(CertStoreProvider lpszStoreProvider, CertEncodingType dwMsgAndCertEncodingType, IntPtr hCryptProv, CertStoreFlags dwFlags, string pvPara)
{
return CertOpenStore((IntPtr)lpszStoreProvider, dwMsgAndCertEncodingType, hCryptProv, dwFlags, pvPara);
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
private static extern SafeCertStoreHandle CertOpenStore(IntPtr lpszStoreProvider, CertEncodingType dwMsgAndCertEncodingType, IntPtr hCryptProv, CertStoreFlags dwFlags, [MarshalAs(UnmanagedType.LPWStr)] string pvPara);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertAddCertificateContextToStore(SafeCertStoreHandle hCertStore, SafeCertContextHandle pCertContext, CertStoreAddDisposition dwAddDisposition, IntPtr ppStoreContext);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertAddCertificateLinkToStore(SafeCertStoreHandle hCertStore, SafeCertContextHandle pCertContext, CertStoreAddDisposition dwAddDisposition, IntPtr ppStoreContext);
/// <summary>
/// A less error-prone wrapper for CertEnumCertificatesInStore().
///
/// To begin the enumeration, set pCertContext to null. Each iteration replaces pCertContext with
/// the next certificate in the iteration. The final call sets pCertContext to an invalid SafeCertStoreHandle
/// and returns "false" to indicate the end of the store has been reached.
/// </summary>
public static bool CertEnumCertificatesInStore(SafeCertStoreHandle hCertStore, ref SafeCertContextHandle pCertContext)
{
unsafe
{
CERT_CONTEXT* pPrevCertContext = pCertContext == null ? null : pCertContext.Disconnect();
pCertContext = CertEnumCertificatesInStore(hCertStore, pPrevCertContext);
return !pCertContext.IsInvalid;
}
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
private static extern unsafe SafeCertContextHandle CertEnumCertificatesInStore(SafeCertStoreHandle hCertStore, CERT_CONTEXT* pPrevCertContext);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern SafeCertStoreHandle PFXImportCertStore([In] ref CRYPTOAPI_BLOB pPFX, string szPassword, PfxCertStoreFlags dwFlags);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CryptMsgGetParam(SafeCryptMsgHandle hCryptMsg, CryptMessageParameterType dwParamType, int dwIndex, [Out] byte[] pvData, [In, Out] ref int pcbData);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CryptMsgGetParam(SafeCryptMsgHandle hCryptMsg, CryptMessageParameterType dwParamType, int dwIndex, out int pvData, [In, Out] ref int pcbData);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertSerializeCertificateStoreElement(SafeCertContextHandle pCertContext, int dwFlags, [Out] byte[] pbElement, [In, Out] ref int pcbElement);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool PFXExportCertStore(SafeCertStoreHandle hStore, [In, Out] ref CRYPTOAPI_BLOB pPFX, string szPassword, PFXExportFlags dwFlags);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertNameToStrW")]
public static extern int CertNameToStr(CertEncodingType dwCertEncodingType, [In] ref CRYPTOAPI_BLOB pName, CertNameStrTypeAndFlags dwStrType, StringBuilder psz, int csz);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertStrToNameW")]
public static extern bool CertStrToName(CertEncodingType dwCertEncodingType, string pszX500, CertNameStrTypeAndFlags dwStrType, IntPtr pvReserved, [Out] byte[] pbEncoded, [In, Out] ref int pcbEncoded, IntPtr ppszError);
public static bool CryptFormatObject(CertEncodingType dwCertEncodingType, FormatObjectType dwFormatType, FormatObjectStringType dwFormatStrType, IntPtr pFormatStruct, FormatObjectStructType lpszStructType, byte[] pbEncoded, int cbEncoded, StringBuilder pbFormat, ref int pcbFormat)
{
return CryptFormatObject(dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, (IntPtr)lpszStructType, pbEncoded, cbEncoded, pbFormat, ref pcbFormat);
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool CryptFormatObject(CertEncodingType dwCertEncodingType, FormatObjectType dwFormatType, FormatObjectStringType dwFormatStrType, IntPtr pFormatStruct, IntPtr lpszStructType, [In] byte[] pbEncoded, int cbEncoded, [Out] StringBuilder pbFormat, [In, Out] ref int pcbFormat);
public static bool CryptDecodeObject(CertEncodingType dwCertEncodingType, CryptDecodeObjectStructType lpszStructType, byte[] pbEncoded, int cbEncoded, CryptDecodeObjectFlags dwFlags, byte[] pvStructInfo, ref int pcbStructInfo)
{
return CryptDecodeObject(dwCertEncodingType, (IntPtr)lpszStructType, pbEncoded, cbEncoded, dwFlags, pvStructInfo, ref pcbStructInfo);
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool CryptDecodeObject(CertEncodingType dwCertEncodingType, IntPtr lpszStructType, [In] byte[] pbEncoded, int cbEncoded, CryptDecodeObjectFlags dwFlags, [Out] byte[] pvStructInfo, [In, Out] ref int pcbStructInfo);
public static unsafe bool CryptDecodeObjectPointer(CertEncodingType dwCertEncodingType, CryptDecodeObjectStructType lpszStructType, byte[] pbEncoded, int cbEncoded, CryptDecodeObjectFlags dwFlags, void* pvStructInfo, ref int pcbStructInfo)
{
return CryptDecodeObjectPointer(dwCertEncodingType, (IntPtr)lpszStructType, pbEncoded, cbEncoded, dwFlags, pvStructInfo, ref pcbStructInfo);
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CryptDecodeObject")]
private static extern unsafe bool CryptDecodeObjectPointer(CertEncodingType dwCertEncodingType, IntPtr lpszStructType, [In] byte[] pbEncoded, int cbEncoded, CryptDecodeObjectFlags dwFlags, [Out] void* pvStructInfo, [In, Out] ref int pcbStructInfo);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CryptDecodeObject")]
public static extern unsafe bool CryptDecodeObjectPointer(CertEncodingType dwCertEncodingType, [MarshalAs(UnmanagedType.LPStr)] string lpszStructType, [In] byte[] pbEncoded, int cbEncoded, CryptDecodeObjectFlags dwFlags, [Out] void* pvStructInfo, [In, Out] ref int pcbStructInfo);
public static unsafe bool CryptEncodeObject(CertEncodingType dwCertEncodingType, CryptDecodeObjectStructType lpszStructType, void* pvStructInfo, byte[] pbEncoded, ref int pcbEncoded)
{
return CryptEncodeObject(dwCertEncodingType, (IntPtr)lpszStructType, pvStructInfo, pbEncoded, ref pcbEncoded);
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
private static extern unsafe bool CryptEncodeObject(CertEncodingType dwCertEncodingType, IntPtr lpszStructType, void* pvStructInfo, [Out] byte[] pbEncoded, [In, Out] ref int pcbEncoded);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe bool CryptEncodeObject(CertEncodingType dwCertEncodingType, [MarshalAs(UnmanagedType.LPStr)] string lpszStructType, void* pvStructInfo, [Out] byte[] pbEncoded, [In, Out] ref int pcbEncoded);
public static unsafe byte[] EncodeObject(CryptDecodeObjectStructType lpszStructType, void* decoded)
{
int cb = 0;
if (!Interop.crypt32.CryptEncodeObject(CertEncodingType.All, lpszStructType, decoded, null, ref cb))
throw Marshal.GetLastWin32Error().ToCryptographicException();
byte[] encoded = new byte[cb];
if (!Interop.crypt32.CryptEncodeObject(CertEncodingType.All, lpszStructType, decoded, encoded, ref cb))
throw Marshal.GetLastWin32Error().ToCryptographicException();
return encoded;
}
public static unsafe byte[] EncodeObject(string lpszStructType, void* decoded)
{
int cb = 0;
if (!Interop.crypt32.CryptEncodeObject(CertEncodingType.All, lpszStructType, decoded, null, ref cb))
throw Marshal.GetLastWin32Error().ToCryptographicException();
byte[] encoded = new byte[cb];
if (!Interop.crypt32.CryptEncodeObject(CertEncodingType.All, lpszStructType, decoded, encoded, ref cb))
throw Marshal.GetLastWin32Error().ToCryptographicException();
return encoded;
}
public static unsafe bool CertGetCertificateChain(ChainEngine hChainEngine, SafeCertContextHandle pCertContext, FILETIME* pTime, SafeCertStoreHandle hStore, [In] ref CERT_CHAIN_PARA pChainPara, CertChainFlags dwFlags, IntPtr pvReserved, out SafeX509ChainHandle ppChainContext)
{
return CertGetCertificateChain((IntPtr)hChainEngine, pCertContext, pTime, hStore, ref pChainPara, dwFlags, pvReserved, out ppChainContext);
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
private static extern unsafe bool CertGetCertificateChain(IntPtr hChainEngine, SafeCertContextHandle pCertContext, FILETIME* pTime, SafeCertStoreHandle hStore, [In] ref CERT_CHAIN_PARA pChainPara, CertChainFlags dwFlags, IntPtr pvReserved, out SafeX509ChainHandle ppChainContext);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CryptHashPublicKeyInfo(IntPtr hCryptProv, int algId, int dwFlags, CertEncodingType dwCertEncodingType, [In] ref CERT_PUBLIC_KEY_INFO pInfo, [Out] byte[] pbComputedHash, [In, Out] ref int pcbComputedHash);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertGetNameStringW")]
public static extern int CertGetNameString(SafeCertContextHandle pCertContext, CertNameType dwType, CertNameFlags dwFlags, [In] ref CertNameStrTypeAndFlags pvPara, [Out] StringBuilder pszNameString, int cchNameString);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertSaveStore(SafeCertStoreHandle hCertStore, CertEncodingType dwMsgAndCertEncodingType, CertStoreSaveAs dwSaveAs, CertStoreSaveTo dwSaveTo, ref CRYPTOAPI_BLOB pvSaveToPara, int dwFlags);
/// <summary>
/// A less error-prone wrapper for CertEnumCertificatesInStore().
///
/// To begin the enumeration, set pCertContext to null. Each iteration replaces pCertContext with
/// the next certificate in the iteration. The final call sets pCertContext to an invalid SafeCertStoreHandle
/// and returns "false" to indicate the end of the store has been reached.
/// </summary>
public static unsafe bool CertFindCertificateInStore(SafeCertStoreHandle hCertStore, CertFindType dwFindType, void* pvFindPara, ref SafeCertContextHandle pCertContext)
{
CERT_CONTEXT* pPrevCertContext = pCertContext == null ? null : pCertContext.Disconnect();
pCertContext = CertFindCertificateInStore(hCertStore, CertEncodingType.All, CertFindFlags.None, dwFindType, pvFindPara, pPrevCertContext);
return !pCertContext.IsInvalid;
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
private static unsafe extern SafeCertContextHandle CertFindCertificateInStore(SafeCertStoreHandle hCertStore, CertEncodingType dwCertEncodingType, CertFindFlags dwFindFlags, CertFindType dwFindType, void* pvFindPara, CERT_CONTEXT* pPrevCertContext);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static unsafe extern int CertVerifyTimeValidity([In] ref FILETIME pTimeToVerify, [In] CERT_INFO* pCertInfo);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static unsafe extern CERT_EXTENSION* CertFindExtension([MarshalAs(UnmanagedType.LPStr)] string pszObjId, int cExtensions, CERT_EXTENSION* rgExtensions);
// Note: It's somewhat unusual to use an API enum as a parameter type to a P/Invoke but in this case, X509KeyUsageFlags was intentionally designed as bit-wise
// identical to the wincrypt CERT_*_USAGE values.
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static unsafe extern bool CertGetIntendedKeyUsage(CertEncodingType dwCertEncodingType, CERT_INFO* pCertInfo, out X509KeyUsageFlags pbKeyUsage, int cbKeyUsage);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static unsafe extern bool CertGetValidUsages(int cCerts, [In] ref SafeCertContextHandle rghCerts, out int cNumOIDs, [Out] void* rghOIDs, [In, Out] ref int pcbOIDs);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertControlStore(SafeCertStoreHandle hCertStore, CertControlStoreFlags dwFlags, CertControlStoreType dwControlType, IntPtr pvCtrlPara);
// Note: CertDeleteCertificateFromStore always calls CertFreeCertificateContext on pCertContext, even if an error is encountered.
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe bool CertDeleteCertificateFromStore(CERT_CONTEXT* pCertContext);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern void CertFreeCertificateChain(IntPtr pChainContext);
public static bool CertVerifyCertificateChainPolicy(ChainPolicy pszPolicyOID, SafeX509ChainHandle pChainContext, ref CERT_CHAIN_POLICY_PARA pPolicyPara, ref CERT_CHAIN_POLICY_STATUS pPolicyStatus)
{
return CertVerifyCertificateChainPolicy((IntPtr)pszPolicyOID, pChainContext, ref pPolicyPara, ref pPolicyStatus);
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool CertVerifyCertificateChainPolicy(IntPtr pszPolicyOID, SafeX509ChainHandle pChainContext, [In] ref CERT_CHAIN_POLICY_PARA pPolicyPara, [In, Out] ref CERT_CHAIN_POLICY_STATUS pPolicyStatus);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertFreeCertificateContext(IntPtr pCertContext);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertCloseStore(IntPtr hCertStore, int dwFlags);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CryptMsgClose(IntPtr hCryptMsg);
#if !NETNATIVE
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe bool CryptImportPublicKeyInfoEx2(CertEncodingType dwCertEncodingType, CERT_PUBLIC_KEY_INFO* pInfo, int dwFlags, void* pvAuxInfo, out SafeBCryptKeyHandle phKey);
#endif
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CryptAcquireCertificatePrivateKey(SafeCertContextHandle pCert, CryptAcquireFlags dwFlags, IntPtr pvParameters, out SafeNCryptKeyHandle phCryptProvOrNCryptKey, out int pdwKeySpec, out bool pfCallerFreeProvOrNCryptKey);
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace NPOI.HSSF.UserModel
{
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using NPOI.HSSF.Record;
using NPOI.HSSF.Model;
using NPOI.Util;
using NPOI.SS.UserModel;
using NPOI.SS;
/// <summary>
/// High level representation of a row of a spReadsheet.
/// Only rows that have cells should be Added to a Sheet.
/// @author Andrew C. Oliver (acoliver at apache dot org)
/// @author Glen Stampoultzis (glens at apache.org)
/// </summary>
[Serializable]
internal class HSSFRow : IComparable,IRow
{
/// <summary>
/// used for collections
/// </summary>
public const int INITIAL_CAPACITY = 5;
private int rowNum;
private SortedDictionary<int, ICell> cells = new SortedDictionary<int, ICell>();
/**
* reference to low level representation
*/
[NonSerialized]
private RowRecord row;
/**
* reference to containing low level Workbook
*/
private HSSFWorkbook book;
/**
* reference to containing Sheet
*/
private HSSFSheet sheet;
// TODO - ditch this constructor
[Obsolete]
public HSSFRow()
{
}
/// <summary>
/// Creates new HSSFRow from scratch. Only HSSFSheet should do this.
/// </summary>
/// <param name="book">low-level Workbook object containing the sheet that Contains this row</param>
/// <param name="sheet">low-level Sheet object that Contains this Row</param>
/// <param name="rowNum">the row number of this row (0 based)</param>
///<see cref="NPOI.HSSF.UserModel.HSSFSheet.CreateRow(int)"/>
public HSSFRow(HSSFWorkbook book, HSSFSheet sheet, int rowNum):this(book, sheet, new RowRecord(rowNum))
{
}
/// <summary>
/// Creates an HSSFRow from a low level RowRecord object. Only HSSFSheet should do
/// this. HSSFSheet uses this when an existing file is Read in.
/// </summary>
/// <param name="book">low-level Workbook object containing the sheet that Contains this row</param>
/// <param name="sheet"> low-level Sheet object that Contains this Row</param>
/// <param name="record">the low level api object this row should represent</param>
///<see cref="NPOI.HSSF.UserModel.HSSFSheet.CreateRow(int)"/>
public HSSFRow(HSSFWorkbook book, HSSFSheet sheet, RowRecord record)
{
this.book = book;
this.sheet = sheet;
row = record;
RowNum=(record.RowNumber);
// Don't trust colIx boundaries as read by other apps
// set the RowRecord empty for the moment
record.SetEmpty();
}
/// <summary>
/// Use this to create new cells within the row and return it.
/// The cell that is returned is a CELL_TYPE_BLANK (<see cref="ICell"/>/<see cref="CellType.BLANK"/>).
/// The type can be changed either through calling <c>SetCellValue</c> or <c>SetCellType</c>.
/// </summary>
/// <param name="column">the column number this cell represents</param>
/// <returns>a high level representation of the created cell.</returns>
public ICell CreateCell(int column)
{
return this.CreateCell(column, CellType.BLANK);
}
/// <summary>
/// Use this to create new cells within the row and return it.
/// The cell that is returned is a CELL_TYPE_BLANK. The type can be changed
/// either through calling setCellValue or setCellType.
/// </summary>
/// <param name="columnIndex">the column number this cell represents</param>
/// <param name="type">a high level representation of the created cell.</param>
/// <returns></returns>
public ICell CreateCell(int columnIndex, CellType type)
{
short shortCellNum = (short)columnIndex;
if (columnIndex > 0x7FFF)
{
shortCellNum = (short)(0xffff - columnIndex);
}
ICell cell = new HSSFCell(book, sheet, RowNum, (short)columnIndex, type);
AddCell(cell);
sheet.Sheet.AddValueRecord(RowNum, ((HSSFCell)cell).CellValueRecord);
return cell;
}
/// <summary>
/// Remove the Cell from this row.
/// </summary>
/// <param name="cell">The cell to Remove.</param>
public void RemoveCell(ICell cell)
{
if (cell == null)
{
throw new ArgumentException("cell must not be null");
}
RemoveCell((HSSFCell)cell, true);
}
/// <summary>
/// Removes the cell.
/// </summary>
/// <param name="cell">The cell.</param>
/// <param name="alsoRemoveRecords">if set to <c>true</c> [also remove records].</param>
private void RemoveCell(ICell cell, bool alsoRemoveRecords)
{
int column = cell.ColumnIndex;
if (column < 0)
{
throw new Exception("Negative cell indexes not allowed");
}
//if (column >= cells.Count || cell != cells[column])
if(!cells.ContainsKey(column)|| cell!=cells[column])
{
throw new Exception("Specified cell is not from this row");
}
if (cell.IsPartOfArrayFormulaGroup)
{
((HSSFCell)cell).NotifyArrayFormulaChanging();
}
cells.Remove(column);
if (alsoRemoveRecords)
{
CellValueRecordInterface cval = ((HSSFCell)cell).CellValueRecord;
sheet.Sheet.RemoveValueRecord(RowNum, cval);
}
if (cell.ColumnIndex + 1 == row.LastCol)
{
row.LastCol = CalculateNewLastCellPlusOne(row.LastCol);
}
if (cell.ColumnIndex == row.FirstCol)
{
row.FirstCol = CalculateNewFirstCell(row.FirstCol);
}
}
/**
* used internally to refresh the "last cell plus one" when the last cell is removed.
* @return 0 when row contains no cells
*/
private int CalculateNewLastCellPlusOne(int lastcell)
{
int cellIx = lastcell - 1;
ICell r = RetrieveCell(cellIx);
while (r == null)
{
if (cellIx < 0)
{
return 0;
}
r = RetrieveCell(--cellIx);
}
return cellIx + 1;
}
/**
* used internally to refresh the "first cell" when the first cell is removed.
* @return 0 when row contains no cells (also when first cell is occupied)
*/
private int CalculateNewFirstCell(int firstcell)
{
int cellIx = firstcell + 1;
ICell r = RetrieveCell(cellIx);
if (cells.Count == 0)
return 0;
while (r == null)
{
if (cellIx <= cells.Count)
{
return 0;
}
r = RetrieveCell(++cellIx);
}
return cellIx;
}
/// <summary>
/// Create a high level Cell object from an existing low level record. Should
/// only be called from HSSFSheet or HSSFRow itself.
/// </summary>
/// <param name="cell">The low level cell to Create the high level representation from</param>
/// <returns> the low level record passed in</returns>
public ICell CreateCellFromRecord(CellValueRecordInterface cell)
{
ICell hcell = new HSSFCell(book, sheet, cell);
AddCell(hcell);
int colIx = cell.Column;
if (row.IsEmpty)
{
row.FirstCol=(colIx);
row.LastCol=(colIx + 1);
}
else
{
if (colIx < row.FirstCol)
{
row.FirstCol = (colIx);
}
else if (colIx > row.LastCol)
{
row.LastCol = (colIx + 1);
}
else
{
// added cell is within first and last cells
}
}
// TODO - RowRecord column boundaries need to be updated for cell comments too
return hcell;
}
/// <summary>
/// true, when the row is invisible. This is the case when the height is zero.
/// </summary>
public bool IsHidden
{
get { return this.ZeroHeight; }
set { this.ZeroHeight = value; }
}
/// <summary>
/// Removes all the cells from the row, and their
/// records too.
/// </summary>
public void RemoveAllCells()
{
int initialLen = cells.Count;
for (int i = 0; i < initialLen; i++)
{
RemoveCell(cells[i], true);
}
//cells = new HSSFCell[INITIAL_CAPACITY];
}
/// <summary>
/// Get row number this row represents
/// </summary>
/// <value>the row number (0 based)</value>
public int RowNum
{
get
{
return rowNum;
}
set
{
int maxrow = SpreadsheetVersion.EXCEL97.LastRowIndex;
if ((value < 0) || (value > maxrow))
{
throw new ArgumentException("Invalid row number (" + value
+ ") outside allowable range (0.." + maxrow + ")");
}
this.rowNum = value;
if (row != null)
{
row.RowNumber = (value); // used only for KEY comparison (HSSFRow)
}
}
}
/// <summary>
/// Returns the rows outline level. Increased as you
/// put it into more Groups (outlines), reduced as
/// you take it out of them.
/// </summary>
/// <value>The outline level.</value>
public int OutlineLevel
{
get { return row.OutlineLevel; }
}
/// <summary>
/// Moves the supplied cell to a new column, which
/// must not already have a cell there!
/// </summary>
/// <param name="cell">The cell to move</param>
/// <param name="newColumn">The new column number (0 based)</param>
public void MoveCell(ICell cell, int newColumn)
{
// Ensure the destination is free
//if (cells.Count > newColumn && cells[newColumn] != null)
if(cells.ContainsKey(newColumn))
{
throw new ArgumentException("Asked to move cell to column " + newColumn + " but there's already a cell there");
}
// Check it's one of ours
bool existflag = false;
foreach (ICell cellinrow in cells.Values)
{
if (cellinrow.Equals(cell))
{
existflag = true;
break;
}
}
if (!existflag)
{
throw new ArgumentException("Asked to move a cell, but it didn't belong to our row");
}
// Move the cell to the new position
// (Don't Remove the records though)
RemoveCell(cell, false);
((HSSFCell)cell).UpdateCellNum(newColumn);
AddCell(cell);
}
/**
* Returns the HSSFSheet this row belongs to
*
* @return the HSSFSheet that owns this row
*/
public ISheet Sheet
{
get
{
return sheet;
}
}
/// <summary>
/// used internally to Add a cell.
/// </summary>
/// <param name="cell">The cell.</param>
private void AddCell(ICell cell)
{
int column = cell.ColumnIndex;
// re-allocate cells array as required.
//if (column >= cells.Count)
//{
// HSSFCell[] oldCells = cells;
// int newSize = oldCells.Length * 2;
// if (newSize < column + 1)
// {
// newSize = column + 1;
// }
// cells = new HSSFCell[newSize];
// Array.Copy(oldCells, 0, cells, 0, oldCells.Length);
//}
if (cells.ContainsKey(column))
{
cells.Remove(column);
}
cells.Add(column, cell);
// fix up firstCol and lastCol indexes
if (row.IsEmpty|| column < row.FirstCol)
{
row.FirstCol=(column);
}
if (row.IsEmpty || column >= row.LastCol)
{
row.LastCol=((short)(column + 1)); // +1 -> for one past the last index
}
}
/// <summary>
/// Get the hssfcell representing a given column (logical cell)
/// 0-based. If you ask for a cell that is not defined, then
/// you Get a null.
/// This is the basic call, with no policies applied
/// </summary>
/// <param name="cellnum">0 based column number</param>
/// <returns>Cell representing that column or null if Undefined.</returns>
private ICell RetrieveCell(int cellnum)
{
if (!cells.ContainsKey(cellnum))
return null;
//if (cellnum < 0 || cellnum >= cells.Count) return null;
return cells[cellnum];
}
/// <summary>
/// Get the hssfcell representing a given column (logical cell)
/// 0-based. If you ask for a cell that is not defined then
/// you get a null, unless you have set a different
/// MissingCellPolicy on the base workbook.
///
/// Short method signature provided to retain binary
/// compatibility.
/// </summary>
/// <param name="cellnum">0 based column number</param>
/// <returns>Cell representing that column or null if undefined.</returns>
[Obsolete]
public ICell GetCell(short cellnum)
{
int ushortCellNum = cellnum & 0x0000FFFF; // avoid sign extension
return GetCell(ushortCellNum);
}
/// <summary>
/// Get the hssfcell representing a given column (logical cell)
/// 0-based. If you ask for a cell that is not defined then
/// you get a null, unless you have set a different
/// MissingCellPolicy on the base workbook.
/// </summary>
/// <param name="cellnum">0 based column number</param>
/// <returns>Cell representing that column or null if undefined.</returns>
public ICell GetCell(int cellnum)
{
return GetCell(cellnum, book.MissingCellPolicy);
}
/// <summary>
/// Get the hssfcell representing a given column (logical cell)
/// 0-based. If you ask for a cell that is not defined, then
/// your supplied policy says what to do
/// </summary>
/// <param name="cellnum">0 based column number</param>
/// <param name="policy">Policy on blank / missing cells</param>
/// <returns>that column or null if Undefined + policy allows.</returns>
public ICell GetCell(int cellnum, MissingCellPolicy policy)
{
ICell cell = RetrieveCell(cellnum);
if (policy == MissingCellPolicy.RETURN_NULL_AND_BLANK)
{
return cell;
}
if (policy == MissingCellPolicy.RETURN_BLANK_AS_NULL)
{
if (cell == null) return cell;
if (cell.CellType == CellType.BLANK)
{
return null;
}
return cell;
}
if (policy == MissingCellPolicy.CREATE_NULL_AS_BLANK)
{
if (cell == null)
{
return CreateCell(cellnum, CellType.BLANK);
}
return cell;
}
throw new ArgumentException("Illegal policy " + policy + " (" + policy.id + ")");
}
/// <summary>
/// Get the number of the first cell contained in this row.
/// </summary>
/// <value>the first logical cell in the row, or -1 if the row does not contain any cells.</value>
public short FirstCellNum
{
get
{
if (row.IsEmpty)
return -1;
else
return (short)row.FirstCol;
}
}
/// <summary>
/// Gets the index of the last cell contained in this row PLUS ONE
/// . The result also happens to be the 1-based column number of the last cell. This value can be used as a
/// standard upper bound when iterating over cells:
/// </summary>
/// <value>
/// short representing the last logical cell in the row PLUS ONE, or -1 if the
/// row does not contain any cells.
///</value>
/// <example>
/// short minColIx = row.GetFirstCellNum();
/// short maxColIx = row.GetLastCellNum();
/// for(short colIx=minColIx; colIx<maxColIx; colIx++) {
/// Cell cell = row.GetCell(colIx);
/// if(cell == null) {
/// continue;
/// }
/// //... do something with cell
/// }
/// </example>
public short LastCellNum
{
get
{
if (row.IsEmpty)
{
return -1;
}
return (short)row.LastCol;
}
}
/// <summary>
/// Gets the number of defined cells (NOT number of cells in the actual row!).
/// That is to say if only columns 0,4,5 have values then there would be 3.
/// </summary>
/// <value>the number of defined cells in the row.</value>
public int PhysicalNumberOfCells
{
get
{
return cells.Count;
}
}
/// <summary>
/// Gets or sets whether or not to Display this row with 0 height
/// </summary>
/// <value>height is zero or not.</value>
public bool ZeroHeight
{
get
{
return row.ZeroHeight;
}
set
{
row.ZeroHeight=(value);
}
}
/// <summary>
/// Get or sets the row's height or ff (-1) for undefined/default-height in twips (1/20th of a point)
/// </summary>
/// <value>rowheight or 0xff for Undefined (use sheet default)</value>
public short Height
{
get
{
short height = row.Height;
//The low-order 15 bits contain the row height.
//The 0x8000 bit indicates that the row is standard height (optional)
if ((height & 0x8000) != 0) height = sheet.Sheet.DefaultRowHeight;
else height &= 0x7FFF;
return height;
}
set
{
if (value == -1)
{
row.Height = 20 * 20;
}
else
{
row.BadFontHeight = true;
row.Height = value;
}
}
}
/// <summary>
/// is this row formatted? Most aren't, but some rows
/// do have whole-row styles. For those that do, you
/// can get the formatting from {@link #getRowStyle()}
/// </summary>
/// <value>
/// <c>true</c> if this instance is formatted; otherwise, <c>false</c>.
/// </value>
public bool IsFormatted
{
get
{
return row.Formatted;
}
}
/// <summary>
/// Returns the whole-row cell styles. Most rows won't
/// have one of these, so will return null. Call IsFormmated to check first
/// </summary>
/// <value>The row style.</value>
public ICellStyle RowStyle
{
get
{
if (!IsFormatted) { return null; }
short styleIndex = row.XFIndex;
ExtendedFormatRecord xf = book.Workbook.GetExFormatAt(styleIndex);
return new HSSFCellStyle(styleIndex, xf, book);
}
set
{
row.Formatted=(true);
row.XFIndex=(value.Index);
}
}
/// <summary>
/// Get the row's height or ff (-1) for Undefined/default-height in points (20*Height)
/// </summary>
/// <value>row height or 0xff for Undefined (use sheet default).</value>
public float HeightInPoints
{
get
{
return (row.Height / 20f);
}
set
{
if (value == -1)
{
row.Height = 20;
}
else
{
row.BadFontHeight = (true);
row.Height = (short)(value * 20);
}
}
}
/// <summary>
/// Get the lowlevel RowRecord represented by this object - should only be called
/// by other parts of the high level API
/// </summary>
/// <value>RowRecord this row represents</value>
public RowRecord RowRecord
{
get
{
return row;
}
}
/// <summary>
/// used internally to refresh the "first cell" when the first cell is Removed.
/// </summary>
/// <param name="firstcell">The first cell index.</param>
/// <returns></returns>
[Obsolete]
private short FindFirstCell(int firstcell)
{
short cellnum = (short)(firstcell + 1);
ICell r = GetCell(cellnum);
while (r == null && cellnum <= LastCellNum)
{
r = GetCell(++cellnum);
}
if (cellnum > LastCellNum)
return -1;
return cellnum;
}
/// <summary>
/// Get cells in the row
/// </summary>
public List<ICell> Cells
{
get {
return new List<ICell>(this.cells.Values);
}
}
/// <summary>
/// Gets the cell enumerator of the physically defined cells.
/// </summary>
/// <remarks>
/// Note that the 4th element might well not be cell 4, as the iterator
/// will not return Un-defined (null) cells.
/// Call CellNum on the returned cells to know which cell they are.
/// </remarks>
public IEnumerator GetEnumerator()
{
//return //new CellEnumerator(this.cells);
return this.cells.Values.GetEnumerator();
}
///// <summary>
///// Alias for {@link CellEnumerator} to allow
///// foreach loops
///// </summary>
///// <returns></returns>
//public IEnumerator GetEnumerator()
//{
// return GetCellEnumerator();
//}
/*
* An iterator over the (physical) cells in the row.
*/
//private class CellEnumerator : IEnumerator
//{
// int thisId = -1;
// int nextId = -1;
// private HSSFCell[] cells;
// public CellEnumerator()
// {
// }
// public CellEnumerator(HSSFCell[] cells)
// {
// this.cells = cells;
// }
// public bool MoveNext()
// {
// FindNext();
// return nextId < cells.Length;
// }
// public Object Current
// {
// get
// {
// thisId = nextId;
// Cell cell = cells[thisId];
// return cell;
// }
// }
// public void Remove()
// {
// if (thisId == -1)
// throw new InvalidOperationException("Remove() called before next()");
// cells[thisId] = null;
// }
// private void FindNext()
// {
// int i = nextId + 1;
// for (; i < cells.Length; i++)
// {
// if (cells[i] != null) break;
// }
// nextId = i;
// }
// public void Reset()
// {
// thisId = -1;
// nextId = -1;
// }
//}
/// <summary>
/// Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object.
/// </summary>
/// <param name="obj">An object to compare with this instance.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has these meanings:
/// Value
/// Meaning
/// Less than zero
/// This instance is less than <paramref name="obj"/>.
/// Zero
/// This instance is equal to <paramref name="obj"/>.
/// Greater than zero
/// This instance is greater than <paramref name="obj"/>.
/// </returns>
/// <exception cref="T:System.ArgumentException">
/// <paramref name="obj"/> is not the same type as this instance.
/// </exception>
public int CompareTo(Object obj)
{
HSSFRow loc = (HSSFRow)obj;
if (this.RowNum == loc.RowNum)
{
return 0;
}
if (this.RowNum < loc.RowNum)
{
return -1;
}
if (this.RowNum > loc.RowNum)
{
return 1;
}
return -1;
}
/// <summary>
/// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>.
/// </summary>
/// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param>
/// <returns>
/// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false.
/// </returns>
/// <exception cref="T:System.NullReferenceException">
/// The <paramref name="obj"/> parameter is null.
/// </exception>
public override bool Equals(Object obj)
{
if (!(obj is HSSFRow))
{
return false;
}
HSSFRow loc = (HSSFRow)obj;
if (this.RowNum == loc.RowNum)
{
return true;
}
return false;
}
/// <summary>
/// Returns a hash code. In this case it is the number of the row.
/// </summary>
public override int GetHashCode ()
{
return RowNum;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using FlatRedBall.Gui;
using FlatRedBall.Math;
using FlatRedBall.Input;
using FlatRedBall;
#if FRB_XNA
using Texture2D = Microsoft.Xna.Framework.Graphics.Texture2D;
//using Microsoft.Xna.Framework.Input;
using Keys = Microsoft.Xna.Framework.Input.Keys;
using FlatRedBall.Math.Geometry;
#elif FRB_MDX
using Keys = Microsoft.DirectX.DirectInput.Key;
using FlatRedBall.Math.Geometry;
#endif
namespace EditorObjects.Gui
{
public class TextureCoordinatesSelectionWindow : Window
{
#region Fields
enum CursorState
{
DraggingCorner,
MovingSelection,
DraggingSides
}
CursorState mCursorState;
Window mSelectedArea;
Window mTextureDisplayArea;
ToggleButton mPixelPerfect;
TextDisplay mMinimumXSelectionLabel;
TextDisplay mMinimumYSelectionLabel;
ComboBox mMinimumXSelection;
ComboBox mMinimumYSelection;
Sides mSideOver = Sides.None;
//ComboBox mPixelPerfectComboBox;
Button mAddToListButton;
float originalClickX;
float originalClickY;
float mLeftTU = 0;
float mRightTU = 1;
float mTopTV = 0;
float mBottomTV = 1;
float mLastFrameCursorXRelativeToWindow;
float mLastFrameCursorYRelativeToWindow;
ScrollBar mVerticalScrollBar;
ScrollBar mHorizontalScrollBar;
FloatRectangle mVisibleBounds = new FloatRectangle(0, 1, 0, 1);
float mZoom = 1;
#endregion
#region Properties
public Texture2D DisplayedTexture
{
set { mTextureDisplayArea.BaseTexture = value; }
get { return mTextureDisplayArea.BaseTexture; }
}
public float LeftTU
{
set
{
mLeftTU = value;
float displayLeft = Math.Max(0, Math.Min(1, mLeftTU));
mSelectedArea.X = (UToX(displayLeft) + UToX(mRightTU)) / 2.0f;
mSelectedArea.ScaleX = (UToX(mRightTU) - UToX(displayLeft)) / 2.0f;
}
get { return mLeftTU; }
}
public float RightTU
{
set
{
mRightTU = value;
float displayRight = Math.Max(0, Math.Min(1, mRightTU));
mSelectedArea.X = (UToX(mLeftTU) + UToX(displayRight)) / 2.0f;
mSelectedArea.ScaleX = (UToX(displayRight) - UToX(mLeftTU)) / 2.0f;
}
get { return mRightTU; }
}
public float TopTV
{
set
{
mTopTV = value;
float displayTop = Math.Max(0, Math.Min(1, mTopTV));
mSelectedArea.Y = (VToY(displayTop) + VToY(mBottomTV)) / 2.0f;
mSelectedArea.ScaleY = (VToY(mBottomTV) - VToY(displayTop)) / 2.0f;
}
get { return mTopTV; }
}
public float BottomTV
{
set
{
mBottomTV = value;
float displayBottom = Math.Max(0, Math.Min(1, mBottomTV));
mSelectedArea.Y = (VToY(mTopTV) + VToY(displayBottom)) / 2.0f;
mSelectedArea.ScaleY = (VToY(displayBottom) - VToY(mTopTV)) / 2.0f;
}
get { return mBottomTV; }
}
public bool IsCursorInSelectedArea
{
get
{
if (!mSelectedArea.Visible)
{
return false;
}
else
{
float cursorTU = XToU(CursorXRelativeToWindowRaw);
float cursorTV = YToV(CursorYRelativeToWindowRaw);
return (cursorTU >= LeftTU && cursorTU <= RightTU &&
cursorTV >= TopTV && cursorTV <= BottomTV);
}
}
}
float CursorXRelativeToWindow
{
get
{
float rawValue = CursorXRelativeToWindowRaw;
if (!mPixelPerfect.IsPressed || mTextureDisplayArea.BaseTexture == null)
return rawValue;
else
{
int minimumXSnapValue = int.Parse(mMinimumXSelection.Text);
// Adjust the value so that the edge is treated as being on-the-pixel
float pixelPerfectLeft =
MathFunctions.RoundFloat(
mVisibleBounds.Left,
minimumXSnapValue /
(float)(mTextureDisplayArea.BaseTexture.Width));
// Difference is how much to adjust the cursor position
float difference = pixelPerfectLeft - mVisibleBounds.Left;
float returnValue = MathFunctions.RoundFloat(
rawValue,
minimumXSnapValue * 2 * this.mTextureDisplayArea.ScaleX /
(float)(mTextureDisplayArea.BaseTexture.Width * mZoom));
returnValue += difference * 2 * this.mTextureDisplayArea.ScaleX / mZoom;
return returnValue;
}
}
}
float CursorXRelativeToWindowRaw
{
get
{
return mCursor.XForUI - X + GuiManager.Camera.XEdge - mTextureDisplayArea.WorldUnitRelativeX
+
mTextureDisplayArea.ScaleX + 0f;
}
}
float CursorYRelativeToWindow
{
get
{
int minimumYSnapValue = int.Parse(mMinimumYSelection.Text);
float rawValue = CursorYRelativeToWindowRaw;
if (!mPixelPerfect.IsPressed || mTextureDisplayArea.BaseTexture == null)
return rawValue;
else
{
float pixelPerfectTop =
MathFunctions.RoundFloat(
mVisibleBounds.Top,
minimumYSnapValue /
(float)(mTextureDisplayArea.BaseTexture.Height));
// Difference is how much to adjust the cursor position
float pixelDifference = pixelPerfectTop - mVisibleBounds.Top;
float returnValue = MathFunctions.RoundFloat(
rawValue,
minimumYSnapValue * 2 * this.mTextureDisplayArea.ScaleY /
(float)(mTextureDisplayArea.BaseTexture.Height * mZoom));
returnValue += pixelDifference * 2 * this.mTextureDisplayArea.ScaleY / mZoom;
return returnValue;
}
}
}
float CursorYRelativeToWindowRaw
{
get
{
float difference = ScaleY - mTextureDisplayArea.Y;
return -mCursor.YForUI - Y + GuiManager.Camera.YEdge + mTextureDisplayArea.ScaleY + difference;
}
}
public bool AddToListButtonShown
{
get { return mAddToListButton.Visible; }
set
{
if (value != mAddToListButton.Visible)
{
mAddToListButton.Visible = value;
OnWindowResize(this);
}
}
}
private float Zoom
{
get{ return mZoom;}
set
{
float centerX = (mVisibleBounds.Right + mVisibleBounds.Left) / 2.0f;
float centerY = (mVisibleBounds.Bottom + mVisibleBounds.Top) / 2.0f;
mZoom = value;
mZoom = Math.Min(mZoom, 1);
mHorizontalScrollBar.Sensitivity = mZoom / 4.0f;
mVerticalScrollBar.Sensitivity = mZoom / 4.0f;
UpdateVisibleBoundsToZoom(centerX, centerY);
UpdateScrollBarView();
UpdateSelectionPositionAndScale();
}
}
#endregion
#region Event
public GuiMessage TextureCoordinateChange;
#endregion
#region Delegate Methods
void AdjustToVerticalScrollBar(Window callingWindow)
{
mVisibleBounds.Left = mHorizontalScrollBar.RatioDown;
mVisibleBounds.Right = mVisibleBounds.Left + (float)mHorizontalScrollBar.View;
mVisibleBounds.Top = mVerticalScrollBar.RatioDown;
mVisibleBounds.Bottom = mVisibleBounds.Top + (float)mVerticalScrollBar.View;
UpdateToVisibleBounds();
UpdateSelectionPositionAndScale();
}
void MouseWheelZoom(Window callingWindow)
{
if (mCursor.ZVelocity > 0)
{
Zoom = Zoom / 2.0f;
}
else
{
Zoom = Zoom * 2.0f;
}
}
void PixelPerfectClick(Window callingWindow)
{
mMinimumXSelection.Visible = mPixelPerfect.IsPressed;
mMinimumYSelection.Visible = mPixelPerfect.IsPressed;
}
void OnWindowPush(Window callingWindow)
{
mLastFrameCursorXRelativeToWindow = CursorXRelativeToWindow;
mLastFrameCursorYRelativeToWindow = CursorYRelativeToWindow;
if (mSideOver != Sides.None)
{
mCursorState = CursorState.DraggingSides;
}
else if (!mCursor.ResizingWindow && !IsCursorInSelectedArea && mCursor.mWindowGrabbed == null)
{
mSelectedArea.Visible = true;
mLeftTU = mRightTU = XToU(CursorXRelativeToWindow);
mTopTV = mBottomTV = YToV(CursorYRelativeToWindow);
originalClickX = CursorXRelativeToWindow;
originalClickY = CursorYRelativeToWindow;
mLastFrameCursorXRelativeToWindow = originalClickX;
mLastFrameCursorYRelativeToWindow = originalClickY;
mSelectedArea.X = CursorXRelativeToWindow;
mSelectedArea.ScaleX = 0;
mSelectedArea.Y = CursorYRelativeToWindow;
mSelectedArea.ScaleY = 0;
mCursorState = CursorState.DraggingCorner;
}
else if (IsCursorInSelectedArea)
{
mCursorState = CursorState.MovingSelection;
}
}
void OnWindowDrag(Window callingWindow)
{
// If the user is resizing the window or moving the window by the move bar,
// don't allow the selection area to change.
bool canModifySelection = !mCursor.ResizingWindow && mCursor.mWindowGrabbed == null;
bool ShouldRaiseCoordinateChangeEvent = false;
#region If Dragging Corner
if (mCursorState == CursorState.DraggingCorner)
{
if (canModifySelection)
{
// holding the Space button lets the user move the origin
if (InputManager.Keyboard.KeyDown(Keys.Space))
{
originalClickX += CursorXRelativeToWindow - mLastFrameCursorXRelativeToWindow;
originalClickY += CursorYRelativeToWindow - mLastFrameCursorYRelativeToWindow;
originalClickX = System.Math.Max(0, originalClickX);
originalClickY = System.Math.Max(0, originalClickY);
originalClickX = System.Math.Min(UToX(1), originalClickX);
originalClickY = System.Math.Min(VToY(1), originalClickY);
}
// Find the left and right points of the rectangle
float left = System.Math.Min(CursorXRelativeToWindow, originalClickX);
float right = System.Math.Max(CursorXRelativeToWindow, originalClickX);
// top is System.Math.Min( because texture values increase when moving down
float top = System.Math.Min(CursorYRelativeToWindow, originalClickY);
float bottom = System.Math.Max(CursorYRelativeToWindow, originalClickY);
mSelectedArea.ScaleX = .5f * (right - left);
mSelectedArea.X = mSelectedArea.ScaleX + left;
mSelectedArea.ScaleY = .5f * (bottom - top);
mSelectedArea.Y = mSelectedArea.ScaleY + top;
UpdateUVsToSelectedArea();
mLastFrameCursorXRelativeToWindow = CursorXRelativeToWindow;
mLastFrameCursorYRelativeToWindow = CursorYRelativeToWindow;
ShouldRaiseCoordinateChangeEvent = true;
}
}
#endregion
#region Else If MovingSelection
else if (mCursorState == CursorState.MovingSelection)
{
if (canModifySelection)
{
float differenceX = CursorXRelativeToWindow - mLastFrameCursorXRelativeToWindow;
float differenceY = CursorYRelativeToWindow - mLastFrameCursorYRelativeToWindow;
if (differenceX < 0)
{
float furthestLeft = UToX(0);
float currentLeft = mSelectedArea.X - mSelectedArea.ScaleX;
differenceX = System.Math.Max(differenceX, furthestLeft - currentLeft);
}
else
{
float furthestRight = UToX(1);
float currentRight = mSelectedArea.X + mSelectedArea.ScaleX;
differenceX = System.Math.Min(differenceX, furthestRight - currentRight);
}
if (differenceY > 0)
{
float furthestBottom = VToY(1);
float currentBottom = mSelectedArea.Y + mSelectedArea.ScaleY;
differenceY = System.Math.Min(differenceY, furthestBottom - currentBottom);
}
else
{
float furthestTop = VToY(0);
float currentTop = mSelectedArea.Y - mSelectedArea.ScaleY;
differenceY = System.Math.Max(differenceY, furthestTop - currentTop);
}
mSelectedArea.X += differenceX;
mSelectedArea.Y += differenceY;
UpdateUVsToSelectedArea();
mLastFrameCursorXRelativeToWindow = CursorXRelativeToWindow;
mLastFrameCursorYRelativeToWindow = CursorYRelativeToWindow;
ShouldRaiseCoordinateChangeEvent = true;
}
}
#endregion
#region Else if DraggingSides
else if (mCursorState == CursorState.DraggingSides)
{
float change = 0;
switch (mSideOver)
{
case Sides.Top:
{
float oldTop = mSelectedArea.Y - mSelectedArea.ScaleY;
float newTop = CursorYRelativeToWindow;
change = newTop - oldTop;
mSelectedArea.Y += change;
float oldBottom = BottomTV;
//mSelectedArea.ScaleY -= change;
UpdateUVsToSelectedArea();
BottomTV = oldBottom;
ShouldRaiseCoordinateChangeEvent = true;
break;
}
case Sides.Bottom:
{
float oldBottom = mSelectedArea.Y + mSelectedArea.ScaleY;
float newBottom = CursorYRelativeToWindow;
change = newBottom - oldBottom;
mSelectedArea.Y += change;
float oldTop = TopTV;
UpdateUVsToSelectedArea();
TopTV = oldTop;
ShouldRaiseCoordinateChangeEvent = true;
}
break;
case Sides.Left:
{
float oldLeft = mSelectedArea.X - mSelectedArea.ScaleX;
float newLeft = CursorXRelativeToWindow;
change = newLeft - oldLeft;
mSelectedArea.X += change;
float oldRight = RightTU;
//mSelectedArea.ScaleY -= change;
UpdateUVsToSelectedArea();
RightTU = oldRight;
ShouldRaiseCoordinateChangeEvent = true;
}
break;
case Sides.Right:
{
float oldRight = mSelectedArea.X + mSelectedArea.ScaleX;
float newRight = CursorXRelativeToWindow;
change = newRight - oldRight;
mSelectedArea.X += change;
float oldLeft = LeftTU;
UpdateUVsToSelectedArea();
LeftTU = oldLeft;
ShouldRaiseCoordinateChangeEvent = true;
break;
}
}
}
#endregion
if (ShouldRaiseCoordinateChangeEvent && TextureCoordinateChange != null)
{
TextureCoordinateChange(this);
}
}
void OnWindowClick(Window callingWindow)
{
if (mTopTV == mBottomTV && mLeftTU == mRightTU)
{
mTopTV = 0;
mBottomTV = 1;
mLeftTU = 0;
mRightTU = 1;
mSelectedArea.Visible = false;
}
}
void OnWindowDoubleClick(Window callingWindow)
{
mSelectedArea.Visible = false;
mLeftTU = 0;
mRightTU = 1;
mTopTV = 0;
mBottomTV = 1;
mSelectedArea.X = 0;
mSelectedArea.ScaleX = 0;
mSelectedArea.Y = 0;
mSelectedArea.ScaleY = 0;
}
void OnWindowResize(Window callingWindow)
{
#region Update the mSelectedArea
UpdateSelectionPositionAndScale();
#endregion
#region Reposition GUI elements according to the new size
mTextureDisplayArea.X = ScaleX - 1f;
mTextureDisplayArea.ScaleX = ScaleX - 1.5f;
mPixelPerfect.X = .5f + mPixelPerfect.ScaleX;
mMinimumXSelection.X =
mPixelPerfect.X + mPixelPerfect.ScaleX +
mMinimumXSelection.ScaleX;
mMinimumYSelection.X =
mMinimumXSelection.X + mMinimumXSelection.ScaleX +
mMinimumYSelection.ScaleX;
if (mAddToListButton.VisibleSettingIgnoringParent)
{
mTextureDisplayArea.Y = ScaleY - 3f;
mTextureDisplayArea.ScaleY = ScaleY - 3.5f;
mAddToListButton.X = ScaleX;
mAddToListButton.ScaleX = ScaleX - .4f;
mAddToListButton.Y = 2 * ScaleY - 1.4f;
}
else
{
mTextureDisplayArea.Y = ScaleY - 2f;
mTextureDisplayArea.ScaleY = ScaleY - 2.5f;
}
mVerticalScrollBar.X = 2*ScaleX - mVerticalScrollBar.ScaleX - .5f;
mVerticalScrollBar.Y = mTextureDisplayArea.Y;
mVerticalScrollBar.ScaleY = mTextureDisplayArea.ScaleY;
mHorizontalScrollBar.X = mTextureDisplayArea.X;
mHorizontalScrollBar.Y = mTextureDisplayArea.Y + mTextureDisplayArea.ScaleY + mHorizontalScrollBar.ScaleY;
mHorizontalScrollBar.ScaleX = mTextureDisplayArea.ScaleX;
mPixelPerfect.Y = mHorizontalScrollBar.Y + mHorizontalScrollBar.ScaleY + mPixelPerfect.ScaleY;
mMinimumXSelection.Y = mPixelPerfect.Y;
mMinimumYSelection.Y = mPixelPerfect.Y;
UpdateScrollBarView();
#endregion
}
void OnRollOver(Window callingWindow)
{
if (InputManager.Mouse.ButtonDown(FlatRedBall.Input.Mouse.MouseButtons.MiddleButton))
{
float coefficient = .02f;
mVisibleBounds.Left += -coefficient * GuiManager.Cursor.XVelocity * mZoom;
mVisibleBounds.Right += -coefficient * GuiManager.Cursor.XVelocity * mZoom;
mVisibleBounds.Top += coefficient * GuiManager.Cursor.YVelocity * mZoom;
mVisibleBounds.Bottom += coefficient * GuiManager.Cursor.YVelocity * mZoom;
FixVisibleBounds();
UpdateScrollBarView();
UpdateToVisibleBounds();
UpdateSelectionPositionAndScale();
}
else
{
if (!InputManager.Mouse.ButtonDown(Mouse.MouseButtons.LeftButton))
{
UpdateSideOver();
}
switch (mSideOver)
{
case Sides.Left:
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.SizeWE;
break;
case Sides.Right:
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.SizeWE;
break;
case Sides.Top:
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.SizeNS;
break;
case Sides.Bottom:
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.SizeNS;
break;
case Sides.None:
if (IsCursorInSelectedArea)
{
// If the cursor is inside the texture coordinate square allow the user
// to drag it around.
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.SizeAll;
}
break;
}
}
}
void RightClickMenu(Window callingWindow)
{
ListBox listBox = GuiManager.AddPerishableListBox();
listBox.AddItem("Zoom In");
listBox.AddItem("Zoom Out");
listBox.SetScaleToContents(0);
listBox.HighlightOnRollOver = true;
GuiManager.PositionTopLeftToCursor(listBox);
listBox.ScrollBarVisible = false;
listBox.Click += SelectItemInRightClickMenu;
}
void SelectItemInRightClickMenu(Window callingWindow)
{
string optionSelected = ((ListBox)callingWindow).GetFirstHighlightedItem().Text;
switch (optionSelected)
{
case "Zoom In":
Zoom = Zoom / 2.0f;
GuiManager.RemoveWindow(callingWindow);
break;
case "Zoom Out":
Zoom = Zoom * 2;
GuiManager.RemoveWindow(callingWindow);
break;
}
}
#endregion
#region Methods
#region Constructor
public TextureCoordinatesSelectionWindow() :
base(GuiManager.Cursor)
{
// Victor says: This class USED to
// add itself to the GuiManager. This
// is no longer recommended as it makes
// windows not as reusable. Therefore, I
// removed the automatic adding to the GuiManager.
// This might break your code if you're using this,
// so if your TextureCoordinatesSelectionWindow isn't
// showing up, you might want to make sure you're adding
// it to the GuiManager.
#region Create "this" and add it to the GuiManager
HasMoveBar = true;
ScaleY = 12.5f;
ScaleX = 11.4f;
Resizable = true;
MinimumScaleX = ScaleX;
MinimumScaleY = ScaleY;
this.Resizing += OnWindowResize;
#endregion
#region Create the texture display area
mTextureDisplayArea = new Window(mCursor);
AddWindow(mTextureDisplayArea);
mTextureDisplayArea.DrawBorders = false;
mTextureDisplayArea.Push += OnWindowPush;
mTextureDisplayArea.Dragging += OnWindowDrag;
mTextureDisplayArea.Click += OnWindowClick;
mTextureDisplayArea.RollingOver += this.OnRollOver;
mTextureDisplayArea.DoubleClick += OnWindowDoubleClick;
mTextureDisplayArea.MouseWheelScroll += MouseWheelZoom;
mTextureDisplayArea.SecondaryClick += RightClickMenu;
#endregion
mSelectedArea = new Window(mCursor);
mTextureDisplayArea.AddWindow(mSelectedArea);
mSelectedArea.ScaleX = 3;
mSelectedArea.ScaleY = 3;
mSelectedArea.BaseTexture =
FlatRedBallServices.Load<Texture2D>("genGfx/targetBox.bmp", GuiManager.InternalGuiContentManagerName);
mSelectedArea.Enabled = false; // so it doesn't block input from the this (the parent Window)
mSelectedArea.DrawBorders = false;
mSelectedArea.Alpha = 127;
mAddToListButton = new Button(mCursor);
AddWindow(mAddToListButton);
mAddToListButton.Text = "Add To List";
mAddToListButton.Visible = false;
#region Pixel Perfect ToggleButton and ComboBoxes
mPixelPerfect = new ToggleButton(mCursor);
AddWindow(mPixelPerfect);
mPixelPerfect.ScaleX = 5;
mPixelPerfect.SetText("Free", "Snapping");
mPixelPerfect.Press();
mPixelPerfect.Click += PixelPerfectClick;
mMinimumXSelection = new ComboBox(mCursor);
AddWindow(mMinimumXSelection);
mMinimumXSelection.ScaleX = 3;
mMinimumXSelection.AddItem("1");
mMinimumXSelection.AddItem("4");
mMinimumXSelection.AddItem("8");
mMinimumXSelection.AddItem("16");
mMinimumXSelection.AddItem("32");
mMinimumXSelection.Text = "1";
mMinimumYSelection = new ComboBox(mCursor);
AddWindow(mMinimumYSelection);
mMinimumYSelection.ScaleX = 3;
mMinimumYSelection.AddItem("1");
mMinimumYSelection.AddItem("4");
mMinimumYSelection.AddItem("8");
mMinimumYSelection.AddItem("16");
mMinimumYSelection.AddItem("32");
mMinimumYSelection.Text = "1";
#endregion
#region Create the ScrollBars
mVerticalScrollBar = new ScrollBar(mCursor);
AddWindow(mVerticalScrollBar);
mVerticalScrollBar.UpButtonClick += AdjustToVerticalScrollBar;
mVerticalScrollBar.DownButtonClick += AdjustToVerticalScrollBar;
mVerticalScrollBar.PositionBarMove += AdjustToVerticalScrollBar;
mHorizontalScrollBar = new ScrollBar(mCursor);
AddWindow(mHorizontalScrollBar);
mHorizontalScrollBar.UpButtonClick += AdjustToVerticalScrollBar;
mHorizontalScrollBar.DownButtonClick += AdjustToVerticalScrollBar;
mHorizontalScrollBar.PositionBarMove += AdjustToVerticalScrollBar;
mHorizontalScrollBar.Alignment = ScrollBar.ScrollBarAlignment.Horizontal;
mHorizontalScrollBar.ScaleY = 1;
#endregion
OnWindowResize(this);
}
#endregion
#region Public Methods
public void AddToListClickEventAdd(GuiMessage AddToListClick)
{
mAddToListButton.Click += AddToListClick;
}
public void AddTextureDragEvent(GuiMessage message)
{
mTextureDisplayArea.Dragging += message;
}
public void ReplaceTexture(Texture2D oldTexture, Texture2D newTexture)
{
if (DisplayedTexture == oldTexture)
{
DisplayedTexture = newTexture;
}
}
#region XML Docs
/// <summary>
/// Sets the texture coordinates of the displayed texture.
/// </summary>
/// <remarks>
/// The base method sets the texture coordinates of the actual window while this
/// override sets the texture coordinates of the texture that is being displayed.
/// The assumption is that the user is not going to ever want to change the way that
/// this window is drawn but rather the coordinates of the texture that is being displayed.
/// </remarks>
/// <param name="top">The top texture coordinate ( V ).</param>
/// <param name="bottom">The bottom texture coordinate ( V ).</param>
/// <param name="left">The left texture coordinate ( U ).</param>
/// <param name="right">The right texture coordinate ( U ).</param>
#endregion
public override void SetTextureCoordinates(float top, float bottom, float left, float right)
{
mLeftTU = left;
mRightTU = right;
mTopTV = top;
mBottomTV = bottom;
UpdateSelectionPositionAndScale();
}
public override string ToString()
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("LeftTU: ").Append(mLeftTU);
stringBuilder.Append("\nTopTV: ").Append(mTopTV);
stringBuilder.Append("\nRightTU: ").Append(mRightTU);
stringBuilder.Append("\nBottomTV: ").Append(mBottomTV);
return stringBuilder.ToString();
}
#endregion
#region Private Methods
private void FixVisibleBounds()
{
if (mVisibleBounds.Left < 0)
{
mVisibleBounds.Right -= mVisibleBounds.Left;
mVisibleBounds.Left -= mVisibleBounds.Left;
}
if (mVisibleBounds.Top < 0)
{
mVisibleBounds.Bottom -= mVisibleBounds.Top;
mVisibleBounds.Top -= mVisibleBounds.Top;
}
if (mVisibleBounds.Right > 1)
{
mVisibleBounds.Left -= mVisibleBounds.Right - 1;
mVisibleBounds.Right = 1;
}
if (mVisibleBounds.Bottom > 1)
{
mVisibleBounds.Top -= mVisibleBounds.Bottom - 1;
mVisibleBounds.Bottom = 1;
}
}
void UpdateScrollBarView()
{
mVerticalScrollBar.View = mVisibleBounds.Bottom - mVisibleBounds.Top;
mHorizontalScrollBar.View = mVisibleBounds.Right - mVisibleBounds.Left;
mVerticalScrollBar.RatioDown = mVisibleBounds.Top;
mHorizontalScrollBar.RatioDown = mVisibleBounds.Left;
}
void UpdateSelectionPositionAndScale()
{
mSelectedArea.X = (UToX(mLeftTU) + UToX(mRightTU)) / 2.0f;
mSelectedArea.ScaleX = (UToX(mRightTU) - UToX(mLeftTU)) / 2.0f;
mSelectedArea.Y = (VToY(mTopTV) + VToY(mBottomTV)) / 2.0f;
mSelectedArea.ScaleY = (VToY(mBottomTV) - VToY(mTopTV)) / 2.0f;
}
private void UpdateSideOver()
{
//float unitThreshold = .5f;
if (mSelectedArea.Visible == false)
{
mSideOver = Sides.None;
}
else
{
Cursor cursor = GuiManager.Cursor;
const float distanceForGrabbing = 1;
mSideOver = Sides.None;
if (CursorXRelativeToWindowRaw > mSelectedArea.X - mSelectedArea.ScaleX &&
CursorXRelativeToWindowRaw < mSelectedArea.X + mSelectedArea.ScaleX)
{
// The cursor is within the left and right boundaries, so let's see if
// we're close enough to the top/bottom to resize it.
float distanceFromTop = Math.Abs(
CursorYRelativeToWindowRaw -
(mSelectedArea.Y - mSelectedArea.ScaleY));
float distanceFromBottom = Math.Abs(
CursorYRelativeToWindowRaw -
(mSelectedArea.Y + mSelectedArea.ScaleY));
if (distanceFromTop < distanceFromBottom && distanceFromTop < distanceForGrabbing)
{
mSideOver = Sides.Top;
}
else if (distanceFromBottom < distanceFromTop && distanceFromBottom < distanceForGrabbing)
{
mSideOver = Sides.Bottom;
}
}
if (CursorYRelativeToWindowRaw > mSelectedArea.Y - mSelectedArea.ScaleY &&
CursorYRelativeToWindowRaw < mSelectedArea.Y + mSelectedArea.ScaleY)
{
// The cursor is within the left and right boundaries, so let's see if
// we're close enough to the top/bottom to resize it.
float distanceFromLeft = Math.Abs(
CursorXRelativeToWindowRaw -
(mSelectedArea.X - mSelectedArea.ScaleX));
float distanceFromRight = Math.Abs(
CursorXRelativeToWindowRaw -
(mSelectedArea.X + mSelectedArea.ScaleX));
if (distanceFromLeft < distanceFromRight && distanceFromLeft < distanceForGrabbing)
{
mSideOver = Sides.Left;
}
else if (distanceFromRight < distanceFromLeft && distanceFromRight < distanceForGrabbing)
{
mSideOver = Sides.Right;
}
}
}
}
void UpdateUVsToSelectedArea()
{
float right = mSelectedArea.X + mSelectedArea.ScaleX;
float left = mSelectedArea.X - mSelectedArea.ScaleX;
float top = mSelectedArea.Y - mSelectedArea.ScaleY;
float bottom = mSelectedArea.Y + mSelectedArea.ScaleY;
mRightTU = XToU(right);
mLeftTU = XToU(left);
mTopTV = YToV(top);
mBottomTV = YToV(bottom);
// make sure that the values don't get moved outside of the range
mRightTU = System.Math.Max(mRightTU, 0);
mLeftTU = System.Math.Max(mLeftTU, 0);
mTopTV = System.Math.Max(mTopTV, 0);
mBottomTV = System.Math.Max(mBottomTV, 0);
mRightTU = System.Math.Min(mRightTU, 1);
mLeftTU = System.Math.Min(mLeftTU, 1);
mTopTV = System.Math.Min(mTopTV, 1);
mBottomTV = System.Math.Min(mBottomTV, 1);
}
private void UpdateVisibleBoundsToZoom(float centerX, float centerY)
{
mVisibleBounds.Left = centerX - mZoom / 2.0f;
mVisibleBounds.Top = centerY - mZoom / 2.0f;
mVisibleBounds.Right = centerX + mZoom / 2.0f;
mVisibleBounds.Bottom = centerY + mZoom / 2.0f;
FixVisibleBounds();
UpdateToVisibleBounds();
}
private void UpdateToVisibleBounds()
{
mTextureDisplayArea.SetTextureCoordinates(mVisibleBounds.Top, mVisibleBounds.Bottom, mVisibleBounds.Left, mVisibleBounds.Right);
}
float UToX(float tu)
{
return (-mVisibleBounds.Left + tu) * (mTextureDisplayArea.ScaleX * 2)/mZoom;
}
float VToY(float tv)
{
return (-mVisibleBounds.Top + tv) * (mTextureDisplayArea.ScaleY * 2)/mZoom;
}
float XToU(float x)
{
float value = mVisibleBounds.Left + (mVisibleBounds.Right - mVisibleBounds.Left) * (x / (mTextureDisplayArea.ScaleX * 2.0f));
// There is sometimes some floating point inaccuracy, so let's solve that here
int minimumXSnapValue = int.Parse(mMinimumXSelection.Text);
if (mPixelPerfect.IsPressed)
{
float pixelValue = value * this.DisplayedTexture.Width;
pixelValue = MathFunctions.RoundFloat(pixelValue, minimumXSnapValue);
value = pixelValue / this.DisplayedTexture.Width;
}
return value;
}
float YToV(float y)
{
float value = mVisibleBounds.Top + (mVisibleBounds.Bottom - mVisibleBounds.Top) * (y / (mTextureDisplayArea.ScaleY * 2.0f));
int minimumYSnapValue = int.Parse(mMinimumYSelection.Text);
if (mPixelPerfect.IsPressed)
{
float pixelValue = value * this.DisplayedTexture.Height;
pixelValue = MathFunctions.RoundFloat(pixelValue, minimumYSnapValue);
value = pixelValue / this.DisplayedTexture.Height;
}
return value;
}
#endregion
#endregion
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Security.Tokens
{
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Security;
using System.Text;
using System.Xml;
public class IssuedSecurityTokenParameters : SecurityTokenParameters
{
const string wsidPrefix = "wsid";
const string wsidNamespace = "http://schemas.xmlsoap.org/ws/2005/05/identity";
static readonly string wsidPPIClaim = String.Format(CultureInfo.InvariantCulture, "{0}/claims/privatepersonalidentifier", wsidNamespace);
internal const SecurityKeyType defaultKeyType = SecurityKeyType.SymmetricKey;
internal const bool defaultUseStrTransform = false;
internal struct AlternativeIssuerEndpoint
{
public EndpointAddress IssuerAddress;
public EndpointAddress IssuerMetadataAddress;
public Binding IssuerBinding;
}
Collection<XmlElement> additionalRequestParameters = new Collection<XmlElement>();
Collection<AlternativeIssuerEndpoint> alternativeIssuerEndpoints = new Collection<AlternativeIssuerEndpoint>();
MessageSecurityVersion defaultMessageSecurityVersion;
EndpointAddress issuerAddress;
EndpointAddress issuerMetadataAddress;
Binding issuerBinding;
int keySize;
SecurityKeyType keyType = defaultKeyType;
Collection<ClaimTypeRequirement> claimTypeRequirements = new Collection<ClaimTypeRequirement>();
bool useStrTransform = defaultUseStrTransform;
string tokenType;
protected IssuedSecurityTokenParameters(IssuedSecurityTokenParameters other)
: base(other)
{
this.defaultMessageSecurityVersion = other.defaultMessageSecurityVersion;
this.issuerAddress = other.issuerAddress;
this.keyType = other.keyType;
this.tokenType = other.tokenType;
this.keySize = other.keySize;
this.useStrTransform = other.useStrTransform;
foreach (XmlElement parameter in other.additionalRequestParameters)
{
this.additionalRequestParameters.Add((XmlElement)parameter.Clone());
}
foreach (ClaimTypeRequirement c in other.claimTypeRequirements)
{
this.claimTypeRequirements.Add(c);
}
if (other.issuerBinding != null)
{
this.issuerBinding = new CustomBinding(other.issuerBinding);
}
this.issuerMetadataAddress = other.issuerMetadataAddress;
}
public IssuedSecurityTokenParameters()
: this(null, null, null)
{
// empty
}
public IssuedSecurityTokenParameters(string tokenType)
: this(tokenType, null, null)
{
// empty
}
public IssuedSecurityTokenParameters(string tokenType, EndpointAddress issuerAddress)
: this(tokenType, issuerAddress, null)
{
// empty
}
public IssuedSecurityTokenParameters(string tokenType, EndpointAddress issuerAddress, Binding issuerBinding)
: base()
{
this.tokenType = tokenType;
this.issuerAddress = issuerAddress;
this.issuerBinding = issuerBinding;
}
internal protected override bool HasAsymmetricKey { get { return this.KeyType == SecurityKeyType.AsymmetricKey; } }
public Collection<XmlElement> AdditionalRequestParameters
{
get
{
return this.additionalRequestParameters;
}
}
public MessageSecurityVersion DefaultMessageSecurityVersion
{
get
{
return this.defaultMessageSecurityVersion;
}
set
{
defaultMessageSecurityVersion = value;
}
}
internal Collection<AlternativeIssuerEndpoint> AlternativeIssuerEndpoints
{
get
{
return this.alternativeIssuerEndpoints;
}
}
public EndpointAddress IssuerAddress
{
get
{
return this.issuerAddress;
}
set
{
this.issuerAddress = value;
}
}
public EndpointAddress IssuerMetadataAddress
{
get
{
return this.issuerMetadataAddress;
}
set
{
this.issuerMetadataAddress = value;
}
}
public Binding IssuerBinding
{
get
{
return this.issuerBinding;
}
set
{
this.issuerBinding = value;
}
}
public SecurityKeyType KeyType
{
get
{
return this.keyType;
}
set
{
SecurityKeyTypeHelper.Validate(value);
this.keyType = value;
}
}
public int KeySize
{
get
{
return this.keySize;
}
set
{
if (value < 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", SR.GetString(SR.ValueMustBeNonNegative)));
this.keySize = value;
}
}
public bool UseStrTransform
{
get
{
return this.useStrTransform;
}
set
{
this.useStrTransform = value;
}
}
public Collection<ClaimTypeRequirement> ClaimTypeRequirements
{
get
{
return this.claimTypeRequirements;
}
}
public string TokenType
{
get
{
return this.tokenType;
}
set
{
this.tokenType = value;
}
}
internal protected override bool SupportsClientAuthentication { get { return true; } }
internal protected override bool SupportsServerAuthentication { get { return true; } }
internal protected override bool SupportsClientWindowsIdentity { get { return false; } }
protected override SecurityTokenParameters CloneCore()
{
return new IssuedSecurityTokenParameters(this);
}
internal protected override SecurityKeyIdentifierClause CreateKeyIdentifierClause(SecurityToken token, SecurityTokenReferenceStyle referenceStyle)
{
if (token is GenericXmlSecurityToken)
return base.CreateGenericXmlTokenKeyIdentifierClause(token, referenceStyle);
else
return this.CreateKeyIdentifierClause<SamlAssertionKeyIdentifierClause, SamlAssertionKeyIdentifierClause>(token, referenceStyle);
}
internal void SetRequestParameters(Collection<XmlElement> requestParameters, TrustDriver trustDriver)
{
if (requestParameters == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("requestParameters");
if (trustDriver == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("trustDriver");
Collection<XmlElement> unknownRequestParameters = new Collection<XmlElement>();
foreach (XmlElement element in requestParameters)
{
int keySize;
string tokenType;
SecurityKeyType keyType;
Collection<XmlElement> requiredClaims;
if (trustDriver.TryParseKeySizeElement(element, out keySize))
this.keySize = keySize;
else if (trustDriver.TryParseKeyTypeElement(element, out keyType))
this.KeyType = keyType;
else if (trustDriver.TryParseTokenTypeElement(element, out tokenType))
this.TokenType = tokenType;
// Only copy RP policy to client policy for TrustFeb2005
else if (trustDriver.StandardsManager.TrustVersion == TrustVersion.WSTrustFeb2005)
{
if (trustDriver.TryParseRequiredClaimsElement(element, out requiredClaims))
{
Collection<XmlElement> unrecognizedRequiredClaims = new Collection<XmlElement>();
foreach (XmlElement claimRequirement in requiredClaims)
{
if (claimRequirement.LocalName == "ClaimType" && claimRequirement.NamespaceURI == wsidNamespace)
{
string claimValue = claimRequirement.GetAttribute("Uri", string.Empty);
if (!string.IsNullOrEmpty(claimValue))
{
ClaimTypeRequirement claimTypeRequirement;
string optional = claimRequirement.GetAttribute("Optional", string.Empty);
if (String.IsNullOrEmpty(optional))
{
claimTypeRequirement = new ClaimTypeRequirement(claimValue);
}
else
{
claimTypeRequirement = new ClaimTypeRequirement(claimValue, XmlConvert.ToBoolean(optional));
}
this.claimTypeRequirements.Add(claimTypeRequirement);
}
}
else
{
unrecognizedRequiredClaims.Add(claimRequirement);
}
}
if (unrecognizedRequiredClaims.Count > 0)
unknownRequestParameters.Add(trustDriver.CreateRequiredClaimsElement(unrecognizedRequiredClaims));
}
else
{
unknownRequestParameters.Add(element);
}
}
}
unknownRequestParameters = trustDriver.ProcessUnknownRequestParameters(unknownRequestParameters, requestParameters);
if (unknownRequestParameters.Count > 0)
{
for (int i = 0; i < unknownRequestParameters.Count; ++i)
this.AdditionalRequestParameters.Add(unknownRequestParameters[i]);
}
}
public Collection<XmlElement> CreateRequestParameters(MessageSecurityVersion messageSecurityVersion, SecurityTokenSerializer securityTokenSerializer)
{
return CreateRequestParameters(SecurityUtils.CreateSecurityStandardsManager(messageSecurityVersion, securityTokenSerializer).TrustDriver);
}
internal Collection<XmlElement> CreateRequestParameters(TrustDriver driver)
{
if (driver == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("driver");
Collection<XmlElement> result = new Collection<XmlElement>();
if (this.tokenType != null)
{
result.Add(driver.CreateTokenTypeElement(tokenType));
}
result.Add(driver.CreateKeyTypeElement(this.keyType));
if (this.keySize != 0)
{
result.Add(driver.CreateKeySizeElement(keySize));
}
if (this.claimTypeRequirements.Count > 0)
{
Collection<XmlElement> claimsElements = new Collection<XmlElement>();
XmlDocument doc = new XmlDocument();
foreach (ClaimTypeRequirement claimType in this.claimTypeRequirements)
{
XmlElement element = doc.CreateElement(wsidPrefix, "ClaimType", wsidNamespace);
XmlAttribute attr = doc.CreateAttribute("Uri");
attr.Value = claimType.ClaimType;
element.Attributes.Append(attr);
if (claimType.IsOptional != ClaimTypeRequirement.DefaultIsOptional)
{
attr = doc.CreateAttribute("Optional");
attr.Value = XmlConvert.ToString(claimType.IsOptional);
element.Attributes.Append(attr);
}
claimsElements.Add(element);
}
result.Add(driver.CreateRequiredClaimsElement(claimsElements));
}
if (this.additionalRequestParameters.Count > 0)
{
Collection<XmlElement> trustNormalizedParameters = NormalizeAdditionalParameters(this.additionalRequestParameters,
driver,
(this.claimTypeRequirements.Count > 0));
foreach (XmlElement parameter in trustNormalizedParameters)
{
result.Add(parameter);
}
}
return result;
}
private Collection<XmlElement> NormalizeAdditionalParameters(Collection<XmlElement> additionalParameters,
TrustDriver driver,
bool clientSideClaimTypeRequirementsSpecified)
{
// Ensure STS trust version is one of the currently supported versions: Feb 05 / Trust 1.3
Fx.Assert(((driver.StandardsManager.TrustVersion == TrustVersion.WSTrustFeb2005) ||
(driver.StandardsManager.TrustVersion == TrustVersion.WSTrust13)),
"Unsupported trust version specified for the STS.");
// We have a mismatch. Make a local copy of additionalParameters for making any potential modifications
// as part of normalization
Collection<XmlElement> tmpCollection = new Collection<XmlElement>();
foreach (XmlElement e in additionalParameters)
{
tmpCollection.Add(e);
}
// 1. For Trust 1.3 EncryptionAlgorithm, CanonicalizationAlgorithm and KeyWrapAlgorithm should not be
// specified as top-level element if "SecondaryParameters" element already specifies this.
if (driver.StandardsManager.TrustVersion == TrustVersion.WSTrust13)
{
Fx.Assert(driver.GetType() == typeof(WSTrustDec2005.DriverDec2005), "Invalid Trust Driver specified for Trust 1.3.");
XmlElement encryptionAlgorithmElement = null;
XmlElement canonicalizationAlgorithmElement = null;
XmlElement keyWrapAlgorithmElement = null;
XmlElement secondaryParameter = null;
for (int i = 0; i < tmpCollection.Count; ++i)
{
string algorithm;
if (driver.IsEncryptionAlgorithmElement(tmpCollection[i], out algorithm))
{
encryptionAlgorithmElement = tmpCollection[i];
}
else if (driver.IsCanonicalizationAlgorithmElement(tmpCollection[i], out algorithm))
{
canonicalizationAlgorithmElement = tmpCollection[i];
}
else if (driver.IsKeyWrapAlgorithmElement(tmpCollection[i], out algorithm))
{
keyWrapAlgorithmElement = tmpCollection[i];
}
else if (((WSTrustDec2005.DriverDec2005)driver).IsSecondaryParametersElement(tmpCollection[i]))
{
secondaryParameter = tmpCollection[i];
}
}
if (secondaryParameter != null)
{
foreach (XmlNode node in secondaryParameter.ChildNodes)
{
XmlElement child = node as XmlElement;
if (child != null)
{
string algorithm = null;
if (driver.IsEncryptionAlgorithmElement(child, out algorithm) && (encryptionAlgorithmElement != null))
{
tmpCollection.Remove(encryptionAlgorithmElement);
}
else if (driver.IsCanonicalizationAlgorithmElement(child, out algorithm) && (canonicalizationAlgorithmElement != null))
{
tmpCollection.Remove(canonicalizationAlgorithmElement);
}
else if (driver.IsKeyWrapAlgorithmElement(child, out algorithm) && (keyWrapAlgorithmElement != null))
{
tmpCollection.Remove(keyWrapAlgorithmElement);
}
}
}
}
}
// 2. Check for Mismatch.
// a. Trust Feb 2005 -> Trust 1.3. do the following,
// (i) Copy EncryptionAlgorithm and CanonicalizationAlgorithm as the top-level elements.
// Note, this is in contradiction to step 1. But we don't have a choice here as we cannot say from the
// Additional Parameters section in the config what came from the service and what came from the client.
// (ii) Convert SignWith and EncryptWith elements to Trust 1.3 namespace.
// b. For Trust 1.3 -> Trust Feb 2005, do the following,
// (i) Find EncryptionAlgorithm, CanonicalizationAlgorithm from inside the "SecondaryParameters" element.
// If found, then promote these as the top-level elements replacing the existing values.
// (ii) Convert the SignWith and EncryptWith elements to the Trust Feb 2005 namespace and drop the KeyWrapAlgorithm
// element.
// make an optimistic check to detect mismatched trust-versions between STS and RP
bool mismatch = (((driver.StandardsManager.TrustVersion == TrustVersion.WSTrustFeb2005) &&
!CollectionContainsElementsWithTrustNamespace(additionalParameters, TrustFeb2005Strings.Namespace)) ||
((driver.StandardsManager.TrustVersion == TrustVersion.WSTrust13) &&
!CollectionContainsElementsWithTrustNamespace(additionalParameters, TrustDec2005Strings.Namespace)));
// if no mismatch, return unmodified collection
if (!mismatch)
{
return tmpCollection;
}
// 2.a
// If we are talking to a Trust 1.3 STS, replace any Feb '05 algorithm parameters with their Trust 1.3 counterparts
if (driver.StandardsManager.TrustVersion == TrustVersion.WSTrust13)
{
SecurityStandardsManager trustFeb2005StandardsManager = SecurityStandardsManager.DefaultInstance;
// the following cast is guaranteed to succeed
WSTrustFeb2005.DriverFeb2005 trustFeb2005Driver = (WSTrustFeb2005.DriverFeb2005)trustFeb2005StandardsManager.TrustDriver;
for (int i = 0; i < tmpCollection.Count; i++)
{
string algorithmParameter = string.Empty;
if (trustFeb2005Driver.IsSignWithElement(tmpCollection[i], out algorithmParameter))
{
tmpCollection[i] = driver.CreateSignWithElement(algorithmParameter);
}
else if (trustFeb2005Driver.IsEncryptWithElement(tmpCollection[i], out algorithmParameter))
{
tmpCollection[i] = driver.CreateEncryptWithElement(algorithmParameter);
}
else if (trustFeb2005Driver.IsEncryptionAlgorithmElement(tmpCollection[i], out algorithmParameter))
{
tmpCollection[i] = driver.CreateEncryptionAlgorithmElement(algorithmParameter);
}
else if (trustFeb2005Driver.IsCanonicalizationAlgorithmElement(tmpCollection[i], out algorithmParameter))
{
tmpCollection[i] = driver.CreateCanonicalizationAlgorithmElement(algorithmParameter);
}
}
}
else
{
// 2.b
// We are talking to a Feb 05 STS. Filter out any SecondaryParameters element.
Collection<XmlElement> childrenToPromote = null;
WSSecurityTokenSerializer trust13Serializer = new WSSecurityTokenSerializer(SecurityVersion.WSSecurity11,
TrustVersion.WSTrust13,
SecureConversationVersion.WSSecureConversation13,
true, null, null, null);
SecurityStandardsManager trust13StandardsManager = new SecurityStandardsManager(MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12, trust13Serializer);
// the following cast is guaranteed to succeed
WSTrustDec2005.DriverDec2005 trust13Driver = (WSTrustDec2005.DriverDec2005)trust13StandardsManager.TrustDriver;
foreach (XmlElement parameter in tmpCollection)
{
// check if SecondaryParameters is present
if (trust13Driver.IsSecondaryParametersElement(parameter))
{
childrenToPromote = new Collection<XmlElement>();
// walk SecondaryParameters and collect any 'non-standard' children
foreach (XmlNode innerNode in parameter.ChildNodes)
{
XmlElement innerElement = innerNode as XmlElement;
if ((innerElement != null) && CanPromoteToRoot(innerElement, trust13Driver, clientSideClaimTypeRequirementsSpecified))
{
childrenToPromote.Add(innerElement);
}
}
// remove SecondaryParameters element
tmpCollection.Remove(parameter);
// we are done - break out of the loop
break;
}
}
// Probe of standard Trust elements and remember them.
if ((childrenToPromote != null) && (childrenToPromote.Count > 0))
{
XmlElement encryptionElement = null;
string encryptionAlgorithm = String.Empty;
XmlElement canonicalizationElement = null;
string canonicalizationAlgoritm = String.Empty;
XmlElement requiredClaimsElement = null;
Collection<XmlElement> requiredClaims = null;
Collection<XmlElement> processedElements = new Collection<XmlElement>();
foreach (XmlElement e in childrenToPromote)
{
if ((encryptionElement == null) && trust13Driver.IsEncryptionAlgorithmElement(e, out encryptionAlgorithm))
{
encryptionElement = driver.CreateEncryptionAlgorithmElement(encryptionAlgorithm);
processedElements.Add(e);
}
else if ((canonicalizationElement == null) && trust13Driver.IsCanonicalizationAlgorithmElement(e, out canonicalizationAlgoritm))
{
canonicalizationElement = driver.CreateCanonicalizationAlgorithmElement(canonicalizationAlgoritm);
processedElements.Add(e);
}
else if ((requiredClaimsElement == null) && trust13Driver.TryParseRequiredClaimsElement(e, out requiredClaims))
{
requiredClaimsElement = driver.CreateRequiredClaimsElement(requiredClaims);
processedElements.Add(e);
}
}
for (int i = 0; i < processedElements.Count; ++i)
{
childrenToPromote.Remove(processedElements[i]);
}
XmlElement keyWrapAlgorithmElement = null;
// Replace the appropriate elements.
for (int i = 0; i < tmpCollection.Count; ++i)
{
string algorithmParameter;
Collection<XmlElement> reqClaims;
if (trust13Driver.IsSignWithElement(tmpCollection[i], out algorithmParameter))
{
tmpCollection[i] = driver.CreateSignWithElement(algorithmParameter);
}
else if (trust13Driver.IsEncryptWithElement(tmpCollection[i], out algorithmParameter))
{
tmpCollection[i] = driver.CreateEncryptWithElement(algorithmParameter);
}
else if (trust13Driver.IsEncryptionAlgorithmElement(tmpCollection[i], out algorithmParameter) && (encryptionElement != null))
{
tmpCollection[i] = encryptionElement;
encryptionElement = null;
}
else if (trust13Driver.IsCanonicalizationAlgorithmElement(tmpCollection[i], out algorithmParameter) && (canonicalizationElement != null))
{
tmpCollection[i] = canonicalizationElement;
canonicalizationElement = null;
}
else if (trust13Driver.IsKeyWrapAlgorithmElement(tmpCollection[i], out algorithmParameter) && (keyWrapAlgorithmElement == null))
{
keyWrapAlgorithmElement = tmpCollection[i];
}
else if (trust13Driver.TryParseRequiredClaimsElement(tmpCollection[i], out reqClaims) && (requiredClaimsElement != null))
{
tmpCollection[i] = requiredClaimsElement;
requiredClaimsElement = null;
}
}
if (keyWrapAlgorithmElement != null)
{
// Remove KeyWrapAlgorithmElement as this is not define in Trust Feb 2005.
tmpCollection.Remove(keyWrapAlgorithmElement);
}
// Add the remaining elements to the additionaParameters list to the end.
if (encryptionElement != null) tmpCollection.Add(encryptionElement);
if (canonicalizationElement != null) tmpCollection.Add(canonicalizationElement);
if (requiredClaimsElement != null) tmpCollection.Add(requiredClaimsElement);
if (childrenToPromote.Count > 0)
{
// There are some non-standard elements. Just bump them to the top-level element.
for (int i = 0; i < childrenToPromote.Count; ++i)
{
tmpCollection.Add(childrenToPromote[i]);
}
}
}
}
return tmpCollection;
}
private bool CollectionContainsElementsWithTrustNamespace(Collection<XmlElement> collection, string trustNamespace)
{
for (int i = 0; i < collection.Count; i++)
{
if ((collection[i] != null) && (collection[i].NamespaceURI == trustNamespace))
{
return true;
}
}
return false;
}
private bool CanPromoteToRoot(XmlElement innerElement, WSTrustDec2005.DriverDec2005 trust13Driver, bool clientSideClaimTypeRequirementsSpecified)
{
SecurityKeyType dummyOutParamForKeyType;
int dummyOutParamForKeySize;
string dummyStringOutParam;
Collection<XmlElement> dummyOutParamForRequiredClaims = null;
// check if SecondaryParameters has claim requirements specified
if (trust13Driver.TryParseRequiredClaimsElement(innerElement, out dummyOutParamForRequiredClaims))
{
// if client has not specified any claim requirements, promote claim requirements
// in SecondaryParameters to root level (and subsequently fix up the trust namespace)
return !clientSideClaimTypeRequirementsSpecified;
}
// KeySize, KeyType and TokenType were converted to top-level property values when the WSDL was
// imported, so drop it here. We check for EncryptWith and SignWith as these are Client specific algorithm values and we
// don't have to promote the service specified values. KeyWrapAlgorithm was never sent in the RST
// in V1 and hence we are dropping it here as well.
return (!trust13Driver.TryParseKeyTypeElement(innerElement, out dummyOutParamForKeyType) &&
!trust13Driver.TryParseKeySizeElement(innerElement, out dummyOutParamForKeySize) &&
!trust13Driver.TryParseTokenTypeElement(innerElement, out dummyStringOutParam) &&
!trust13Driver.IsSignWithElement(innerElement, out dummyStringOutParam) &&
!trust13Driver.IsEncryptWithElement(innerElement, out dummyStringOutParam) &&
!trust13Driver.IsKeyWrapAlgorithmElement(innerElement, out dummyStringOutParam));
}
internal void AddAlgorithmParameters(SecurityAlgorithmSuite algorithmSuite, SecurityStandardsManager standardsManager, SecurityKeyType issuedKeyType)
{
this.additionalRequestParameters.Insert(0, standardsManager.TrustDriver.CreateEncryptionAlgorithmElement(algorithmSuite.DefaultEncryptionAlgorithm));
this.additionalRequestParameters.Insert(0, standardsManager.TrustDriver.CreateCanonicalizationAlgorithmElement(algorithmSuite.DefaultCanonicalizationAlgorithm));
if (this.keyType == SecurityKeyType.BearerKey)
{
// As the client does not have a proof token in the Bearer case
// we don't have any specific algorithms to request for.
return;
}
string signWithAlgorithm = (this.keyType == SecurityKeyType.SymmetricKey) ? algorithmSuite.DefaultSymmetricSignatureAlgorithm : algorithmSuite.DefaultAsymmetricSignatureAlgorithm;
this.additionalRequestParameters.Insert(0, standardsManager.TrustDriver.CreateSignWithElement(signWithAlgorithm));
string encryptWithAlgorithm;
if (issuedKeyType == SecurityKeyType.SymmetricKey)
{
encryptWithAlgorithm = algorithmSuite.DefaultEncryptionAlgorithm;
}
else
{
encryptWithAlgorithm = algorithmSuite.DefaultAsymmetricKeyWrapAlgorithm;
}
this.additionalRequestParameters.Insert(0, standardsManager.TrustDriver.CreateEncryptWithElement(encryptWithAlgorithm));
if (standardsManager.TrustVersion != TrustVersion.WSTrustFeb2005)
{
this.additionalRequestParameters.Insert(0, ((WSTrustDec2005.DriverDec2005)standardsManager.TrustDriver).CreateKeyWrapAlgorithmElement(algorithmSuite.DefaultAsymmetricKeyWrapAlgorithm));
}
return;
}
internal bool DoAlgorithmsMatch(SecurityAlgorithmSuite algorithmSuite, SecurityStandardsManager standardsManager, out Collection<XmlElement> otherRequestParameters)
{
bool doesSignWithAlgorithmMatch = false;
bool doesEncryptWithAlgorithmMatch = false;
bool doesEncryptionAlgorithmMatch = false;
bool doesCanonicalizationAlgorithmMatch = false;
bool doesKeyWrapAlgorithmMatch = false;
otherRequestParameters = new Collection<XmlElement>();
bool trustNormalizationPerformed = false;
Collection<XmlElement> trustVersionNormalizedParameterCollection;
// For Trust 1.3 we move all the additional parameters into the secondaryParameters
// element. So the list contains just one element called SecondaryParameters that
// contains all the other elements as child elements.
if ((standardsManager.TrustVersion == TrustVersion.WSTrust13) &&
(this.AdditionalRequestParameters.Count == 1) &&
(((WSTrustDec2005.DriverDec2005)standardsManager.TrustDriver).IsSecondaryParametersElement(this.AdditionalRequestParameters[0])))
{
trustNormalizationPerformed = true;
trustVersionNormalizedParameterCollection = new Collection<XmlElement>();
foreach (XmlElement innerElement in this.AdditionalRequestParameters[0])
{
trustVersionNormalizedParameterCollection.Add(innerElement);
}
}
else
{
trustVersionNormalizedParameterCollection = this.AdditionalRequestParameters;
}
for (int i = 0; i < trustVersionNormalizedParameterCollection.Count; i++)
{
string algorithm;
XmlElement element = trustVersionNormalizedParameterCollection[i];
if (standardsManager.TrustDriver.IsCanonicalizationAlgorithmElement(element, out algorithm))
{
if (algorithmSuite.DefaultCanonicalizationAlgorithm != algorithm)
{
return false;
}
doesCanonicalizationAlgorithmMatch = true;
}
else if (standardsManager.TrustDriver.IsSignWithElement(element, out algorithm))
{
if ((this.keyType == SecurityKeyType.SymmetricKey && algorithm != algorithmSuite.DefaultSymmetricSignatureAlgorithm)
|| (this.keyType == SecurityKeyType.AsymmetricKey && algorithm != algorithmSuite.DefaultAsymmetricSignatureAlgorithm))
{
return false;
}
doesSignWithAlgorithmMatch = true;
}
else if (standardsManager.TrustDriver.IsEncryptWithElement(element, out algorithm))
{
if ((this.keyType == SecurityKeyType.SymmetricKey && algorithm != algorithmSuite.DefaultEncryptionAlgorithm)
|| (this.keyType == SecurityKeyType.AsymmetricKey && algorithm != algorithmSuite.DefaultAsymmetricKeyWrapAlgorithm))
{
return false;
}
doesEncryptWithAlgorithmMatch = true;
}
else if (standardsManager.TrustDriver.IsEncryptionAlgorithmElement(element, out algorithm))
{
if (algorithm != algorithmSuite.DefaultEncryptionAlgorithm)
{
return false;
}
doesEncryptionAlgorithmMatch = true;
}
else if (standardsManager.TrustDriver.IsKeyWrapAlgorithmElement(element, out algorithm))
{
if (algorithm != algorithmSuite.DefaultAsymmetricKeyWrapAlgorithm)
{
return false;
}
doesKeyWrapAlgorithmMatch = true;
}
else
{
otherRequestParameters.Add(element);
}
}
// Undo normalization if performed
// move all back into secondaryParameters
if (trustNormalizationPerformed)
{
otherRequestParameters = this.AdditionalRequestParameters;
}
if (this.keyType == SecurityKeyType.BearerKey)
{
// As the client does not have a proof token in the Bearer case
// we don't have any specific algorithms to request for.
return true;
}
if (standardsManager.TrustVersion == TrustVersion.WSTrustFeb2005)
{
// For V1 compatibility check all algorithms
return (doesSignWithAlgorithmMatch && doesCanonicalizationAlgorithmMatch && doesEncryptionAlgorithmMatch && doesEncryptWithAlgorithmMatch);
}
else
{
return (doesSignWithAlgorithmMatch && doesCanonicalizationAlgorithmMatch && doesEncryptionAlgorithmMatch && doesEncryptWithAlgorithmMatch && doesKeyWrapAlgorithmMatch);
}
}
internal static IssuedSecurityTokenParameters CreateInfoCardParameters(SecurityStandardsManager standardsManager, SecurityAlgorithmSuite algorithm)
{
IssuedSecurityTokenParameters result = new IssuedSecurityTokenParameters(SecurityXXX2005Strings.SamlTokenType);
result.KeyType = SecurityKeyType.AsymmetricKey;
result.ClaimTypeRequirements.Add(new ClaimTypeRequirement(wsidPPIClaim));
result.IssuerAddress = null;
result.AddAlgorithmParameters(algorithm, standardsManager, result.KeyType);
return result;
}
internal static bool IsInfoCardParameters(IssuedSecurityTokenParameters parameters, SecurityStandardsManager standardsManager)
{
if (parameters == null)
return false;
if (parameters.TokenType != SecurityXXX2005Strings.SamlTokenType)
return false;
if (parameters.KeyType != SecurityKeyType.AsymmetricKey)
return false;
if (parameters.ClaimTypeRequirements.Count == 1)
{
ClaimTypeRequirement claimTypeRequirement = parameters.ClaimTypeRequirements[0] as ClaimTypeRequirement;
if (claimTypeRequirement == null)
return false;
if (claimTypeRequirement.ClaimType != wsidPPIClaim)
return false;
}
else if ((parameters.AdditionalRequestParameters != null) && (parameters.AdditionalRequestParameters.Count > 0))
{
// Check the AdditionalRequest Parameters to see if ClaimTypeRequirements got imported there.
bool claimTypeRequirementMatched = false;
XmlElement claimTypeRequirement = GetClaimTypeRequirement(parameters.AdditionalRequestParameters, standardsManager);
if (claimTypeRequirement != null && claimTypeRequirement.ChildNodes.Count == 1)
{
XmlElement claimTypeElement = claimTypeRequirement.ChildNodes[0] as XmlElement;
if (claimTypeElement != null)
{
XmlNode claimType = claimTypeElement.Attributes.GetNamedItem("Uri");
if (claimType != null && claimType.Value == wsidPPIClaim)
{
claimTypeRequirementMatched = true;
}
}
}
if (!claimTypeRequirementMatched)
{
return false;
}
}
else
{
return false;
}
if (parameters.IssuerAddress != null)
return false;
if (parameters.AlternativeIssuerEndpoints != null && parameters.AlternativeIssuerEndpoints.Count > 0)
{
return false;
}
return true;
}
// The method walks through the entire set of AdditionalRequestParameters and return the Claims Type requirement alone.
internal static XmlElement GetClaimTypeRequirement(Collection<XmlElement> additionalRequestParameters, SecurityStandardsManager standardsManager)
{
foreach (XmlElement requestParameter in additionalRequestParameters)
{
if ((requestParameter.LocalName == ((System.ServiceModel.Security.WSTrust.Driver)standardsManager.TrustDriver).DriverDictionary.Claims.Value) &&
(requestParameter.NamespaceURI == ((System.ServiceModel.Security.WSTrust.Driver)standardsManager.TrustDriver).DriverDictionary.Namespace.Value))
{
return requestParameter;
}
if ((requestParameter.LocalName == DXD.TrustDec2005Dictionary.SecondaryParameters.Value) &&
(requestParameter.NamespaceURI == DXD.TrustDec2005Dictionary.Namespace.Value))
{
Collection<XmlElement> secondaryParameters = new Collection<XmlElement>();
foreach (XmlNode node in requestParameter.ChildNodes)
{
XmlElement nodeAsElement = node as XmlElement;
if (nodeAsElement != null)
{
secondaryParameters.Add(nodeAsElement);
}
}
XmlElement claimTypeRequirement = GetClaimTypeRequirement(secondaryParameters, standardsManager);
if (claimTypeRequirement != null)
{
return claimTypeRequirement;
}
}
}
return null;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(base.ToString());
sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "TokenType: {0}", this.tokenType == null ? "null" : this.tokenType));
sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "KeyType: {0}", this.keyType.ToString()));
sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "KeySize: {0}", this.keySize.ToString(CultureInfo.InvariantCulture)));
sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "IssuerAddress: {0}", this.issuerAddress == null ? "null" : this.issuerAddress.ToString()));
sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "IssuerMetadataAddress: {0}", this.issuerMetadataAddress == null ? "null" : this.issuerMetadataAddress.ToString()));
sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "DefaultMessgeSecurityVersion: {0}", this.defaultMessageSecurityVersion == null ? "null" : this.defaultMessageSecurityVersion.ToString()));
sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "UseStrTransform: {0}", this.useStrTransform.ToString()));
if (this.issuerBinding == null)
{
sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "IssuerBinding: null"));
}
else
{
sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "IssuerBinding:"));
BindingElementCollection bindingElements = this.issuerBinding.CreateBindingElements();
for (int i = 0; i < bindingElements.Count; i++)
{
sb.AppendLine(String.Format(CultureInfo.InvariantCulture, " BindingElement[{0}]:", i.ToString(CultureInfo.InvariantCulture)));
sb.AppendLine(" " + bindingElements[i].ToString().Trim().Replace("\n", "\n "));
}
}
if (this.claimTypeRequirements.Count == 0)
{
sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "ClaimTypeRequirements: none"));
}
else
{
sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "ClaimTypeRequirements:"));
for (int i = 0; i < this.claimTypeRequirements.Count; i++)
{
sb.AppendLine(String.Format(CultureInfo.InvariantCulture, " {0}, optional={1}", this.claimTypeRequirements[i].ClaimType, this.claimTypeRequirements[i].IsOptional));
}
}
return sb.ToString().Trim();
}
protected internal override void InitializeSecurityTokenRequirement(SecurityTokenRequirement requirement)
{
requirement.TokenType = this.TokenType;
requirement.RequireCryptographicToken = true;
requirement.KeyType = this.KeyType;
ServiceModelSecurityTokenRequirement serviceModelSecurityTokenRequirement = requirement as ServiceModelSecurityTokenRequirement;
if (serviceModelSecurityTokenRequirement != null)
{
serviceModelSecurityTokenRequirement.DefaultMessageSecurityVersion = this.DefaultMessageSecurityVersion;
}
else
{
requirement.Properties[ServiceModelSecurityTokenRequirement.DefaultMessageSecurityVersionProperty] = this.DefaultMessageSecurityVersion;
}
if (this.KeySize > 0)
{
requirement.KeySize = this.KeySize;
}
requirement.Properties[ServiceModelSecurityTokenRequirement.IssuerAddressProperty] = this.IssuerAddress;
if (this.IssuerBinding != null)
{
requirement.Properties[ServiceModelSecurityTokenRequirement.IssuerBindingProperty] = this.IssuerBinding;
}
requirement.Properties[ServiceModelSecurityTokenRequirement.IssuedSecurityTokenParametersProperty] = this.Clone();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Drawing.Internal;
namespace System.Drawing.Drawing2D
{
public sealed class LinearGradientBrush : Brush
{
private bool _interpolationColorsWasSet;
public LinearGradientBrush(PointF point1, PointF point2, Color color1, Color color2)
{
IntPtr nativeBrush;
int status = SafeNativeMethods.Gdip.GdipCreateLineBrush(new GPPOINTF(point1),
new GPPOINTF(point2),
color1.ToArgb(),
color2.ToArgb(),
(int)WrapMode.Tile,
out nativeBrush);
SafeNativeMethods.Gdip.CheckStatus(status);
SetNativeBrushInternal(nativeBrush);
}
public LinearGradientBrush(Point point1, Point point2, Color color1, Color color2)
{
IntPtr nativeBrush;
int status = SafeNativeMethods.Gdip.GdipCreateLineBrushI(new GPPOINT(point1),
new GPPOINT(point2),
color1.ToArgb(),
color2.ToArgb(),
(int)WrapMode.Tile,
out nativeBrush);
SafeNativeMethods.Gdip.CheckStatus(status);
SetNativeBrushInternal(nativeBrush);
}
public LinearGradientBrush(RectangleF rect, Color color1, Color color2, LinearGradientMode linearGradientMode)
{
if (linearGradientMode < LinearGradientMode.Horizontal || linearGradientMode > LinearGradientMode.BackwardDiagonal)
{
throw new InvalidEnumArgumentException(nameof(linearGradientMode), unchecked((int)linearGradientMode), typeof(LinearGradientMode));
}
if (rect.Width == 0.0 || rect.Height == 0.0)
{
throw new ArgumentException(SR.Format(SR.GdiplusInvalidRectangle, rect.ToString()));
}
var gprectf = new GPRECTF(rect);
IntPtr nativeBrush;
int status = SafeNativeMethods.Gdip.GdipCreateLineBrushFromRect(ref gprectf,
color1.ToArgb(),
color2.ToArgb(),
unchecked((int)linearGradientMode),
(int)WrapMode.Tile,
out nativeBrush);
SafeNativeMethods.Gdip.CheckStatus(status);
SetNativeBrushInternal(nativeBrush);
}
public LinearGradientBrush(Rectangle rect, Color color1, Color color2, LinearGradientMode linearGradientMode)
{
if (linearGradientMode < LinearGradientMode.Horizontal || linearGradientMode > LinearGradientMode.BackwardDiagonal)
{
throw new InvalidEnumArgumentException(nameof(linearGradientMode), unchecked((int)linearGradientMode), typeof(LinearGradientMode));
}
if (rect.Width == 0 || rect.Height == 0)
{
throw new ArgumentException(SR.Format(SR.GdiplusInvalidRectangle, rect.ToString()));
}
var gpRect = new GPRECT(rect);
IntPtr nativeBrush;
int status = SafeNativeMethods.Gdip.GdipCreateLineBrushFromRectI(ref gpRect,
color1.ToArgb(),
color2.ToArgb(),
unchecked((int)linearGradientMode),
(int)WrapMode.Tile,
out nativeBrush);
SafeNativeMethods.Gdip.CheckStatus(status);
SetNativeBrushInternal(nativeBrush);
}
public LinearGradientBrush(RectangleF rect, Color color1, Color color2, float angle) : this(rect, color1, color2, angle, false)
{
}
public LinearGradientBrush(RectangleF rect, Color color1, Color color2, float angle, bool isAngleScaleable)
{
if (rect.Width == 0.0 || rect.Height == 0.0)
{
throw new ArgumentException(SR.Format(SR.GdiplusInvalidRectangle, rect.ToString()));
}
var gprectf = new GPRECTF(rect);
IntPtr nativeBrush;
int status = SafeNativeMethods.Gdip.GdipCreateLineBrushFromRectWithAngle(ref gprectf,
color1.ToArgb(),
color2.ToArgb(),
angle,
isAngleScaleable,
(int)WrapMode.Tile,
out nativeBrush);
SafeNativeMethods.Gdip.CheckStatus(status);
SetNativeBrushInternal(nativeBrush);
}
public LinearGradientBrush(Rectangle rect, Color color1, Color color2, float angle) : this(rect, color1, color2, angle, false)
{
}
public LinearGradientBrush(Rectangle rect, Color color1, Color color2, float angle, bool isAngleScaleable)
{
if (rect.Width == 0 || rect.Height == 0)
{
throw new ArgumentException(SR.Format(SR.GdiplusInvalidRectangle, rect.ToString()));
}
var gprect = new GPRECT(rect);
IntPtr nativeBrush;
int status = SafeNativeMethods.Gdip.GdipCreateLineBrushFromRectWithAngleI(ref gprect,
color1.ToArgb(),
color2.ToArgb(),
angle,
isAngleScaleable,
(int)WrapMode.Tile,
out nativeBrush);
SafeNativeMethods.Gdip.CheckStatus(status);
SetNativeBrushInternal(nativeBrush);
}
internal LinearGradientBrush(IntPtr nativeBrush)
{
Debug.Assert(nativeBrush != IntPtr.Zero, "Initializing native brush with null.");
SetNativeBrushInternal(nativeBrush);
}
public override object Clone()
{
IntPtr clonedBrush;
int status = SafeNativeMethods.Gdip.GdipCloneBrush(new HandleRef(this, NativeBrush), out clonedBrush);
SafeNativeMethods.Gdip.CheckStatus(status);
return new LinearGradientBrush(clonedBrush);
}
public Color[] LinearColors
{
get
{
int[] colors = new int[] { 0, 0 };
int status = SafeNativeMethods.Gdip.GdipGetLineColors(new HandleRef(this, NativeBrush), colors);
SafeNativeMethods.Gdip.CheckStatus(status);
return new Color[]
{
Color.FromArgb(colors[0]),
Color.FromArgb(colors[1])
};
}
set
{
int status = SafeNativeMethods.Gdip.GdipSetLineColors(new HandleRef(this, NativeBrush),
value[0].ToArgb(),
value[1].ToArgb());
SafeNativeMethods.Gdip.CheckStatus(status);
}
}
public RectangleF Rectangle
{
get
{
var rect = new GPRECTF();
int status = SafeNativeMethods.Gdip.GdipGetLineRect(new HandleRef(this, NativeBrush), ref rect);
SafeNativeMethods.Gdip.CheckStatus(status);
return rect.ToRectangleF();
}
}
public bool GammaCorrection
{
get
{
int status = SafeNativeMethods.Gdip.GdipGetLineGammaCorrection(new HandleRef(this, NativeBrush),
out bool useGammaCorrection);
SafeNativeMethods.Gdip.CheckStatus(status);
return useGammaCorrection;
}
set
{
int status = SafeNativeMethods.Gdip.GdipSetLineGammaCorrection(new HandleRef(this, NativeBrush), value);
SafeNativeMethods.Gdip.CheckStatus(status);
}
}
public Blend Blend
{
get
{
// Interpolation colors and blends don't work together very well. Getting the Blend when InterpolationColors
// is set set puts the Brush into an unusable state afterwards.
// Bail out here to avoid that.
if (_interpolationColorsWasSet)
{
return null;
}
// Figure out the size of blend factor array.
int status = SafeNativeMethods.Gdip.GdipGetLineBlendCount(new HandleRef(this, NativeBrush), out int retval);
SafeNativeMethods.Gdip.CheckStatus(status);
if (retval <= 0)
{
return null;
}
// Allocate a temporary native memory buffer.
int count = retval;
IntPtr factors = IntPtr.Zero;
IntPtr positions = IntPtr.Zero;
try
{
int size = checked(4 * count);
factors = Marshal.AllocHGlobal(size);
positions = Marshal.AllocHGlobal(size);
// Retrieve horizontal blend factors.
status = SafeNativeMethods.Gdip.GdipGetLineBlend(new HandleRef(this, NativeBrush), factors, positions, count);
SafeNativeMethods.Gdip.CheckStatus(status);
// Return the result in a managed array.
var blend = new Blend(count);
Marshal.Copy(factors, blend.Factors, 0, count);
Marshal.Copy(positions, blend.Positions, 0, count);
return blend;
}
finally
{
if (factors != IntPtr.Zero)
{
Marshal.FreeHGlobal(factors);
}
if (positions != IntPtr.Zero)
{
Marshal.FreeHGlobal(positions);
}
}
}
set
{
// Do explicit parameter validation here; libgdiplus does not correctly validate the arguments
if (value == null || value.Factors == null)
{
// This is the original behavior on Desktop .NET
throw new NullReferenceException();
}
if (value.Positions == null)
{
throw new ArgumentNullException("source");
}
int count = value.Factors.Length;
if (count == 0 || value.Positions.Length == 0)
{
throw new ArgumentException(SR.BlendObjectMustHaveTwoElements);
}
if (count >=2 && count != value.Positions.Length)
{
throw new ArgumentOutOfRangeException();
}
if (count >= 2 && value.Positions[0] != 0.0F)
{
throw new ArgumentException(SR.BlendObjectFirstElementInvalid);
}
if (count >= 2 && value.Positions[count - 1] != 1.0F)
{
throw new ArgumentException(SR.BlendObjectLastElementInvalid);
}
// Allocate temporary native memory buffer and copy input blend factors into it.
IntPtr factors = IntPtr.Zero;
IntPtr positions = IntPtr.Zero;
try
{
int size = checked(4 * count);
factors = Marshal.AllocHGlobal(size);
positions = Marshal.AllocHGlobal(size);
Marshal.Copy(value.Factors, 0, factors, count);
Marshal.Copy(value.Positions, 0, positions, count);
// Set blend factors.
int status = SafeNativeMethods.Gdip.GdipSetLineBlend(new HandleRef(this, NativeBrush), new HandleRef(null, factors), new HandleRef(null, positions), count);
SafeNativeMethods.Gdip.CheckStatus(status);
}
finally
{
if (factors != IntPtr.Zero)
{
Marshal.FreeHGlobal(factors);
}
if (positions != IntPtr.Zero)
{
Marshal.FreeHGlobal(positions);
}
}
}
}
public void SetSigmaBellShape(float focus) => SetSigmaBellShape(focus, (float)1.0);
public void SetSigmaBellShape(float focus, float scale)
{
if (focus < 0 || focus > 1 || scale < 0 || scale > 1)
{
throw new ArgumentException(SR.Format(SR.GdiplusInvalidParameter));
}
int status = SafeNativeMethods.Gdip.GdipSetLineSigmaBlend(new HandleRef(this, NativeBrush), focus, scale);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void SetBlendTriangularShape(float focus) => SetBlendTriangularShape(focus, (float)1.0);
public void SetBlendTriangularShape(float focus, float scale)
{
if (focus < 0 || focus > 1 || scale < 0 || scale > 1)
{
throw new ArgumentException(SR.Format(SR.GdiplusInvalidParameter));
}
int status = SafeNativeMethods.Gdip.GdipSetLineLinearBlend(new HandleRef(this, NativeBrush), focus, scale);
SafeNativeMethods.Gdip.CheckStatus(status);
// Setting a triangular shape overrides the explicitly set interpolation colors. libgdiplus correctly clears
// the interpolation colors (https://github.com/mono/libgdiplus/blob/master/src/lineargradientbrush.c#L959) but
// returns WrongState instead of ArgumentException (https://github.com/mono/libgdiplus/blob/master/src/lineargradientbrush.c#L814)
// when calling GdipGetLinePresetBlend, so it is important we set this to false. This way, we are sure get_InterpolationColors
// will return an ArgumentException.
_interpolationColorsWasSet = false;
}
public ColorBlend InterpolationColors
{
get
{
if (!_interpolationColorsWasSet)
{
throw new ArgumentException(SR.Format(SR.InterpolationColorsCommon,
SR.Format(SR.InterpolationColorsColorBlendNotSet), string.Empty));
}
// Figure out the size of blend factor array.
int status = SafeNativeMethods.Gdip.GdipGetLinePresetBlendCount(new HandleRef(this, NativeBrush), out int retval);
SafeNativeMethods.Gdip.CheckStatus(status);
// Allocate temporary native memory buffer.
int count = retval;
IntPtr colors = IntPtr.Zero;
IntPtr positions = IntPtr.Zero;
try
{
int size = checked(4 * count);
colors = Marshal.AllocHGlobal(size);
positions = Marshal.AllocHGlobal(size);
// Retrieve horizontal blend factors.
status = SafeNativeMethods.Gdip.GdipGetLinePresetBlend(new HandleRef(this, NativeBrush), colors, positions, count);
SafeNativeMethods.Gdip.CheckStatus(status);
// Return the result in a managed array.
var blend = new ColorBlend(count);
int[] argb = new int[count];
Marshal.Copy(colors, argb, 0, count);
Marshal.Copy(positions, blend.Positions, 0, count);
// Copy ARGB values into Color array of ColorBlend.
blend.Colors = new Color[argb.Length];
for (int i = 0; i < argb.Length; i++)
{
blend.Colors[i] = Color.FromArgb(argb[i]);
}
return blend;
}
finally
{
if (colors != IntPtr.Zero)
{
Marshal.FreeHGlobal(colors);
}
if (positions != IntPtr.Zero)
{
Marshal.FreeHGlobal(positions);
}
}
}
set
{
_interpolationColorsWasSet = true;
if (value == null)
{
throw new ArgumentException(SR.Format(SR.InterpolationColorsCommon,
SR.Format(SR.InterpolationColorsInvalidColorBlendObject), string.Empty));
}
else if (value.Colors.Length < 2)
{
throw new ArgumentException(SR.Format(SR.InterpolationColorsCommon,
SR.Format(SR.InterpolationColorsInvalidColorBlendObject),
SR.Format(SR.InterpolationColorsLength)));
}
else if (value.Colors.Length != value.Positions.Length)
{
throw new ArgumentException(SR.Format(SR.InterpolationColorsCommon,
SR.Format(SR.InterpolationColorsInvalidColorBlendObject),
SR.Format(SR.InterpolationColorsLengthsDiffer)));
}
else if (value.Positions[0] != 0.0f)
{
throw new ArgumentException(SR.Format(SR.InterpolationColorsCommon,
SR.Format(SR.InterpolationColorsInvalidColorBlendObject),
SR.Format(SR.InterpolationColorsInvalidStartPosition)));
}
else if (value.Positions[value.Positions.Length - 1] != 1.0f)
{
throw new ArgumentException(SR.Format(SR.InterpolationColorsCommon,
SR.Format(SR.InterpolationColorsInvalidColorBlendObject),
SR.Format(SR.InterpolationColorsInvalidEndPosition)));
}
// Allocate a temporary native memory buffer and copy input blend factors into it.
int count = value.Colors.Length;
IntPtr colors = IntPtr.Zero;
IntPtr positions = IntPtr.Zero;
try
{
int size = checked(4 * count);
colors = Marshal.AllocHGlobal(size);
positions = Marshal.AllocHGlobal(size);
int[] argbs = new int[count];
for (int i = 0; i < count; i++)
{
argbs[i] = value.Colors[i].ToArgb();
}
Marshal.Copy(argbs, 0, colors, count);
Marshal.Copy(value.Positions, 0, positions, count);
// Set blend factors.
int status = SafeNativeMethods.Gdip.GdipSetLinePresetBlend(new HandleRef(this, NativeBrush), new HandleRef(null, colors), new HandleRef(null, positions), count);
SafeNativeMethods.Gdip.CheckStatus(status);
}
finally
{
if (colors != IntPtr.Zero)
{
Marshal.FreeHGlobal(colors);
}
if (positions != IntPtr.Zero)
{
Marshal.FreeHGlobal(positions);
}
}
}
}
public WrapMode WrapMode
{
get
{
int status = SafeNativeMethods.Gdip.GdipGetLineWrapMode(new HandleRef(this, NativeBrush), out int mode);
SafeNativeMethods.Gdip.CheckStatus(status);
return (WrapMode)mode;
}
set
{
if (value < WrapMode.Tile || value > WrapMode.Clamp)
{
throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(WrapMode));
}
int status = SafeNativeMethods.Gdip.GdipSetLineWrapMode(new HandleRef(this, NativeBrush), unchecked((int)value));
SafeNativeMethods.Gdip.CheckStatus(status);
}
}
public Matrix Transform
{
get
{
var matrix = new Matrix();
int status = SafeNativeMethods.Gdip.GdipGetLineTransform(new HandleRef(this, NativeBrush), new HandleRef(matrix, matrix.nativeMatrix));
SafeNativeMethods.Gdip.CheckStatus(status);
return matrix;
}
set
{
if (value == null)
{
throw new ArgumentNullException("matrix");
}
int status = SafeNativeMethods.Gdip.GdipSetLineTransform(new HandleRef(this, NativeBrush), new HandleRef(value, value.nativeMatrix));
SafeNativeMethods.Gdip.CheckStatus(status);
}
}
public void ResetTransform()
{
int status = SafeNativeMethods.Gdip.GdipResetLineTransform(new HandleRef(this, NativeBrush));
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void MultiplyTransform(Matrix matrix) => MultiplyTransform(matrix, MatrixOrder.Prepend);
public void MultiplyTransform(Matrix matrix, MatrixOrder order)
{
if (matrix == null)
{
throw new ArgumentNullException(nameof(matrix));
}
int status = SafeNativeMethods.Gdip.GdipMultiplyLineTransform(new HandleRef(this, NativeBrush),
new HandleRef(matrix, matrix.nativeMatrix),
order);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void TranslateTransform(float dx, float dy) => TranslateTransform(dx, dy, MatrixOrder.Prepend);
public void TranslateTransform(float dx, float dy, MatrixOrder order)
{
int status = SafeNativeMethods.Gdip.GdipTranslateLineTransform(new HandleRef(this, NativeBrush),
dx,
dy,
order);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void ScaleTransform(float sx, float sy) => ScaleTransform(sx, sy, MatrixOrder.Prepend);
public void ScaleTransform(float sx, float sy, MatrixOrder order)
{
int status = SafeNativeMethods.Gdip.GdipScaleLineTransform(new HandleRef(this, NativeBrush),
sx,
sy,
order);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void RotateTransform(float angle) => RotateTransform(angle, MatrixOrder.Prepend);
public void RotateTransform(float angle, MatrixOrder order)
{
int status = SafeNativeMethods.Gdip.GdipRotateLineTransform(new HandleRef(this, NativeBrush),
angle,
order);
SafeNativeMethods.Gdip.CheckStatus(status);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Versioning;
using Mono.Cecil;
using NuGet;
using Ullink.NugetConverter.model;
using Ullink.NugetConverter.services.configuration;
using Ullink.NugetConverter.utils;
namespace Ullink.NugetConverter.services.assemblyCacheService
{
public class AssemblyCacheService
{
private readonly VersionResolverService _versionresolverService;
private readonly ConfigurationService _configurationGetter;
private readonly bool _useCache;
private SortedDictionary<Tuple<SemanticVersion, string>, DllReference> _assemblies;
/// <summary>
/// dll ignored by the user. ie filtered by nugetconverter.ini
/// </summary>
public SortedDictionary<Tuple<SemanticVersion, string>, DllReference> IgnoredAssemblies { get; }
/// <summary>
/// It happens that assembly version is the same for more than one assemblies, but assembly file version are differents
/// Key : The assemblyVersion
/// Value: SortedSet<SemanticVersion> contains list of assemblies with same assembly version
/// </summary>
private IDictionary<Tuple<Version, string>, SortedSet<SemanticVersion>> _conflictingAssemblies;
/// <summary>
/// The only purpose of this is to use Cecil to read References
/// </summary>
private readonly DefaultAssemblyResolver _assemblyResolver = new/**/ DefaultAssemblyResolver();
private readonly ReaderParameters _readerParameters;
public AssemblyCacheService(IEnumerable<string> dlls, VersionResolverService versionresolverService, ConfigurationService configurationService, bool useCache)
{
_versionresolverService = versionresolverService;
_configurationGetter = configurationService;
_useCache = useCache;
_readerParameters = new/**/ ReaderParameters { AssemblyResolver = _assemblyResolver };
_conflictingAssemblies = new/**/ Dictionary<Tuple<Version, string>, SortedSet<SemanticVersion>>();
IgnoredAssemblies = new/**/ SortedDictionary<Tuple<SemanticVersion, string>, DllReference>();
_conflictingAssemblies = new/**/ Dictionary<Tuple<Version, string>, SortedSet<SemanticVersion>>();
_assemblies = CreateOrUpdateAssemblies(dlls);
}
/// <summary>
/// For a specific assembly contains all the Known Exisiting Versions
/// Tuple<SemanticVersion, string>: Expected Version
/// SortedSet<SemanticVersion> : Exisiting conflicting version
///
/// The main issue is that some folder have version where dll inside have an other.
/// API are the main example. folder will have for example
/// 1.0 (folder) but AssemblyVersion will be 1.0
/// 1.1 (folder) but AssemblyVersion will be 1.0
/// 1.2 (folder) but AssemblyVersion will be 1.0
/// This Cache is used to keep conflicting folder & dll
/// </summary>
public IDictionary<Tuple<Version, string>, SortedSet<SemanticVersion>> ConflictingAssemblies => _conflictingAssemblies;
public SortedDictionary<Tuple<SemanticVersion, string>, DllReference> Assemblies => _assemblies;
public Tuple<SemanticVersion, string> AddOrUpdateAssembly(string fullPath)
{
var result = CreateOrUpdateAssembly(fullPath);
return result;
}
private SortedDictionary<Tuple<SemanticVersion, string>, DllReference> CreateOrUpdateAssemblies(IEnumerable<string> dlls)
{
_assemblies = new SortedDictionary<Tuple<SemanticVersion, string>, DllReference>();
//Ugly Performance...
var notAlreadyCompute = dlls
.Where(dll => !_assemblies.Any(_ => dll.Equals(_.Value.Path)))
.ToList();
foreach (var dll in notAlreadyCompute)
{
CreateOrUpdateAssembly(dll);
}
return Assemblies;
}
private Tuple<SemanticVersion, string> CreateOrUpdateAssembly(string dll)
{
// Read assembly and change reference according to one passed in parameters
try
{
// Read assembly and change reference according to one passed in parameters
AssemblyDefinition assemblyDefinition = AssemblyDefinition.ReadAssembly(dll, _readerParameters);
var mainAssemblyId = _versionresolverService.ResolveVersion(assemblyDefinition, dll);
if (mainAssemblyId == null)
{
throw new VersionNotFoundException($"Unable to extract Version from {dll}");
}
var assemblyReferences = from asm in assemblyDefinition.MainModule.AssemblyReferences select new /*?*/ AssemblyReference(asm.Name, asm.Version, asm.FullName);
var frameworkVersionName = GetFrameworkVersion(assemblyDefinition);
if (_configurationGetter.Get(dll).Ignore)
{
CreateOrUpdateAssembly(IgnoredAssemblies, dll, frameworkVersionName, mainAssemblyId, assemblyReferences);
Trace.TraceInformation("IGNORE : {0} because a nugetconverter.ini file ask to do so", dll);
return null;
}
return CreateOrUpdateAssembly(_assemblies, dll, frameworkVersionName, mainAssemblyId, assemblyReferences);
}
catch (Exception exception)
{
Trace.TraceInformation("IGNORE : {0} due to {1}", dll, exception.Message);
}
return null;
}
private static string GetFrameworkVersion(AssemblyDefinition assemblyDefinition)
{
//Framework .net Version
string frameworkVersionName = null;
var targetFrameworkAttribute = assemblyDefinition.CustomAttributes.FirstOrDefault(_ => _.AttributeType.Name.Equals(typeof (TargetFrameworkAttribute).Name));
if (targetFrameworkAttribute != null)
{
var targetFrameworkVersion = targetFrameworkAttribute.Properties.FirstOrDefault().Argument.Value.ToString();
frameworkVersionName = "net" + targetFrameworkVersion.Where(Char.IsDigit).Aggregate(String.Empty, (s, c) => s+c).PadRight(2, '0');
}
else
{
var targetRuntime = assemblyDefinition.MainModule.Runtime;
switch (targetRuntime)
{
case TargetRuntime.Net_1_0:
case TargetRuntime.Net_1_1:
case TargetRuntime.Net_2_0:
frameworkVersionName = "net35";
break;
case TargetRuntime.Net_4_0:
frameworkVersionName = "net40";
break;
}
}
return frameworkVersionName;
}
private Tuple<SemanticVersion, string> CreateOrUpdateAssembly(SortedDictionary<Tuple<SemanticVersion, string>, DllReference> cache,
string dll,
string frameworkVersionName,
FileAssemblyVersion mainAssemblyId,
IEnumerable<AssemblyReference> assemblyReferences)
{
if (cache.ContainsKey(mainAssemblyId))
return UpdateAssembly(cache, dll, frameworkVersionName, mainAssemblyId, assemblyReferences);
return CreateAssembly(cache, dll, frameworkVersionName, mainAssemblyId, assemblyReferences);
}
private Tuple<SemanticVersion, string> CreateAssembly(SortedDictionary<Tuple<SemanticVersion, string>, DllReference> cache,
string dll,
string frameworkVersionName,
FileAssemblyVersion mainAssemblyId,
IEnumerable<AssemblyReference> assemblyReferences)
{
Trace.TraceInformation($"ADDED : Assembly {mainAssemblyId.Item2}, {mainAssemblyId.Item1}");
//For a specific version (Version+Name) it might exist multiple real File (SemanticVersion+Name)
//For exampl snapshot. We store them here will see later which one to choose
var assemblyId = new Tuple<Version, string>(mainAssemblyId.AssemblyVersion, mainAssemblyId.Item2);
if (!ConflictingAssemblies.ContainsKey(assemblyId))
ConflictingAssemblies.Add(assemblyId, new /**/ SortedSet<SemanticVersion>());
ConflictingAssemblies[assemblyId].Add(mainAssemblyId.Item1);
// While adding references we ignore assembly in the GAC
cache.Add(mainAssemblyId,
new /**/ DllReference(dll,
frameworkVersionName,
mainAssemblyId,
assemblyReferences.Where(
_ =>
!GacUtil.IsFullNameAssemblyInGAC(_.FullName))));
return cache[mainAssemblyId].Id;
}
private Tuple<SemanticVersion, string> UpdateAssembly(SortedDictionary<Tuple<SemanticVersion, string>, DllReference> cache,
string dll,
string frameworkVersion,
FileAssemblyVersion mainAssemblyId,
IEnumerable<AssemblyReference> assemblyReferences)
{
//Not the same path, but it seems more correct as AssemblyName match dll name
if (cache.ContainsKey(mainAssemblyId) && !mainAssemblyId.Item2.Equals(Path.GetFileNameWithoutExtension(cache[mainAssemblyId].Path))
&& mainAssemblyId.Item2.Equals(Path.GetFileNameWithoutExtension(dll)))
{
Trace.TraceInformation($"UPDATE : {mainAssemblyId.Item2}, {mainAssemblyId.Item1} found in {dll} replace {cache[mainAssemblyId].Path} as assembly name match dll name");
cache[mainAssemblyId].Path = dll;
}
//Not the same path, ignore it
else if(cache.ContainsKey(mainAssemblyId) && !dll.Equals(cache[mainAssemblyId].Path, StringComparison.OrdinalIgnoreCase))
{
Trace.TraceInformation($"IGNORE : {mainAssemblyId.Item2}, {mainAssemblyId.Item1} found in {dll} already registered from {cache[mainAssemblyId].Path}");
return cache[mainAssemblyId].Id;
}
var assembly = cache[mainAssemblyId];
//We never know it might need updated. let's do it everytime
assembly.FrameworkVersion = frameworkVersion;
//Update References if References Changed
var newReferences = assemblyReferences.Where(_ => !GacUtil.IsFullNameAssemblyInGAC(_.FullName));
if (!newReferences.All(_ => Enumerable.Contains(cache[mainAssemblyId].AssemblyReferences, _)))
{
Trace.TraceInformation($"UPDATE : Dependencies for {mainAssemblyId.Item2}, {mainAssemblyId.Item1} has changed");
cache[mainAssemblyId].AssemblyReferences = newReferences;
}
return assembly.Id;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Xunit;
namespace System.Collections.Immutable.Tests
{
public class ImmutableQueueTest : SimpleElementImmutablesTestBase
{
private void EnqueueDequeueTestHelper<T>(params T[] items)
{
Assert.NotNull(items);
var queue = ImmutableQueue<T>.Empty;
int i = 0;
foreach (T item in items)
{
var nextQueue = queue.Enqueue(item);
Assert.NotSame(queue, nextQueue); //, "Enqueue returned this instead of a new instance.");
Assert.Equal(i, queue.Count()); //, "Enqueue mutated the queue.");
Assert.Equal(++i, nextQueue.Count());
queue = nextQueue;
}
i = 0;
foreach (T element in queue)
{
AssertAreSame(items[i++], element);
}
i = 0;
foreach (T element in (System.Collections.IEnumerable)queue)
{
AssertAreSame(items[i++], element);
}
i = items.Length;
foreach (T expectedItem in items)
{
T actualItem = queue.Peek();
AssertAreSame(expectedItem, actualItem);
var nextQueue = queue.Dequeue();
Assert.NotSame(queue, nextQueue); //, "Dequeue returned this instead of a new instance.");
Assert.Equal(i, queue.Count());
Assert.Equal(--i, nextQueue.Count());
queue = nextQueue;
}
}
[Fact]
public void EnumerationOrder()
{
var queue = ImmutableQueue<int>.Empty;
// Push elements onto the backwards stack.
queue = queue.Enqueue(1).Enqueue(2).Enqueue(3);
Assert.Equal(1, queue.Peek());
// Force the backwards stack to be reversed and put into forwards.
queue = queue.Dequeue();
// Push elements onto the backwards stack again.
queue = queue.Enqueue(4).Enqueue(5);
// Now that we have some elements on the forwards and backwards stack,
// 1. enumerate all elements to verify order.
Assert.Equal<int>(new[] { 2, 3, 4, 5 }, queue.ToArray());
// 2. dequeue all elements to verify order
var actual = new int[queue.Count()];
for (int i = 0; i < actual.Length; i++)
{
actual[i] = queue.Peek();
queue = queue.Dequeue();
}
}
[Fact]
public void GetEnumeratorText()
{
var queue = ImmutableQueue.Create(5);
var enumeratorStruct = queue.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumeratorStruct.Current);
Assert.True(enumeratorStruct.MoveNext());
Assert.Equal(5, enumeratorStruct.Current);
Assert.False(enumeratorStruct.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumeratorStruct.Current);
var enumerator = ((IEnumerable<int>)queue).GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal(5, enumerator.Current);
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal(5, enumerator.Current);
Assert.False(enumerator.MoveNext());
enumerator.Dispose();
}
[Fact]
public void EnumeratorRecyclingMisuse()
{
var queue = ImmutableQueue.Create(5);
var enumerator = ((IEnumerable<int>)queue).GetEnumerator();
var enumeratorCopy = enumerator;
Assert.True(enumerator.MoveNext());
enumerator.Dispose();
Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumerator.Reset());
Assert.Throws<ObjectDisposedException>(() => enumerator.Current);
// As pure structs with no disposable reference types inside it,
// we have nothing to track across struct copies, and this just works.
////Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.MoveNext());
////Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Reset());
////Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Current);
enumerator.Dispose(); // double-disposal should not throw
enumeratorCopy.Dispose();
// We expect that acquiring a new enumerator will use the same underlying Stack<T> object,
// but that it will not throw exceptions for the new enumerator.
enumerator = ((IEnumerable<int>)queue).GetEnumerator();
Assert.True(enumerator.MoveNext());
Assert.Equal(queue.Peek(), enumerator.Current);
enumerator.Dispose();
}
[Fact]
public void EnqueueDequeueTest()
{
this.EnqueueDequeueTestHelper(new GenericParameterHelper(1), new GenericParameterHelper(2), new GenericParameterHelper(3));
this.EnqueueDequeueTestHelper<GenericParameterHelper>();
// interface test
IImmutableQueue<GenericParameterHelper> queueInterface = ImmutableQueue.Create<GenericParameterHelper>();
IImmutableQueue<GenericParameterHelper> populatedQueueInterface = queueInterface.Enqueue(new GenericParameterHelper(5));
Assert.Equal(new GenericParameterHelper(5), populatedQueueInterface.Peek());
}
[Fact]
public void DequeueOutValue()
{
var queue = ImmutableQueue<int>.Empty.Enqueue(5).Enqueue(6);
int head;
queue = queue.Dequeue(out head);
Assert.Equal(5, head);
var emptyQueue = queue.Dequeue(out head);
Assert.Equal(6, head);
Assert.True(emptyQueue.IsEmpty);
// Also check that the interface extension method works.
IImmutableQueue<int> interfaceQueue = queue;
Assert.Same(emptyQueue, interfaceQueue.Dequeue(out head));
Assert.Equal(6, head);
}
[Fact]
public void ClearTest()
{
var emptyQueue = ImmutableQueue.Create<GenericParameterHelper>();
AssertAreSame(emptyQueue, emptyQueue.Clear());
var nonEmptyQueue = emptyQueue.Enqueue(new GenericParameterHelper(3));
AssertAreSame(emptyQueue, nonEmptyQueue.Clear());
// Interface test
IImmutableQueue<GenericParameterHelper> queueInterface = nonEmptyQueue;
AssertAreSame(emptyQueue, queueInterface.Clear());
}
[Fact]
public void EqualsTest()
{
Assert.False(ImmutableQueue<int>.Empty.Equals(null));
Assert.False(ImmutableQueue<int>.Empty.Equals("hi"));
Assert.True(ImmutableQueue<int>.Empty.Equals(ImmutableQueue<int>.Empty));
Assert.False(ImmutableQueue<int>.Empty.Enqueue(3).Equals(ImmutableQueue<int>.Empty.Enqueue(3)));
Assert.False(ImmutableQueue<int>.Empty.Enqueue(5).Equals(ImmutableQueue<int>.Empty.Enqueue(3)));
Assert.False(ImmutableQueue<int>.Empty.Enqueue(3).Enqueue(5).Equals(ImmutableQueue<int>.Empty.Enqueue(3)));
Assert.False(ImmutableQueue<int>.Empty.Enqueue(3).Equals(ImmutableQueue<int>.Empty.Enqueue(3).Enqueue(5)));
// Also be sure to compare equality of partially dequeued queues since that moves data to different fields.
Assert.False(ImmutableQueue<int>.Empty.Enqueue(3).Enqueue(1).Enqueue(2).Dequeue().Equals(ImmutableQueue<int>.Empty.Enqueue(1).Enqueue(2)));
}
[Fact]
public void PeekEmptyThrows()
{
Assert.Throws<InvalidOperationException>(() => ImmutableQueue<GenericParameterHelper>.Empty.Peek());
}
[Fact]
public void DequeueEmptyThrows()
{
Assert.Throws<InvalidOperationException>(() => ImmutableQueue<GenericParameterHelper>.Empty.Dequeue());
}
[Fact]
public void Create()
{
ImmutableQueue<int> queue = ImmutableQueue.Create<int>();
Assert.True(queue.IsEmpty);
queue = ImmutableQueue.Create(1);
Assert.False(queue.IsEmpty);
Assert.Equal(new[] { 1 }, queue);
queue = ImmutableQueue.Create(1, 2);
Assert.False(queue.IsEmpty);
Assert.Equal(new[] { 1, 2 }, queue);
queue = ImmutableQueue.CreateRange((IEnumerable<int>)new[] { 1, 2 });
Assert.False(queue.IsEmpty);
Assert.Equal(new[] { 1, 2 }, queue);
queue = ImmutableQueue.CreateRange(new List<int> { 1, 2 });
Assert.False(queue.IsEmpty);
Assert.Equal(new[] { 1, 2 }, queue);
AssertExtensions.Throws<ArgumentNullException>("items", () => ImmutableQueue.CreateRange((IEnumerable<int>)null));
AssertExtensions.Throws<ArgumentNullException>("items", () => ImmutableQueue.Create((int[])null));
}
[Fact]
public void Empty()
{
// We already test Create(), so just prove that Empty has the same effect.
Assert.Same(ImmutableQueue.Create<int>(), ImmutableQueue<int>.Empty);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")]
public void DebuggerAttributesValid()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableQueue.Create<int>());
ImmutableQueue<string> queue = ImmutableQueue.Create("One", "Two");
DebuggerAttributeInfo info = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(queue);
PropertyInfo itemProperty = info.Properties.Single(pr => pr.GetCustomAttribute<DebuggerBrowsableAttribute>().State == DebuggerBrowsableState.RootHidden);
string[] items = itemProperty.GetValue(info.Instance) as string[];
Assert.Equal(queue, items);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")]
public static void TestDebuggerAttributes_Null()
{
Type proxyType = DebuggerAttributes.GetProxyType(ImmutableQueue.Create<int>());
TargetInvocationException tie = Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(proxyType, (object)null));
Assert.IsType<ArgumentNullException>(tie.InnerException);
}
[Fact]
public void PeekRef()
{
var queue = ImmutableQueue<int>.Empty
.Enqueue(1)
.Enqueue(2)
.Enqueue(3);
ref readonly var safeRef = ref queue.PeekRef();
ref var unsafeRef = ref Unsafe.AsRef(safeRef);
Assert.Equal(1, queue.PeekRef());
unsafeRef = 4;
Assert.Equal(4, queue.PeekRef());
}
[Fact]
public void PeekRef_Empty()
{
var queue = ImmutableQueue<int>.Empty;
Assert.Throws<InvalidOperationException>(() => queue.PeekRef());
}
protected override IEnumerable<T> GetEnumerableOf<T>(params T[] contents)
{
var queue = ImmutableQueue<T>.Empty;
foreach (var item in contents)
{
queue = queue.Enqueue(item);
}
return queue;
}
}
}
| |
namespace PokerTell.PokerHand.Services
{
using System;
using System.Collections.Generic;
using System.Reflection;
using Interfaces;
using log4net;
using PokerTell.Infrastructure.Enumerations.PokerHand;
using PokerTell.Infrastructure.Interfaces;
using PokerTell.Infrastructure.Interfaces.PokerHand;
using PokerTell.PokerHand.Base;
/// <summary>
/// Static class which provides methos to convert a Hand with absolute Action Ratios
/// into a hand with relative Action Ratios
/// </summary>
public class PokerHandConverter : IPokerHandConverter
{
static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
readonly IConstructor<IConvertedPokerHand> _convertedHandMake;
readonly IConstructor<IConvertedPokerPlayer> _convertedPlayerMake;
readonly IPokerRoundsConverter _pokerRoundsConverter;
public PokerHandConverter(
IConstructor<IConvertedPokerPlayer> convertedPlayerMake,
IConstructor<IConvertedPokerHand> convertedHandMake,
IPokerRoundsConverter pokerRoundsConverter)
{
_convertedPlayerMake = convertedPlayerMake;
_convertedHandMake = convertedHandMake;
_pokerRoundsConverter = pokerRoundsConverter;
}
/// <summary>
/// Converts the given Hand with absolute ratios into a Hand with relative ratios
/// It assumes all Players of the Hand were sorted previously
/// </summary>
/// <param name="sortedAquiredHand">Hand to be converted</param>
/// <returns>Converted Hand</returns>
public IConvertedPokerHand ConvertAquiredHand(IAquiredPokerHand sortedAquiredHand)
{
if (sortedAquiredHand == null)
{
Log.Debug("AquiredHand was null, returning null");
return null;
}
if (sortedAquiredHand.TotalPlayers < 2 || sortedAquiredHand.TotalPlayers > 10)
{
Log.DebugFormat("AquiredHand had {0} players.\n<{1}>", sortedAquiredHand.TotalPlayers, sortedAquiredHand);
return null;
}
// At this point Players are already sorted according to their Positions
// Now parse through the hand and create the relative actions
// Start w/ SB except for Preflop
try
{
// First we just need to call the big blind
double toCall = sortedAquiredHand.BB;
double theoreticalStartingPot = sortedAquiredHand.BB + sortedAquiredHand.SB +
(sortedAquiredHand.Ante * sortedAquiredHand.TotalPlayers);
// This could be different from the theoretical starting pot if a player
// posted out of line (like from middle position) -> the actual pot at the beginning
// of the hand will be bigger than the theoretical pot
double pot = RemovePostingActionsAndCalculatePotAfterPosting(ref sortedAquiredHand);
// PokerOffice sometimes didn't store posting Actions
// This will ignore Ante though
if (pot <= 0)
{
pot = theoreticalStartingPot;
}
IConvertedPokerHand convertedHand =
_convertedHandMake.New
.InitializeWith(sortedAquiredHand)
.AddPlayersFrom(sortedAquiredHand, theoreticalStartingPot, _convertedPlayerMake);
convertedHand =
_pokerRoundsConverter
.InitializeWith(sortedAquiredHand, convertedHand, pot, toCall)
.ConvertPreflop()
.ConvertFlopTurnAndRiver();
convertedHand
.RemoveInactivePlayers()
.SetNumOfPlayersInEachRound()
.AdjustOrderOfPlayersIfItIsHeadsUp()
.SetWhoHasPositionInEachRound();
foreach (var player in convertedHand)
{
player.SetActionSequencesAndBetSizeKeysFromSequenceStrings();
}
return convertedHand;
}
catch (Exception excep)
{
Log.Error("Unhandled", excep);
return null;
}
}
/// <summary>
/// Converts the given Hands with absolute ratios into Hands with relative ratios
/// This is done by replaying the hand and determining the relation of each action ratio
/// to the pot or the amount that needed to be called
/// </summary>
/// <param name="sortedAquiredHands">Hands to be converted</param>
/// <returns>Converted Hands</returns>
public IPokerHands ConvertAquiredHands(IPokerHands sortedAquiredHands)
{
var convertedHands = new PokerHands();
for (int i = 0; i < sortedAquiredHands.Hands.Count; i++)
{
IConvertedPokerHand convertedHand = ConvertAquiredHand((IAquiredPokerHand)sortedAquiredHands.Hands[i]);
// Only add hands with active players
if (convertedHand != null)
{
convertedHands.AddHand(convertedHand);
}
}
return convertedHands;
}
/// <summary>
/// Remove Posting and set BettingRound to null if no actions were left
/// Antes and Blinds will be added to pot during removal
/// </summary>
/// <param name="aquiredHand">PokerHand</param>
/// <returns>The pot at the beginning of the hand - containing blinds and antes</returns>
protected virtual double RemovePostingActionsAndCalculatePotAfterPosting(ref IAquiredPokerHand aquiredHand)
{
double sumOfAllPostingAmounts = 0;
var playersToRemove = new List<IAquiredPokerPlayer>();
foreach (IAquiredPokerPlayer aquiredPlayer in aquiredHand)
{
// Does player have a round?
if (aquiredPlayer.Count > (int)Streets.PreFlop)
{
IAquiredPokerRound preflopRound = aquiredPlayer[Streets.PreFlop];
if (NoActionsLeftAfterRemovingPostingActionsFromRound(ref preflopRound, ref sumOfAllPostingAmounts))
{
// Must have been a sitout, otherwise he's have at least a preflop fold left
playersToRemove.Add(aquiredPlayer);
}
}
else
{
// if player has no round, remove him b/c there is nothing he contributed to the hand
// not even a fold (so he was probably sitting out)
playersToRemove.Add(aquiredPlayer);
}
}
foreach (IAquiredPokerPlayer aquiredPlayer in playersToRemove)
{
aquiredHand.RemovePlayer(aquiredPlayer);
}
return sumOfAllPostingAmounts;
}
/// <summary>
/// Removes all posting actions (antes and blinds) while adding their values to the pot
/// This is done, because posting is involuntary and doesn't say anything about a player's playing style
/// </summary>
/// <param name="aquiredPokerRound">The Poker round from which to remove posting actions</param>
/// <param name="potAfterPosting">The pot, that the posted amounts will be added to</param>
/// <returns></returns>
static bool NoActionsLeftAfterRemovingPostingActionsFromRound(
ref IAquiredPokerRound aquiredPokerRound, ref double potAfterPosting)
{
try
{
// if no action in round initiate Player removal
if (aquiredPokerRound.Actions.Count < 1)
{
return true;
}
// remove first actions in round as long as they are posting actions
while (aquiredPokerRound[0].What == ActionTypes.P)
{
// Update pot
potAfterPosting += aquiredPokerRound[0].Ratio;
// Remove
aquiredPokerRound.RemoveAction(0);
// If no action left initiate Player removal
if (aquiredPokerRound.Actions.Count < 1)
{
return true;
}
}
}
catch (Exception excep)
{
excep.Data.Add("Round: ", aquiredPokerRound.ToString());
Log.Error("Unhandled", excep);
}
return false;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace ODataValidator.Rule.Helper
{
#region Namespaces
using System;
using System.Collections.Generic;
using System.Data.Metadata.Edm;
using System.Linq;
using System.Text;
using System.Web;
using System.Xml.Linq;
using System.Xml.XPath;
using ODataValidator.RuleEngine;
using ODataValidator.RuleEngine.Common;
#endregion
/// <summary>
/// Class of URI resporce path.
/// </summary>
public class ResourcePathHelper
{
/// <summary>
/// Separator of query part in URI string.
/// </summary>
private const string QuerySeparator = "?";
/// <summary>
/// Separator between query options.
/// </summary>
private const string OptionSeparator = "&";
/// <summary>
/// Separator of name and value within a query option.
/// </summary>
private const string NameValueSeparator = "=";
/// <summary>
/// Separator bewteen key-value pairs in combined key.
/// </summary>
private const char KeyValuePairSeparator = ',';
/// <summary>
/// Separator between key and value within single key-value pair in combined key.
/// </summary>
private const char KeyValueSeparator = '=';
/// <summary>
/// Separator between values of combined value only literal.
/// </summary>
private const string ValueSeparator = ",";
/// <summary>
/// String of URI exclusding queries.
/// </summary>
private string basePath;
/// <summary>
/// Collection of query key-value pairs.
/// </summary>
private Dictionary<string, string> queries;
/// <summary>
/// Creates an instance of ResourcePathHelper from a Uri object
/// </summary>
/// <param name="uri">The input Uri object</param>
public ResourcePathHelper(Uri uri)
{
if (uri == null)
{
throw new ArgumentNullException("uri");
}
this.basePath = uri.GetLeftPart(UriPartial.Path);
this.queries = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
var collection = HttpUtility.ParseQueryString(uri.Query);
foreach (var key in collection.AllKeys)
{
this.queries.Add(key, collection[key]);
}
}
/// <summary>
/// Gets the product of URI string.
/// </summary>
public string Product
{
get
{
StringBuilder sb = new StringBuilder(this.basePath);
if (this.queries.Any())
{
var queryStrings = from q in this.queries
select q.Key + ResourcePathHelper.NameValueSeparator + q.Value;
var queryOptions = string.Join(ResourcePathHelper.OptionSeparator, queryStrings.ToArray());
sb.AppendFormat("{0}{1}", ResourcePathHelper.QuerySeparator, queryOptions);
}
return sb.ToString();
}
}
/// <summary>
/// Gets the combined value literal from the combined key.
/// </summary>
/// <param name="combinedKey">The key combination</param>
/// <returns>The value combination</returns>
public static string GetValuesOfKey(string combinedKey)
{
if (string.IsNullOrEmpty(combinedKey))
{
return null;
}
string[] keyValuePairs = combinedKey.Split(ResourcePathHelper.KeyValuePairSeparator);
List<string> values = new List<string>();
foreach (var pair in keyValuePairs)
{
string[] items = pair.Split(ResourcePathHelper.KeyValueSeparator);
switch (items.Length)
{
case 1:
values.Add(items[0]);
break;
case 2:
values.Add(items[1]);
break;
}
}
return string.Join(ResourcePathHelper.ValueSeparator, values.ToArray());
}
/// <summary>
/// Adds a query option.
/// </summary>
/// <param name="key">The key of query option to be added</param>
/// <param name="value">The value of query option to be added</param>
public void AddQueryOption(string key, string value)
{
this.queries.Add(key, value);
}
/// <summary>
/// Removes a query string having the specified query key.
/// </summary>
/// <param name="key">The key of query option to be removed</param>
public void RemoveQueryOption(string key)
{
this.queries.Remove(key);
}
/// <summary>
/// Gets the value of query option having the specified key.
/// </summary>
/// <param name="key">The key of query option</param>
/// <returns>literal of query option value</returns>
public string GetQueryValue(string key)
{
string result = null;
this.queries.TryGetValue(key, out result);
return result;
}
/// <summary>
/// Checks whether the target Uri of context has only one segment after the base of service document resourse
/// </summary>
/// <param name="context">The context object</param>
/// <param name="segment">The output parameter of the only segment</param>
/// <returns>Returns true if the target is one segemnt after the base uri; false otherwise</returns>
public static bool IsOneSegmentPath(ServiceContext context, out string segment)
{
bool result = false;
segment = string.Empty;
if (context.ServiceBaseUri != null)
{
string pathRelative = context.DestinationBasePath.Substring(context.ServiceBaseUri.AbsoluteUri.Length);
segment = pathRelative.Trim('/');
if (!string.IsNullOrEmpty(pathRelative) && !pathRelative.Equals(Constants.Metadata, StringComparison.Ordinal))
{
result = pathRelative.IndexOf('/') < 0;
}
}
return result;
}
/// <summary>
/// Gets collection of path segments of expansion definition
/// </summary>
/// <param name="expandValue">The expansion definion of expand query option</param>
/// <returns>The collection of path segments</returns>
public static IEnumerable<string[]> GetBranchedSegments(string expandValue)
{
List<string[]> result = new List<string[]>();
if (!string.IsNullOrEmpty(expandValue))
{
string[] branches = expandValue.Split(',');
foreach (var branch in branches)
{
var br = branch.Trim().Trim('/');
string[] paths = br.Split('/');
result.Add(paths);
}
}
return result;
}
/// <summary>
/// Gets the complex type definition node with the specific name from the metadata document
/// </summary>
/// <param name="typeName">The type name</param>
/// <param name="meta">The metadata document</param>
/// <returns>The XML node of the named complex type if one is found; null otherwise</returns>
public static XElement GetComplexType(string typeName, XElement meta)
{
string fmtXPathToComplexType = "//*[local-name()='Schema' and @Namespace='{0}']/*[local-name()='ComplexType' and @Name='{1}']";
string xpath = string.Format(fmtXPathToComplexType, GetNamespaceName(typeName), GetBaseName(typeName));
var node = meta.XPathSelectElement(xpath);
return node;
}
/// <summary>
/// Gets segments of URI relative path from ServiceContext instance
/// </summary>
/// <param name="context">The ServiceContext instance</param>
/// <returns>The segments of relative path</returns>
public static IEnumerable<string> GetPathSegments(ServiceContext context)
{
var path = context.DestinationBasePath.Substring(context.ServiceBaseUri.AbsoluteUri.Length);
return ResourcePathHelper.GetPathSegments(path);
}
/// <summary>
/// Gets segments from URI relative path
/// </summary>
/// <param name="path">The path in URI relative format</param>
/// <returns>The segments of the path</returns>
public static IEnumerable<string> GetPathSegments(string path)
{
path = path.Trim('/');
return path.Split('/');
}
/// <summary>
/// Gets Namespace name part of a type name
/// </summary>
/// <param name="typeName">The type name</param>
/// <returns>The namespoace name; empty if type name is not a fully-qualified one</returns>
public static string GetNamespaceName(string typeName)
{
int indexOfLastDot = typeName.LastIndexOf('.');
return indexOfLastDot <= 0 ? "" : typeName.Substring(0, indexOfLastDot);
}
/// <summary>
/// Gets the base name part of a type name
/// </summary>
/// <param name="typeName">The type name</param>
/// <returns>The base name</returns>
public static string GetBaseName(string typeName)
{
int indexOfLastDot = typeName.LastIndexOf('.');
return indexOfLastDot <= 0 ? typeName : typeName.Substring(indexOfLastDot + 1);
}
/// <summary>
/// Gets segment core from a path segment input
/// </summary>
/// <param name="segment">The segment input</param>
/// <param name="inParenthesis">Output parameter of segment parameters enclosed by parenthesis</param>
/// <returns>The segment core before the parenthesis</returns>
public static string ParseSegment(string segment, out string inParenthesis)
{
string result = segment;
inParenthesis = null;
if (!string.IsNullOrEmpty(segment))
{
int posLP = segment.IndexOf('(');
if (posLP > 0)
{
int posRP = segment.LastIndexOf(')');
if (posRP > posLP)
{
result = segment.Substring(0, posLP);
inParenthesis = segment.Substring(posLP + 1, posRP - posLP - 1).Trim();
}
}
}
return result;
}
/// <summary>
/// Gets URI object from resource path and base OData service root
/// </summary>
/// <param name="path">The resource path</param>
/// <param name="uriBase">The OData service root Uri</param>
/// <returns>The URI object generated; or null if none valid one is possible</returns>
public static Uri GetODataResourceUri(string path, Uri uriBase)
{
Uri result;
if (Uri.TryCreate(path, UriKind.Absolute, out result))
{
return result;
}
else if (Uri.TryCreate(uriBase, path, out result))
{
return result;
}
else
{
return null;
}
}
/// <summary>
/// Gets the dataservice namespace from payload literal
/// </summary>
/// <param name="payload">The payload literal</param>
/// <returns>The dataservice namespace defined in payload; or the implicit dataservie namespace</returns>
public static string GetDataServiceNamespace(XElement payload)
{
var ps = payload.XPathSelectElement("//m:properties/*", ODataNamespaceManager.Instance);
if (ps != null && !string.IsNullOrEmpty(ps.Name.NamespaceName))
{
return ps.Name.NamespaceName;
}
else
{
// the default implcit dataservice namespace as defined in [MS-OData] spec
return "http://schemas.microsoft.com/ado/2007/08/dataservices";
}
}
/// <summary>
/// Gets the short name of the entity for the context
/// </summary>
/// <param name="context">The context object which directly or indirectly points to an entry</param>
/// <returns>The short name of entity</returns>
public static string GetEntityName(ServiceContext context)
{
string entityName = context.EntityTypeShortName;
if (string.IsNullOrEmpty(entityName))
{
var edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
var segments = ResourcePathHelper.GetPathSegments(context);
var segsToEntity = GetEntryUriSegments(segments.Take(segments.Count() - 1), edmxHelper);
UriType uriType;
var target = edmxHelper.GetTargetType(segsToEntity, out uriType);
entityName = ((EntityType)target).Name;
}
return entityName;
}
/// <summary>
/// Gets the segments pointing to an entry based
/// </summary>
/// <param name="segments">The segments pointing to derived resources of the entry</param>
/// <param name="edmxHelper">The EdmxHelper instance</param>
/// <returns>The segments pointing to the entry</returns>
public static IEnumerable<string> GetEntryUriSegments(IEnumerable<string> segments, EdmxHelper edmxHelper)
{
if (!segments.Any())
{
return segments;
}
UriType uriType;
var target = edmxHelper.GetTargetType(segments, out uriType);
if (uriType == UriType.URI2)
{
return segments;
}
return GetEntryUriSegments(segments.Take(segments.Count() - 1), edmxHelper);
}
/// <summary>
/// Gets the concurrency token property of the specified entity as defined in the metadata document
/// </summary>
/// <param name="meta">The metadata document</param>
/// <param name="entityName">The short name of the entity</param>
/// <returns>The concurrency property; or null if none is defined</returns>
public static string GetConcurrencyProperty(XElement meta, string entityName)
{
string result = null;
string xpath = string.Format("//*[local-name()='EntityType' and @Name='{0}']/*[local-name()='Property' and @Name and @ConcurrencyMode='Fixed']",
entityName);
var concurrencyProperty = meta.XPathSelectElement(xpath, ODataNamespaceManager.Instance);
if (concurrencyProperty != null)
{
result = concurrencyProperty.GetAttributeValue("Name");
}
return result;
}
/// <summary>
/// Gets the major part of header value
/// </summary>
/// <param name="value">The header value</param>
/// <returns>The major part of value</returns>
public static string GetMajorHeaderValue(string value)
{
string result = null;
string[] parts = value.Split(';');
if (parts.Length >= 1)
{
result = parts[0];
}
return result;
}
/// <summary>
/// Checks whether the entity type definition has any property mapping
/// </summary>
/// <param name="meta">The metadata document</param>
/// <param name="entityType">The entity type</param>
/// <returns>flag of proerty being mapped</returns>
public static bool HasPropertyMapping(XElement meta, string entityType)
{
if (meta == null)
{
throw new ArgumentNullException("meta");
}
if (string.IsNullOrEmpty(entityType))
{
throw new ArgumentException("parameter should not be null or empty", "entityType");
}
const string tmplXPath2EntityType = @"//*[local-name()='EntityType' and @Name = '{0}']";
const string xPath2Property = @"./*[local-name()='Property' and @m:FC_KeepInContent='false']";
string typeShortName = ResourcePathHelper.GetBaseName(entityType);
string xPath2EntityType = string.Format(tmplXPath2EntityType, typeShortName);
var nodeEntityType = meta.XPathSelectElement(xPath2EntityType, ODataNamespaceManager.Instance);
var nodeProperty = nodeEntityType.XPathSelectElement(xPath2Property, ODataNamespaceManager.Instance);
if (nodeProperty != null)
{
return true;
}
else
{
string baseType = nodeEntityType.GetAttributeValue("BaseType");
if (baseType == null)
{
return false;
}
else
{
return HasPropertyMapping(meta, baseType);
}
}
}
/// <summary>
/// Checks whether a query string has the specied query option
/// </summary>
/// <param name="query">The query string</param>
/// <param name="option">The query option name</param>
/// <param name="value">Output parameter of found query option value</param>
/// <returns>true if the named option is found; false otherwise</returns>
public static bool HasQueryOption(string query, string option, out string value)
{
bool result = false;
var qs = HttpUtility.ParseQueryString(query);
result = qs.AllKeys.Contains(option);
value = result ? qs[option] : null;
return result;
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="UpdateTranslator.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System.Collections.Generic;
using System.Data.Objects;
using System.Data.Common.Utils;
using System.Data.Common.CommandTrees;
using System.Data.Common;
using System.Threading;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Data.Metadata.Edm;
using System.Data.EntityClient;
using System.Data.Spatial;
using System.Globalization;
using System.Data.Entity;
using System.Linq;
namespace System.Data.Mapping.Update.Internal
{
/// <summary>
/// This class performs to following tasks to persist C-Space changes to the store:
/// <list>
/// <item>Extract changes from the entity state manager</item>
/// <item>Group changes by C-Space extent</item>
/// <item>For each affected S-Space table, perform propagation (get changes in S-Space terms)</item>
/// <item>Merge S-Space inserts and deletes into updates where appropriate</item>
/// <item>Produce S-Space commands implementating the modifications (insert, delete and update SQL statements)</item>
/// </list>
/// </summary>
internal partial class UpdateTranslator
{
#region Constructors
/// <summary>
/// Constructs a grouper based on the contents of the given entity state manager.
/// </summary>
/// <param name="stateManager">Entity state manager containing changes to be processed.</param>
/// <param name="metadataWorkspace">Metadata workspace.</param>
/// <param name="connection">Map connection</param>
/// <param name="commandTimeout">Timeout for update commands; null means 'use provider default'</param>
private UpdateTranslator(IEntityStateManager stateManager, MetadataWorkspace metadataWorkspace, EntityConnection connection, int? commandTimeout)
{
EntityUtil.CheckArgumentNull(stateManager, "stateManager");
EntityUtil.CheckArgumentNull(metadataWorkspace, "metadataWorkspace");
EntityUtil.CheckArgumentNull(connection, "connection");
// propagation state
m_changes = new Dictionary<EntitySetBase, ChangeNode>();
m_functionChanges = new Dictionary<EntitySetBase, List<ExtractedStateEntry>>();
m_stateEntries = new List<IEntityStateEntry>();
m_knownEntityKeys = new Set<EntityKey>();
m_requiredEntities = new Dictionary<EntityKey, AssociationSet>();
m_optionalEntities = new Set<EntityKey>();
m_includedValueEntities = new Set<EntityKey>();
// workspace state
m_metadataWorkspace = metadataWorkspace;
m_viewLoader = metadataWorkspace.GetUpdateViewLoader();
m_stateManager = stateManager;
// ancillary propagation services
m_recordConverter = new RecordConverter(this);
m_constraintValidator = new RelationshipConstraintValidator(this);
m_providerServices = DbProviderServices.GetProviderServices(connection.StoreProviderFactory);
m_connection = connection;
m_commandTimeout = commandTimeout;
// metadata cache
m_extractorMetadata = new Dictionary<Tuple<EntitySetBase, StructuralType>, ExtractorMetadata>(); ;
// key management
KeyManager = new KeyManager(this);
KeyComparer = CompositeKey.CreateComparer(KeyManager);
}
#endregion
#region Fields
// propagation state
private readonly Dictionary<EntitySetBase, ChangeNode> m_changes;
private readonly Dictionary<EntitySetBase, List<ExtractedStateEntry>> m_functionChanges;
private readonly List<IEntityStateEntry> m_stateEntries;
private readonly Set<EntityKey> m_knownEntityKeys;
private readonly Dictionary<EntityKey, AssociationSet> m_requiredEntities;
private readonly Set<EntityKey> m_optionalEntities;
private readonly Set<EntityKey> m_includedValueEntities;
// workspace state
private readonly MetadataWorkspace m_metadataWorkspace;
private readonly ViewLoader m_viewLoader;
private readonly IEntityStateManager m_stateManager;
// ancillary propagation services
private readonly RecordConverter m_recordConverter;
private readonly RelationshipConstraintValidator m_constraintValidator;
// provider information
private readonly DbProviderServices m_providerServices;
private readonly EntityConnection m_connection;
private readonly int? m_commandTimeout;
private Dictionary<StorageModificationFunctionMapping, DbCommandDefinition> m_modificationFunctionCommandDefinitions;
// metadata cache
private readonly Dictionary<Tuple<EntitySetBase, StructuralType>, ExtractorMetadata> m_extractorMetadata;
// static members
private static readonly List<string> s_emptyMemberList = new List<string>();
#endregion
#region Properties
/// <summary>
/// Gets workspace used in this session.
/// </summary>
internal MetadataWorkspace MetadataWorkspace
{
get { return m_metadataWorkspace; }
}
/// <summary>
/// Gets key manager that handles interpretation of keys (including resolution of
/// referential-integrity/foreign key constraints)
/// </summary>
internal readonly KeyManager KeyManager;
/// <summary>
/// Gets the view loader metadata wrapper for the current workspace.
/// </summary>
internal ViewLoader ViewLoader
{
get { return m_viewLoader; }
}
/// <summary>
/// Gets record converter which translates state entry records into propagator results.
/// </summary>
internal RecordConverter RecordConverter
{
get { return m_recordConverter; }
}
/// <summary>
/// Gets command timeout for update commands. If null, use default.
/// </summary>
internal int? CommandTimeout
{
get { return m_commandTimeout; }
}
internal readonly IEqualityComparer<CompositeKey> KeyComparer;
#endregion
#region Methods
/// <summary>
/// Registers any referential constraints contained in the state entry (so that
/// constrained members have the same identifier values). Only processes relationships
/// with referential constraints defined.
/// </summary>
/// <param name="stateEntry">State entry</param>
internal void RegisterReferentialConstraints(IEntityStateEntry stateEntry)
{
if (stateEntry.IsRelationship)
{
AssociationSet associationSet = (AssociationSet)stateEntry.EntitySet;
if (0 < associationSet.ElementType.ReferentialConstraints.Count)
{
DbDataRecord record = stateEntry.State == EntityState.Added ?
(DbDataRecord)stateEntry.CurrentValues : stateEntry.OriginalValues;
foreach (ReferentialConstraint constraint in associationSet.ElementType.ReferentialConstraints)
{
// retrieve keys at the ends
EntityKey principalKey = (EntityKey)record[constraint.FromRole.Name];
EntityKey dependentKey = (EntityKey)record[constraint.ToRole.Name];
// associate keys, where the from side 'owns' the to side
using (ReadOnlyMetadataCollection<EdmProperty>.Enumerator principalPropertyEnum = constraint.FromProperties.GetEnumerator())
using (ReadOnlyMetadataCollection<EdmProperty>.Enumerator dependentPropertyEnum = constraint.ToProperties.GetEnumerator())
{
while (principalPropertyEnum.MoveNext() && dependentPropertyEnum.MoveNext())
{
int principalKeyMemberCount;
int dependentKeyMemberCount;
// get offsets for from and to key properties
int principalOffset = GetKeyMemberOffset(constraint.FromRole, principalPropertyEnum.Current,
out principalKeyMemberCount);
int dependentOffset = GetKeyMemberOffset(constraint.ToRole, dependentPropertyEnum.Current,
out dependentKeyMemberCount);
int principalIdentifier = this.KeyManager.GetKeyIdentifierForMemberOffset(principalKey, principalOffset, principalKeyMemberCount);
int dependentIdentifier = this.KeyManager.GetKeyIdentifierForMemberOffset(dependentKey, dependentOffset, dependentKeyMemberCount);
// register equivalence of identifiers
this.KeyManager.AddReferentialConstraint(stateEntry, dependentIdentifier, principalIdentifier);
}
}
}
}
}
else if (!stateEntry.IsKeyEntry)
{
if (stateEntry.State == EntityState.Added || stateEntry.State == EntityState.Modified)
{
RegisterEntityReferentialConstraints(stateEntry, true);
}
if (stateEntry.State == EntityState.Deleted || stateEntry.State == EntityState.Modified)
{
RegisterEntityReferentialConstraints(stateEntry, false);
}
}
}
private void RegisterEntityReferentialConstraints(IEntityStateEntry stateEntry, bool currentValues)
{
IExtendedDataRecord record = currentValues
? (IExtendedDataRecord)stateEntry.CurrentValues
: (IExtendedDataRecord)stateEntry.OriginalValues;
EntitySet entitySet = (EntitySet)stateEntry.EntitySet;
EntityKey dependentKey = stateEntry.EntityKey;
foreach (var foreignKey in entitySet.ForeignKeyDependents)
{
AssociationSet associationSet = foreignKey.Item1;
ReferentialConstraint constraint = foreignKey.Item2;
EntityType dependentType = MetadataHelper.GetEntityTypeForEnd((AssociationEndMember)constraint.ToRole);
if (dependentType.IsAssignableFrom(record.DataRecordInfo.RecordType.EdmType))
{
EntityKey principalKey = null;
// First, check for an explicit reference
if (!currentValues || !m_stateManager.TryGetReferenceKey(dependentKey, (AssociationEndMember)constraint.FromRole, out principalKey))
{
// build a key based on the foreign key values
EntityType principalType = MetadataHelper.GetEntityTypeForEnd((AssociationEndMember)constraint.FromRole);
bool hasNullValue = false;
object[] keyValues = new object[principalType.KeyMembers.Count];
for (int i = 0, n = keyValues.Length; i < n; i++)
{
EdmProperty keyMember = (EdmProperty)principalType.KeyMembers[i];
// Find corresponding foreign key value
int constraintOrdinal = constraint.FromProperties.IndexOf((EdmProperty)keyMember);
int recordOrdinal = record.GetOrdinal(constraint.ToProperties[constraintOrdinal].Name);
if (record.IsDBNull(recordOrdinal))
{
hasNullValue = true;
break;
}
keyValues[i] = record.GetValue(recordOrdinal);
}
if (!hasNullValue)
{
EntitySet principalSet = associationSet.AssociationSetEnds[constraint.FromRole.Name].EntitySet;
if (1 == keyValues.Length)
{
principalKey = new EntityKey(principalSet, keyValues[0]);
}
else
{
principalKey = new EntityKey(principalSet, keyValues);
}
}
}
if (null != principalKey)
{
// find the right principal key... (first, existing entities; then, added entities; finally, just the key)
IEntityStateEntry existingPrincipal;
EntityKey tempKey;
if (m_stateManager.TryGetEntityStateEntry(principalKey, out existingPrincipal))
{
// nothing to do. the principal key will resolve to the existing entity
}
else if (currentValues && this.KeyManager.TryGetTempKey(principalKey, out tempKey))
{
// if we aren't dealing with current values, we cannot resolve to a temp key (original values
// cannot indicate a relationship to an 'added' entity).
if (null == tempKey)
{
throw EntityUtil.Update(Strings.Update_AmbiguousForeignKey(constraint.ToRole.DeclaringType.FullName), null, stateEntry);
}
else
{
principalKey = tempKey;
}
}
// pull the principal end into the update pipeline (supports value propagation)
AddValidAncillaryKey(principalKey, m_optionalEntities);
// associate keys, where the from side 'owns' the to side
for (int i = 0, n = constraint.FromProperties.Count; i < n; i++)
{
var principalProperty = constraint.FromProperties[i];
var dependentProperty = constraint.ToProperties[i];
int principalKeyMemberCount;
// get offsets for from and to key properties
int principalOffset = GetKeyMemberOffset(constraint.FromRole, principalProperty, out principalKeyMemberCount);
int principalIdentifier = this.KeyManager.GetKeyIdentifierForMemberOffset(principalKey, principalOffset, principalKeyMemberCount);
int dependentIdentifier;
if (entitySet.ElementType.KeyMembers.Contains(dependentProperty))
{
int dependentKeyMemberCount;
int dependentOffset = GetKeyMemberOffset(constraint.ToRole, dependentProperty,
out dependentKeyMemberCount);
dependentIdentifier = this.KeyManager.GetKeyIdentifierForMemberOffset(dependentKey, dependentOffset, dependentKeyMemberCount);
}
else
{
dependentIdentifier = this.KeyManager.GetKeyIdentifierForMember(dependentKey, dependentProperty.Name, currentValues);
}
// don't allow the user to insert or update an entity that refers to a deleted principal
if (currentValues && null != existingPrincipal && existingPrincipal.State == EntityState.Deleted &&
(stateEntry.State == EntityState.Added || stateEntry.State == EntityState.Modified))
{
throw EntityUtil.Update(
Strings.Update_InsertingOrUpdatingReferenceToDeletedEntity(associationSet.ElementType.FullName),
null,
stateEntry,
existingPrincipal);
}
// register equivalence of identifiers
this.KeyManager.AddReferentialConstraint(stateEntry, dependentIdentifier, principalIdentifier);
}
}
}
}
}
// requires: role must not be null and property must be a key member for the role end
private static int GetKeyMemberOffset(RelationshipEndMember role, EdmProperty property, out int keyMemberCount)
{
Debug.Assert(null != role);
Debug.Assert(null != property);
Debug.Assert(BuiltInTypeKind.RefType == role.TypeUsage.EdmType.BuiltInTypeKind,
"relationship ends must be of RefType");
RefType endType = (RefType)role.TypeUsage.EdmType;
Debug.Assert(BuiltInTypeKind.EntityType == endType.ElementType.BuiltInTypeKind,
"relationship ends must reference EntityType");
EntityType entityType = (EntityType)endType.ElementType;
keyMemberCount = entityType.KeyMembers.Count;
return entityType.KeyMembers.IndexOf(property);
}
/// <summary>
/// Yields all relationship state entries with the given key as an end.
/// </summary>
/// <param name="entityKey"></param>
/// <returns></returns>
internal IEnumerable<IEntityStateEntry> GetRelationships(EntityKey entityKey)
{
return m_stateManager.FindRelationshipsByKey(entityKey);
}
/// <summary>
/// Persists stateManager changes to the store.
/// </summary>
/// <param name="stateManager">StateManager containing changes to persist.</param>
/// <param name="adapter">Map adapter requesting the changes.</param>
/// <returns>Total number of state entries affected</returns>
internal static Int32 Update(IEntityStateManager stateManager, IEntityAdapter adapter)
{
// provider/connection details
EntityConnection connection = (EntityConnection)adapter.Connection;
MetadataWorkspace metadataWorkspace = connection.GetMetadataWorkspace();
int? commandTimeout = adapter.CommandTimeout;
UpdateTranslator translator = new UpdateTranslator(stateManager, metadataWorkspace, connection, commandTimeout);
// tracks values for identifiers in this session
Dictionary<int, object> identifierValues = new Dictionary<int, object>();
// tracks values for generated values in this session
List<KeyValuePair<PropagatorResult, object>> generatedValues = new List<KeyValuePair<PropagatorResult, object>>();
IEnumerable<UpdateCommand> orderedCommands = translator.ProduceCommands();
// used to track the source of commands being processed in case an exception is thrown
UpdateCommand source = null;
try
{
foreach (UpdateCommand command in orderedCommands)
{
// Remember the data sources so that we can throw meaningful exception
source = command;
long rowsAffected = command.Execute(translator, connection, identifierValues, generatedValues);
translator.ValidateRowsAffected(rowsAffected, source);
}
}
catch (Exception e)
{
// we should not be wrapping all exceptions
if (UpdateTranslator.RequiresContext(e))
{
throw EntityUtil.Update(System.Data.Entity.Strings.Update_GeneralExecutionException, e, translator.DetermineStateEntriesFromSource(source));
}
throw;
}
translator.BackPropagateServerGen(generatedValues);
int totalStateEntries = translator.AcceptChanges(adapter);
return totalStateEntries;
}
private IEnumerable<UpdateCommand> ProduceCommands()
{
// load all modified state entries
PullModifiedEntriesFromStateManager();
PullUnchangedEntriesFromStateManager();
// check constraints
m_constraintValidator.ValidateConstraints();
this.KeyManager.ValidateReferentialIntegrityGraphAcyclic();
// gather all commands (aggregate in a dependency orderer to determine operation order
IEnumerable<UpdateCommand> dynamicCommands = this.ProduceDynamicCommands();
IEnumerable<UpdateCommand> functionCommands = this.ProduceFunctionCommands();
UpdateCommandOrderer orderer = new UpdateCommandOrderer(dynamicCommands.Concat(functionCommands), this);
IEnumerable<UpdateCommand> orderedCommands;
IEnumerable<UpdateCommand> remainder;
if (!orderer.TryTopologicalSort(out orderedCommands, out remainder))
{
// throw an exception if it is not possible to perform dependency ordering
throw DependencyOrderingError(remainder);
}
return orderedCommands;
}
// effects: given rows affected, throws if the count suggests a concurrency failure.
// Throws a concurrency exception based on the current command sources (which allow
// us to populated the EntityStateEntries on UpdateException)
private void ValidateRowsAffected(long rowsAffected, UpdateCommand source)
{
// 0 rows affected indicates a concurrency failure; negative values suggest rowcount is off;
// positive values suggest at least one row was affected (we generally expect exactly one,
// but triggers/view logic/logging may change this value)
if (0 == rowsAffected)
{
var stateEntries = DetermineStateEntriesFromSource(source);
throw EntityUtil.UpdateConcurrency(rowsAffected, null, stateEntries);
}
}
private IEnumerable<IEntityStateEntry> DetermineStateEntriesFromSource(UpdateCommand source)
{
if (null == source)
{
return Enumerable.Empty<IEntityStateEntry>();
}
return source.GetStateEntries(this);
}
// effects: Given a list of pairs describing the contexts for server generated values and their actual
// values, backpropagates to the relevant state entries
private void BackPropagateServerGen(List<KeyValuePair<PropagatorResult, object>> generatedValues)
{
foreach (KeyValuePair<PropagatorResult, object> generatedValue in generatedValues)
{
PropagatorResult context;
// check if a redirect to "owner" result is possible
if (PropagatorResult.NullIdentifier == generatedValue.Key.Identifier ||
!KeyManager.TryGetIdentifierOwner(generatedValue.Key.Identifier, out context))
{
// otherwise, just use the straightforward context
context = generatedValue.Key;
}
object value = generatedValue.Value;
if (context.Identifier == PropagatorResult.NullIdentifier)
{
SetServerGenValue(context, value);
}
else
{
// check if we need to back propagate this value to any other positions (e.g. for foreign keys)
foreach (int dependent in this.KeyManager.GetDependents(context.Identifier))
{
if (this.KeyManager.TryGetIdentifierOwner(dependent, out context))
{
SetServerGenValue(context, value);
}
}
}
}
}
private void SetServerGenValue(PropagatorResult context, object value)
{
if (context.RecordOrdinal != PropagatorResult.NullOrdinal)
{
CurrentValueRecord targetRecord = context.Record;
// determine if type compensation is required
IExtendedDataRecord recordWithMetadata = (IExtendedDataRecord)targetRecord;
EdmMember member = recordWithMetadata.DataRecordInfo.FieldMetadata[context.RecordOrdinal].FieldType;
value = value ?? DBNull.Value; // records expect DBNull rather than null
value = AlignReturnValue(value, member, context);
targetRecord.SetValue(context.RecordOrdinal, value);
}
}
/// <summary>
/// Aligns a value returned from the store with the expected type for the member.
/// </summary>
/// <param name="value">Value to convert.</param>
/// <param name="member">Metadata for the member being set.</param>
/// <param name="context">The context generating the return value.</param>
/// <returns>Converted return value</returns>
private object AlignReturnValue(object value, EdmMember member, PropagatorResult context)
{
if (DBNull.Value.Equals(value))
{
// check if there is a nullability constraint on the value
if (BuiltInTypeKind.EdmProperty == member.BuiltInTypeKind &&
!((EdmProperty)member).Nullable)
{
throw EntityUtil.Update(System.Data.Entity.Strings.Update_NullReturnValueForNonNullableMember(
member.Name,
member.DeclaringType.FullName), null);
}
}
else if (!Helper.IsSpatialType(member.TypeUsage))
{
Type clrType;
Type clrEnumType = null;
if (Helper.IsEnumType(member.TypeUsage.EdmType))
{
PrimitiveType underlyingType = Helper.AsPrimitive(member.TypeUsage.EdmType);
clrEnumType = context.Record.GetFieldType(context.RecordOrdinal);
clrType = underlyingType.ClrEquivalentType;
Debug.Assert(clrEnumType.IsEnum);
}
else
{
// convert the value to the appropriate CLR type
Debug.Assert(BuiltInTypeKind.PrimitiveType == member.TypeUsage.EdmType.BuiltInTypeKind,
"we only allow return values that are instances of EDM primitive or enum types");
PrimitiveType primitiveType = (PrimitiveType)member.TypeUsage.EdmType;
clrType = primitiveType.ClrEquivalentType;
}
try
{
value = Convert.ChangeType(value, clrType, CultureInfo.InvariantCulture);
if (clrEnumType != null)
{
value = Enum.ToObject(clrEnumType, value);
}
}
catch (Exception e)
{
// we should not be wrapping all exceptions
if (UpdateTranslator.RequiresContext(e))
{
Type userClrType = clrEnumType ?? clrType;
throw EntityUtil.Update(System.Data.Entity.Strings.Update_ReturnValueHasUnexpectedType(
value.GetType().FullName,
userClrType.FullName,
member.Name,
member.DeclaringType.FullName), e);
}
throw;
}
}
// return the adjusted value
return value;
}
/// <summary>
/// Accept changes to entities and relationships processed by this translator instance.
/// </summary>
/// <param name="adapter">Data adapter</param>
/// <returns>Number of state entries affected.</returns>
private int AcceptChanges(IEntityAdapter adapter)
{
int affectedCount = 0;
foreach (IEntityStateEntry stateEntry in m_stateEntries)
{
// only count and accept changes for state entries that are being explicitly modified
if (EntityState.Unchanged != stateEntry.State)
{
if (adapter.AcceptChangesDuringUpdate)
{
stateEntry.AcceptChanges();
}
affectedCount++;
}
}
return affectedCount;
}
/// <summary>
/// Gets extents for which this translator has identified changes to be handled
/// by the standard update pipeline.
/// </summary>
/// <returns>Enumeration of modified C-Space extents.</returns>
private IEnumerable<EntitySetBase> GetDynamicModifiedExtents()
{
return m_changes.Keys;
}
/// <summary>
/// Gets extents for which this translator has identified changes to be handled
/// by function mappings.
/// </summary>
/// <returns>Enumreation of modified C-Space extents.</returns>
private IEnumerable<EntitySetBase> GetFunctionModifiedExtents()
{
return m_functionChanges.Keys;
}
/// <summary>
/// Produce dynamic store commands for this translator's changes.
/// </summary>
/// <returns>Database commands in a safe order</returns>
private IEnumerable<UpdateCommand> ProduceDynamicCommands()
{
// Initialize DBCommand update compiler
UpdateCompiler updateCompiler = new UpdateCompiler(this);
// Determine affected
Set<EntitySet> tables = new Set<EntitySet>();
foreach (EntitySetBase extent in GetDynamicModifiedExtents())
{
Set<EntitySet> affectedTables = m_viewLoader.GetAffectedTables(extent, m_metadataWorkspace);
//Since these extents don't have Functions defined for update operations,
//the affected tables should be provided via MSL.
//If we dont find any throw an exception
if (affectedTables.Count == 0)
{
throw EntityUtil.Update(System.Data.Entity.Strings.Update_MappingNotFound(
extent.Name), null /*stateEntries*/);
}
foreach (EntitySet table in affectedTables)
{
tables.Add(table);
}
}
// Determine changes to apply to each table
foreach (EntitySet table in tables)
{
DbQueryCommandTree umView = m_connection.GetMetadataWorkspace().GetCqtView(table);
// Propagate changes to root of tree (at which point they are S-Space changes)
ChangeNode changeNode = Propagator.Propagate(this, table, umView);
// Process changes for the table
TableChangeProcessor change = new TableChangeProcessor(table);
foreach (UpdateCommand command in change.CompileCommands(changeNode, updateCompiler))
{
yield return command;
}
}
}
// Generates and caches a command definition for the given function
internal DbCommandDefinition GenerateCommandDefinition(StorageModificationFunctionMapping functionMapping)
{
if (null == m_modificationFunctionCommandDefinitions)
{
m_modificationFunctionCommandDefinitions = new Dictionary<StorageModificationFunctionMapping,DbCommandDefinition>();
}
DbCommandDefinition commandDefinition;
if (!m_modificationFunctionCommandDefinitions.TryGetValue(functionMapping, out commandDefinition))
{
// synthesize a RowType for this mapping
TypeUsage resultType = null;
if (null != functionMapping.ResultBindings && 0 < functionMapping.ResultBindings.Count)
{
List<EdmProperty> properties = new List<EdmProperty>(functionMapping.ResultBindings.Count);
foreach (StorageModificationFunctionResultBinding resultBinding in functionMapping.ResultBindings)
{
properties.Add(new EdmProperty(resultBinding.ColumnName, resultBinding.Property.TypeUsage));
}
RowType rowType = new RowType(properties);
CollectionType collectionType = new CollectionType(rowType);
resultType = TypeUsage.Create(collectionType);
}
// add function parameters
IEnumerable<KeyValuePair<string, TypeUsage>> functionParams =
functionMapping.Function.Parameters.Select(paramInfo => new KeyValuePair<string, TypeUsage>(paramInfo.Name, paramInfo.TypeUsage));
// construct DbFunctionCommandTree including implict return type
DbFunctionCommandTree tree = new DbFunctionCommandTree(m_metadataWorkspace, DataSpace.SSpace,
functionMapping.Function, resultType, functionParams);
commandDefinition = m_providerServices.CreateCommandDefinition(tree);
}
return commandDefinition;
}
// Produces all function commands in a safe order
private IEnumerable<UpdateCommand> ProduceFunctionCommands()
{
foreach (EntitySetBase extent in GetFunctionModifiedExtents())
{
// Get a handle on the appropriate translator
ModificationFunctionMappingTranslator translator = m_viewLoader.GetFunctionMappingTranslator(extent, m_metadataWorkspace);
if (null != translator)
{
// Compile commands
foreach (ExtractedStateEntry stateEntry in GetExtentFunctionModifications(extent))
{
FunctionUpdateCommand command = translator.Translate(this, stateEntry);
if (null != command)
{
yield return command;
}
}
}
}
}
/// <summary>
/// Gets a metadata wrapper for the given type. The wrapper makes
/// certain tasks in the update pipeline more efficient.
/// </summary>
/// <param name="type">Structural type</param>
/// <returns>Metadata wrapper</returns>
internal ExtractorMetadata GetExtractorMetadata(EntitySetBase entitySetBase, StructuralType type)
{
ExtractorMetadata metadata;
var key = Tuple.Create(entitySetBase, type);
if (!m_extractorMetadata.TryGetValue(key, out metadata))
{
metadata = new ExtractorMetadata(entitySetBase, type, this);
m_extractorMetadata.Add(key, metadata);
}
return metadata;
}
/// <summary>
/// Returns error when it is not possible to order update commands. Argument is the 'remainder', or commands
/// that could not be ordered due to a cycle.
/// </summary>
private UpdateException DependencyOrderingError(IEnumerable<UpdateCommand> remainder)
{
Debug.Assert(null != remainder && remainder.Count() > 0, "must provide non-empty remainder");
HashSet<IEntityStateEntry> stateEntries = new HashSet<IEntityStateEntry>();
foreach (UpdateCommand command in remainder)
{
stateEntries.UnionWith(command.GetStateEntries(this));
}
// throw exception containing all related state entries
throw EntityUtil.Update(System.Data.Entity.Strings.Update_ConstraintCycle, null, stateEntries);
}
/// <summary>
/// Creates a command in the current context.
/// </summary>
/// <param name="commandTree">DbCommand tree</param>
/// <returns>DbCommand produced by the current provider.</returns>
internal DbCommand CreateCommand(DbModificationCommandTree commandTree)
{
DbCommand command;
Debug.Assert(null != m_providerServices, "constructor ensures either the command definition " +
"builder or provider service is available");
Debug.Assert(null != m_connection.StoreConnection, "EntityAdapter.Update ensures the store connection is set");
try
{
command = m_providerServices.CreateCommand(commandTree);
}
catch (Exception e)
{
// we should not be wrapping all exceptions
if (UpdateTranslator.RequiresContext(e))
{
// we don't wan't folks to have to know all the various types of exceptions that can
// occur, so we just rethrow a CommandDefinitionException and make whatever we caught
// the inner exception of it.
throw EntityUtil.CommandCompilation(System.Data.Entity.Strings.EntityClient_CommandDefinitionPreparationFailed, e);
}
throw;
}
return command;
}
/// <summary>
/// Helper method to allow the setting of parameter values to update stored procedures.
/// Allows the DbProvider an opportunity to rewrite the parameter to suit provider specific needs.
/// </summary>
/// <param name="parameter">Parameter to set.</param>
/// <param name="typeUsage">The type of the parameter.</param>
/// <param name="value">The value to which to set the parameter.</param>
internal void SetParameterValue(DbParameter parameter, TypeUsage typeUsage, object value)
{
m_providerServices.SetParameterValue(parameter, typeUsage, value);
}
/// <summary>
/// Determines whether the given exception requires additional context from the update pipeline (in other
/// words, whether the exception should be wrapped in an UpdateException).
/// </summary>
/// <param name="e">Exception to test.</param>
/// <returns>true if exception should be wrapped; false otherwise</returns>
internal static bool RequiresContext(Exception e)
{
// if the exception isn't catchable, never wrap
if (!EntityUtil.IsCatchableExceptionType(e)) { return false; }
// update and incompatible provider exceptions already contain the necessary context
return !(e is UpdateException) && !(e is ProviderIncompatibleException);
}
#region Private initialization methods
/// <summary>
/// Retrieve all modified entries from the state manager.
/// </summary>
private void PullModifiedEntriesFromStateManager()
{
// do a first pass over added entries to register 'by value' entity key targets that may be resolved as
// via a foreign key
foreach (IEntityStateEntry addedEntry in m_stateManager.GetEntityStateEntries(EntityState.Added))
{
if (!addedEntry.IsRelationship && !addedEntry.IsKeyEntry)
{
this.KeyManager.RegisterKeyValueForAddedEntity(addedEntry);
}
}
// do a second pass over entries to register referential integrity constraints
// for server-generation
foreach (IEntityStateEntry modifiedEntry in m_stateManager.GetEntityStateEntries(EntityState.Modified | EntityState.Added | EntityState.Deleted))
{
RegisterReferentialConstraints(modifiedEntry);
}
foreach (IEntityStateEntry modifiedEntry in m_stateManager.GetEntityStateEntries(EntityState.Modified | EntityState.Added | EntityState.Deleted))
{
LoadStateEntry(modifiedEntry);
}
}
/// <summary>
/// Retrieve all required/optional/value entries into the state manager. These are entries that --
/// although unmodified -- affect or are affected by updates.
/// </summary>
private void PullUnchangedEntriesFromStateManager()
{
foreach (KeyValuePair<EntityKey, AssociationSet> required in m_requiredEntities)
{
EntityKey key = required.Key;
if (!m_knownEntityKeys.Contains(key))
{
// pull the value into the translator if we don't already it
IEntityStateEntry requiredEntry;
if (m_stateManager.TryGetEntityStateEntry(key, out requiredEntry) && !requiredEntry.IsKeyEntry)
{
// load the object as a no-op update
LoadStateEntry(requiredEntry);
}
else
{
// throw an exception
throw EntityUtil.UpdateMissingEntity(required.Value.Name, TypeHelpers.GetFullName(key.EntityContainerName, key.EntitySetName));
}
}
}
foreach (EntityKey key in m_optionalEntities)
{
if (!m_knownEntityKeys.Contains(key))
{
IEntityStateEntry optionalEntry;
if (m_stateManager.TryGetEntityStateEntry(key, out optionalEntry) && !optionalEntry.IsKeyEntry)
{
// load the object as a no-op update
LoadStateEntry(optionalEntry);
}
}
}
foreach (EntityKey key in m_includedValueEntities)
{
if (!m_knownEntityKeys.Contains(key))
{
IEntityStateEntry valueEntry;
if (m_stateManager.TryGetEntityStateEntry(key, out valueEntry))
{
// Convert state entry so that its values are known to the update pipeline.
var result = m_recordConverter.ConvertCurrentValuesToPropagatorResult(valueEntry, ModifiedPropertiesBehavior.NoneModified);
}
}
}
}
/// <summary>
/// Validates and tracks a state entry being processed by this translator.
/// </summary>
/// <param name="stateEntry"></param>
private void ValidateAndRegisterStateEntry(IEntityStateEntry stateEntry)
{
EntityUtil.CheckArgumentNull(stateEntry, "stateEntry");
EntitySetBase extent = stateEntry.EntitySet;
if (null == extent)
{
throw EntityUtil.InternalError(EntityUtil.InternalErrorCode.InvalidStateEntry, 1);
}
// Determine the key. May be null if the state entry does not represent an entity.
EntityKey entityKey = stateEntry.EntityKey;
IExtendedDataRecord record = null;
// verify the structure of the entry values
if (0 != ((EntityState.Added | EntityState.Modified | EntityState.Unchanged) & stateEntry.State))
{
// added, modified and unchanged entries have current values
record = (IExtendedDataRecord)stateEntry.CurrentValues;
ValidateRecord(extent, record, stateEntry);
}
if (0 != ((EntityState.Modified | EntityState.Deleted | EntityState.Unchanged) & stateEntry.State))
{
// deleted, modified and unchanged entries have original values
record = (IExtendedDataRecord)stateEntry.OriginalValues;
ValidateRecord(extent, record, stateEntry);
}
Debug.Assert(null != record, "every state entry must contain a record");
// check for required ends of relationships
AssociationSet associationSet = extent as AssociationSet;
if (null != associationSet)
{
AssociationSetMetadata associationSetMetadata = m_viewLoader.GetAssociationSetMetadata(associationSet, m_metadataWorkspace);
if (associationSetMetadata.HasEnds)
{
foreach (FieldMetadata field in record.DataRecordInfo.FieldMetadata)
{
// ends of relationship record must be EntityKeys
EntityKey end = (EntityKey)record.GetValue(field.Ordinal);
// ends of relationships must have AssociationEndMember metadata
AssociationEndMember endMetadata = (AssociationEndMember)field.FieldType;
if (associationSetMetadata.RequiredEnds.Contains(endMetadata))
{
if (!m_requiredEntities.ContainsKey(end))
{
m_requiredEntities.Add(end, associationSet);
}
}
else if (associationSetMetadata.OptionalEnds.Contains(endMetadata))
{
AddValidAncillaryKey(end, m_optionalEntities);
}
else if (associationSetMetadata.IncludedValueEnds.Contains(endMetadata))
{
AddValidAncillaryKey(end, m_includedValueEntities);
}
}
}
// register relationship with validator
m_constraintValidator.RegisterAssociation(associationSet, record, stateEntry);
}
else
{
// register entity with validator
m_constraintValidator.RegisterEntity(stateEntry);
}
// add to the list of entries being tracked
m_stateEntries.Add(stateEntry);
if (null != (object)entityKey) { m_knownEntityKeys.Add(entityKey); }
}
/// <summary>
/// effects: given an entity key and a set, adds key to the set iff. the corresponding entity
/// is:
///
/// not a stub (or 'key') entry, and;
/// not a core element in the update pipeline (it's not being directly modified)
/// </summary>
private void AddValidAncillaryKey(EntityKey key, Set<EntityKey> keySet)
{
// Note: an entity is ancillary iff. it is unchanged (otherwise it is tracked as a "standard" changed entity)
IEntityStateEntry endEntry;
if (m_stateManager.TryGetEntityStateEntry(key, out endEntry) && // make sure the entity is tracked
!endEntry.IsKeyEntry && // make sure the entity is not a stub
endEntry.State == EntityState.Unchanged) // if the entity is being modified, it's already included anyways
{
keySet.Add(key);
}
}
private void ValidateRecord(EntitySetBase extent, IExtendedDataRecord record, IEntityStateEntry entry)
{
Debug.Assert(null != extent, "must be verified by caller");
DataRecordInfo recordInfo;
if ((null == record) ||
(null == (recordInfo = record.DataRecordInfo)) ||
(null == recordInfo.RecordType))
{
throw EntityUtil.InternalError(EntityUtil.InternalErrorCode.InvalidStateEntry, 2);
}
VerifyExtent(MetadataWorkspace, extent);
// additional validation happens lazily as values are loaded from the record
}
// Verifies the given extent is present in the given workspace.
private static void VerifyExtent(MetadataWorkspace workspace, EntitySetBase extent)
{
// get the container to which the given extent belongs
EntityContainer actualContainer = extent.EntityContainer;
// try to retrieve the container in the given workspace
EntityContainer referenceContainer = null;
if (null != actualContainer)
{
workspace.TryGetEntityContainer(
actualContainer.Name, actualContainer.DataSpace, out referenceContainer);
}
// determine if the given extent lives in a container from the given workspace
// (the item collections for each container are reference equivalent when they are declared in the
// same item collection)
if (null == actualContainer || null == referenceContainer ||
!Object.ReferenceEquals(actualContainer, referenceContainer))
{
//
throw EntityUtil.Update(System.Data.Entity.Strings.Update_WorkspaceMismatch, null);
}
}
private void LoadStateEntry(IEntityStateEntry stateEntry)
{
Debug.Assert(null != stateEntry, "state entry must exist");
// make sure the state entry doesn't contain invalid data and register it with the
// update pipeline
ValidateAndRegisterStateEntry(stateEntry);
// use data structure internal to the update pipeline instead of the raw state entry
ExtractedStateEntry extractedStateEntry = new ExtractedStateEntry(this, stateEntry);
// figure out if this state entry is being handled by a function (stored procedure) or
// through dynamic SQL
EntitySetBase extent = stateEntry.EntitySet;
if (null == m_viewLoader.GetFunctionMappingTranslator(extent, m_metadataWorkspace))
{
// if there is no function mapping, register a ChangeNode (used for update
// propagation and dynamic SQL generation)
ChangeNode changeNode = GetExtentModifications(extent);
if (null != extractedStateEntry.Original)
{
changeNode.Deleted.Add(extractedStateEntry.Original);
}
if (null != extractedStateEntry.Current)
{
changeNode.Inserted.Add(extractedStateEntry.Current);
}
}
else
{
// for function updates, store off the extracted state entry in its entirety
// (used when producing FunctionUpdateCommands)
List<ExtractedStateEntry> functionEntries = GetExtentFunctionModifications(extent);
functionEntries.Add(extractedStateEntry);
}
}
/// <summary>
/// Retrieve a change node for an extent. If none exists, creates and registers a new one.
/// </summary>
/// <param name="extent">Extent for which to return a change node.</param>
/// <returns>Change node for requested extent.</returns>
internal ChangeNode GetExtentModifications(EntitySetBase extent)
{
EntityUtil.CheckArgumentNull(extent, "extent");
Debug.Assert(null != m_changes, "(UpdateTranslator/GetChangeNodeForExtent) method called before translator initialized");
ChangeNode changeNode;
if (!m_changes.TryGetValue(extent, out changeNode))
{
changeNode = new ChangeNode(TypeUsage.Create(extent.ElementType));
m_changes.Add(extent, changeNode);
}
return changeNode;
}
/// <summary>
/// Retrieve a list of state entries being processed by custom user functions.
/// </summary>
/// <param name="extent">Extent for which to return entries.</param>
/// <returns>List storing the entries.</returns>
internal List<ExtractedStateEntry> GetExtentFunctionModifications(EntitySetBase extent)
{
EntityUtil.CheckArgumentNull(extent, "extent");
Debug.Assert(null != m_functionChanges, "method called before translator initialized");
List<ExtractedStateEntry> entries;
if (!m_functionChanges.TryGetValue(extent, out entries))
{
entries = new List<ExtractedStateEntry>();
m_functionChanges.Add(extent, entries);
}
return entries;
}
#endregion
#endregion
}
/// <summary>
/// Enumeration of possible operators.
/// </summary>
/// <remarks>
/// The values are used to determine the order of operations (in the absence of any strong dependencies).
/// The chosen order is based on the observation that hidden dependencies (e.g. due to temporary keys in
/// the state manager or unknown FKs) favor deletes before inserts and updates before deletes. For instance,
/// a deleted entity may have the same real key value as an inserted entity. Similarly, a self-reference
/// may require a new dependent row to be updated before the prinpical row is inserted. Obviously, the actual
/// constraints are required to make reliable decisions so this ordering is merely a heuristic.
/// </remarks>
internal enum ModificationOperator : byte
{
Update = 0,
Delete = 1,
Insert = 2,
}
}
| |
// 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.
// File System.Single.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System
{
public partial struct Single : IComparable, IFormattable, IConvertible, IComparable<float>, IEquatable<float>
{
#region Methods and constructors
public static bool operator != (float left, float right)
{
Contract.Ensures(Contract.Result<bool>() == ((left == right) == false));
return default(bool);
}
public static bool operator < (float left, float right)
{
Contract.Ensures(Contract.Result<bool>() == (left < right));
return default(bool);
}
public static bool operator <=(float left, float right)
{
Contract.Ensures(Contract.Result<bool>() == ((left > right) == false));
return default(bool);
}
public static bool operator == (float left, float right)
{
Contract.Ensures(Contract.Result<bool>() == (left == right));
return default(bool);
}
public static bool operator > (float left, float right)
{
Contract.Ensures(Contract.Result<bool>() == (left > right));
return default(bool);
}
public static bool operator >= (float left, float right)
{
Contract.Ensures(Contract.Result<bool>() == ((left < right) == false));
return default(bool);
}
public int CompareTo(float value)
{
return default(int);
}
public int CompareTo(Object value)
{
return default(int);
}
public override bool Equals(Object obj)
{
return default(bool);
}
public bool Equals(float obj)
{
return default(bool);
}
public override int GetHashCode()
{
return default(int);
}
public TypeCode GetTypeCode()
{
return default(TypeCode);
}
public static bool IsInfinity(float f)
{
return default(bool);
}
public static bool IsNaN(float f)
{
return default(bool);
}
public static bool IsNegativeInfinity(float f)
{
return default(bool);
}
public static bool IsPositiveInfinity(float f)
{
return default(bool);
}
public static float Parse(string s)
{
return default(float);
}
public static float Parse(string s, System.Globalization.NumberStyles style, IFormatProvider provider)
{
return default(float);
}
public static float Parse(string s, System.Globalization.NumberStyles style)
{
return default(float);
}
public static float Parse(string s, IFormatProvider provider)
{
return default(float);
}
bool System.IConvertible.ToBoolean(IFormatProvider provider)
{
return default(bool);
}
byte System.IConvertible.ToByte(IFormatProvider provider)
{
return default(byte);
}
char System.IConvertible.ToChar(IFormatProvider provider)
{
return default(char);
}
DateTime System.IConvertible.ToDateTime(IFormatProvider provider)
{
return default(DateTime);
}
Decimal System.IConvertible.ToDecimal(IFormatProvider provider)
{
return default(Decimal);
}
double System.IConvertible.ToDouble(IFormatProvider provider)
{
return default(double);
}
short System.IConvertible.ToInt16(IFormatProvider provider)
{
return default(short);
}
int System.IConvertible.ToInt32(IFormatProvider provider)
{
return default(int);
}
long System.IConvertible.ToInt64(IFormatProvider provider)
{
return default(long);
}
sbyte System.IConvertible.ToSByte(IFormatProvider provider)
{
return default(sbyte);
}
float System.IConvertible.ToSingle(IFormatProvider provider)
{
return default(float);
}
Object System.IConvertible.ToType(Type type, IFormatProvider provider)
{
return default(Object);
}
ushort System.IConvertible.ToUInt16(IFormatProvider provider)
{
return default(ushort);
}
uint System.IConvertible.ToUInt32(IFormatProvider provider)
{
return default(uint);
}
ulong System.IConvertible.ToUInt64(IFormatProvider provider)
{
return default(ulong);
}
public override string ToString()
{
return default(string);
}
public string ToString(string format, IFormatProvider provider)
{
return default(string);
}
public string ToString(string format)
{
return default(string);
}
public string ToString(IFormatProvider provider)
{
return default(string);
}
public static bool TryParse(string s, out float result)
{
result = default(float);
return default(bool);
}
public static bool TryParse(string s, System.Globalization.NumberStyles style, IFormatProvider provider, out float result)
{
result = default(float);
return default(bool);
}
#endregion
#region Fields
public static float Epsilon;
public static float MaxValue;
public static float MinValue;
public static float NaN;
public static float NegativeInfinity;
public static float PositiveInfinity;
#endregion
}
}
| |
// ==++==
//
//
// Copyright (c) 2006 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
namespace Microsoft.JScript
{
using Microsoft.JScript.Vsa;
using System;
using System.Reflection;
using System.Reflection.Emit;
using Microsoft.Vsa;
using System.Globalization;
using System.IO;
using System.CodeDom;
using System.Collections.Specialized;
internal class VsaStaticCode : VsaItem, IVsaCodeItem
{
internal Context codeContext;
private Type compiledClass;
private ScriptBlock block;
internal VsaStaticCode(VsaEngine engine, string itemName, VsaItemFlag flag)
: base(engine, itemName, VsaItemType.Code, flag)
{
this.compiledClass = null;
this.codeContext = new Context(new DocumentContext(this), "");
}
public void AddEventSource(string eventSourceName, string eventSourceType)
{
// JScript does not support adding event sources (user must add an AppGlobal instead and manually hook up event handlers)
if (this.engine == null)
throw new VsaException(VsaError.EngineClosed);
throw new System.NotSupportedException();
}
public System.CodeDom.CodeObject CodeDOM
{
get
{
if (this.engine == null)
throw new VsaException(VsaError.EngineClosed);
throw new VsaException(VsaError.CodeDOMNotAvailable);
}
}
public void AppendSourceText(string SourceCode)
{
if (this.engine == null)
throw new VsaException(VsaError.EngineClosed);
if (SourceCode == null || SourceCode.Length == 0) return;
this.codeContext.SetSourceContext(this.codeContext.document, this.codeContext.source_string + SourceCode);
this.compiledClass = null;
this.isDirty = true;
this.engine.IsDirty = true;
}
internal override void CheckForErrors()
{
if (this.compiledClass == null)
{
JSParser p = new JSParser(this.codeContext);
AST prog = (ScriptBlock)p.Parse();
//prog.PartiallyEvaluate();
}
}
internal override void Close()
{
base.Close();
this.codeContext = null;
this.compiledClass = null;
}
internal override Type GetCompiledType()
{
TypeBuilder tb = this.compiledClass as TypeBuilder;
if (tb != null) this.compiledClass = tb.CreateType();
return this.compiledClass;
}
public override String Name
{
set
{
base.Name = value;
if (this.codebase == null)
{
// The codeContext document was named according to the engine's RootMoniker and the item name
string rootMoniker = this.engine.RootMoniker;
this.codeContext.document.documentName = rootMoniker + (rootMoniker.EndsWith("/", StringComparison.Ordinal) ? "" : "/") + this.name;
}
}
}
internal void Parse()
{
if (this.block == null && this.compiledClass == null)
{
GlobalScope glob = (GlobalScope)this.engine.GetGlobalScope().GetObject();
//Provide for the possibility of forward references to declarations in code blocks yet to come.
glob.evilScript = !glob.fast || this.engine.GetStaticCodeBlockCount() > 1;
this.engine.Globals.ScopeStack.Push(glob);
try
{
JSParser p = new JSParser(this.codeContext);
this.block = (ScriptBlock)p.Parse();
if (p.HasAborted)
this.block = null;
}
finally
{
this.engine.Globals.ScopeStack.Pop();
}
}
}
internal void ProcessAssemblyAttributeLists()
{
if (this.block == null) return;
this.block.ProcessAssemblyAttributeLists();
}
internal void PartiallyEvaluate()
{
if (this.block != null && this.compiledClass == null)
{
GlobalScope glob = (GlobalScope)this.engine.GetGlobalScope().GetObject();
this.engine.Globals.ScopeStack.Push(glob);
try
{
this.block.PartiallyEvaluate();
if (this.engine.HasErrors && !this.engine.alwaysGenerateIL)
throw new EndOfFile();
}
finally
{
this.engine.Globals.ScopeStack.Pop();
}
}
}
internal override void Remove()
{
if (this.engine == null)
throw new VsaException(VsaError.EngineClosed);
base.Remove();
}
public void RemoveEventSource(string eventSourceName)
{
if (this.engine == null)
throw new VsaException(VsaError.EngineClosed);
throw new System.NotSupportedException();
}
internal override void Reset()
{
this.compiledClass = null;
this.block = null;
// We reset codeContext because the DocumentContext holds a reference to engine.compilerGlobals
// (which we must have set to null before calling Reset on the VsaItems).
this.codeContext = new Context(new DocumentContext(this), this.codeContext.source_string);
}
internal override void Run()
{
if (this.compiledClass != null)
{
GlobalScope scriptBlockScope = (GlobalScope)Activator.CreateInstance(this.GetCompiledType(), new Object[] { this.engine.GetGlobalScope().GetObject() });
this.engine.Globals.ScopeStack.Push(scriptBlockScope);
try
{
MethodInfo main = this.compiledClass.GetMethod("Global Code");
try
{
main.Invoke(scriptBlockScope, null);
}
catch (TargetInvocationException e)
{
throw e.InnerException;
}
}
finally
{
this.engine.Globals.ScopeStack.Pop();
}
}
}
public override void SetOption(String name, Object value)
{
if (this.engine == null)
throw new VsaException(VsaError.EngineClosed);
if (0 == String.Compare(name, "codebase", StringComparison.OrdinalIgnoreCase))
{
this.codebase = (string)value;
this.codeContext.document.documentName = this.codebase;
}
else
throw new VsaException(VsaError.OptionNotSupported);
this.isDirty = true;
this.engine.IsDirty = true;
}
public Object SourceContext
{
get
{
return null;
}
set
{
}
}
public String SourceText
{
get
{
if (this.engine == null)
throw new VsaException(VsaError.EngineClosed);
return this.codeContext.source_string;
}
set
{
if (this.engine == null)
throw new VsaException(VsaError.EngineClosed);
this.codeContext.SetSourceContext(this.codeContext.document, (value == null ? "" : value));
this.compiledClass = null;
this.isDirty = true;
this.engine.IsDirty = true;
}
}
internal void TranslateToIL()
{
if (this.block != null && this.compiledClass == null)
{
GlobalScope glob = (GlobalScope)this.engine.GetGlobalScope().GetObject();
this.engine.Globals.ScopeStack.Push(glob);
try
{
this.compiledClass = this.block.TranslateToILClass(this.engine.CompilerGlobals, false);
}
finally
{
this.engine.Globals.ScopeStack.Pop();
}
}
}
}
}
| |
//Copyright (C) 2005 Richard J. Northedge
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//This file is based on the Parse.java source file found in the
//original java implementation of OpenNLP. That source file contains the following header:
//Copyright (C) 2003 Thomas Morton
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with this program; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Metadata.W3cXsd2001;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.Serialization;
namespace OpenNLP.Tools.Parser
{
/// <summary>
/// Exception class for problems detected during parsing.
/// </summary>
[Serializable]
public class ParseException : ApplicationException
{
public ParseException(){}
public ParseException(string message) : base(message){}
public ParseException(string message, Exception innerException) : base(message, innerException){}
protected ParseException(SerializationInfo info, StreamingContext context) : base(info, context){}
}
/// <summary>
/// Class for holding constituents.
/// </summary>
public class Parse : ICloneable, IComparable
{
/// <summary>
/// The sub-constituents of this parse.
/// </summary>
private List<Parse> _parts;
/// <summary>
/// The string buffer used to track the derivation of this parse.
/// </summary>
private StringBuilder _derivation;
// property accessors and methods for manipulating properties -------
/// <summary>
/// The text string on which this parse is based. This object is shared among all parses for the same sentence.
/// </summary>
public virtual string Text{ get; private set; }
/// /// <summary>
/// The character offsets into the text for this constituent.
/// </summary>
public virtual Util.Span Span { get; private set; }
/// <summary>
/// The syntactic type of this parse.
/// </summary>
public virtual string Type { get; set; }
public string Value
{
get { return this.Text.Substring(this.Span.Start, this.Span.Length()); }
}
public bool IsLeaf
{
get { return !this.GetChildren().Any(); }
}
/// <summary>
/// The sub-constituents of this parse.
/// </summary>
public virtual Parse[] GetChildren()
{
return _parts.ToArray();
}
/// <summary>
/// The number of children for this parse node.
/// </summary>
public int ChildCount
{
get
{
return _parts.Count;
}
}
/// <summary>
/// The head parse of this parse. A parse can be its own head.
/// </summary>
public virtual Parse Head { get; private set; }
/// <summary>
/// The outcome assigned to this parse during construction of its parent parse.
/// </summary>
public virtual string Label { get; set; }
/// <summary>
/// The parent parse of this parse.
/// </summary>
public virtual Parse Parent { get; set; }
///<summary>
///Returns the log of the product of the probability associated with all the decisions which formed this constituent.
///</summary>
public virtual double Probability { get; private set; }
public virtual string Derivation
{
get
{
return _derivation.ToString();
}
}
public virtual bool IsPosTag
{
get
{
return (_parts.Count == 1 && (_parts[0]).Type == MaximumEntropyParser.TokenNode);
}
}
///<summary>Returns whether this parse is complete.</summary>
///<returns>Returns true if the parse contains a single top-most node.</returns>
public virtual bool IsComplete
{
get
{
return (_parts.Count == 1);
}
}
// Methods ---------------------
/// <summary>
/// Replaces the child at the specified index with a new child with the specified label.
/// </summary>
/// <param name="index">
/// The index of the child to be replaced.
/// </param>
/// <param name="label">
/// The label to be assigned to the new child.
/// </param>
public void SetChild(int index, string label)
{
var newChild = (Parse)(_parts[index]).Clone();
newChild.Label = label;
_parts[index] = newChild;
}
/// <summary>
/// Returns the index of this specified child.
/// </summary>
/// <param name="child">
/// A child of this parse.
/// </param>
/// <returns>
/// the index of this specified child or -1 if the specified child is not a child of this parse.
/// </returns>
public int IndexOf(Parse child)
{
return _parts.IndexOf(child);
}
///<summary>
///Adds the specified probability log to this current log for this parse.
///</summary>
///<param name="logProbability">
///The probaility of an action performed on this parse.
///</param>
internal void AddProbability(double logProbability)
{
Probability += logProbability;
}
internal void InitializeDerivationBuffer()
{
_derivation = new StringBuilder(100);
}
internal void AppendDerivationBuffer(string derivationData)
{
_derivation.Append(derivationData);
}
// IClonable implementation ---------------------------
public object Clone()
{
var clonedParse = (Parse)base.MemberwiseClone();
clonedParse._parts = new List<Parse>(_parts);
if (_derivation != null)
{
clonedParse.InitializeDerivationBuffer();
clonedParse.AppendDerivationBuffer(_derivation.ToString());
}
return (clonedParse);
}
// IComparable implementation ------------------------
public virtual int CompareTo(object o)
{
if (!(o is Parse))
{
throw new ArgumentException("A Parse object is required for comparison.");
}
var testParse = (Parse) o;
if (this.Probability > testParse.Probability)
{
return - 1;
}
else if (this.Probability < testParse.Probability)
{
return 1;
}
return 0;
}
// constructors -----------------------
public Parse(string parseText, Util.Span span, string type, double probability)
{
Text = parseText;
Span = span;
Type = type;
Probability = probability;
Head = this;
_parts = new List<Parse>();
Label = null;
Parent = null;
}
public Parse(string parseText, Util.Span span, string type, double probability, Parse head) : this(parseText, span, type, probability)
{
Head = head;
}
// System.Object overrides -------------------------
public override string ToString()
{
return Text.Substring(Span.Start, Span.Length());
}
//public override bool Equals (Object o)
//{
// if (o == null) return false;
// if (this.GetType() != o.GetType())
// {
// return false;
// }
// Parse testParse = (Parse)o;
// return (this.Probability == testParse.Probability);
//}
//public override int GetHashCode ()
//{
// return _probability.GetHashCode();
//}
///<summary>
///Returns the probability associated with the pos-tag sequence assigned to this parse.
///</summary>
///<returns>
///The probability associated with the pos-tag sequence assigned to this parse.
///</returns>
public virtual double GetTagSequenceProbability()
{
//System.Console.Error.WriteLine("Parse.GetTagSequenceProbability: " + _type + " " + this);
if (_parts.Count == 1 && (_parts[0]).Type == MaximumEntropyParser.TokenNode)
{
//System.Console.Error.WriteLine(this + " " + mParseProbability);
return Math.Log(Probability);
}
else
{
if (_parts.Count == 0)
{
throw new ParseException("Parse.GetTagSequenceProbability(): Wrong base case!");
//return 0.0;
}
else
{
double sum = 0.0;
foreach (Parse oChildParse in _parts)
{
sum += oChildParse.GetTagSequenceProbability();
}
return sum;
}
}
}
///<summary>
///Inserts the specified constituent into this parse based on its text span. This
///method assumes that the specified constituent can be inserted into this parse.
///</summary>
///<param name="constituent">
///The constituent to be inserted.
///</param>
public virtual void Insert(Parse constituent)
{
Util.Span constituentSpan = constituent.Span;
if (Span.Contains(constituentSpan))
{
int currentPart;
int partCount = _parts.Count;
for (currentPart = 0; currentPart < partCount; currentPart++)
{
Parse subPart = _parts[currentPart];
Util.Span subPartSpan = subPart.Span;
if (subPartSpan.Start > constituentSpan.End)
{
break;
}
// constituent Contains subPart
else if (constituentSpan.Contains(subPartSpan))
{
_parts.RemoveAt(currentPart);
currentPart--;
constituent._parts.Add(subPart);
subPart.Parent = constituent;
partCount = _parts.Count;
}
else if (subPartSpan.Contains(constituentSpan))
{
//System.Console.WriteLine("Parse.insert:subPart contains con");
subPart.Insert(constituent);
return;
}
}
_parts.Insert(currentPart, constituent);
constituent.Parent = this;
}
else
{
throw new ParseException("Inserting constituent not contained in the sentence!");
}
}
///<summary>
///Displays this parse using Penn Treebank-style formatting.
///</summary>
public virtual string Show()
{
var buffer = new StringBuilder();
int start = Span.Start;
if (Type != MaximumEntropyParser.TokenNode)
{
buffer.Append("(");
buffer.Append(Type + " ");
}
foreach (Parse childParse in _parts)
{
Util.Span childSpan = childParse.Span;
if (start < childSpan.Start)
{
//System.Console.Out.WriteLine("pre " + start + " " + childSpan.Start);
buffer.Append(Text.Substring(start, (childSpan.Start) - (start)));
}
buffer.Append(childParse.Show());
start = childSpan.End;
}
buffer.Append(Text.Substring(start, this.Span.End - start));
if (Type != MaximumEntropyParser.TokenNode)
{
buffer.Append(")");
}
return buffer.ToString();
}
/// <summary>
/// Computes the head parses for this parse and its sub-parses and stores this information
/// in the parse data structure.
/// </summary>
/// <param name="rules">
/// The head rules which determine how the head of the parse is computed.
/// </param>
public virtual void UpdateHeads(IHeadRules rules)
{
if (_parts != null && _parts.Count != 0)
{
for (int currentPart = 0, partCount = _parts.Count; currentPart < partCount; currentPart++)
{
Parse currentParse = _parts[currentPart];
currentParse.UpdateHeads(rules);
}
Head = rules.GetHead(_parts.ToArray(), Type) ?? this;
}
else
{
Head = this;
}
}
/// <summary>
/// Returns the parse nodes which are children of this node and which are pos tags.
/// </summary>
/// <returns>
/// the parse nodes which are children of this node and which are pos tags.
/// </returns>
public virtual Parse[] GetTagNodes()
{
var tags = new List<Parse>();
var nodes = new List<Parse>(_parts);
while (nodes.Count != 0)
{
Parse currentParse = nodes[0];
nodes.RemoveAt(0);
if (currentParse.IsPosTag)
{
tags.Add(currentParse);
}
else
{
nodes.InsertRange(0, currentParse.GetChildren());
}
}
return tags.ToArray();
}
/// <summary>
/// Returns the deepest shared parent of this node and the specified node.
/// If the nodes are identical then their parent is returned.
/// If one node is the parent of the other then the parent node is returned.
/// </summary>
/// <param name="node">
/// The node from which parents are compared to this node's parents.
/// </param>
/// <returns>
/// the deepest shared parent of this node and the specified node.
/// </returns>
public virtual Parse GetCommonParent(Parse node)
{
if (this == node)
{
return this.Parent;
}
var parents = new Util.HashSet<Parse>();
Parse parentParse = this;
while (parentParse != null)
{
parents.Add(parentParse);
parentParse = parentParse.Parent;
}
while (node != null)
{
if (parents.Contains(node))
{
return node;
}
node = node.Parent;
}
return null;
}
protected internal void UpdateChildParents()
{
foreach (Parse childParse in _parts)
{
childParse.Parent = this;
childParse.UpdateChildParents();
}
}
// static methods used to create a Parse from a Penn Treebank parse string ----
/// <summary>
/// The pattern used to find the base constituent label of a Penn Treebank labeled constituent.
/// </summary>
private static readonly Regex TypePattern = new Regex("^([^ =-]+)", RegexOptions.Compiled);
/// <summary>
/// The pattern used to identify tokens in Penn Treebank labeled constituents.
/// </summary>
private static readonly Regex TokenPattern = new Regex("^[^ ()]+ ([^ ()]+)\\s*\\)", RegexOptions.Compiled);
private static string GetType(string rest)
{
if (rest.StartsWith("-LCB-"))
{
return "-LCB-";
}
else if (rest.StartsWith("-RCB-"))
{
return "-RCB-";
}
else if (rest.StartsWith("-LRB-"))
{
return "-LRB-";
}
else if (rest.StartsWith("-RRB-"))
{
return "-RRB-";
}
else
{
MatchCollection typeMatches = TypePattern.Matches(rest);
if (typeMatches.Count > 0)
{
return typeMatches[0].Groups[1].Value;
}
}
return null;
}
private static string GetToken(string rest)
{
MatchCollection tokenMatches = TokenPattern.Matches(rest);
if (tokenMatches.Count > 0)
{
return tokenMatches[0].Groups[1].Value;
}
return null;
// int start = rest.IndexOf(" ");
// if (start > -1)
// {
// int end = rest.IndexOfAny(new char[] {'(', ')'}, start);
// if ((end > -1) && (end - start > 1))
// {
// return rest.Substring(start + 1, end - start - 1);
// }
// }
// return null;
}
/// <summary>
/// Generates a Parse structure from the specified tree-bank style parse string.
/// </summary>
/// <param name="parse">
/// A tree-bank style parse string.
/// </param>
/// <returns>
/// a Parse structure for the specified tree-bank style parse string.
/// </returns>
public static Parse FromParseString(string parse)
{
var textBuffer = new StringBuilder();
int offset = 0;
var parseStack = new Stack<Tuple<string, int>>();
var consitutents = new List<Tuple<string, Util.Span>>();
for (int currentChar = 0, charCount = parse.Length; currentChar < charCount; currentChar++)
{
char c = parse[currentChar];
if (c == '(')
{
string rest = parse.Substring(currentChar + 1);
string type = GetType(rest);
if (type == null)
{
throw new ParseException("null type for: " + rest);
}
string token = GetToken(rest);
parseStack.Push(new Tuple<string, int>(type, offset));
if ((object) token != null && type != "-NONE-")
{
consitutents.Add(new Tuple<string, Util.Span>(MaximumEntropyParser.TokenNode, new Util.Span(offset, offset + token.Length)));
textBuffer.Append(token).Append(" ");
offset += token.Length + 1;
}
}
else if (c == ')')
{
Tuple<string, int> parts = parseStack.Pop();
string type = parts.Item1;
if (type != "-NONE-")
{
int start = parts.Item2;
consitutents.Add(new Tuple<string, Util.Span>(parts.Item1, new Util.Span(start, offset - 1)));
}
}
}
string text = textBuffer.ToString();
var rootParse = new Parse(text, new Util.Span(0, text.Length), MaximumEntropyParser.TopNode, 1);
for (int currentConstituent = 0, constituentCount = consitutents.Count; currentConstituent < constituentCount; currentConstituent++)
{
Tuple<string, Util.Span> parts = consitutents[currentConstituent];
string type = parts.Item1;
if (type != MaximumEntropyParser.TopNode)
{
var newConstituent = new Parse(text, parts.Item2, type, 1);
rootParse.Insert(newConstituent);
}
}
return rootParse;
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// LoadingScreen.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Threading;
using System.Diagnostics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Net;
#endregion
namespace NetworkStateManagement
{
/// <summary>
/// The loading screen coordinates transitions between the menu system and the
/// game itself. Normally one screen will transition off at the same time as
/// the next screen is transitioning on, but for larger transitions that can
/// take a longer time to load their data, we want the menu system to be entirely
/// gone before we start loading the game. This is done as follows:
///
/// - Tell all the existing screens to transition off.
/// - Activate a loading screen, which will transition on at the same time.
/// - The loading screen watches the state of the previous screens.
/// - When it sees they have finished transitioning off, it activates the real
/// next screen, which may take a long time to load its data. The loading
/// screen will be the only thing displayed while this load is taking place.
/// </summary>
class LoadingScreen : GameScreen
{
#region Fields
bool loadingIsSlow;
bool otherScreensAreGone;
GameScreen[] screensToLoad;
Thread backgroundThread;
EventWaitHandle backgroundThreadExit;
GraphicsDevice graphicsDevice;
NetworkSession networkSession;
IMessageDisplay messageDisplay;
GameTime loadStartTime;
TimeSpan loadAnimationTimer;
#endregion
#region Initialization
/// <summary>
/// The constructor is private: loading screens should
/// be activated via the static Load method instead.
/// </summary>
private LoadingScreen(ScreenManager screenManager, bool loadingIsSlow,
GameScreen[] screensToLoad)
{
this.loadingIsSlow = loadingIsSlow;
this.screensToLoad = screensToLoad;
TransitionOnTime = TimeSpan.FromSeconds(0.5);
// If this is going to be a slow load operation, create a background
// thread that will update the network session and draw the load screen
// animation while the load is taking place.
if (loadingIsSlow)
{
backgroundThread = new Thread(BackgroundWorkerThread);
backgroundThreadExit = new ManualResetEvent(false);
graphicsDevice = screenManager.GraphicsDevice;
// Look up some services that will be used by the background thread.
IServiceProvider services = screenManager.Game.Services;
networkSession = (NetworkSession)services.GetService(
typeof(NetworkSession));
messageDisplay = (IMessageDisplay)services.GetService(
typeof(IMessageDisplay));
}
}
/// <summary>
/// Activates the loading screen.
/// </summary>
public static void Load(ScreenManager screenManager, bool loadingIsSlow,
PlayerIndex? controllingPlayer,
params GameScreen[] screensToLoad)
{
// Tell all the current screens to transition off.
foreach (GameScreen screen in screenManager.GetScreens())
screen.ExitScreen();
// Create and activate the loading screen.
LoadingScreen loadingScreen = new LoadingScreen(screenManager,
loadingIsSlow,
screensToLoad);
screenManager.AddScreen(loadingScreen, controllingPlayer);
}
#endregion
#region Update and Draw
/// <summary>
/// Updates the loading screen.
/// </summary>
public override void Update(GameTime gameTime, bool otherScreenHasFocus,
bool coveredByOtherScreen)
{
base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
// If all the previous screens have finished transitioning
// off, it is time to actually perform the load.
if (otherScreensAreGone)
{
// Start up the background thread, which will update the network
// session and draw the animation while we are loading.
if (backgroundThread != null)
{
loadStartTime = gameTime;
backgroundThread.Start();
}
// Perform the load operation.
ScreenManager.RemoveScreen(this);
foreach (GameScreen screen in screensToLoad)
{
if (screen != null)
{
ScreenManager.AddScreen(screen, ControllingPlayer);
}
}
// Signal the background thread to exit, then wait for it to do so.
if (backgroundThread != null)
{
backgroundThreadExit.Set();
backgroundThread.Join();
}
// Once the load has finished, we use ResetElapsedTime to tell
// the game timing mechanism that we have just finished a very
// long frame, and that it should not try to catch up.
ScreenManager.Game.ResetElapsedTime();
}
}
/// <summary>
/// Draws the loading screen.
/// </summary>
public override void Draw(GameTime gameTime)
{
// If we are the only active screen, that means all the previous screens
// must have finished transitioning off. We check for this in the Draw
// method, rather than in Update, because it isn't enough just for the
// screens to be gone: in order for the transition to look good we must
// have actually drawn a frame without them before we perform the load.
if ((ScreenState == ScreenState.Active) &&
(ScreenManager.GetScreens().Length == 1))
{
otherScreensAreGone = true;
}
// The gameplay screen takes a while to load, so we display a loading
// message while that is going on, but the menus load very quickly, and
// it would look silly if we flashed this up for just a fraction of a
// second while returning from the game to the menus. This parameter
// tells us how long the loading is going to take, so we know whether
// to bother drawing the message.
if (loadingIsSlow)
{
SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
SpriteFont font = ScreenManager.Font;
string message = Resources.Loading;
// Center the text in the viewport.
Viewport viewport = ScreenManager.GraphicsDevice.Viewport;
Vector2 viewportSize = new Vector2(viewport.Width, viewport.Height);
Vector2 textSize = font.MeasureString(message);
Vector2 textPosition = (viewportSize - textSize) / 2;
Color color = Color.White * TransitionAlpha;
// Animate the number of dots after our "Loading..." message.
loadAnimationTimer += gameTime.ElapsedGameTime;
int dotCount = (int)(loadAnimationTimer.TotalSeconds * 5) % 10;
message += new string('.', dotCount);
// Draw the text.
spriteBatch.Begin();
spriteBatch.DrawString(font, message, textPosition, color);
spriteBatch.End();
}
}
#endregion
#region Background Thread
/// <summary>
/// Worker thread draws the loading animation and updates the network
/// session while the load is taking place.
/// </summary>
void BackgroundWorkerThread()
{
long lastTime = Stopwatch.GetTimestamp();
// EventWaitHandle.WaitOne will return true if the exit signal has
// been triggered, or false if the timeout has expired. We use the
// timeout to update at regular intervals, then break out of the
// loop when we are signalled to exit.
while (!backgroundThreadExit.WaitOne(1000 / 30))
{
GameTime gameTime = GetGameTime(ref lastTime);
DrawLoadAnimation(gameTime);
UpdateNetworkSession();
}
}
/// <summary>
/// Works out how long it has been since the last background thread update.
/// </summary>
GameTime GetGameTime(ref long lastTime)
{
long currentTime = Stopwatch.GetTimestamp();
long elapsedTicks = currentTime - lastTime;
lastTime = currentTime;
TimeSpan elapsedTime = TimeSpan.FromTicks(elapsedTicks *
TimeSpan.TicksPerSecond /
Stopwatch.Frequency);
return new GameTime(loadStartTime.TotalGameTime + elapsedTime, elapsedTime);
}
/// <summary>
/// Calls directly into our Draw method from the background worker thread,
/// so as to update the load animation in parallel with the actual loading.
/// </summary>
void DrawLoadAnimation(GameTime gameTime)
{
if ((graphicsDevice == null) || graphicsDevice.IsDisposed)
return;
try
{
graphicsDevice.Clear(Color.Black);
// Draw the loading screen.
Draw(gameTime);
// If we have a message display component, we want to display
// that over the top of the loading screen, too.
if (messageDisplay != null)
{
messageDisplay.Update(gameTime);
messageDisplay.Draw(gameTime);
}
graphicsDevice.Present();
}
catch
{
// If anything went wrong (for instance the graphics device was lost
// or reset) we don't have any good way to recover while running on a
// background thread. Setting the device to null will stop us from
// rendering, so the main game can deal with the problem later on.
graphicsDevice = null;
}
}
/// <summary>
/// Updates the network session from the background worker thread, to avoid
/// disconnecting due to network timeouts even if loading takes a long time.
/// </summary>
void UpdateNetworkSession()
{
if ((networkSession == null) ||
(networkSession.SessionState == NetworkSessionState.Ended))
return;
try
{
networkSession.Update();
}
catch
{
// If anything went wrong, we don't have a good way to report that
// error while running on a background thread. Setting the session to
// null will stop us from updating it, so the main game can deal with
// the problem later on.
networkSession = null;
}
}
#endregion
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia.Collections;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Templates;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.LogicalTree;
using Avalonia.Markup.Data;
using Avalonia.UnitTests;
using Xunit;
namespace Avalonia.Controls.UnitTests
{
public class TreeViewTests
{
[Fact]
public void Items_Should_Be_Created()
{
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = CreateTestTreeData(),
DataTemplates = CreateNodeDataTemplate(),
};
ApplyTemplates(target);
Assert.Equal(new[] { "Root" }, ExtractItemHeader(target, 0));
Assert.Equal(new[] { "Child1", "Child2" }, ExtractItemHeader(target, 1));
Assert.Equal(new[] { "Grandchild2a" }, ExtractItemHeader(target, 2));
}
[Fact]
public void Items_Should_Be_Created_Using_ItemTemplate_If_Present()
{
TreeView target;
var root = new TestRoot
{
Child = target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = CreateTestTreeData(),
ItemTemplate = new FuncTreeDataTemplate<Node>(
_ => new Canvas(),
x => x.Children),
}
};
ApplyTemplates(target);
var items = target.ItemContainerGenerator.Index.Items
.OfType<TreeViewItem>()
.ToList();
Assert.Equal(4, items.Count);
Assert.All(items, x => Assert.IsType<Canvas>(x.HeaderPresenter.Child));
}
[Fact]
public void Root_ItemContainerGenerator_Containers_Should_Be_Root_Containers()
{
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = CreateTestTreeData(),
DataTemplates = CreateNodeDataTemplate(),
};
ApplyTemplates(target);
var container = (TreeViewItem)target.ItemContainerGenerator.Containers.Single().ContainerControl;
var header = (TextBlock)container.Header;
Assert.Equal("Root", header.Text);
}
[Fact]
public void Root_TreeContainerFromItem_Should_Return_Descendent_Item()
{
var tree = CreateTestTreeData();
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = tree,
DataTemplates = CreateNodeDataTemplate(),
};
// For TreeViewItem to find its parent TreeView, OnAttachedToLogicalTree needs
// to be called, which requires an IStyleRoot.
var root = new TestRoot();
root.Child = target;
ApplyTemplates(target);
var container = target.ItemContainerGenerator.Index.ContainerFromItem(
tree[0].Children[1].Children[0]);
Assert.NotNull(container);
var header = ((TreeViewItem)container).Header;
var headerContent = ((TextBlock)header).Text;
Assert.Equal("Grandchild2a", headerContent);
}
[Fact]
public void Clicking_Item_Should_Select_It()
{
var tree = CreateTestTreeData();
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = tree,
DataTemplates = CreateNodeDataTemplate(),
};
var visualRoot = new TestRoot();
visualRoot.Child = target;
ApplyTemplates(target);
var item = tree[0].Children[1].Children[0];
var container = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(item);
Assert.NotNull(container);
container.RaiseEvent(new PointerPressedEventArgs
{
RoutedEvent = InputElement.PointerPressedEvent,
MouseButton = MouseButton.Left,
});
Assert.Equal(item, target.SelectedItem);
Assert.True(container.IsSelected);
}
[Fact]
public void Setting_SelectedItem_Should_Set_Container_Selected()
{
var tree = CreateTestTreeData();
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = tree,
DataTemplates = CreateNodeDataTemplate(),
};
var visualRoot = new TestRoot();
visualRoot.Child = target;
ApplyTemplates(target);
var item = tree[0].Children[1].Children[0];
var container = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(item);
Assert.NotNull(container);
target.SelectedItem = item;
Assert.True(container.IsSelected);
}
[Fact]
public void LogicalChildren_Should_Be_Set()
{
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = new[] { "Foo", "Bar", "Baz " },
};
ApplyTemplates(target);
var result = target.GetLogicalChildren()
.OfType<TreeViewItem>()
.Select(x => x.Header)
.OfType<TextBlock>()
.Select(x => x.Text)
.ToList();
Assert.Equal(new[] { "Foo", "Bar", "Baz " }, result);
}
[Fact]
public void Removing_Item_Should_Remove_Itself_And_Children_From_Index()
{
var tree = CreateTestTreeData();
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
DataTemplates = CreateNodeDataTemplate(),
Items = tree,
};
var root = new TestRoot();
root.Child = target;
ApplyTemplates(target);
Assert.Equal(4, target.ItemContainerGenerator.Index.Items.Count());
tree[0].Children.RemoveAt(1);
Assert.Equal(2, target.ItemContainerGenerator.Index.Items.Count());
}
[Fact]
public void DataContexts_Should_Be_Correctly_Set()
{
var items = new object[]
{
"Foo",
new Node { Value = "Bar" },
new TextBlock { Text = "Baz" },
new TreeViewItem { Header = "Qux" },
};
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
DataContext = "Base",
DataTemplates = new DataTemplates
{
new FuncDataTemplate<Node>(x => new Button { Content = x })
},
Items = items,
};
ApplyTemplates(target);
var dataContexts = target.Presenter.Panel.Children
.Cast<Control>()
.Select(x => x.DataContext)
.ToList();
Assert.Equal(
new object[] { items[0], items[1], "Base", "Base" },
dataContexts);
}
[Fact]
public void Control_Item_Should_Not_Be_NameScope()
{
var items = new object[]
{
new TreeViewItem(),
};
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = items,
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
var item = target.Presenter.Panel.LogicalChildren[0];
Assert.Null(NameScope.GetNameScope((TreeViewItem)item));
}
[Fact]
public void DataTemplate_Created_Item_Should_Be_NameScope()
{
var items = new object[]
{
"foo",
};
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = items,
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
var item = target.Presenter.Panel.LogicalChildren[0];
Assert.NotNull(NameScope.GetNameScope((TreeViewItem)item));
}
[Fact]
public void Should_React_To_Children_Changing()
{
var data = CreateTestTreeData();
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = data,
DataTemplates = CreateNodeDataTemplate(),
};
ApplyTemplates(target);
Assert.Equal(new[] { "Root" }, ExtractItemHeader(target, 0));
Assert.Equal(new[] { "Child1", "Child2" }, ExtractItemHeader(target, 1));
Assert.Equal(new[] { "Grandchild2a" }, ExtractItemHeader(target, 2));
// Make sure that the binding to Node.Children does not get collected.
GC.Collect();
data[0].Children = new AvaloniaList<Node>
{
new Node
{
Value = "NewChild1",
}
};
Assert.Equal(new[] { "Root" }, ExtractItemHeader(target, 0));
Assert.Equal(new[] { "NewChild1" }, ExtractItemHeader(target, 1));
}
private void ApplyTemplates(TreeView tree)
{
tree.ApplyTemplate();
tree.Presenter.ApplyTemplate();
ApplyTemplates(tree.Presenter.Panel.Children);
}
private void ApplyTemplates(IEnumerable<IControl> controls)
{
foreach (TreeViewItem control in controls)
{
control.Template = CreateTreeViewItemTemplate();
control.ApplyTemplate();
control.Presenter.ApplyTemplate();
control.HeaderPresenter.ApplyTemplate();
ApplyTemplates(control.Presenter.Panel.Children);
}
}
private IList<Node> CreateTestTreeData()
{
return new AvaloniaList<Node>
{
new Node
{
Value = "Root",
Children = new AvaloniaList<Node>
{
new Node
{
Value = "Child1",
},
new Node
{
Value = "Child2",
Children = new AvaloniaList<Node>
{
new Node
{
Value = "Grandchild2a",
},
},
},
}
}
};
}
private DataTemplates CreateNodeDataTemplate()
{
return new DataTemplates
{
new TestTreeDataTemplate()
};
}
private IControlTemplate CreateTreeViewTemplate()
{
return new FuncControlTemplate<TreeView>(parent => new ItemsPresenter
{
Name = "PART_ItemsPresenter",
[~ItemsPresenter.ItemsProperty] = parent[~ItemsControl.ItemsProperty],
});
}
private IControlTemplate CreateTreeViewItemTemplate()
{
return new FuncControlTemplate<TreeViewItem>(parent => new Panel
{
Children = new Controls
{
new ContentPresenter
{
Name = "PART_HeaderPresenter",
[~ContentPresenter.ContentProperty] = parent[~TreeViewItem.HeaderProperty],
},
new ItemsPresenter
{
Name = "PART_ItemsPresenter",
[~ItemsPresenter.ItemsProperty] = parent[~ItemsControl.ItemsProperty],
}
}
});
}
private List<string> ExtractItemHeader(TreeView tree, int level)
{
return ExtractItemContent(tree.Presenter.Panel, 0, level)
.Select(x => x.Header)
.OfType<TextBlock>()
.Select(x => x.Text)
.ToList();
}
private IEnumerable<TreeViewItem> ExtractItemContent(IPanel panel, int currentLevel, int level)
{
foreach (TreeViewItem container in panel.Children)
{
if (container.Template == null)
{
container.Template = CreateTreeViewItemTemplate();
container.ApplyTemplate();
}
if (currentLevel == level)
{
yield return container;
}
else
{
foreach (var child in ExtractItemContent(container.Presenter.Panel, currentLevel + 1, level))
{
yield return child;
}
}
}
}
private class Node : NotifyingBase
{
private IAvaloniaList<Node> _children;
public string Value { get; set; }
public IAvaloniaList<Node> Children
{
get
{
return _children;
}
set
{
_children = value;
RaisePropertyChanged(nameof(Children));
}
}
}
private class TestTreeDataTemplate : ITreeDataTemplate
{
public IControl Build(object param)
{
var node = (Node)param;
return new TextBlock { Text = node.Value };
}
public bool SupportsRecycling => false;
public InstancedBinding ItemsSelector(object item)
{
var obs = new ExpressionObserver(item, nameof(Node.Children));
return new InstancedBinding(obs);
}
public bool Match(object data)
{
return data is Node;
}
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Apis.FirebaseCloudMessaging.v1
{
/// <summary>The FirebaseCloudMessaging Service.</summary>
public class FirebaseCloudMessagingService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public FirebaseCloudMessagingService() : this(new Google.Apis.Services.BaseClientService.Initializer())
{
}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public FirebaseCloudMessagingService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer)
{
Projects = new ProjectsResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features => new string[0];
/// <summary>Gets the service name.</summary>
public override string Name => "fcm";
/// <summary>Gets the service base URI.</summary>
public override string BaseUri =>
#if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45
BaseUriOverride ?? "https://fcm.googleapis.com/";
#else
"https://fcm.googleapis.com/";
#endif
/// <summary>Gets the service base path.</summary>
public override string BasePath => "";
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri => "https://fcm.googleapis.com/batch";
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath => "batch";
#endif
/// <summary>Available OAuth 2.0 scopes for use with the Firebase Cloud Messaging API.</summary>
public class Scope
{
/// <summary>
/// See, edit, configure, and delete your Google Cloud data and see the email address for your Google
/// Account.
/// </summary>
public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
/// <summary>Send messages and manage messaging subscriptions for your Firebase applications</summary>
public static string FirebaseMessaging = "https://www.googleapis.com/auth/firebase.messaging";
}
/// <summary>Available OAuth 2.0 scope constants for use with the Firebase Cloud Messaging API.</summary>
public static class ScopeConstants
{
/// <summary>
/// See, edit, configure, and delete your Google Cloud data and see the email address for your Google
/// Account.
/// </summary>
public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
/// <summary>Send messages and manage messaging subscriptions for your Firebase applications</summary>
public const string FirebaseMessaging = "https://www.googleapis.com/auth/firebase.messaging";
}
/// <summary>Gets the Projects resource.</summary>
public virtual ProjectsResource Projects { get; }
}
/// <summary>A base abstract class for FirebaseCloudMessaging requests.</summary>
public abstract class FirebaseCloudMessagingBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
/// <summary>Constructs a new FirebaseCloudMessagingBaseServiceRequest instance.</summary>
protected FirebaseCloudMessagingBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1 = 0,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2 = 1,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json = 0,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media = 1,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto = 2,
}
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>
/// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required
/// unless you provide an OAuth 2.0 token.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>
/// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a
/// user, but should not exceed 40 characters.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes FirebaseCloudMessaging parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "projects" collection of methods.</summary>
public class ProjectsResource
{
private const string Resource = "projects";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ProjectsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
Messages = new MessagesResource(service);
}
/// <summary>Gets the Messages resource.</summary>
public virtual MessagesResource Messages { get; }
/// <summary>The "messages" collection of methods.</summary>
public class MessagesResource
{
private const string Resource = "messages";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public MessagesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Send a message to specified target (a registration token, topic or condition).</summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">
/// Required. It contains the Firebase project id (i.e. the unique identifier for your Firebase project), in
/// the format of `projects/{project_id}`. For legacy support, the numeric project number with no padding is
/// also supported in the format of `projects/{project_number}`.
/// </param>
public virtual SendRequest Send(Google.Apis.FirebaseCloudMessaging.v1.Data.SendMessageRequest body, string parent)
{
return new SendRequest(service, body, parent);
}
/// <summary>Send a message to specified target (a registration token, topic or condition).</summary>
public class SendRequest : FirebaseCloudMessagingBaseServiceRequest<Google.Apis.FirebaseCloudMessaging.v1.Data.Message>
{
/// <summary>Constructs a new Send request.</summary>
public SendRequest(Google.Apis.Services.IClientService service, Google.Apis.FirebaseCloudMessaging.v1.Data.SendMessageRequest body, string parent) : base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>
/// Required. It contains the Firebase project id (i.e. the unique identifier for your Firebase
/// project), in the format of `projects/{project_id}`. For legacy support, the numeric project number
/// with no padding is also supported in the format of `projects/{project_number}`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.FirebaseCloudMessaging.v1.Data.SendMessageRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "send";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+parent}/messages:send";
/// <summary>Initializes Send parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+$",
});
}
}
}
}
}
namespace Google.Apis.FirebaseCloudMessaging.v1.Data
{
/// <summary>
/// Android specific options for messages sent through [FCM connection server](https://goo.gl/4GLdUl).
/// </summary>
public class AndroidConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// An identifier of a group of messages that can be collapsed, so that only the last message gets sent when
/// delivery can be resumed. A maximum of 4 different collapse keys is allowed at any given time.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("collapseKey")]
public virtual string CollapseKey { get; set; }
/// <summary>
/// Arbitrary key/value payload. If present, it will override google.firebase.fcm.v1.Message.data.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("data")]
public virtual System.Collections.Generic.IDictionary<string, string> Data { get; set; }
/// <summary>
/// If set to true, messages will be allowed to be delivered to the app while the device is in direct boot mode.
/// See [Support Direct Boot mode](https://developer.android.com/training/articles/direct-boot).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("directBootOk")]
public virtual System.Nullable<bool> DirectBootOk { get; set; }
/// <summary>Options for features provided by the FCM SDK for Android.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("fcmOptions")]
public virtual AndroidFcmOptions FcmOptions { get; set; }
/// <summary>Notification to send to android devices.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("notification")]
public virtual AndroidNotification Notification { get; set; }
/// <summary>
/// Message priority. Can take "normal" and "high" values. For more information, see [Setting the priority of a
/// message](https://goo.gl/GjONJv).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("priority")]
public virtual string Priority { get; set; }
/// <summary>
/// Package name of the application where the registration token must match in order to receive the message.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("restrictedPackageName")]
public virtual string RestrictedPackageName { get; set; }
/// <summary>
/// How long (in seconds) the message should be kept in FCM storage if the device is offline. The maximum time
/// to live supported is 4 weeks, and the default value is 4 weeks if not set. Set it to 0 if want to send the
/// message immediately. In JSON format, the Duration type is encoded as a string rather than an object, where
/// the string ends in the suffix "s" (indicating seconds) and is preceded by the number of seconds, with
/// nanoseconds expressed as fractional seconds. For example, 3 seconds with 0 nanoseconds should be encoded in
/// JSON format as "3s", while 3 seconds and 1 nanosecond should be expressed in JSON format as "3.000000001s".
/// The ttl will be rounded down to the nearest second.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("ttl")]
public virtual object Ttl { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Options for features provided by the FCM SDK for Android.</summary>
public class AndroidFcmOptions : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Label associated with the message's analytics data.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("analyticsLabel")]
public virtual string AnalyticsLabel { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Notification to send to android devices.</summary>
public class AndroidNotification : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The notification's body text. If present, it will override google.firebase.fcm.v1.Notification.body.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("body")]
public virtual string Body { get; set; }
/// <summary>
/// Variable string values to be used in place of the format specifiers in body_loc_key to use to localize the
/// body text to the user's current localization. See [Formatting and Styling](https://goo.gl/MalYE3) for more
/// information.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("bodyLocArgs")]
public virtual System.Collections.Generic.IList<string> BodyLocArgs { get; set; }
/// <summary>
/// The key to the body string in the app's string resources to use to localize the body text to the user's
/// current localization. See [String Resources](https://goo.gl/NdFZGI) for more information.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("bodyLocKey")]
public virtual string BodyLocKey { get; set; }
/// <summary>
/// The [notification's channel
/// id](https://developer.android.com/guide/topics/ui/notifiers/notifications#ManageChannels) (new in Android
/// O). The app must create a channel with this channel ID before any notification with this channel ID is
/// received. If you don't send this channel ID in the request, or if the channel ID provided has not yet been
/// created by the app, FCM uses the channel ID specified in the app manifest.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("channelId")]
public virtual string ChannelId { get; set; }
/// <summary>
/// The action associated with a user click on the notification. If specified, an activity with a matching
/// intent filter is launched when a user clicks on the notification.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("clickAction")]
public virtual string ClickAction { get; set; }
/// <summary>The notification's icon color, expressed in #rrggbb format.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("color")]
public virtual string Color { get; set; }
/// <summary>
/// If set to true, use the Android framework's default LED light settings for the notification. Default values
/// are specified in
/// [config.xml](https://android.googlesource.com/platform/frameworks/base/+/master/core/res/res/values/config.xml).
/// If `default_light_settings` is set to true and `light_settings` is also set, the user-specified
/// `light_settings` is used instead of the default value.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("defaultLightSettings")]
public virtual System.Nullable<bool> DefaultLightSettings { get; set; }
/// <summary>
/// If set to true, use the Android framework's default sound for the notification. Default values are specified
/// in
/// [config.xml](https://android.googlesource.com/platform/frameworks/base/+/master/core/res/res/values/config.xml).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("defaultSound")]
public virtual System.Nullable<bool> DefaultSound { get; set; }
/// <summary>
/// If set to true, use the Android framework's default vibrate pattern for the notification. Default values are
/// specified in
/// [config.xml](https://android.googlesource.com/platform/frameworks/base/+/master/core/res/res/values/config.xml).
/// If `default_vibrate_timings` is set to true and `vibrate_timings` is also set, the default value is used
/// instead of the user-specified `vibrate_timings`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("defaultVibrateTimings")]
public virtual System.Nullable<bool> DefaultVibrateTimings { get; set; }
/// <summary>
/// Set the time that the event in the notification occurred. Notifications in the panel are sorted by this
/// time. A point in time is represented using
/// [protobuf.Timestamp](https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/Timestamp).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("eventTime")]
public virtual object EventTime { get; set; }
/// <summary>
/// The notification's icon. Sets the notification icon to myicon for drawable resource myicon. If you don't
/// send this key in the request, FCM displays the launcher icon specified in your app manifest.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("icon")]
public virtual string Icon { get; set; }
/// <summary>
/// Contains the URL of an image that is going to be displayed in a notification. If present, it will override
/// google.firebase.fcm.v1.Notification.image.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("image")]
public virtual string Image { get; set; }
/// <summary>
/// Settings to control the notification's LED blinking rate and color if LED is available on the device. The
/// total blinking time is controlled by the OS.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("lightSettings")]
public virtual LightSettings LightSettings { get; set; }
/// <summary>
/// Set whether or not this notification is relevant only to the current device. Some notifications can be
/// bridged to other devices for remote display, such as a Wear OS watch. This hint can be set to recommend this
/// notification not be bridged. See [Wear OS
/// guides](https://developer.android.com/training/wearables/notifications/bridger#existing-method-of-preventing-bridging)
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("localOnly")]
public virtual System.Nullable<bool> LocalOnly { get; set; }
/// <summary>
/// Sets the number of items this notification represents. May be displayed as a badge count for launchers that
/// support badging.See [Notification Badge](https://developer.android.com/training/notify-user/badges). For
/// example, this might be useful if you're using just one notification to represent multiple new messages but
/// you want the count here to represent the number of total new messages. If zero or unspecified, systems that
/// support badging use the default, which is to increment a number displayed on the long-press menu each time a
/// new notification arrives.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("notificationCount")]
public virtual System.Nullable<int> NotificationCount { get; set; }
/// <summary>
/// Set the relative priority for this notification. Priority is an indication of how much of the user's
/// attention should be consumed by this notification. Low-priority notifications may be hidden from the user in
/// certain situations, while the user might be interrupted for a higher-priority notification. The effect of
/// setting the same priorities may differ slightly on different platforms. Note this priority differs from
/// `AndroidMessagePriority`. This priority is processed by the client after the message has been delivered,
/// whereas
/// [AndroidMessagePriority](https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#androidmessagepriority)
/// is an FCM concept that controls when the message is delivered.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("notificationPriority")]
public virtual string NotificationPriority { get; set; }
/// <summary>
/// The sound to play when the device receives the notification. Supports "default" or the filename of a sound
/// resource bundled in the app. Sound files must reside in /res/raw/.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("sound")]
public virtual string Sound { get; set; }
/// <summary>
/// When set to false or unset, the notification is automatically dismissed when the user clicks it in the
/// panel. When set to true, the notification persists even when the user clicks it.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("sticky")]
public virtual System.Nullable<bool> Sticky { get; set; }
/// <summary>
/// Identifier used to replace existing notifications in the notification drawer. If not specified, each request
/// creates a new notification. If specified and a notification with the same tag is already being shown, the
/// new notification replaces the existing one in the notification drawer.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("tag")]
public virtual string Tag { get; set; }
/// <summary>
/// Sets the "ticker" text, which is sent to accessibility services. Prior to API level 21 (`Lollipop`), sets
/// the text that is displayed in the status bar when the notification first arrives.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("ticker")]
public virtual string Ticker { get; set; }
/// <summary>
/// The notification's title. If present, it will override google.firebase.fcm.v1.Notification.title.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("title")]
public virtual string Title { get; set; }
/// <summary>
/// Variable string values to be used in place of the format specifiers in title_loc_key to use to localize the
/// title text to the user's current localization. See [Formatting and Styling](https://goo.gl/MalYE3) for more
/// information.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("titleLocArgs")]
public virtual System.Collections.Generic.IList<string> TitleLocArgs { get; set; }
/// <summary>
/// The key to the title string in the app's string resources to use to localize the title text to the user's
/// current localization. See [String Resources](https://goo.gl/NdFZGI) for more information.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("titleLocKey")]
public virtual string TitleLocKey { get; set; }
/// <summary>
/// Set the vibration pattern to use. Pass in an array of
/// [protobuf.Duration](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.Duration)
/// to turn on or off the vibrator. The first value indicates the `Duration` to wait before turning the vibrator
/// on. The next value indicates the `Duration` to keep the vibrator on. Subsequent values alternate between
/// `Duration` to turn the vibrator off and to turn the vibrator on. If `vibrate_timings` is set and
/// `default_vibrate_timings` is set to `true`, the default value is used instead of the user-specified
/// `vibrate_timings`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("vibrateTimings")]
public virtual System.Collections.Generic.IList<object> VibrateTimings { get; set; }
/// <summary>
/// Set the
/// [Notification.visibility](https://developer.android.com/reference/android/app/Notification.html#visibility)
/// of the notification.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("visibility")]
public virtual string Visibility { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>[Apple Push Notification Service](https://goo.gl/MXRTPa) specific options.</summary>
public class ApnsConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Options for features provided by the FCM SDK for iOS.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("fcmOptions")]
public virtual ApnsFcmOptions FcmOptions { get; set; }
/// <summary>
/// HTTP request headers defined in Apple Push Notification Service. Refer to [APNs request
/// headers](https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/sending_notification_requests_to_apns)
/// for supported headers such as `apns-expiration` and `apns-priority`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("headers")]
public virtual System.Collections.Generic.IDictionary<string, string> Headers { get; set; }
/// <summary>
/// APNs payload as a JSON object, including both `aps` dictionary and custom payload. See [Payload Key
/// Reference](https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/generating_a_remote_notification).
/// If present, it overrides google.firebase.fcm.v1.Notification.title and
/// google.firebase.fcm.v1.Notification.body. The backend sets a default value for `apns-expiration` of 30 days
/// and a default value for `apns-priority` of 10 if not explicitly set.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("payload")]
public virtual System.Collections.Generic.IDictionary<string, object> Payload { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Options for features provided by the FCM SDK for iOS.</summary>
public class ApnsFcmOptions : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Label associated with the message's analytics data.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("analyticsLabel")]
public virtual string AnalyticsLabel { get; set; }
/// <summary>
/// Contains the URL of an image that is going to be displayed in a notification. If present, it will override
/// google.firebase.fcm.v1.Notification.image.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("image")]
public virtual string Image { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Represents a color in the RGBA color space. This representation is designed for simplicity of conversion to/from
/// color representations in various languages over compactness. For example, the fields of this representation can
/// be trivially provided to the constructor of `java.awt.Color` in Java; it can also be trivially provided to
/// UIColor's `+colorWithRed:green:blue:alpha` method in iOS; and, with just a little work, it can be easily
/// formatted into a CSS `rgba()` string in JavaScript. This reference page doesn't carry information about the
/// absolute color space that should be used to interpret the RGB value (e.g. sRGB, Adobe RGB, DCI-P3, BT.2020,
/// etc.). By default, applications should assume the sRGB color space. When color equality needs to be decided,
/// implementations, unless documented otherwise, treat two colors as equal if all their red, green, blue, and alpha
/// values each differ by at most 1e-5. Example (Java): import com.google.type.Color; // ... public static
/// java.awt.Color fromProto(Color protocolor) { float alpha = protocolor.hasAlpha() ?
/// protocolor.getAlpha().getValue() : 1.0; return new java.awt.Color( protocolor.getRed(), protocolor.getGreen(),
/// protocolor.getBlue(), alpha); } public static Color toProto(java.awt.Color color) { float red = (float)
/// color.getRed(); float green = (float) color.getGreen(); float blue = (float) color.getBlue(); float denominator
/// = 255.0; Color.Builder resultBuilder = Color .newBuilder() .setRed(red / denominator) .setGreen(green /
/// denominator) .setBlue(blue / denominator); int alpha = color.getAlpha(); if (alpha != 255) { result.setAlpha(
/// FloatValue .newBuilder() .setValue(((float) alpha) / denominator) .build()); } return resultBuilder.build(); }
/// // ... Example (iOS / Obj-C): // ... static UIColor* fromProto(Color* protocolor) { float red = [protocolor
/// red]; float green = [protocolor green]; float blue = [protocolor blue]; FloatValue* alpha_wrapper = [protocolor
/// alpha]; float alpha = 1.0; if (alpha_wrapper != nil) { alpha = [alpha_wrapper value]; } return [UIColor
/// colorWithRed:red green:green blue:blue alpha:alpha]; } static Color* toProto(UIColor* color) { CGFloat red,
/// green, blue, alpha; if (![color getRed:&amp;red green:&amp;green blue:&amp;blue
/// alpha:&amp;alpha]) { return nil; } Color* result = [[Color alloc] init]; [result setRed:red]; [result
/// setGreen:green]; [result setBlue:blue]; if (alpha &lt;= 0.9999) { [result
/// setAlpha:floatWrapperWithValue(alpha)]; } [result autorelease]; return result; } // ... Example (JavaScript): //
/// ... var protoToCssColor = function(rgb_color) { var redFrac = rgb_color.red || 0.0; var greenFrac =
/// rgb_color.green || 0.0; var blueFrac = rgb_color.blue || 0.0; var red = Math.floor(redFrac * 255); var green =
/// Math.floor(greenFrac * 255); var blue = Math.floor(blueFrac * 255); if (!('alpha' in rgb_color)) { return
/// rgbToCssColor(red, green, blue); } var alphaFrac = rgb_color.alpha.value || 0.0; var rgbParams = [red, green,
/// blue].join(','); return ['rgba(', rgbParams, ',', alphaFrac, ')'].join(''); }; var rgbToCssColor = function(red,
/// green, blue) { var rgbNumber = new Number((red &lt;&lt; 16) | (green &lt;&lt; 8) | blue); var
/// hexString = rgbNumber.toString(16); var missingZeros = 6 - hexString.length; var resultBuilder = ['#']; for (var
/// i = 0; i &lt; missingZeros; i++) { resultBuilder.push('0'); } resultBuilder.push(hexString); return
/// resultBuilder.join(''); }; // ...
/// </summary>
public class Color : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The fraction of this color that should be applied to the pixel. That is, the final pixel color is defined by
/// the equation: `pixel color = alpha * (this color) + (1.0 - alpha) * (background color)` This means that a
/// value of 1.0 corresponds to a solid color, whereas a value of 0.0 corresponds to a completely transparent
/// color. This uses a wrapper message rather than a simple float scalar so that it is possible to distinguish
/// between a default value and the value being unset. If omitted, this color object is rendered as a solid
/// color (as if the alpha value had been explicitly given a value of 1.0).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("alpha")]
public virtual System.Nullable<float> Alpha { get; set; }
/// <summary>The amount of blue in the color as a value in the interval [0, 1].</summary>
[Newtonsoft.Json.JsonPropertyAttribute("blue")]
public virtual System.Nullable<float> Blue { get; set; }
/// <summary>The amount of green in the color as a value in the interval [0, 1].</summary>
[Newtonsoft.Json.JsonPropertyAttribute("green")]
public virtual System.Nullable<float> Green { get; set; }
/// <summary>The amount of red in the color as a value in the interval [0, 1].</summary>
[Newtonsoft.Json.JsonPropertyAttribute("red")]
public virtual System.Nullable<float> Red { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Platform independent options for features provided by the FCM SDKs.</summary>
public class FcmOptions : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Label associated with the message's analytics data.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("analyticsLabel")]
public virtual string AnalyticsLabel { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Settings to control notification LED.</summary>
public class LightSettings : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Required. Set `color` of the LED with
/// [google.type.Color](https://github.com/googleapis/googleapis/blob/master/google/type/color.proto).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("color")]
public virtual Color Color { get; set; }
/// <summary>
/// Required. Along with `light_on_duration `, define the blink rate of LED flashes. Resolution defined by
/// [proto.Duration](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.Duration)
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("lightOffDuration")]
public virtual object LightOffDuration { get; set; }
/// <summary>
/// Required. Along with `light_off_duration`, define the blink rate of LED flashes. Resolution defined by
/// [proto.Duration](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.Duration)
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("lightOnDuration")]
public virtual object LightOnDuration { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Message to send by Firebase Cloud Messaging Service.</summary>
public class Message : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Input only. Android specific options for messages sent through [FCM connection
/// server](https://goo.gl/4GLdUl).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("android")]
public virtual AndroidConfig Android { get; set; }
/// <summary>Input only. [Apple Push Notification Service](https://goo.gl/MXRTPa) specific options.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("apns")]
public virtual ApnsConfig Apns { get; set; }
/// <summary>Condition to send a message to, e.g. "'foo' in topics && 'bar' in topics".</summary>
[Newtonsoft.Json.JsonPropertyAttribute("condition")]
public virtual string Condition { get; set; }
/// <summary>
/// Input only. Arbitrary key/value payload, which must be UTF-8 encoded. The key should not be a reserved word
/// ("from", "message_type", or any word starting with "google" or "gcm"). When sending payloads containing only
/// data fields to iOS devices, only normal priority (`"apns-priority": "5"`) is allowed in
/// [`ApnsConfig`](/docs/reference/fcm/rest/v1/projects.messages#apnsconfig).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("data")]
public virtual System.Collections.Generic.IDictionary<string, string> Data { get; set; }
/// <summary>Input only. Template for FCM SDK feature options to use across all platforms.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("fcmOptions")]
public virtual FcmOptions FcmOptions { get; set; }
/// <summary>
/// Output Only. The identifier of the message sent, in the format of `projects/*/messages/{message_id}`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>Input only. Basic notification template to use across all platforms.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("notification")]
public virtual Notification Notification { get; set; }
/// <summary>Registration token to send a message to.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("token")]
public virtual string Token { get; set; }
/// <summary>
/// Topic name to send a message to, e.g. "weather". Note: "/topics/" prefix should not be provided.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("topic")]
public virtual string Topic { get; set; }
/// <summary>Input only. [Webpush protocol](https://tools.ietf.org/html/rfc8030) options.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("webpush")]
public virtual WebpushConfig Webpush { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Basic notification template to use across all platforms.</summary>
public class Notification : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The notification's body text.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("body")]
public virtual string Body { get; set; }
/// <summary>
/// Contains the URL of an image that is going to be downloaded on the device and displayed in a notification.
/// JPEG, PNG, BMP have full support across platforms. Animated GIF and video only work on iOS. WebP and HEIF
/// have varying levels of support across platforms and platform versions. Android has 1MB image size limit.
/// Quota usage and implications/costs for hosting image on Firebase Storage:
/// https://firebase.google.com/pricing
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("image")]
public virtual string Image { get; set; }
/// <summary>The notification's title.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("title")]
public virtual string Title { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request to send a message to specified target.</summary>
public class SendMessageRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. Message to send.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("message")]
public virtual Message Message { get; set; }
/// <summary>Flag for testing the request without actually delivering the message.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("validateOnly")]
public virtual System.Nullable<bool> ValidateOnly { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>[Webpush protocol](https://tools.ietf.org/html/rfc8030) options.</summary>
public class WebpushConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Arbitrary key/value payload. If present, it will override google.firebase.fcm.v1.Message.data.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("data")]
public virtual System.Collections.Generic.IDictionary<string, string> Data { get; set; }
/// <summary>Options for features provided by the FCM SDK for Web.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("fcmOptions")]
public virtual WebpushFcmOptions FcmOptions { get; set; }
/// <summary>
/// HTTP headers defined in webpush protocol. Refer to [Webpush
/// protocol](https://tools.ietf.org/html/rfc8030#section-5) for supported headers, e.g. "TTL": "15".
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("headers")]
public virtual System.Collections.Generic.IDictionary<string, string> Headers { get; set; }
/// <summary>
/// Web Notification options as a JSON object. Supports Notification instance properties as defined in [Web
/// Notification API](https://developer.mozilla.org/en-US/docs/Web/API/Notification). If present, "title" and
/// "body" fields override [google.firebase.fcm.v1.Notification.title] and
/// [google.firebase.fcm.v1.Notification.body].
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("notification")]
public virtual System.Collections.Generic.IDictionary<string, object> Notification { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Options for features provided by the FCM SDK for Web.</summary>
public class WebpushFcmOptions : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Label associated with the message's analytics data.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("analyticsLabel")]
public virtual string AnalyticsLabel { get; set; }
/// <summary>
/// The link to open when the user clicks on the notification. For all URL values, HTTPS is required.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("link")]
public virtual string Link { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
using System;
using UIKit;
using Foundation;
using System.Collections.Generic;
using System.Globalization;
using Occur.TextStyles.Core;
using System.Linq;
using System.Text.RegularExpressions;
namespace Occur.TextStyles.Touch
{
public class TextStyle
{
#region Parameters
/// <summary>
/// The default size for text.
/// </summary>
public static float DefaultTextSize = 18f;
public event EventHandler StylesChanged;
internal static Type typeLabel = typeof(UILabel);
internal static Type typeTextView = typeof(UITextView);
internal static Type typeTextField = typeof(UITextField);
static TextStyle instance = null;
static readonly object padlock = new object ();
public static readonly Regex MatchHtmlTags = new Regex (@"</?\w+((\s+\w+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)+\s*|\s*)/?>");
internal Dictionary<string, TextStyleParameters> _textStyles;
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="Occur.TextStyles.Touch.TextStyle"/> class.
/// </summary>
TextStyle ()
{
}
#region Public Methods
/// <summary>
/// Sets the CSS string
/// </summary>
/// <param name="css">Css Style Sheet</param>
public virtual void SetCSS (string css)
{
var styles = CssTextStyleParser.Parse (css);
SetStyles (styles);
}
/// <summary>
/// Sets the styles dictionary
/// </summary>
/// <param name="styles">Styles dictionary</param>
public virtual void SetStyles (Dictionary<string, TextStyleParameters> styles)
{
_textStyles = styles;
Refresh ();
}
/// <summary>
/// Gets a style by its selector
/// </summary>
/// <returns>The style.</returns>
/// <param name="selector">Selector.</param>
public static TextStyleParameters GetStyle (string selector)
{
return instance._textStyles.ContainsKey (selector) ? instance._textStyles [selector] : null;
}
/// <summary>
/// Returns the main instance of TextStyle
/// </summary>
/// <value>The instance.</value>
public static TextStyle Instance {
get {
lock (padlock) {
if (instance == null) {
instance = new TextStyle ();
}
return instance;
}
}
}
/// <summary>
/// Creates an NSAttibutedString html string using the custom tags for styling.
/// </summary>
/// <returns>NSAttibutedString</returns>
/// <param name="text">Text to display including html tags</param>
/// <param name="customTags">A list of custom <c>CSSTagStyle</c> instances that set the styling for the html</param>
/// <param name="useExistingStyles">Existing CSS styles willl be used If set to <c>true</c></param>
/// <param name="encoding">String encoding type</param>
public static NSAttributedString CreateHtmlString (string text, List<CssTagStyle> customTags = null, bool useExistingStyles = true, NSStringEncoding encoding = NSStringEncoding.UTF8)
{
var error = new NSError ();
text = HtmlTextStyleParser.StyleString (text, Instance._textStyles, customTags, useExistingStyles);
var stringAttribs = new NSAttributedStringDocumentAttributes {
DocumentType = NSDocumentType.HTML,
StringEncoding = encoding
};
var htmlString = new NSAttributedString (text, stringAttribs, ref error);
return htmlString;
}
/// <summary>
/// Creates a styled string as an NSAttibutedString
/// </summary>
/// <returns>NSMutableAttributedString</returns>
/// <param name="styleID">The CSS selector name for the style</param>
/// <param name="text">Text to style</param>
/// <param name="startIndex">Style start index</param>
/// <param name="endIndex">Style end index</param>
public static NSMutableAttributedString CreateStyledString (string styleID, string text, int startIndex = 0, int endIndex = -1)
{
var style = GetStyle (styleID);
return CreateStyledString (style, text, startIndex, endIndex);
}
/// <summary>
/// Creates a styled string as an NSAttibutedString
/// </summary>
/// <returns>The styled string.</returns>
/// <param name="style">TextStyleParameters for styling</param>
/// <param name="text">Text to style</param>
/// <param name="startIndex">Style start index</param>
/// <param name="endIndex">Style end index</param>
public static NSMutableAttributedString CreateStyledString (TextStyleParameters style, string text, int startIndex = 0, int endIndex = -1)
{
var attribs = GetStringAttributes (style);
text = ParseString (style, text);
if (endIndex == -1) {
endIndex = text.Length;
}
var prettyString = new NSMutableAttributedString (text);
prettyString.SetAttributes (attribs, new NSRange (startIndex, endIndex));
return prettyString;
}
/// <summary>
/// Signals that the styles have been updated.
/// </summary>
public void Refresh ()
{
StylesChanged?.Invoke (this, EventArgs.Empty);
}
/// <summary>
/// Sets the body css style for the customTags.
/// </summary>
/// <param name="baseStyleID">The CSS selector name for the body style</param>
/// <param name="customTags">A list of CSSTagStyle custom tags</param>
public static void SetBaseStyle (string baseStyleID, ref List<CssTagStyle> customTags)
{
if (customTags == null)
customTags = new List<CssTagStyle> ();
if (!customTags.Any (x => x.Tag == "body")) {
customTags.Add (new CssTagStyle (HtmlTextStyleParser.BODYTAG){ StyleID = baseStyleID });
}
}
/// <summary>
/// Creates and styles a new Text container (UIlabel, UITextView, UITextField)
/// </summary>
/// <param name="styleID">The CSS selector name for the style</param>
/// <param name="text">Text to display including html tags</param>
/// <param name="customTags">A list of custom <c>CSSTagStyle</c> instances that set the styling for the html</param>
/// <param name="useExistingStyles">Existing CSS styles willl be used If set to <c>true</c></param>
/// <param name="encoding">String encoding type</param>
/// <typeparam name="T">Text container type (UIlabel, UITextView, UITextField)</typeparam>
public static T Create<T> (string styleID, string text = "", List<CssTagStyle> customTags = null, bool useExistingStyles = true, NSStringEncoding encoding = NSStringEncoding.UTF8)
{
var isHTML = (!string.IsNullOrEmpty (text) && MatchHtmlTags.IsMatch (text));
var target = Activator.CreateInstance<T> ();
// If this is a plain string view, style it and return it
if (!string.IsNullOrEmpty (text) && !isHTML) {
Style<T> (target, styleID, text);
return target;
} else if (isHTML) {
SetBaseStyle (styleID, ref customTags);
}
var formattedText = isHTML ?
TextStyle.CreateHtmlString (text, customTags, useExistingStyles, encoding) :
TextStyle.CreateStyledString (styleID, text);
var type = typeof(T);
if (type == typeLabel) {
var label = target as UILabel;
label.AttributedText = formattedText;
if (!isHTML)
StyleUILabel (label, GetStyle (styleID), true);
} else if (type == typeTextView) {
var textView = target as UITextView;
textView.AttributedText = formattedText;
if (!isHTML)
StyleUITextView (textView, GetStyle (styleID), true);
} else if (type == typeTextField) {
var textField = target as UITextField;
textField.AttributedText = formattedText;
if (!isHTML)
StyleUITextField (textField, GetStyle (styleID), true);
} else {
throw new NotSupportedException ("The specified type is not supported, please use a UILabel, UITextView or UITextField: " + type.ToString ());
}
return target;
}
/// <summary>
/// Styles a text container (UIlabel, UITextView, UITextField)
/// </summary>
/// <param name="target">Target text container</param>
/// <param name="styleID">The CSS selector name for the style</param>
/// <param name="text">Text to display</param>
/// <typeparam name="T">Text container type (UIlabel, UITextView, UITextField)</typeparam>
public static void Style<T> (T target, string styleID, string text = null)
{
var style = GetStyle (styleID);
var type = typeof(T);
if (type == typeLabel) {
var label = target as UILabel;
label.AttributedText = ParseHtmlString (style, text ?? label.Text);
StyleUILabel (label, style, false);
} else if (type == typeTextView) {
var textView = target as UITextView;
textView.AttributedText = ParseHtmlString (style, text ?? textView.Text);
StyleUITextView (textView, style, false);
} else if (type == typeTextField) {
var textField = target as UITextField;
textField.AttributedText = ParseHtmlString (style, text ?? textField.Text);
StyleUITextField (textField, style, false);
} else {
throw new NotSupportedException ("The specified type is not supported, please use a UILabel, UITextView or UITextField: " + type.ToString ());
}
}
#endregion
#region Private Methods
private static void UpdateMargins (TextStyleParameters style, ref UIEdgeInsets inset)
{
inset.Top = (style.PaddingTop > float.MinValue) ? style.PaddingTop : inset.Top;
inset.Bottom = (style.PaddingBottom > float.MinValue) ? style.PaddingBottom : inset.Bottom;
inset.Left = (style.PaddingLeft > float.MinValue) ? style.PaddingLeft : inset.Left;
inset.Right = (style.PaddingRight > float.MinValue) ? style.PaddingRight : inset.Right;
}
internal static void StyleUILabel (UILabel target, TextStyleParameters style, bool setFonts)
{
// TODO fix this as its not helping as it stands
var attribs = GetStringAttributes (style);
target.TextColor = attribs.ForegroundColor;
// If setting the font attributes
if (setFonts) {
target.Font = attribs.Font;
}
// Lines
if (style.Lines > int.MinValue) {
target.Lines = style.Lines;
}
// Text Alignment
target.TextAlignment = GetAlignment (style.TextAlign);
// Overflow
switch (style.TextOverflow) {
case TextStyleTextOverflow.Ellipsis:
target.LineBreakMode = UILineBreakMode.TailTruncation;
break;
case TextStyleTextOverflow.Clip:
target.LineBreakMode = UILineBreakMode.Clip;
break;
default:
target.LineBreakMode = UILineBreakMode.WordWrap;
break;
}
}
internal static void StyleUITextView (UITextView target, TextStyleParameters style, bool setFonts)
{
var attribs = GetStringAttributes (style);
target.Font = attribs.Font;
// If setting the font attributes
if (setFonts) {
target.TextColor = attribs.ForegroundColor;
}
// Text Alignment
target.TextAlignment = GetAlignment (style.TextAlign);
// Padding
if (style.Padding != null) {
var padding = style.Padding;
target.TextContainerInset = new UIEdgeInsets (padding [0], padding [1], padding [2], padding [3]);
} else {
var curInset = target.TextContainerInset;
UpdateMargins (style, ref curInset);
target.TextContainerInset = curInset;
}
}
internal static void StyleUITextField (UITextField target, TextStyleParameters style, bool setFonts)
{
var attribs = GetStringAttributes (style);
target.TextColor = attribs.ForegroundColor;
// If setting the font attributes
if (setFonts) {
target.Font = attribs.Font;
}
target.TextAlignment = GetAlignment (style.TextAlign);
// Padding
if (style.Padding != null) {
var padding = style.Padding;
target.LayoutMargins = new UIEdgeInsets (padding [0], padding [1], padding [2], padding [3]);
} else {
var curInset = target.LayoutMargins;
UpdateMargins (style, ref curInset);
target.LayoutMargins = curInset;
}
}
private static UIStringAttributes GetStringAttributes (TextStyleParameters style)
{
var stringAttribs = new UIStringAttributes ();
var fontSize = style.FontSize;
if (fontSize <= 0f)
fontSize = DefaultTextSize;
if (!string.IsNullOrEmpty (style.Font))
stringAttribs.Font = UIFont.FromName (style.Font, fontSize);
if (!string.IsNullOrEmpty (style.Color))
stringAttribs.ForegroundColor = UIColor.Clear.FromHex (style.Color);
if (!string.IsNullOrEmpty (style.BackgroundColor))
stringAttribs.BackgroundColor = UIColor.Clear.FromHex (style.BackgroundColor);
if (style.LetterSpacing > 0f)
stringAttribs.KerningAdjustment = style.LetterSpacing;
// Does nothing on the string attribs, needs to be part of a NSMutableAttributedString
if (style.LineHeight != 0f) {
var paragraphStyle = new NSMutableParagraphStyle () {
LineHeightMultiple = style.LineHeight / fontSize,
Alignment = GetAlignment (style.TextAlign)
};
stringAttribs.ParagraphStyle = paragraphStyle;
}
if (style.TextDecoration != TextStyleDecoration.None) {
switch (style.TextDecoration) {
case TextStyleDecoration.LineThrough:
stringAttribs.StrikethroughStyle = NSUnderlineStyle.Single;
break;
case TextStyleDecoration.Underline:
stringAttribs.UnderlineStyle = NSUnderlineStyle.Single;
break;
}
if (!string.IsNullOrEmpty (style.TextDecorationColor))
stringAttribs.StrikethroughColor = UIColor.Clear.FromHex (style.TextDecorationColor);
}
return stringAttribs;
}
internal static NSAttributedString ParseHtmlString (TextStyleParameters style, string text)
{
var attribs = GetStringAttributes (style);
text = ParseString (style, text);
var prettyString = new NSMutableAttributedString (text);
prettyString.AddAttributes (attribs, new NSRange (0, text.Length));
return prettyString;
}
internal static string ParseString (TextStyleParameters style, string text)
{
// Text transformations
if (!string.IsNullOrEmpty (text)) {
if (style.TextTransform != TextStyleTextTransform.None) {
switch (style.TextTransform) {
case TextStyleTextTransform.UpperCase:
text = text.ToUpper ();
break;
case TextStyleTextTransform.LowerCase:
text = text.ToLower ();
break;
case TextStyleTextTransform.Capitalize:
text = CultureInfo.CurrentCulture.TextInfo.ToTitleCase (text.ToLower ());
break;
}
}
}
return text;
}
private static UITextAlignment GetAlignment (TextStyleAlign alignment)
{
switch (alignment) {
case TextStyleAlign.Left:
return UITextAlignment.Left;
case TextStyleAlign.Right:
return UITextAlignment.Right;
case TextStyleAlign.Center:
return UITextAlignment.Center;
case TextStyleAlign.Justified:
return UITextAlignment.Justified;
default:
return UITextAlignment.Left;
}
}
/// <summary>
/// Dummy method to ensure classes are included for the Linker
/// </summary>
/// <param name="injector">Injector.</param>
/// <param name="textView">Text view.</param>
/// <param name="textField">Text field.</param>
private void LinkerInclude (UILabel injector, UITextView textView, UITextField textField)
{
injector = new UILabel ();
textView = new UITextView ();
textField = new UITextField ();
}
#endregion
}
/// <summary>
/// Text attributes range.
/// </summary>
public class TextAttributesRange
{
public int StartIndex;
public int Length;
public string Text;
public UIStringAttributes Attributes;
}
}
| |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// Order Product Feed
///<para>SObject Name: OrderItemFeed</para>
///<para>Custom Object: False</para>
///</summary>
public class SfOrderItemFeed : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "OrderItemFeed"; }
}
///<summary>
/// Feed Item ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Parent ID
/// <para>Name: ParentId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "parentId")]
[Updateable(false), Createable(false)]
public string ParentId { get; set; }
///<summary>
/// ReferenceTo: OrderItem
/// <para>RelationshipName: Parent</para>
///</summary>
[JsonProperty(PropertyName = "parent")]
[Updateable(false), Createable(false)]
public SfOrderItem Parent { get; set; }
///<summary>
/// Feed Item Type
/// <para>Name: Type</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "type")]
[Updateable(false), Createable(false)]
public string Type { get; set; }
///<summary>
/// Created By ID
/// <para>Name: CreatedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdById")]
[Updateable(false), Createable(false)]
public string CreatedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: CreatedBy</para>
///</summary>
[JsonProperty(PropertyName = "createdBy")]
[Updateable(false), Createable(false)]
public SfUser CreatedBy { get; set; }
///<summary>
/// Created Date
/// <para>Name: CreatedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? CreatedDate { get; set; }
///<summary>
/// Deleted
/// <para>Name: IsDeleted</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isDeleted")]
[Updateable(false), Createable(false)]
public bool? IsDeleted { get; set; }
///<summary>
/// Last Modified Date
/// <para>Name: LastModifiedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastModifiedDate { get; set; }
///<summary>
/// System Modstamp
/// <para>Name: SystemModstamp</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "systemModstamp")]
[Updateable(false), Createable(false)]
public DateTimeOffset? SystemModstamp { get; set; }
///<summary>
/// Comment Count
/// <para>Name: CommentCount</para>
/// <para>SF Type: int</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "commentCount")]
[Updateable(false), Createable(false)]
public int? CommentCount { get; set; }
///<summary>
/// Like Count
/// <para>Name: LikeCount</para>
/// <para>SF Type: int</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "likeCount")]
[Updateable(false), Createable(false)]
public int? LikeCount { get; set; }
///<summary>
/// Title
/// <para>Name: Title</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "title")]
[Updateable(false), Createable(false)]
public string Title { get; set; }
///<summary>
/// Body
/// <para>Name: Body</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "body")]
[Updateable(false), Createable(false)]
public string Body { get; set; }
///<summary>
/// Link Url
/// <para>Name: LinkUrl</para>
/// <para>SF Type: url</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "linkUrl")]
[Updateable(false), Createable(false)]
public string LinkUrl { get; set; }
///<summary>
/// Is Rich Text
/// <para>Name: IsRichText</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isRichText")]
[Updateable(false), Createable(false)]
public bool? IsRichText { get; set; }
///<summary>
/// Related Record ID
/// <para>Name: RelatedRecordId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "relatedRecordId")]
[Updateable(false), Createable(false)]
public string RelatedRecordId { get; set; }
///<summary>
/// InsertedBy ID
/// <para>Name: InsertedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "insertedById")]
[Updateable(false), Createable(false)]
public string InsertedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: InsertedBy</para>
///</summary>
[JsonProperty(PropertyName = "insertedBy")]
[Updateable(false), Createable(false)]
public SfUser InsertedBy { get; set; }
///<summary>
/// Best Comment ID
/// <para>Name: BestCommentId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "bestCommentId")]
[Updateable(false), Createable(false)]
public string BestCommentId { get; set; }
///<summary>
/// ReferenceTo: FeedComment
/// <para>RelationshipName: BestComment</para>
///</summary>
[JsonProperty(PropertyName = "bestComment")]
[Updateable(false), Createable(false)]
public SfFeedComment BestComment { get; set; }
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Web.Mvc;
using System.Collections;
using System.Reflection;
using System.Web.Mvc.Html;
namespace MvcContrib.UI.Html
{
[Obsolete]
public static class ModelVisualizerExtension
{
/// <summary>
/// Snipped that allows the rendered table to be collapsed
/// </summary>
public static string HtmlContainer = @"
<div class=""ToHtmlTableContainer"" >
<div class=""ToHtmlTableClosedContainer"" style=""cursor: pointer"" >- Click to open model information
</div>
<div class=""ToHtmlTableOpenedContainer"">
<div class=""ToHtmlTableCloseText"" style=""cursor: pointer"" >
+ Click to close model information
</div>
<table border=1 >{0}</table></div></div>
";
public static string OpenCloseScript = @"
<script language=""javascript"" >
$(document).ready(function() {
setToHtmlControlHandlers();
defaultToHtmlUI();
});
function openToHtmlTable() {
$(this).parent().children("".ToHtmlTableOpenedContainer"").show();
$(this).hide();
}
function closeToHtmlTable() {
$(this).parent().hide();
$(this).parent().parent().children("".ToHtmlTableClosedContainer"").show();
}
//Events der Buttons registrieren
function setToHtmlControlHandlers() {
$("".ToHtmlTableClosedContainer"").bind('click', openToHtmlTable );
$("".ToHtmlTableCloseText"").bind('click', closeToHtmlTable);
}
function defaultToHtmlUI() {
$("".ToHtmlTableOpenedContainer"").hide();
$("".ToHtmlTableClosedContainer"").show();
}
</script> ";
/// <summary>
/// Renders Model as table
/// </summary>
/// <param name="htmlHelper"></param>
/// <returns></returns>
public static string ModelVisualizer(this HtmlHelper htmlHelper)
{
if (htmlHelper.ViewContext.ViewData.Model != null)
{
//render Model of strongly typed View
return ModelToHtmlTable(htmlHelper.ViewContext.ViewData.Model);
}
else
{
//render untyped ViewData collection
return ModelToHtmlTable(htmlHelper.ViewContext.ViewData);
}
}
/// <summary>
/// render items of SelectList (ie for DropDown)
/// </summary>
/// <param name="selectListToRender"></param>
/// <returns></returns>
private static string RenderSelectListTable(System.Collections.Generic.IEnumerable<SelectListItem> selectListToRender)
{
var result = new StringBuilder();
result.AppendFormat("<tr>");
result.AppendFormat(@"<td colspan=""3"">SelectList</td>");
result.AppendFormat("</tr>");
result.AppendFormat("<tr>");
result.AppendFormat("<td>Name</td>");
result.AppendFormat("<td>Value</td>");
result.AppendFormat("<td>Selected</td>");
result.AppendFormat("</tr>");
foreach (SelectListItem selectItem in selectListToRender)
{
result.AppendFormat("<tr>");
result.AppendFormat("<td>{0}</td>", HttpUtility.HtmlEncode(selectItem.Text));
result.AppendFormat("<td>{0}</td>", HttpUtility.HtmlEncode(selectItem.Value));
result.AppendFormat("<td>{0}</td>", selectItem.Selected ? "selected" : "");
result.AppendFormat("</tr>");
}
string retvalue = result.ToString();
retvalue = String.Format(HtmlContainer, retvalue);
return retvalue;
}
/// <summary>
/// Render properties of an object as table
/// </summary>
/// <param name="objectToRender"></param>
/// <returns></returns>
private static string RenderObjectTable(object objectToRender)
{
string result = @"<table border=""1"" >";
Type t = objectToRender.GetType();
result += @"<tr><td colspan=""2"" >" + t.ToString() + "</td></tr>";
Dictionary<string, object> dataDic = new Dictionary<string, object>();
foreach (System.Reflection.PropertyInfo pi in t.GetProperties())
{
dataDic.Add(pi.Name, pi.GetValue(objectToRender, null));
}
string rows = RenderDictionaryTable(dataDic);
result += rows;
result += "</table>";
return result;
}
/// <summary>
/// Render list of objects
/// </summary>
/// <param name="listToRender"></param>
/// <returns></returns>
private static string RenderGenericList(IEnumerable listToRender)
{
var result = new StringBuilder();
var propertyArray = new System.Reflection.PropertyInfo[0];
bool isFirstRow = true;
foreach (object listItem in listToRender)
{
if (isFirstRow)
{
propertyArray = listItem.GetType().GetProperties();
result.Append("<tr>");
foreach (PropertyInfo colObject in propertyArray)
{
result.AppendFormat("<td><b>{0}</b></td>", colObject.Name);
}
result.Append("</tr>");
isFirstRow = false;
}
result.Append("<tr>");
foreach (PropertyInfo colObject in propertyArray)
{
result.AppendFormat("<td>{0}</td>", colObject.GetValue(listItem, null));
}
result.Append("</tr>");
}
string htmlRows = result.ToString();
string completeTable = string.Format(HtmlContainer, htmlRows);
return completeTable;
}
/// <summary>
/// Framework types are rendered with "ToString"
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
static bool IsMicrosoftType(Type type)
{
object[] attrs = type.Assembly.GetCustomAttributes(typeof(AssemblyCompanyAttribute), false);
return attrs.OfType<AssemblyCompanyAttribute>().Any(attr => attr.Company == "Microsoft Corporation");
}
/// <summary>
/// Enables Rendering of typed Model and untyped ViewData
/// </summary>
/// <param name="viewData"></param>
/// <returns></returns>
static string RenderDictionaryTable(IDictionary<string, object> viewData)
{
var htmlRows = new StringBuilder();
foreach (string dictionaryKey in viewData.Keys.OrderBy(val => val).ToList())
{
object value = viewData[dictionaryKey];
htmlRows.AppendFormat("<tr>");
htmlRows.AppendFormat("<td>{0}</td>", HttpUtility.HtmlEncode(dictionaryKey));
if (value == null)
{
htmlRows.AppendFormat("<td>null</td>");
}
else if (value is Enum)
{
htmlRows.AppendFormat("<td>{0}</td>", value ?? String.Empty);
}
else if (!IsMicrosoftType(value.GetType()))
{
htmlRows.AppendFormat("<td>{0}</td>", RenderObjectTable(value));
}
else if (value is IEnumerable<System.Web.Mvc.SelectListItem>)
{
htmlRows.AppendFormat("<td>{0}</td>", RenderSelectListTable((IEnumerable<System.Web.Mvc.SelectListItem>)value));
}
else if (value.GetType().ToString().StartsWith("System.Collections.Generic.List"))
{
htmlRows.AppendFormat("<td>{0}</td>", RenderGenericList((IEnumerable)value));
}
else
{
htmlRows.AppendFormat("<td>{0}</td>", value ?? String.Empty);
}
htmlRows.AppendFormat("</tr>");
}
return htmlRows.ToString();
}
/// <summary>
/// render object as table
/// </summary>
/// <param name="objectToRender"></param>
/// <returns></returns>
private static string ModelToHtmlTable(object objectToRender)
{
var result = new StringBuilder();
result.Append(OpenCloseScript);
IDictionary<string, object> dataDic = null;
if (objectToRender is ViewDataDictionary)
{
//Handle untyped ViewData
dataDic = (IDictionary<string, object>)objectToRender;
}
else
{
//Handle Model of strongly typed View
dataDic = new Dictionary<string, object>();
var propertyArray = objectToRender.GetType().GetProperties();
foreach (var prop in propertyArray)
{
dataDic.Add(prop.Name, prop.GetValue(objectToRender, null));
}
}
string rows = "";
if (dataDic.Count > 0)
{
rows = RenderDictionaryTable(dataDic);
}
else
{
rows = "<tr><td>There is no data in ViewData</td></tr>";
}
string tableAndRows = string.Format(HtmlContainer, rows);
result.Append(tableAndRows);
string retvalue = result.ToString();
return retvalue;
}
}
}
| |
// 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.IO;
namespace DotSpatial.Data
{
/// <summary>
/// Stream extensions
/// </summary>
public static class StreamExt
{
#region Methods
/// <summary>
/// Attempts to read count of bytes from stream.
/// </summary>
/// <param name="stream">Input stream.</param>
/// <param name="count">Count of bytes.</param>
/// <returns>Bytes array.</returns>
public static byte[] ReadBytes(this Stream stream, int count)
{
var bytes = new byte[count];
stream.Read(bytes, 0, bytes.Length);
return bytes;
}
/// <summary>
/// Reads a double precision value from the stream. If this system
/// is not little endian, it will reverse the individual memebrs.
/// </summary>
/// <param name="stream">The stream to read the values from.</param>
/// <returns>A double precision value</returns>
public static double ReadDouble(this Stream stream)
{
return ReadDouble(stream, 1)[0];
}
/// <summary>
/// Reads the specified number of double precision values. If this system
/// does not match the specified endian, the bytes will be reversed.
/// </summary>
/// <param name="stream">The stream to read the values from.</param>
/// <param name="count">The integer count of doubles to read.</param>
/// <param name="endian">The endian to use.</param>
/// <returns>An array with the double values that were read.</returns>
public static double[] ReadDouble(this Stream stream, int count, Endian endian = Endian.LittleEndian)
{
var val = new byte[count * 8];
stream.Read(val, 0, count * 8);
if ((endian == Endian.LittleEndian) != BitConverter.IsLittleEndian)
{
for (var i = 0; i < count; i++)
{
var temp = new byte[8];
Array.Copy(val, i * 8, temp, 0, 8);
Array.Reverse(temp);
Array.Copy(temp, 0, val, i * 8, 8);
}
}
var result = new double[count];
Buffer.BlockCopy(val, 0, result, 0, count * 8);
return result;
}
/// <summary>
/// Attempts to read the specified T. If this system is
/// doesn't match the specified endian, then this will reverse the array of bytes,
/// so that it corresponds with the big-endian format.
/// </summary>
/// <param name="stream">The stream to read the value from</param>
/// <param name="endian">Specifies what endian property should be used.</param>
/// <returns>The integer value</returns>
public static int ReadInt32(this Stream stream, Endian endian = Endian.LittleEndian)
{
var val = new byte[4];
stream.Read(val, 0, 4);
if ((endian == Endian.LittleEndian) != BitConverter.IsLittleEndian)
{
Array.Reverse(val);
}
return BitConverter.ToInt32(val, 0);
}
/// <summary>
/// Reads the specified number of integers. If a value other than the
/// systems endian format is specified the values will be reversed.
/// </summary>
/// <param name="stream">The stream to read from</param>
/// <param name="count">The integer count of integers to read</param>
/// <param name="endian">The endian order of the bytes.</param>
/// <returns>The array of integers that will have count integers.</returns>
public static int[] ReadInt32(this Stream stream, int count, Endian endian = Endian.LittleEndian)
{
var result = new int[count];
var val = new byte[4 * count];
stream.Read(val, 0, val.Length);
if ((endian == Endian.LittleEndian) != BitConverter.IsLittleEndian)
{
for (var i = 0; i < count; i++)
{
var temp = new byte[4];
Array.Copy(val, i * 4, temp, 0, 4);
Array.Reverse(temp);
Array.Copy(temp, 0, val, i * 4, 4);
}
}
Buffer.BlockCopy(val, 0, result, 0, count * 4);
return result;
}
/// <summary>
/// Writes the specified integer value to the stream as big endian.
/// </summary>
/// <param name="stream">The stream to write to.</param>
/// <param name="value">The integer value to write in big endian form.</param>
public static void WriteBe(this Stream stream, int value)
{
var val = BitConverter.GetBytes(value);
if (BitConverter.IsLittleEndian) Array.Reverse(val);
stream.Write(val, 0, 4);
}
/// <summary>
/// Writes the specified integer value to the stream as little endian.
/// </summary>
/// <param name="stream">The stream to write to.</param>
/// <param name="value">The integer value to write in little endian form.</param>
public static void WriteLe(this Stream stream, int value)
{
var val = BitConverter.GetBytes(value);
if (!BitConverter.IsLittleEndian) Array.Reverse(val);
stream.Write(val, 0, 4);
}
/// <summary>
/// Checks that the endian order is ok for integers and then writes the number of array items
/// that are defined by startIndex and count to the stream.
/// </summary>
/// <param name="stream">The stream to write to.</param>
/// <param name="values">The integer values to write in little endian form.</param>
/// <param name="startIndex">The integer start index in the integer array to begin writing.</param>
/// <param name="count">The integer count of integer to write.</param>
public static void WriteLe(this Stream stream, int[] values, int startIndex, int count)
{
var bytes = new byte[count * 4];
Buffer.BlockCopy(values, startIndex * 4, bytes, 0, bytes.Length);
if (!BitConverter.IsLittleEndian)
{
// Reverse to little endian if this is a big endian machine
var temp = bytes;
bytes = new byte[temp.Length];
Array.Reverse(temp);
for (var i = 0; i < count; i++)
{
Array.Copy(temp, i * 4, bytes, (count - i - 1) * 4, 4);
}
}
stream.Write(bytes, 0, bytes.Length);
}
/// <summary>
/// Writes the specified double value to the stream as little endian.
/// </summary>
/// <param name="stream">The stream to write to.</param>
/// <param name="value">The double value to write in little endian form.</param>
public static void WriteLe(this Stream stream, double value)
{
var val = BitConverter.GetBytes(value);
if (!BitConverter.IsLittleEndian) Array.Reverse(val);
stream.Write(val, 0, 8);
}
/// <summary>
/// Checks that the endian order is ok for doubles and then writes the entire array to the stream.
/// </summary>
/// <param name="stream">The stream to write to.</param>
/// <param name="values">The double values to write in little endian form.</param>
public static void WriteLe(this Stream stream, double[] values)
{
WriteLe(stream, values, 0, values.Length);
}
/// <summary>
/// Checks that the endian order is ok for doubles and then writes the number of array items
/// that are defined by startIndex and count to the stream.
/// </summary>
/// <param name="stream">The stream to write to.</param>
/// <param name="values">The double values to write in little endian form.</param>
/// <param name="startIndex">The integer start index in the double array to begin writing.</param>
/// <param name="count">The integer count of doubles to write.</param>
public static void WriteLe(this Stream stream, double[] values, int startIndex, int count)
{
var bytes = new byte[count * 8];
Buffer.BlockCopy(values, startIndex * 8, bytes, 0, bytes.Length);
if (!BitConverter.IsLittleEndian)
{
// Reverse to little endian if this is a big endian machine
var temp = bytes;
bytes = new byte[temp.Length];
Array.Reverse(temp);
for (var i = 0; i < count; i++)
{
Array.Copy(temp, i * 8, bytes, (count - i - 1) * 8, 8);
}
}
stream.Write(bytes, 0, bytes.Length);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Util;
namespace GCMSharp.Client
{
public class GCMRegistrar
{
const string TAG = "GCMRegistrar";
const string BACKOFF_MS = "backoff_ms";
const string GSF_PACKAGE = "com.google.android.gsf";
const string PREFERENCES = "com.google.android.gcm";
const int DEFAULT_BACKOFF_MS = 3000;
const string PROPERTY_REG_ID = "regId";
const string PROPERTY_APP_VERSION = "appVersion";
const string PROPERTY_ON_SERVER = "onServer";
static GCMBroadcastReceiver sRetryReceiver;
public static void CheckDevice(Context context)
{
var version = (int)Build.VERSION.SdkInt;
if (version < 8)
throw new InvalidOperationException("Device must be at least API Level 8 (instead of " + version + ")");
var packageManager = context.PackageManager;
try
{
packageManager.GetPackageInfo(GSF_PACKAGE, (Android.Content.PM.PackageInfoFlags)0);
}
catch
{
throw new InvalidOperationException("Device does not have package " + GSF_PACKAGE);
}
}
public static void CheckManifest(Context context)
{
var packageManager = context.PackageManager;
var packageName = context.PackageName;
var permissionName = packageName + ".permission.C2D_MESSAGE";
try
{
packageManager.GetPermissionInfo(permissionName, Android.Content.PM.PackageInfoFlags.Permissions);
}
catch
{
throw new AccessViolationException("Application does not define permission: " + permissionName);
}
Android.Content.PM.PackageInfo receiversInfo;
try
{
receiversInfo = packageManager.GetPackageInfo(packageName, Android.Content.PM.PackageInfoFlags.Receivers);
}
catch
{
throw new InvalidOperationException("Could not get receivers for package " + packageName);
}
var receivers = receiversInfo.Receivers;
if (receivers == null || receivers.Count <= 0)
throw new InvalidOperationException("No Receiver for package " + packageName);
if (Log.IsLoggable(TAG, LogPriority.Verbose))
Log.Verbose(TAG, "number of receivers for " + packageName + ": " + receivers.Count);
var allowedReceivers = new HashSet<string>();
foreach (var receiver in receivers)
{
if (GCMConstants.PERMISSION_GCM_INTENTS.Equals(receiver.Permission))
allowedReceivers.Add(receiver.Name);
}
if (allowedReceivers.Count <= 0)
throw new InvalidOperationException("No receiver allowed to receive " + GCMConstants.PERMISSION_GCM_INTENTS);
CheckReceiver(context, allowedReceivers, GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK);
CheckReceiver(context, allowedReceivers, GCMConstants.INTENT_FROM_GCM_MESSAGE);
}
private static void CheckReceiver(Context context, HashSet<string> allowedReceivers, string action)
{
var pm = context.PackageManager;
var packageName = context.PackageName;
var intent = new Intent(action);
intent.SetPackage(packageName);
var receivers = pm.QueryBroadcastReceivers(intent, Android.Content.PM.PackageInfoFlags.IntentFilters);
if (receivers == null || receivers.Count <= 0)
throw new InvalidOperationException("No receivers for action " + action);
if (Log.IsLoggable(TAG, LogPriority.Verbose))
Log.Verbose(TAG, "Found " + receivers.Count + " receivers for action " + action);
foreach (var receiver in receivers)
{
var name = receiver.ActivityInfo.Name;
if (!allowedReceivers.Contains(name))
throw new InvalidOperationException("Receiver " + name + " is not set with permission " + GCMConstants.PERMISSION_GCM_INTENTS);
}
}
public static void Register(Context context, params string[] senderIds)
{
SetRetryBroadcastReceiver(context);
ResetBackoff(context);
internalRegister(context, senderIds);
}
internal static void internalRegister(Context context, params string[] senderIds)
{
if (senderIds == null || senderIds.Length <= 0)
throw new ArgumentException("No senderIds");
var senders = string.Join(",", senderIds);
Log.Verbose(TAG, "Registering app " + context.PackageName + " of senders " + senders);
var intent = new Intent(GCMConstants.INTENT_TO_GCM_REGISTRATION);
intent.SetPackage(GSF_PACKAGE);
intent.PutExtra(GCMConstants.EXTRA_APPLICATION_PENDING_INTENT,
PendingIntent.GetBroadcast(context, 0, new Intent(), 0));
intent.PutExtra(GCMConstants.EXTRA_SENDER, senders);
context.StartService(intent);
}
public static void UnRegister(Context context)
{
SetRetryBroadcastReceiver(context);
ResetBackoff(context);
internalUnRegister(context);
}
internal static void internalUnRegister(Context context)
{
Log.Verbose(TAG, "Unregistering app " + context.PackageName);
var intent = new Intent(GCMConstants.INTENT_TO_GCM_UNREGISTRATION);
intent.SetPackage(GSF_PACKAGE);
intent.PutExtra(GCMConstants.EXTRA_APPLICATION_PENDING_INTENT,
PendingIntent.GetBroadcast(context, 0, new Intent(), 0));
context.StartService(intent);
}
static void SetRetryBroadcastReceiver(Context context)
{
if (sRetryReceiver == null)
{
sRetryReceiver = new GCMBroadcastReceiver();
var category = context.PackageName;
var filter = new IntentFilter(GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY);
filter.AddCategory(category);
var permission = category + ".permission.C2D_MESSAGE";
Log.Verbose(TAG, "Registering receiver");
context.RegisterReceiver(sRetryReceiver, filter, permission, null);
}
}
public static string GetRegistrationId(Context context)
{
var prefs = GetGCMPreferences(context);
var registrationId = prefs.GetString(PROPERTY_REG_ID, "");
int oldVersion = prefs.GetInt(PROPERTY_APP_VERSION, int.MinValue);
int newVersion = GetAppVersion(context);
if (oldVersion != int.MinValue && oldVersion != newVersion)
{
Log.Verbose(TAG, "App version changed from " + oldVersion + " to " + newVersion + "; resetting registration id");
ClearRegistrationId(context);
}
return registrationId;
}
public static bool IsRegistered(Context context)
{
var registrationId = GetRegistrationId(context);
return !string.IsNullOrEmpty(registrationId);
}
internal static string ClearRegistrationId(Context context)
{
return SetRegistrationId(context, "");
}
internal static string SetRegistrationId(Context context, string registrationId)
{
var prefs = GetGCMPreferences(context);
var oldRegistrationId = prefs.GetString(PROPERTY_REG_ID, "");
int appVersion = GetAppVersion(context);
Log.Verbose(TAG, "Saving registrationId on app version " + appVersion);
var editor = prefs.Edit();
editor.PutString(PROPERTY_REG_ID, registrationId);
editor.PutInt(PROPERTY_APP_VERSION, appVersion);
editor.Commit();
return oldRegistrationId;
}
public static void SetRegisteredOnServer(Context context, bool flag)
{
var prefs = GetGCMPreferences(context);
Log.Verbose(TAG, "Setting registered on server status as: " + flag);
var editor = prefs.Edit();
editor.PutBoolean(PROPERTY_ON_SERVER, flag);
editor.Commit();
}
public static bool IsRegisteredOnServer(Context context)
{
var prefs = GetGCMPreferences(context);
bool isRegistered = prefs.GetBoolean(PROPERTY_ON_SERVER, false);
Log.Verbose(TAG, "Is registered on server: " + isRegistered);
return isRegistered;
}
static int GetAppVersion(Context context)
{
try
{
var packageInfo = context.PackageManager.GetPackageInfo(context.PackageName, 0);
return packageInfo.VersionCode;
}
catch
{
throw new InvalidOperationException("Could not get package name");
}
}
internal static void ResetBackoff(Context context)
{
Log.Debug(TAG, "resetting backoff for " + context.PackageName);
SetBackoff(context, DEFAULT_BACKOFF_MS);
}
internal static int GetBackoff(Context context)
{
var prefs = GetGCMPreferences(context);
return prefs.GetInt(BACKOFF_MS, DEFAULT_BACKOFF_MS);
}
internal static void SetBackoff(Context context, int backoff)
{
var prefs = GetGCMPreferences(context);
var editor = prefs.Edit();
editor.PutInt(BACKOFF_MS, backoff);
editor.Commit();
}
static ISharedPreferences GetGCMPreferences(Context context)
{
return context.GetSharedPreferences(PREFERENCES, FileCreationMode.Private);
}
}
}
| |
// #define DEBUG_LABELS
// #define DEBUG_AXIS_TITLE
using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
namespace WalletWasabi.Fluent.Controls
{
public partial class LineChart : Control
{
public LineChart()
{
AddHandler(PointerPressedEvent, PointerPressedHandler, RoutingStrategies.Tunnel);
AddHandler(PointerReleasedEvent, PointerReleasedHandler, RoutingStrategies.Tunnel);
AddHandler(PointerMovedEvent, PointerMovedHandler, RoutingStrategies.Tunnel);
AddHandler(PointerLeaveEvent, PointerLeaveHandler, RoutingStrategies.Tunnel);
}
private static double Clamp(double val, double min, double max)
{
return Math.Min(Math.Max(val, min), max);
}
private static double ScaleHorizontal(double value, double max, double range)
{
return value / max * range;
}
private static double ScaleVertical(double value, double max, double range)
{
return range - value / max * range;
}
private static Geometry CreateFillGeometry(IReadOnlyList<Point> points, double width, double height)
{
var geometry = new StreamGeometry();
using var context = geometry.Open();
context.BeginFigure(points[0], true);
for (var i = 1; i < points.Count; i++)
{
context.LineTo(points[i]);
}
context.LineTo(new Point(width, height));
context.LineTo(new Point(0, height));
context.EndFigure(true);
return geometry;
}
private static Geometry CreateStrokeGeometry(IReadOnlyList<Point> points)
{
var geometry = new StreamGeometry();
using var context = geometry.Open();
context.BeginFigure(points[0], false);
for (var i = 1; i < points.Count; i++)
{
context.LineTo(points[i]);
}
context.EndFigure(false);
return geometry;
}
private static FormattedText CreateFormattedText(string text, Typeface typeface, TextAlignment alignment, double fontSize, Size constraint)
{
return new FormattedText()
{
Typeface = typeface,
Text = text,
TextAlignment = alignment,
TextWrapping = TextWrapping.NoWrap,
FontSize = fontSize,
Constraint = constraint
};
}
private void UpdateCursorPosition(double x)
{
var rangeValues = XAxisMaxValue - XAxisMinValue;
var rangeArea = Bounds.Width - AreaMargin.Left - AreaMargin.Right;
var value = Clamp(x - AreaMargin.Left, 0, rangeArea);
XAxisCurrentValue = XAxisMaxValue - rangeValues / rangeArea * value;
}
private Rect GetCursorHitTestRect()
{
var chartWidth = Bounds.Width;
var chartHeight = Bounds.Height;
var areaMargin = AreaMargin;
var areaWidth = chartWidth - areaMargin.Left - areaMargin.Right;
var areaHeight = chartHeight - areaMargin.Top - areaMargin.Bottom;
var areaRect = new Rect(areaMargin.Left, areaMargin.Top, areaWidth, areaHeight);
var cursorValue = XAxisCurrentValue;
var cursorPosition = ScaleHorizontal(XAxisMaxValue - cursorValue, XAxisMaxValue, areaWidth);
var cursorHitTestSize = 5;
var cursorStrokeThickness = CursorStrokeThickness;
var cursorHitTestRect = new Rect(
areaMargin.Left + cursorPosition - cursorHitTestSize + cursorStrokeThickness / 2,
areaRect.Top,
cursorHitTestSize + cursorHitTestSize,
areaRect.Height);
return cursorHitTestRect;
}
private void PointerLeaveHandler(object? sender, PointerEventArgs e)
{
Cursor = new Cursor(StandardCursorType.Arrow);
}
private void PointerMovedHandler(object? sender, PointerEventArgs e)
{
var position = e.GetPosition(this);
if (_captured)
{
UpdateCursorPosition(position.X);
}
else
{
if (CursorStroke is null)
{
return;
}
var cursorHitTestRect = GetCursorHitTestRect();
var cursorSizeWestEast = cursorHitTestRect.Contains(position);
Cursor = cursorSizeWestEast ?
new Cursor(StandardCursorType.SizeWestEast)
: new Cursor(StandardCursorType.Arrow);
}
}
private void PointerReleasedHandler(object? sender, PointerReleasedEventArgs e)
{
if (_captured)
{
var position = e.GetPosition(this);
var cursorHitTestRect = GetCursorHitTestRect();
var cursorSizeWestEast = cursorHitTestRect.Contains(position);
if (!cursorSizeWestEast)
{
Cursor = new Cursor(StandardCursorType.Arrow);
}
_captured = false;
}
}
private void PointerPressedHandler(object? sender, PointerPressedEventArgs e)
{
var position = e.GetPosition(this);
UpdateCursorPosition(position.X);
Cursor = new Cursor(StandardCursorType.SizeWestEast);
_captured = true;
}
private LineChartState CreateChartState(double width, double height)
{
var state = new LineChartState();
state.ChartWidth = width;
state.ChartHeight = height;
state.AreaMargin = AreaMargin;
state.AreaWidth = width - state.AreaMargin.Left - state.AreaMargin.Right;
state.AreaHeight = height - state.AreaMargin.Top - state.AreaMargin.Bottom;
var values = YAxisValues;
if (values is not null)
{
var logarithmicScale = YAxisLogarithmicScale;
var valuesList = logarithmicScale
? values.Select(y => Math.Log(y)).ToList()
: values.ToList();
var valuesListMax = valuesList.Max();
var scaledValues = valuesList
.Select(y => ScaleVertical(y, valuesListMax, state.AreaHeight))
.ToList();
state.Step = state.AreaWidth / (scaledValues.Count - 1);
state.Points = new Point[scaledValues.Count];
for (var i = 0; i < scaledValues.Count; i++)
{
state.Points[i] = new Point(i * state.Step, scaledValues[i]);
}
}
var labels = XAxisLabels;
if (labels is not null)
{
state.XLabels = labels.ToList();
}
var minValue = XAxisMinValue;
var maxValue = XAxisMaxValue;
var cursorValue = XAxisCurrentValue;
state.CursorPosition = ScaleHorizontal(maxValue - cursorValue, maxValue, state.AreaWidth);
return state;
}
private void DrawAreaFill(DrawingContext context, LineChartState state)
{
if (state.Points is null)
{
return;
}
var brush = AreaFill;
if (brush is null)
{
return;
}
if (state.AreaWidth <= 0
|| state.AreaHeight <= 0
|| state.AreaWidth < AreaMinViableWidth
|| state.AreaHeight < AreaMinViableHeight)
{
return;
}
var deflate = 0.5;
var geometry = CreateFillGeometry(state.Points, state.AreaWidth, state.AreaHeight);
var transform = context.PushPreTransform(
Matrix.CreateTranslation(
state.AreaMargin.Left + deflate,
state.AreaMargin.Top + deflate));
context.DrawGeometry(brush, null, geometry);
transform.Dispose();
}
private void DrawAreaStroke(DrawingContext context, LineChartState state)
{
if (state.Points is null)
{
return;
}
var brush = AreaStroke;
if (brush is null)
{
return;
}
if (state.AreaWidth <= 0
|| state.AreaHeight <= 0
|| state.AreaWidth < AreaMinViableWidth
|| state.AreaHeight < AreaMinViableHeight)
{
return;
}
var thickness = AreaStrokeThickness;
var dashStyle = AreaStrokeDashStyle;
var lineCap = AreaStrokeLineCap;
var lineJoin = AreaStrokeLineJoin;
var miterLimit = AreaStrokeMiterLimit;
var pen = new Pen(brush, thickness, dashStyle, lineCap, lineJoin, miterLimit);
var deflate = thickness * 0.5;
var geometry = CreateStrokeGeometry(state.Points);
var transform = context.PushPreTransform(
Matrix.CreateTranslation(
state.AreaMargin.Left + deflate,
state.AreaMargin.Top + deflate));
context.DrawGeometry(null, pen, geometry);
transform.Dispose();
}
private void DrawCursor(DrawingContext context, LineChartState state)
{
var brush = CursorStroke;
if (brush is null)
{
return;
}
if (state.AreaWidth <= 0
|| state.AreaHeight <= 0
|| state.AreaWidth < AreaMinViableWidth
|| state.AreaHeight < AreaMinViableHeight)
{
return;
}
var thickness = CursorStrokeThickness;
var dashStyle = CursorStrokeDashStyle;
var lineCap = CursorStrokeLineCap;
var lineJoin = CursorStrokeLineJoin;
var miterLimit = CursorStrokeMiterLimit;
var pen = new Pen(brush, thickness, dashStyle, lineCap, lineJoin, miterLimit);
var deflate = thickness * 0.5;
var p1 = new Point(state.CursorPosition + deflate, 0);
var p2 = new Point(state.CursorPosition + deflate, state.AreaHeight);
var transform = context.PushPreTransform(
Matrix.CreateTranslation(
state.AreaMargin.Left,
state.AreaMargin.Top));
context.DrawLine(pen, p1, p2);
transform.Dispose();
}
private void DrawXAxis(DrawingContext context, LineChartState state)
{
var brush = XAxisStroke;
if (brush is null)
{
return;
}
if (state.AreaWidth <= 0
|| state.AreaHeight <= 0
|| state.AreaWidth < XAxisMinViableWidth
|| state.AreaHeight < XAxisMinViableHeight)
{
return;
}
var size = XAxisArrowSize;
var opacity = XAxisOpacity;
var thickness = XAxisStrokeThickness;
var pen = new Pen(brush, thickness, null, PenLineCap.Round, PenLineJoin.Miter, 10.0);
var deflate = thickness * 0.5;
var offset = XAxisOffset;
var p1 = new Point(
state.AreaMargin.Left + offset.X,
state.AreaMargin.Top + state.AreaHeight + offset.Y + deflate);
var p2 = new Point(
state.AreaMargin.Left + state.AreaWidth,
state.AreaMargin.Top + state.AreaHeight + offset.Y + deflate);
var opacityState = context.PushOpacity(opacity);
context.DrawLine(pen, p1, p2);
var p3 = new Point(p2.X, p2.Y);
var p4 = new Point(p2.X - size, p2.Y - size);
context.DrawLine(pen, p3, p4);
var p5 = new Point(p2.X, p2.Y);
var p6 = new Point(p2.X - size, p2.Y + size);
context.DrawLine(pen, p5, p6);
opacityState.Dispose();
}
private void DrawXAxisLabels(DrawingContext context, LineChartState state)
{
if (state.XLabels is null)
{
return;
}
var foreground = XAxisLabelForeground;
if (foreground is null)
{
return;
}
var opacity = XAxisLabelOpacity;
var fontFamily = XAxisLabelFontFamily;
var fontStyle = XAxisLabelFontStyle;
var fontWeight = XAxisLabelFontWeight;
var typeface = new Typeface(fontFamily, fontStyle, fontWeight);
var fontSize = XAxisLabelFontSize;
var offset = XAxisLabelOffset;
var size = XAxisLabelSize;
var angleRadians = Math.PI / 180.0 * XAxisLabelAngle;
var alignment = XAxisLabelAlignment;
var originTop = state.AreaHeight + state.AreaMargin.Top;
var offsetTransform = context.PushPreTransform(Matrix.CreateTranslation(offset.X, offset.Y));
for (var i = 0; i < state.XLabels.Count; i++)
{
var origin = new Point(i * state.Step - size.Width / 2 + state.AreaMargin.Left, originTop);
var constraint = new Size(size.Width, size.Height);
var formattedText = CreateFormattedText(state.XLabels[i], typeface, alignment, fontSize, constraint);
var xPosition = origin.X + size.Width / 2;
var yPosition = origin.Y + size.Height / 2;
var matrix = Matrix.CreateTranslation(-xPosition, -yPosition)
* Matrix.CreateRotation(angleRadians)
* Matrix.CreateTranslation(xPosition, yPosition);
var labelTransform = context.PushPreTransform(matrix);
var offsetCenter = new Point(0, size.Height / 2 - formattedText.Bounds.Height / 2);
var opacityState = context.PushOpacity(opacity);
context.DrawText(foreground, origin + offsetCenter, formattedText);
#if DEBUG_LABELS
context.DrawRectangle(null, new Pen(new SolidColorBrush(Colors.Magenta)), new Rect(origin, constraint));
#endif
opacityState.Dispose();
labelTransform.Dispose();
#if DEBUG_LABELS
context.DrawRectangle(null, new Pen(new SolidColorBrush(Colors.Cyan)), new Rect(origin, constraint));
#endif
}
offsetTransform.Dispose();
}
private void DrawYAxis(DrawingContext context, LineChartState state)
{
var brush = YAxisStroke;
if (brush is null)
{
return;
}
if (state.AreaWidth <= 0
|| state.AreaHeight <= 0
|| state.AreaWidth < YAxisMinViableWidth
|| state.AreaHeight < YAxisMinViableHeight)
{
return;
}
var size = YAxisArrowSize;
var opacity = YAxisOpacity;
var thickness = YAxisStrokeThickness;
var pen = new Pen(brush, thickness, null, PenLineCap.Round, PenLineJoin.Miter, 10.0);
var deflate = thickness * 0.5;
var offset = YAxisOffset;
var p1 = new Point(
state.AreaMargin.Left + offset.X + deflate,
state.AreaMargin.Top);
var p2 = new Point(
state.AreaMargin.Left + offset.X + deflate,
state.AreaMargin.Top + state.AreaHeight + offset.Y);
var opacityState = context.PushOpacity(opacity);
context.DrawLine(pen, p1, p2);
var p3 = new Point(p1.X, p1.Y);
var p4 = new Point(p1.X - size, p1.Y + size);
context.DrawLine(pen, p3, p4);
var p5 = new Point(p1.X, p1.Y);
var p6 = new Point(p1.X + size, p1.Y + size);
context.DrawLine(pen, p5, p6);
opacityState.Dispose();
}
private void DrawYAxisTitle(DrawingContext context, LineChartState state)
{
var foreground = YAxisTitleForeground;
if (foreground is null)
{
return;
}
if (state.AreaWidth <= 0
|| state.AreaHeight <= 0
|| state.AreaWidth < YAxisMinViableWidth
|| state.AreaHeight < YAxisMinViableHeight)
{
return;
}
var opacity = YAxisTitleOpacity;
var fontFamily = YAxisTitleFontFamily;
var fontStyle = YAxisTitleFontStyle;
var fontWeight = YAxisTitleFontWeight;
var typeface = new Typeface(fontFamily, fontStyle, fontWeight);
var fontSize = YAxisTitleFontSize;
var offset = YAxisTitleOffset;
var size = YAxisTitleSize;
var angleRadians = Math.PI / 180.0 * YAxisTitleAngle;
var alignment = YAxisTitleAlignment;
var offsetTransform = context.PushPreTransform(Matrix.CreateTranslation(offset.X, offset.Y));
var origin = new Point(state.AreaMargin.Left, state.AreaHeight + state.AreaMargin.Top);
var constraint = new Size(size.Width, size.Height);
var formattedText = CreateFormattedText(YAxisTitle, typeface, alignment, fontSize, constraint);
var xPosition = origin.X + size.Width / 2;
var yPosition = origin.Y + size.Height / 2;
var matrix = Matrix.CreateTranslation(-xPosition, -yPosition)
* Matrix.CreateRotation(angleRadians)
* Matrix.CreateTranslation(xPosition, yPosition);
var labelTransform = context.PushPreTransform(matrix);
var offsetCenter = new Point(0, size.Height / 2 - formattedText.Bounds.Height / 2);
var opacityState = context.PushOpacity(opacity);
context.DrawText(foreground, origin + offsetCenter, formattedText);
#if DEBUG_AXIS_TITLE
context.DrawRectangle(null, new Pen(new SolidColorBrush(Colors.Magenta)), new Rect(origin, constraint));
#endif
opacityState.Dispose();
labelTransform.Dispose();
#if DEBUG_AXIS_TITLE
context.DrawRectangle(null, new Pen(new SolidColorBrush(Colors.Cyan)), new Rect(origin, constraint));
#endif
offsetTransform.Dispose();
}
private void DrawBorder(DrawingContext context, LineChartState state)
{
var brush = BorderBrush;
if (brush is null)
{
return;
}
if (state.AreaWidth <= 0 || state.AreaHeight <= 0)
{
return;
}
var thickness = BorderThickness;
var radiusX = BorderRadiusX;
var radiusY = BorderRadiusY;
var pen = new Pen(brush, thickness, null, PenLineCap.Round, PenLineJoin.Miter, 10.0);
var rect = new Rect(0, 0, state.ChartWidth, state.ChartHeight);
var rectDeflate = rect.Deflate(thickness * 0.5);
context.DrawRectangle(Brushes.Transparent, pen, rectDeflate, radiusX, radiusY);
}
public override void Render(DrawingContext context)
{
base.Render(context);
var state = CreateChartState(Bounds.Width, Bounds.Height);
DrawAreaFill(context, state);
DrawAreaStroke(context, state);
DrawCursor(context, state);
DrawXAxis(context, state);
DrawYAxis(context, state);
DrawYAxisTitle(context, state);
DrawXAxisLabels(context, state);
DrawBorder(context, state);
}
private class LineChartState
{
public double ChartWidth { get; set; }
public double ChartHeight { get; set; }
public double AreaWidth { get; set; }
public double AreaHeight { get; set; }
public Thickness AreaMargin { get; set; }
public Point[]? Points { get; set; }
public List<string>? XLabels { get; set; }
public double Step { get; set; }
public double CursorPosition { get; set; }
}
}
}
| |
//
// Copyright (C) 2008 Jordi Mas i Hernandez, jmas@softcatala.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.IO;
using System.Text;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Xml.Serialization;
using Mono.Unix;
using Gdk;
using Mistelix;
using Mistelix.Core;
using Mistelix.Backends;
namespace Mistelix.DataModel
{
// Container for an authoring project and its elements
public class Project
{
List <ProjectElement> elements;
ObservableList <ButtonProjectElement> buttons;
public ProjectDetails details;
public Project ()
{
// Default projects
details = new ProjectDetails ();
buttons = new ObservableList <ButtonProjectElement> ();
elements = new List <ProjectElement> ();
}
public List <ProjectElement> Elements {
get { return elements;}
}
public ObservableList <ButtonProjectElement> Buttons {
get { return buttons;}
}
public bool AudioSupportedFormat (out string msg)
{
SlideShow slide;
foreach (ProjectElement element in Elements)
{
slide = element as SlideShow;
if (slide == null)
continue;
if (slide.AudioSupportedFormat (out msg) == false)
return false;
}
msg = string.Empty;
return true;
}
public string FileToFullPath (string file)
{
return Path.Combine (details.OutputDir, file);
}
// TODO: Think how this relates to Visible elements and to be export to other formats & extensibility
// Returns a list of project elements that require processing (currently elements involving video)
public List <ProjectElement> ElementsGenerate {
get {
List <ProjectElement> generate = new List <ProjectElement> ();
foreach (ProjectElement element in Elements)
{
if ((typeof (SlideShow) != element.GetType ()) &&
(typeof (Video) != element.GetType ()))
continue;
generate.Add (element);
}
return generate;
}
}
public ProjectDetails Details {
get { return details;}
}
public VisibleProjectElement ElementFromID (int id)
{
// This a linear search at the cost of O(N) but very few elements are expected
foreach (VisibleProjectElement elem in elements)
{
if (elem.id == id)
return elem;
}
throw new ArgumentException ("VisibleProjectElement.ElementFromID: ID not found");
}
public void AddElement (VisibleProjectElement element)
{
// It is not necessary to reflect the ID in the object passed (passed by value)
element.id = details.NextID;
details.IncreaseNextID ();
elements.Add (element);
}
public void RemoveElement (VisibleProjectElement element)
{
int id = element.id;
foreach (Button button in buttons)
{
if (button.LinkedId == id) {
Logger.Debug ("Project.RemoveElement. Deleting button {0}", button.LinkedId);
RemoveButton (button);
break;
}
}
Logger.Debug ("Project.RemoveElement. Deleting element {0}", element.id);
elements.Remove (element);
}
public void AddButton (ButtonProjectElement element)
{
buttons.Add (element);
}
public void RemoveButton (ButtonProjectElement element)
{
buttons.Remove (element);
}
void Clear ()
{
elements.Clear ();
buttons.Clear ();
}
public void Load (string file)
{
XmlStorage ps = new XmlStorage ();
List <VideoProjectElement> videos = new List <VideoProjectElement> ();
List <SlideShowProjectElement> slides = new List <SlideShowProjectElement> ();
List <ButtonProjectElement> bts = new List <ButtonProjectElement> ();
Logger.Debug ("Project.Load. Loading project {0}", file);
ps.Load (file);
Clear ();
ps.Get <ProjectDetails> ("details", ref details);
ps.Get <List <ButtonProjectElement>> ("buttons", ref bts);
ps.Get <List <VideoProjectElement>> ("videos", ref videos);
ps.Get <List <SlideShowProjectElement>> ("slides", ref slides);
details.Filename = file; // After the details have been loaded
foreach (Video video in videos)
elements.Add (video);
foreach (SlideShow slide in slides)
elements.Add (slide);
foreach (Button button in bts)
buttons.Add (button);
Logger.Debug ("Project.Load. Loaded {0} - {1} elements", Details.Filename, elements.Count);
}
public void Save (string file)
{
XmlStorage ps = new XmlStorage ();
ps.New ("project");
ps.Add (details, "details");
details.Filename = file;
//
// Save elements in separate arrays classified by type
//
List <VideoProjectElement> videos = new List <VideoProjectElement> ();
List <SlideShowProjectElement> slides = new List <SlideShowProjectElement> ();
List <ButtonProjectElement> bts = new List <ButtonProjectElement> ();
for (int i = 0; i < Elements.Count; i++)
{
if (typeof (Video) == Elements[i].GetType ()) {
videos.Add ((VideoProjectElement)Elements [i]);
continue;
}
if (typeof (SlideShow) == Elements[i].GetType ()) {
slides.Add ((SlideShowProjectElement) Elements [i]);
continue;
}
Logger.Debug ("Project.Save. Skipping {0}", Elements[i].GetType ());
}
foreach (Button button in Buttons)
bts.Add (button);
ps.Add (videos, "videos");
ps.Add (slides, "slides");
ps.Add (bts, "buttons");
Logger.Debug ("Project.Save. Saving {0}", Details.Filename);
ps.Save (Details.Filename);
for (int i = 0; i < Elements.Count; i++)
Logger.Debug ("Project.Save. {0}", Elements[i]);
}
public Gdk.Pixbuf GetThumbnail (int width, int height)
{
Gdk.Pixbuf thumbnail = null;
foreach (VisibleProjectElement element in Elements)
{
if ((typeof (SlideShow) != element.GetType ()) &&
(typeof (Video) != element.GetType ()))
continue;
thumbnail = element.GetThumbnail (width, height);
break;
}
return thumbnail;
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Data.dll
// Description: The data access libraries for the DotSpatial project.
//
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is DotSpatial.dll for the DotSpatial project
//
// The Initial Developer of this Original Code is Ted Dunsford. Created in January 2008.
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using DotSpatial.Data.MiscUtil;
using DotSpatial.Projections;
namespace DotSpatial.Data
{
/// <summary>
/// This basically demonstrates how you would combine a type with a calculator in order to
/// construct a Binary Raster for the Integer type. It is effectively the same as
/// constructing a new BinaryRaster and specifying the parameter types int and IntCalculator.
/// </summary>
internal class BinaryRaster<T> : Raster<T> where T : struct, IEquatable<T>, IComparable<T>
{
public static readonly T MaxValue = ReadStaticField("MaxValue");
public static readonly T MinValue = ReadStaticField("MinValue");
#region Constructors
/// <summary>
/// Creates a completely empty raster that can be custom configured
/// </summary>
public BinaryRaster()
{
// This is basically an empty place holder until someone calls an Open or something.
}
/// <summary>
/// Creates a new BinaryRaster with the specified rows and columns.
/// If if the raster is less than 64 Million cells, it will be created only in memory,
/// and a Save method should be called when ready to save it to a file. Otherwise, it creates a blank file with
/// NoData values...which start out as 0.
/// </summary>
/// <param name="fileName">The fileName to write to</param>
/// <param name="numRows">Integer number of rows</param>
/// <param name="numColumns">Integer number of columns</param>
public BinaryRaster(string fileName, int numRows, int numColumns) :
this(fileName, numRows, numColumns, true)
{
// this just forces the inRam to default to true.
}
/// <summary>
/// Creates a new BinaryRaster with the specified rows and columns.
/// If inRam is true and the raster is less than 64 Million cells, it will be created only in memory,
/// and a Save method should be called when ready to save it to a file. Otherwise, it creates a blank file with
/// NoData values.
/// </summary>
/// <param name="fileName">The fileName to write to</param>
/// <param name="numRows">Integer number of rows</param>
/// <param name="numColumns">Integer number of columns</param>
/// <param name="inRam">If this is true and the raster is small enough, it will load this into memory and not save anything to the file.</param>
public BinaryRaster(string fileName, int numRows, int numColumns, bool inRam)
{
if (File.Exists(fileName))
base.Filename = fileName;
if (inRam && numColumns * numRows < 64000000)
base.IsInRam = true;
else
base.IsInRam = false;
base.NumRows = numRows;
base.NumColumns = numColumns;
Initialize();
}
#endregion
#region Methods
/// <summary>
/// Creates a duplicate version of this file. If copyValues is set to false, then a raster of NoData values is created
/// that has the same georeferencing information as the source file of this Raster, even if this raster is just a window.
/// If the specified fileName exists, rather than throwing an exception or taking an "overwrite" parameter, this
/// will throw the FileExists event, and cancel the copy if the cancel argument is set to true.
/// </summary>
/// <param name="fileName">The string fileName specifying where to create the new file.</param>
/// <param name="copyValues">If this is false, the same size and georeferencing values are used, but they are all set to NoData.</param>
public override void Copy(string fileName, bool copyValues)
{
if (fileName == Filename)
throw new ArgumentException(DataStrings.CannotCopyToSelf_S.Replace("%S", fileName));
if (File.Exists(fileName))
{
if (OnFileExists(fileName))
return; // The copy event was cancelled
// The copy event was not cancelled, so overwrite the file
File.Delete(fileName);
}
if (copyValues)
{
// this should be faster than copying values in code
File.Copy(Filename, fileName);
}
else
{
// since at this point, there is no file, a blank file will be created with empty values.
Write(fileName);
}
}
/// <summary>
/// This creates a completely new raster from the windowed domain on the original raster. This new raster
/// will have a separate source file, and values like NumRowsInFile will correspond to the newly created file.
/// All the values will be copied to the new source file. If inRam = true and the new raster is small enough,
/// the raster values will be loaded into memory.
/// </summary>
/// <param name="fileName"></param>
/// <param name="startRow">The 0 based integer index of the top row to copy from this raster. If this raster is itself a window, 0 represents the startRow from the file.</param>
/// <param name="endRow">The integer index of the bottom row to copy from this raster. The largest allowed value is NumRows - 1.</param>
/// <param name="startColumn">The 0 based integer index of the leftmost column to copy from this raster. If this raster is a window, 0 represents the startColumn from the file.</param>
/// <param name="endColumn">The 0 based integer index of the rightmost column to copy from this raster. The largest allowed value is NumColumns - 1</param>
/// <param name="copyValues">If this is true, the values are saved to the file. If this is false and the data can be loaded into Ram, no file handling is done. Otherwise, a file of NoData values is created.</param>
/// <param name="inRam">Boolean. If this is true and the window is small enough, a copy of the values will be loaded into memory.</param>
/// <returns>An implementation of IRaster</returns>
public new IRaster CopyWindow(string fileName, int startRow, int endRow, int startColumn, int endColumn,
bool copyValues, bool inRam)
{
int numCols = endColumn - startColumn + 1;
int numRows = endRow - startRow + 1;
var result = new BinaryRaster<T>(fileName, numCols, numRows, inRam) {Projection = Projection};
// The affine coefficients defining the world file are the same except that they are translated over. Only the position of the
// upper left corner changes. Everything else is the same as the previous raster.
var ac = new AffineTransform(Bounds.AffineCoefficients).TransfromToCorner(startColumn, startRow);
result.Bounds = new RasterBounds(result.NumRows, result.NumColumns, ac);
if (IsInRam)
{
ProgressMeter pm = new ProgressMeter(ProgressHandler, DataStrings.CopyingValues, numRows);
// copy values directly using both data structures
for (int row = 0; row < numRows; row++)
{
for (int col = 0; col < numCols; col++)
{
result.Data[row][col] = Data[startRow + row][startColumn + col];
}
pm.CurrentValue = row;
}
pm.Reset();
if (result.IsInRam == false)
{
// Force the result raster to write itself to a file and then purge its memory.
result.Write(fileName);
result.Data = null;
}
}
else
{
if (result.IsInRam)
{
// the source is not in memory, so we just read the values from the file as if opening it directly from the file.
result.OpenWindow(Filename, startRow, endRow, startColumn, endColumn, true);
}
else
{
// Both sources are file based so we basically copy rows of bytes from one to the other.
FileStream source = new FileStream(Filename, FileMode.Open, FileAccess.Read, FileShare.Read);
result.WriteHeader(fileName);
FileStream dest = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.None);
source.Seek(HeaderSize, SeekOrigin.Begin);
BinaryReader bReader = new BinaryReader(source);
BinaryWriter bWriter = new BinaryWriter(dest);
ProgressMeter pm = new ProgressMeter(ProgressHandler, DataStrings.CopyingValues, numRows);
// copy values directly using both data structures
source.Seek(NumColumnsInFile * startRow * ByteSize, SeekOrigin.Current);
for (int row = 0; row < numRows; row++)
{
source.Seek(numCols * ByteSize, SeekOrigin.Current);
byte[] rowData = bReader.ReadBytes(ByteSize * numCols);
bWriter.Write(rowData);
source.Seek(NumColumnsInFile - endColumn + 1, SeekOrigin.Current);
bWriter.Flush();
pm.CurrentValue = row;
}
pm.Reset();
}
}
return result;
}
/// <summary>
/// Gets the statistics for the entire file, not just the window portion specified for this raster.
/// </summary>
public override void GetStatistics()
{
if (IsInRam && this.IsFullyWindowed())
{
// The in-memory version of this is a little faster, so use it, but only if we can.
base.GetStatistics();
return;
}
// If we get here, we either need to check the file because no data is in memory or because
// the window that is in memory does not have all the values.
FileStream fs = new FileStream(Filename, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
fs.Seek(HeaderSize, SeekOrigin.Begin);
ProgressMeter pm = new ProgressMeter(ProgressHandler,
"Calculating Statistics for the entire raster " + Filename,
NumRowsInFile);
int count = 0;
T min = MinValue;
T max = MaxValue;
double total = 0;
double sqrTotal = 0;
T noDataValue = ConvertTo<T>(NoDataValue);
for (int row = 0; row < NumRowsInFile; row++)
{
for (int col = 0; col < NumColumnsInFile; col++)
{
T val = br.Read<T>();
if (!EqualityComparer<T>.Default.Equals(val, noDataValue))
{
if (Operator.GreaterThan(val, max)) max = val;
if (Operator.LessThan(val, min)) min = val;
double valAsDouble = Convert.ToDouble(val);
total += valAsDouble;
sqrTotal += valAsDouble * valAsDouble;
count++;
}
}
pm.CurrentValue = row;
}
Value.Updated = false;
Minimum = Convert.ToDouble(min);
Maximum = Convert.ToDouble(max);
Mean = total / count;
NumValueCells = count;
StdDeviation = (float)Math.Sqrt((sqrTotal / NumValueCells) - (total / NumValueCells) * (total / NumValueCells));
br.Close();
}
/// <summary>
/// This creates a window from this raster. The window will still save to the same
/// source file, but only has access to a small window of data, so it can be loaded like a buffer.
/// The georeferenced extents will be for the new window, not the original raster. startRow and endRow
/// will exist in the new raster, however, so that it knows how to copy values back to the original raster.
/// </summary>
/// <param name="startRow">The 0 based integer index of the top row to get from this raster. If this raster is itself a window, 0 represents the startRow from the file.</param>
/// <param name="endRow">The integer index of the bottom row to get from this raster. The largest allowed value is NumRows - 1.</param>
/// <param name="startColumn">The 0 based integer index of the leftmost column to get from this raster. If this raster is a window, 0 represents the startColumn from the file.</param>
/// <param name="endColumn">The 0 based integer index of the rightmost column to get from this raster. The largest allowed value is NumColumns - 1</param>
/// <param name="inRam">Boolean. If this is true and the window is small enough, a copy of the values will be loaded into memory.</param>
/// <returns>An implementation of IRaster</returns>
public new IRaster GetWindow(int startRow, int endRow, int startColumn, int endColumn, bool inRam)
{
int numCols = endColumn - startColumn + 1;
int numRows = endRow - startRow + 1;
var result = new BinaryRaster<T>
{
Filename = Filename,
Projection = Projection,
DataType = typeof (int),
NumRows = endRow - startRow + 1,
NumColumns = endColumn - startColumn + 1,
NumRowsInFile = NumRowsInFile,
NumColumnsInFile = NumColumnsInFile,
NoDataValue = NoDataValue,
StartColumn = startColumn + StartColumn,
StartRow = startRow + StartRow,
EndColumn = endColumn + StartColumn,
EndRow = EndRow + StartRow
};
// Reposition the "raster" so that it matches the window, not the whole raster
var ac = new AffineTransform(Bounds.AffineCoefficients).TransfromToCorner(startColumn, startRow);
result.Bounds = new RasterBounds(result.NumRows, result.NumColumns, ac);
// Now we can copy any values currently in memory.
if (IsInRam)
{
//result.ReadHeader(Filename);
result.Data = new T[numRows][];
ProgressMeter pm = new ProgressMeter(ProgressHandler, DataStrings.CopyingValues, endRow)
{
StartValue = startRow
};
// copy values directly using both data structures
for (int row = 0; row < numRows; row++)
{
result.Data[row] = new T[numCols];
for (int col = 0; col < numCols; col++)
{
result.Data[row][col] = Data[startRow + row][startColumn + col];
}
pm.CurrentValue = row;
}
pm.Reset();
}
else
result.OpenWindow(Filename, startRow, endRow, startColumn, endColumn, inRam);
result.Value = new ValueGrid<T>(result);
return result;
}
/// <summary>
/// Obtains only the statistics for the small window specified by startRow, endRow etc.
/// </summary>
public new void GetWindowStatistics()
{
if (IsInRam)
{
// don't bother to do file calculations if the whole raster is in memory
base.GetWindowStatistics();
return;
}
// The window was not in memory, so go ahead and get statistics for the window from the file.
FileStream fs = new FileStream(Filename, FileMode.Open, FileAccess.Read, FileShare.Read, NumColumns * ByteSize);
BinaryReader br = new BinaryReader(fs);
fs.Seek(HeaderSize, SeekOrigin.Begin);
ProgressMeter pm = new ProgressMeter(ProgressHandler,
"Calculating Statistics for the entire raster " + Filename, NumRows);
double total = 0;
double sqrTotal = 0;
int count = 0;
int byteSize = ByteSize; // cache this for faster calcs
int min = int.MaxValue;
int max = int.MinValue;
fs.Seek(StartRow * ByteSize * NumColumnsInFile, SeekOrigin.Current); // To top edge of the Window
int noDataValue = Convert.ToInt32(NoDataValue);
for (int row = 0; row < NumRows; row++)
{
fs.Seek(StartColumn * byteSize, SeekOrigin.Current); // to the left edge of the window
for (int col = 0; col < NumColumns; col++)
{
int val = br.ReadInt32();
if (val == noDataValue || val <= -100000) continue;
if (val > max) max = val;
if (val < min) min = val;
double dblVal = val;
total += dblVal;
sqrTotal += dblVal * dblVal;
count++;
}
fs.Seek(NumColumnsInFile - EndRow - 1, SeekOrigin.Current); // skip to the end of this row.
pm.CurrentValue = row;
}
Minimum = min;
Maximum = max;
NumValueCells = count;
StdDeviation = (float)Math.Sqrt((sqrTotal / NumValueCells) - (total / NumValueCells) * (total / NumValueCells));
br.Close();
}
/// <summary>
/// Opens the specified file into this raster.
/// </summary>
public override void Open()
{
Open(Filename, true);
}
/// <summary>
/// Opens a new instance of the BinaryRaster
/// </summary>
/// <param name="fileName">The string fileName of the raster file to open</param>
/// <param name="inRam">Boolean, indicates whether or not the values for the raster should be loaded into memory</param>
public virtual void Open(string fileName, bool inRam)
{
Filename = fileName;
ReadHeader(fileName);
if (inRam)
{
if (NumRowsInFile * NumColumnsInFile < 64000000)
{
IsInRam = true;
Read();
}
}
Value = new ValueGrid<T>(this);
}
/// <summary>
/// This converts this object into a raster defined by the specified window dimensions.
/// </summary>
/// <param name="fileName">The string fileName to open</param>
/// <param name="startRow">The integer row index to become the first row to load into this raster.</param>
/// <param name="endRow">The 0 based integer row index to become the last row included in this raster.</param>
/// <param name="startColumn">The 0 based integer column index for the first column of the raster.</param>
/// <param name="endColumn">The 0 based integer column index for the last column to include in this raster.</param>
/// <param name="inRam">Boolean. If this is true and the window is small enough, this will load the window into ram.</param>
public virtual void OpenWindow(string fileName, int startRow, int endRow, int startColumn, int endColumn,
bool inRam)
{
Filename = fileName;
ReadHeader(fileName);
NumRows = endRow - startRow + 1;
NumColumns = endColumn - startColumn + 1;
StartColumn = startColumn;
StartRow = startRow;
EndColumn = endColumn;
EndRow = EndRow;
// Reposition the "raster" so that it matches the window, not the whole raster
Bounds.AffineCoefficients = new AffineTransform(Bounds.AffineCoefficients).TransfromToCorner(startColumn, startRow);
if (inRam)
{
if (NumRows * NumColumns < 64000000)
{
IsInRam = true;
Read();
}
}
Value = new ValueGrid<T>(this);
}
/// <summary>
/// Copies the contents from the specified sourceRaster into this sourceRaster. If both rasters are InRam, this does not affect the files.
/// </summary>
/// <param name="sourceRaster">The raster of values to paste into this raster. If the CellWidth and CellHeight values do not match between the files,
/// an exception will be thrown. If the sourceRaster overlaps with the edge of this raster, only the intersecting region will be
/// pasted.</param>
/// <param name="startRow">Specifies the row in this raster where the top row of the sourceRaster will be pasted </param>
/// <param name="startColumn">Specifies the column in this raster where the left column of the sourceRaster will be pasted.</param>
public void PasteRaster(Raster<T> sourceRaster, int startRow, int startColumn)
{
int byteSize = ByteSize;
if (sourceRaster.DataType != typeof(int))
{
throw new ArgumentException(
DataStrings.ArgumentOfWrongType_S1_S2.Replace("%S1", "sourceRaster").Replace("%S2", "BinaryRaster"));
}
if (startRow + sourceRaster.NumRows <= 0) return; // sourceRaster is above this raster
if (startColumn + sourceRaster.NumColumns <= 0) return; // sourceRaster is left of this raster
if (startRow > NumRows) return; // sourceRaster is below this raster
if (startColumn > NumColumns) return; // sourceRaster is to the right of this raster
if (sourceRaster.CellWidth != CellWidth || sourceRaster.CellHeight != CellHeight)
throw new ArgumentException(DataStrings.RastersNeedSameCellSize);
// These are specified in coordinates that match the source raster
int sourceStartColumn = 0;
int sourceStartRow = 0;
int destStartColumn = startColumn;
int destStartRow = startRow;
int numPasteColumns = sourceRaster.NumColumns;
int numPasteRows = sourceRaster.NumRows;
// adjust range to cover only the overlapping sections
if (startColumn < 0)
{
sourceStartColumn = -startColumn;
destStartColumn = 0;
}
if (startRow < 0)
{
sourceStartRow = -startRow;
destStartRow = 0;
}
if (numPasteRows + destStartRow > NumRows) numPasteRows = (NumRows - destStartRow);
if (numPasteColumns + destStartColumn > NumColumns) numPasteColumns = (NumColumns - destStartRow);
if (IsInRam)
{
// ---------------------- RAM BASED ------------------------------------------------------
if (sourceRaster.IsInRam)
{
// both members are inram, so directly copy values.
for (int row = 0; row < numPasteRows; row++)
{
for (int col = 0; col < numPasteColumns; col++)
{
// since we are copying direct, we don't have to do a type check on T
Data[destStartRow + row][destStartColumn + col] =
sourceRaster.Data[sourceStartRow + row][sourceStartColumn + col];
}
}
}
else
{
FileStream fs = new FileStream(sourceRaster.Filename, FileMode.Open, FileAccess.Write,
FileShare.None, (numPasteColumns) * byteSize);
ProgressMeter pm = new ProgressMeter(ProgressHandler,
DataStrings.ReadingValuesFrom_S.Replace("%S",
sourceRaster.
Filename),
numPasteRows);
fs.Seek(HeaderSize, SeekOrigin.Begin);
// Position the binary reader at the top of the "sourceRaster"
fs.Seek(sourceStartRow * sourceRaster.NumColumnsInFile * byteSize, SeekOrigin.Current);
BinaryReader br = new BinaryReader(fs);
for (int row = 0; row < numPasteRows; row++)
{
// Position the binary reader at the beginning of the sourceRaster
fs.Seek(byteSize * sourceStartColumn, SeekOrigin.Current);
for (int col = 0; col < numPasteColumns; col++)
{
Data[destStartRow + row][destStartColumn + col] = br.Read<T>();
}
pm.CurrentValue = row;
fs.Seek(byteSize * (NumColumnsInFile - sourceStartColumn - numPasteColumns), SeekOrigin.Current);
}
br.Close();
}
// The statistics will have changed with the newly pasted data involved
GetStatistics();
}
else
{
// ----------------------------------------- FILE BASED ---------------------------------
FileStream writefs = new FileStream(Filename, FileMode.Open, FileAccess.Write, FileShare.None,
NumColumns * byteSize);
BinaryWriter bWriter = new BinaryWriter(writefs);
ProgressMeter pm = new ProgressMeter(ProgressHandler,
DataStrings.WritingValues_S.Replace("%S", Filename),
numPasteRows);
writefs.Seek(HeaderSize, SeekOrigin.Begin);
writefs.Seek(destStartRow * NumColumnsInFile * byteSize, SeekOrigin.Current);
// advance to top of paste window area
if (sourceRaster.IsInRam)
{
// we can just write values
for (int row = 0; row < numPasteColumns; row++)
{
// Position the binary reader at the beginning of the sourceRaster
writefs.Seek(byteSize * destStartColumn, SeekOrigin.Current);
for (int col = 0; col < numPasteColumns; col++)
{
T val = sourceRaster.Data[sourceStartRow + row][sourceStartColumn + col];
bWriter.Write(val);
}
pm.CurrentValue = row;
writefs.Seek(byteSize * (NumColumnsInFile - destStartColumn - numPasteColumns), SeekOrigin.Current);
}
}
else
{
// Since everything is handled from a file, we don't have to type check. Just copy the bytes.
FileStream readfs = new FileStream(sourceRaster.Filename, FileMode.Open, FileAccess.Read,
FileShare.Read, numPasteColumns * byteSize);
BinaryReader bReader = new BinaryReader(readfs);
readfs.Seek(HeaderSize, SeekOrigin.Begin);
readfs.Seek(sourceStartRow * sourceRaster.NumColumnsInFile * byteSize, SeekOrigin.Current);
// advances to top of paste window area
for (int row = 0; row < numPasteRows; row++)
{
readfs.Seek(sourceStartColumn * byteSize, SeekOrigin.Current);
writefs.Seek(destStartColumn * byteSize, SeekOrigin.Current);
byte[] rowData = bReader.ReadBytes(numPasteColumns * byteSize);
bWriter.Write(rowData);
readfs.Seek(sourceRaster.NumColumnsInFile - sourceStartColumn - numPasteColumns,
SeekOrigin.Current);
writefs.Seek(NumColumnsInFile - destStartColumn - numPasteColumns, SeekOrigin.Current);
}
bReader.Close();
}
bWriter.Close();
}
}
private U ConvertTo<U>(double value)
{
// we don't consider whether the current culture might cause an incorrect conversion.
object ret = null;
if (typeof(U) == typeof(Byte))
ret = Convert.ToByte(value);
else if (typeof(U) == typeof(Double))
ret = Convert.ToDouble(value);
else if (typeof(U) == typeof(Decimal))
ret = Convert.ToDecimal(value);
else if (typeof(U) == typeof(Int16))
ret = Convert.ToInt16(value);
else if (typeof(U) == typeof(Int32))
ret = Convert.ToInt32(value);
else if (typeof(U) == typeof(Int64))
ret = Convert.ToInt64(value);
else if (typeof(U) == typeof(Single))
ret = Convert.ToSingle(value);
else if (typeof(U) == typeof(Boolean))
ret = Convert.ToBoolean(value);
if (ret == null)
throw new NotSupportedException("Unable to convert type - " + typeof(U));
return (U)ret;
}
/// <summary>
/// Reads the the contents for the "window" specified by the start and end values
/// for the rows and columns.
/// </summary>
public void Read()
{
FileStream fs = new FileStream(Filename, FileMode.Open, FileAccess.Read, FileShare.Read, NumColumns * ByteSize);
ProgressMeter pm = new ProgressMeter(ProgressHandler, DataStrings.ReadingValuesFrom_S.Replace("%S", Filename), NumRows);
fs.Seek(HeaderSize, SeekOrigin.Begin);
// Position the binary reader at the top of the "window"
fs.Seek(StartRow * NumColumnsInFile * ByteSize, SeekOrigin.Current);
BinaryReader br = new BinaryReader(fs);
Data = new T[NumRows][];
T min = MinValue;
T max = MaxValue;
double total = 0;
double sqrTotal = 0;
T noDataValue = ConvertTo<T>(NoDataValue);
for (int row = 0; row < NumRows; row++)
{
Data[row] = new T[NumColumns];
// Position the binary reader at the beginning of the window
fs.Seek(4 * StartColumn, SeekOrigin.Current);
for (int col = 0; col < NumColumns; col++)
{
T val = br.Read<T>();
if (!EqualityComparer<T>.Default.Equals(val, noDataValue))
{
if (Operator.GreaterThan(val, max)) max = val;
if (Operator.LessThan(val, min)) min = val;
double valAsDouble = Convert.ToDouble(val);
total += valAsDouble;
sqrTotal += valAsDouble * valAsDouble;
NumValueCells++;
}
Data[row][col] = val;
}
pm.CurrentValue = row;
fs.Seek(ByteSize * (NumColumnsInFile - EndColumn - 1), SeekOrigin.Current);
}
Maximum = Convert.ToDouble(max);
Minimum = Convert.ToDouble(min);
StdDeviation = Math.Sqrt((sqrTotal / NumValueCells) - (total / NumValueCells) * (total / NumValueCells));
br.Close();
}
// http://stackoverflow.com/questions/4418636/c-sharp-generics-how-to-use-x-maxvalue-x-minvalue-int-float-double-in-a
private static T ReadStaticField(string name)
{
FieldInfo field = typeof(T).GetField(name, BindingFlags.Public | BindingFlags.Static);
if (field == null)
{
// There's no TypeArgumentException, unfortunately.
throw new InvalidOperationException("Invalid type argument: " + typeof(T).Name);
}
return (T)field.GetValue(null);
}
/// <summary>
/// Writes the header, regardless of which subtype of binary raster this is written for
/// </summary>
/// <param name="fileName">The string fileName specifying what file to load</param>
public void ReadHeader(string fileName)
{
BinaryReader br = new BinaryReader(new FileStream(fileName, FileMode.Open));
StartColumn = 0;
NumColumns = br.ReadInt32();
NumColumnsInFile = NumColumns;
EndColumn = NumColumns - 1;
StartRow = 0;
NumRows = br.ReadInt32();
NumRowsInFile = NumRows;
EndRow = NumRows - 1;
Bounds = new RasterBounds(NumRows, NumColumns, new[] { 0.0, 1.0, 0.0, NumRows, 0.0, -1.0 });
CellWidth = br.ReadDouble();
Bounds.AffineCoefficients[5] = -br.ReadDouble(); // dy
Xllcenter = br.ReadDouble();
Yllcenter = br.ReadDouble();
RasterDataType dataType = (RasterDataType)br.ReadInt32();
if (dataType != RasterDataType.INTEGER)
{
throw new ArgumentException(
DataStrings.ArgumentOfWrongType_S1_S2.Replace("%S1", fileName).Replace("%S2", "BinaryShortRaster"));
}
NoDataValue = br.ReadInt32();
string proj = Encoding.ASCII.GetString(br.ReadBytes(255)).Replace('\0', ' ').Trim();
Projection = ProjectionInfo.FromProj4String(proj);
Notes = Encoding.ASCII.GetString(br.ReadBytes(255)).Replace('\0', ' ').Trim();
if (Notes.Length == 0) Notes = null;
br.Close();
}
/// <summary>
/// The string fileName where this will begin to write data by clearing the existing file
/// </summary>
/// <param name="fileName">a fileName to write data to</param>
public void WriteHeader(string fileName)
{
using (var bw = new BinaryWriter(new FileStream(fileName, FileMode.OpenOrCreate)))
{
bw.Write(NumColumnsInFile);
bw.Write(NumRowsInFile);
bw.Write(CellWidth);
bw.Write(CellHeight);
bw.Write(Xllcenter);
bw.Write(Yllcenter);
bw.Write((int) RasterDataType.INTEGER);
bw.Write(Convert.ToInt32(NoDataValue));
// These are each 256 bytes because they are ASCII encoded, not the standard DotNet Unicode
byte[] proj = new byte[255];
if (Projection != null)
{
byte[] temp = Encoding.ASCII.GetBytes(Projection.ToProj4String());
int len = Math.Min(temp.Length, 255);
for (int i = 0; i < len; i++)
{
proj[i] = temp[i];
}
}
bw.Write(proj);
byte[] note = new byte[255];
if (Notes != null)
{
byte[] temp = Encoding.ASCII.GetBytes(Notes);
int len = Math.Min(temp.Length, 255);
for (int i = 0; i < len; i++)
{
note[i] = temp[i];
}
}
bw.Write(note);
}
}
/// <summary>
/// This would be a horrible choice for any kind of serious process, but is provided as
/// a way to write values directly to the file.
/// </summary>
/// <param name="row">The 0 based integer row index for the file to write to.</param>
/// <param name="column">The 0 based column index for the file to write to.</param>
/// <param name="value">The actual value to write.</param>
public void WriteValue(int row, int column, int value)
{
using (var fs = new FileStream(Filename, FileMode.Open, FileAccess.Write, FileShare.None))
{
fs.Seek(HeaderSize, SeekOrigin.Begin);
fs.Seek(row*NumColumnsInFile*ByteSize, SeekOrigin.Current);
fs.Seek(column*ByteSize, SeekOrigin.Current);
using (var bw = new BinaryWriter(fs))
{
bw.Write(value);
}
}
}
/// <summary>
/// Saves the values in memory to the disk.
/// </summary>
public override void Save()
{
Write(Filename);
}
/// <summary>
/// If no file exists, this writes the header and no-data values. If a file exists, it will assume
/// that data already has been filled in the file and will attempt to insert the data values
/// as a window into the file. If you want to create a copy of the file and values, just use
/// System.IO.File.Copy, it almost certainly would be much more optimized.
/// </summary>
/// <param name="fileName">The string fileName to write values to.</param>
public void Write(string fileName)
{
FileStream fs;
BinaryWriter bw;
ProgressMeter pm = new ProgressMeter(ProgressHandler, "Writing values to " + fileName, NumRows);
long expectedByteCount = NumRows * NumColumns * ByteSize;
if (expectedByteCount < 1000000) pm.StepPercent = 5;
if (expectedByteCount < 5000000) pm.StepPercent = 10;
if (expectedByteCount < 100000) pm.StepPercent = 50;
if (File.Exists(fileName))
{
FileInfo fi = new FileInfo(fileName);
// if the following test fails, then the target raster doesn't fit the bill for pasting into, so clear it and write a new one.
if (fi.Length == HeaderSize + ByteSize * NumColumnsInFile * NumRowsInFile)
{
WriteHeader(fileName);
// assume that we already have a file set up for us, and just write the window of values into the appropriate place.
fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None,
ByteSize * NumColumns);
fs.Seek(HeaderSize, SeekOrigin.Begin);
fs.Seek(ByteSize * StartRow, SeekOrigin.Current);
bw = new BinaryWriter(fs); // encoding doesn't matter because we don't have characters
for (int row = 0; row < NumRows; row++)
{
fs.Seek(StartColumn * ByteSize, SeekOrigin.Current);
for (int col = 0; col < NumColumns; col++)
{
// this is the only line that is type dependant, but I don't want to type check on every value
bw.Write(Data[row][col]);
}
fs.Flush(); // Since I am buffering, make sure that I write the buffered data before seeking
fs.Seek((NumColumnsInFile - EndColumn - 1) * ByteSize, SeekOrigin.Current);
pm.CurrentValue = row;
}
pm.Reset();
bw.Close();
return;
}
// If we got here, either the file didn't exist or didn't match the specifications correctly, so write a new one.
Debug.WriteLine("The size of the file was " + fi.Length + " which didn't match the expected " +
HeaderSize + ByteSize * NumColumnsInFile * NumRowsInFile);
File.Delete(fileName);
}
if (File.Exists(fileName)) File.Delete(fileName);
WriteHeader(fileName);
// Open as append and it will automatically skip the header for us.
fs = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.None, ByteSize * NumColumnsInFile);
bw = new BinaryWriter(fs);
// the row and column counters here are relative to the whole file, not just the window that is currently in memory.
pm.EndValue = NumRowsInFile;
int noDataValue = Convert.ToInt32(NoDataValue);
for (int row = 0; row < NumRowsInFile; row++)
{
for (int col = 0; col < NumColumnsInFile; col++)
{
if (row < StartRow || row > EndRow || col < StartColumn || col > EndColumn)
bw.Write(Convert.ToInt32(noDataValue));
else
bw.Write(Data[row - StartRow][col - StartColumn]);
}
pm.CurrentValue = row;
}
fs.Flush(); // flush anything that hasn't gotten written yet.
pm.Reset();
bw.Close();
}
#endregion
#region Properties
/// <summary>
/// Returns the size of T in bytes. This should be overridden, but
/// exists as a "just-in-case" implementation that works for structs,
/// but definitely won't work correctly for objects.
/// </summary>
public override int ByteSize
{
get { return Marshal.SizeOf(typeof(T)); }
}
/// <summary>
/// All the binary rasters use the Binary file type
/// </summary>
public override RasterFileType FileType
{
get { return RasterFileType.BINARY; }
}
/// <summary>
/// This is always 1 band
/// </summary>
public override int NumBands
{
get { return 1; }
}
/// <summary>
/// Gets the size of the header. There is one no-data value in the header.
/// </summary>
public virtual int HeaderSize
{
get { return 554 + ByteSize; }
}
#endregion
}
}
| |
// 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 Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests
{
public class ManagedAddressOfTests : ExpressionCompilerTestBase
{
[Fact]
public void AddressOfParameter()
{
var source =
@"class C
{
void M(string s)
{
}
}";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
context.CompileExpression("&s", out error, testData);
Assert.Null(error);
var methodData = testData.GetMethodData("<>x.<>m0");
AssertIsIntPtrPointer(methodData.Method.ReturnType);
methodData.VerifyIL(@"
{
// Code size 4 (0x4)
.maxstack 1
IL_0000: ldarga.s V_1
IL_0002: conv.u
IL_0003: ret
}
");
});
}
[Fact]
public void AddressOfLocal()
{
var source =
@"class C
{
void M()
{
string s = ""hello"";
}
}";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
context.CompileExpression("&s", out error, testData);
Assert.Null(error);
var methodData = testData.GetMethodData("<>x.<>m0");
AssertIsIntPtrPointer(methodData.Method.ReturnType);
methodData.VerifyIL(@"
{
// Code size 4 (0x4)
.maxstack 1
.locals init (string V_0) //s
IL_0000: ldloca.s V_0
IL_0002: conv.u
IL_0003: ret
}
");
});
}
[Fact]
public void AddressOfField()
{
var source =
@"class C
{
string s = ""hello"";
void M()
{
}
}";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
context.CompileExpression("&s", out error, testData);
Assert.Null(error);
var methodData = testData.GetMethodData("<>x.<>m0");
AssertIsIntPtrPointer(methodData.Method.ReturnType);
methodData.VerifyIL(@"
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldflda ""string C.s""
IL_0006: conv.u
IL_0007: ret
}
");
});
}
/// <remarks>
/// It seems like we could make this work, but there are special cases for arrays
/// and interfaces and some of the checks would have to be recursive. Furthermore,
/// dev12 didn't support it.
/// </remarks>
[Fact]
public void DisallowSizeof()
{
var source = @"
class C
{
void M<T>()
{
}
}
delegate void D();
interface I
{
}
enum E
{
A
}
struct Generic<T>
{
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var types = new[]
{
"C", // class
"D", // delegate
"I", // interface
"T", // type parameter
"int[]",
"Generic<int>",
"dynamic",
};
foreach (var type in types)
{
string error;
CompilationTestData testData = new CompilationTestData();
context.CompileExpression(string.Format("sizeof({0})", type), out error, testData);
// CONSIDER: change error code to make text less confusing?
Assert.Equal(string.Format("error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('{0}')", type), error);
}
});
}
[Fact]
public void DisallowStackalloc()
{
var source =
@"class C
{
void M()
{
System.Action a;
}
}";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
context.CompileAssignment("a", "() => { var s = stackalloc string[1]; }", out error, testData);
// CONSIDER: change error code to make text less confusing?
Assert.Equal("error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string')", error);
});
}
[Fact]
public void DisallowPointerType()
{
var source =
@"class C
{
void M()
{
}
}";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
context.CompileExpression("(string*)null", out error, testData);
// CONSIDER: change error code to make text less confusing?
Assert.Equal("error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string')", error);
});
}
/// <remarks>
/// This is not so much disallowed as not specifically enabled.
/// </remarks>
[Fact]
public void DisallowFixedArray()
{
var source =
@"class C
{
void M(string[] args)
{
System.Action a;
}
}";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
context.CompileAssignment("a", "() => { fixed (void* p = args) { } }", out error, testData);
// CONSIDER: change error code to make text less confusing?
Assert.Equal("error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string')", error);
});
}
private static void AssertIsIntPtrPointer(ITypeSymbol returnType)
{
Assert.Equal(TypeKind.Pointer, returnType.TypeKind);
Assert.Equal(SpecialType.System_IntPtr, ((PointerTypeSymbol)returnType).PointedAtType.SpecialType);
}
}
}
| |
// 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;
namespace System.Collections.Immutable
{
/// <content>
/// Contains the inner <see cref="ImmutableHashSet{T}.HashBucket"/> struct.
/// </content>
public partial class ImmutableHashSet<T>
{
/// <summary>
/// The result of a mutation operation.
/// </summary>
internal enum OperationResult
{
/// <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,
}
/// <summary>
/// Contains all the keys in the collection that hash to the same value.
/// </summary>
internal readonly struct HashBucket
{
/// <summary>
/// One of the values in this bucket.
/// </summary>
private readonly T _firstValue;
/// <summary>
/// Any other elements that hash to the same value.
/// </summary>
/// <value>
/// This is null if and only if the entire bucket is empty (including <see cref="_firstValue"/>).
/// It's empty if <see cref="_firstValue"/> has an element but no additional elements.
/// </value>
private readonly ImmutableList<T>.Node _additionalElements;
/// <summary>
/// Initializes a new instance of the <see cref="HashBucket"/> struct.
/// </summary>
/// <param name="firstElement">The first element.</param>
/// <param name="additionalElements">The additional elements.</param>
private HashBucket(T firstElement, ImmutableList<T>.Node additionalElements = null)
{
_firstValue = firstElement;
_additionalElements = additionalElements ?? ImmutableList<T>.Node.EmptyNode;
}
/// <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>
internal bool IsEmpty
{
get { return _additionalElements == null; }
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
/// <summary>
/// Throws an exception to catch any errors in comparing <see cref="HashBucket"/> instances.
/// </summary>
public override bool Equals(object obj)
{
// This should never be called, as hash buckets don't know how to equate themselves.
throw new NotSupportedException();
}
/// <summary>
/// Throws an exception to catch any errors in comparing <see cref="HashBucket"/> instances.
/// </summary>
public override int GetHashCode()
{
// This should never be called, as hash buckets don't know how to hash themselves.
throw new NotSupportedException();
}
/// <summary>
/// Checks whether this <see cref="HashBucket"/> is exactly like another one,
/// comparing by reference. For use when type parameter T is an object.
/// </summary>
/// <param name="other">The other bucket.</param>
/// <returns><c>true</c> if the two <see cref="HashBucket"/> structs have precisely the same values.</returns>
internal bool EqualsByRef(HashBucket other)
{
return object.ReferenceEquals(_firstValue, other._firstValue)
&& object.ReferenceEquals(_additionalElements, other._additionalElements);
}
/// <summary>
/// Checks whether this <see cref="HashBucket"/> is exactly like another one,
/// comparing by value. For use when type parameter T is a struct.
/// </summary>
/// <param name="other">The other bucket.</param>
/// <param name="valueComparer">The comparer to use for the first value in the bucket.</param>
/// <returns><c>true</c> if the two <see cref="HashBucket"/> structs have precisely the same values.</returns>
internal bool EqualsByValue(HashBucket other, IEqualityComparer<T> valueComparer)
{
return valueComparer.Equals(_firstValue, other._firstValue)
&& object.ReferenceEquals(_additionalElements, other._additionalElements);
}
/// <summary>
/// Adds the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="valueComparer">The value comparer.</param>
/// <param name="result">A description of the effect was on adding an element to this <see cref="HashBucket"/>.</param>
/// <returns>A new <see cref="HashBucket"/> that contains the added value and any values already held by this <see cref="HashBucket"/>.</returns>
internal HashBucket Add(T value, IEqualityComparer<T> valueComparer, out OperationResult result)
{
if (this.IsEmpty)
{
result = OperationResult.SizeChanged;
return new HashBucket(value);
}
if (valueComparer.Equals(value, _firstValue) || _additionalElements.IndexOf(value, valueComparer) >= 0)
{
result = OperationResult.NoChangeRequired;
return this;
}
result = OperationResult.SizeChanged;
return new HashBucket(_firstValue, _additionalElements.Add(value));
}
/// <summary>
/// Determines whether the <see cref="HashBucket"/> contains the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="valueComparer">The value comparer.</param>
internal bool Contains(T value, IEqualityComparer<T> valueComparer)
{
if (this.IsEmpty)
{
return false;
}
return valueComparer.Equals(value, _firstValue) || _additionalElements.IndexOf(value, valueComparer) >= 0;
}
/// <summary>
/// Searches the set for a given value and returns the equal value it finds, if any.
/// </summary>
/// <param name="value">The value to search for.</param>
/// <param name="valueComparer">The value comparer.</param>
/// <param name="existingValue">The value from the set that the search found, or the original value if the search yielded no match.</param>
/// <returns>
/// A value indicating whether the search was successful.
/// </returns>
internal bool TryExchange(T value, IEqualityComparer<T> valueComparer, out T existingValue)
{
if (!this.IsEmpty)
{
if (valueComparer.Equals(value, _firstValue))
{
existingValue = _firstValue;
return true;
}
int index = _additionalElements.IndexOf(value, valueComparer);
if (index >= 0)
{
#if !NETSTANDARD1_0
existingValue = _additionalElements.ItemRef(index);
#else
existingValue = _additionalElements[index];
#endif
return true;
}
}
existingValue = value;
return false;
}
/// <summary>
/// Removes the specified value if it exists in the collection.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="equalityComparer">The equality comparer.</param>
/// <param name="result">A description of the effect was on adding an element to this <see cref="HashBucket"/>.</param>
/// <returns>A new <see cref="HashBucket"/> that does not contain the removed value and any values already held by this <see cref="HashBucket"/>.</returns>
internal HashBucket Remove(T value, IEqualityComparer<T> equalityComparer, out OperationResult result)
{
if (this.IsEmpty)
{
result = OperationResult.NoChangeRequired;
return this;
}
if (equalityComparer.Equals(_firstValue, value))
{
if (_additionalElements.IsEmpty)
{
result = OperationResult.SizeChanged;
return new HashBucket();
}
else
{
// We can promote any element from the list into the first position, but it's most efficient
// to remove the root node in the binary tree that implements the list.
int indexOfRootNode = _additionalElements.Left.Count;
result = OperationResult.SizeChanged;
return new HashBucket(_additionalElements.Key, _additionalElements.RemoveAt(indexOfRootNode));
}
}
int index = _additionalElements.IndexOf(value, equalityComparer);
if (index < 0)
{
result = OperationResult.NoChangeRequired;
return this;
}
else
{
result = OperationResult.SizeChanged;
return new HashBucket(_firstValue, _additionalElements.RemoveAt(index));
}
}
/// <summary>
/// Freezes this instance so that any further mutations require new memory allocations.
/// </summary>
internal void Freeze()
{
if (_additionalElements != null)
{
_additionalElements.Freeze();
}
}
/// <summary>
/// Enumerates all the elements in this instance.
/// </summary>
internal struct Enumerator : IEnumerator<T>, IDisposable
{
/// <summary>
/// The bucket being enumerated.
/// </summary>
private readonly HashBucket _bucket;
/// <summary>
/// A value indicating whether this enumerator has been disposed.
/// </summary>
private bool _disposed;
/// <summary>
/// The current position of this enumerator.
/// </summary>
private Position _currentPosition;
/// <summary>
/// The enumerator that represents the current position over the <see cref="_additionalElements"/> of the <see cref="HashBucket"/>.
/// </summary>
private ImmutableList<T>.Enumerator _additionalEnumerator;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableHashSet{T}.HashBucket.Enumerator"/> struct.
/// </summary>
/// <param name="bucket">The bucket.</param>
internal Enumerator(HashBucket bucket)
{
_disposed = false;
_bucket = bucket;
_currentPosition = Position.BeforeFirst;
_additionalEnumerator = default(ImmutableList<T>.Enumerator);
}
/// <summary>
/// Describes the positions the enumerator state machine may be in.
/// </summary>
private enum Position
{
/// <summary>
/// The first element has not yet been moved to.
/// </summary>
BeforeFirst,
/// <summary>
/// We're at the <see cref="_firstValue"/> of the containing bucket.
/// </summary>
First,
/// <summary>
/// We're enumerating the <see cref="_additionalElements"/> in the bucket.
/// </summary>
Additional,
/// <summary>
/// The end of enumeration has been reached.
/// </summary>
End,
}
/// <summary>
/// Gets the current element.
/// </summary>
object IEnumerator.Current
{
get { return this.Current; }
}
/// <summary>
/// Gets the current element.
/// </summary>
public T Current
{
get
{
this.ThrowIfDisposed();
return _currentPosition switch
{
Position.First => _bucket._firstValue,
Position.Additional => _additionalEnumerator.Current,
_ => throw new InvalidOperationException(),
};
}
}
/// <summary>
/// Advances the enumerator to the next element of the collection.
/// </summary>
/// <returns>
/// true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.
/// </returns>
/// <exception cref="InvalidOperationException">The collection was modified after the enumerator was created. </exception>
public bool MoveNext()
{
this.ThrowIfDisposed();
if (_bucket.IsEmpty)
{
_currentPosition = Position.End;
return false;
}
switch (_currentPosition)
{
case Position.BeforeFirst:
_currentPosition = Position.First;
return true;
case Position.First:
if (_bucket._additionalElements.IsEmpty)
{
_currentPosition = Position.End;
return false;
}
_currentPosition = Position.Additional;
_additionalEnumerator = new ImmutableList<T>.Enumerator(_bucket._additionalElements);
return _additionalEnumerator.MoveNext();
case Position.Additional:
return _additionalEnumerator.MoveNext();
case Position.End:
return false;
default:
throw new InvalidOperationException();
}
}
/// <summary>
/// Sets the enumerator to its initial position, which is before the first element in the collection.
/// </summary>
/// <exception cref="InvalidOperationException">The collection was modified after the enumerator was created. </exception>
public void Reset()
{
this.ThrowIfDisposed();
_additionalEnumerator.Dispose();
_currentPosition = Position.BeforeFirst;
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
_disposed = true;
_additionalEnumerator.Dispose();
}
/// <summary>
/// Throws an <see cref="ObjectDisposedException"/> if this enumerator has been disposed.
/// </summary>
private void ThrowIfDisposed()
{
if (_disposed)
{
Requires.FailObjectDisposed(this);
}
}
}
}
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.Collections.Generic;
using System.Text;
namespace Mono.Cecil.Rocks {
public class DocCommentId
{
StringBuilder id;
DocCommentId ()
{
id = new StringBuilder ();
}
void WriteField (FieldDefinition field)
{
WriteDefinition ('F', field);
}
void WriteEvent (EventDefinition @event)
{
WriteDefinition ('E', @event);
}
void WriteType (TypeDefinition type)
{
id.Append ('T').Append (':');
WriteTypeFullName (type);
}
void WriteMethod (MethodDefinition method)
{
WriteDefinition ('M', method);
if (method.HasGenericParameters) {
id.Append ('`').Append ('`');
id.Append (method.GenericParameters.Count);
}
if (method.HasParameters)
WriteParameters (method.Parameters);
if (IsConversionOperator (method))
WriteReturnType (method);
}
static bool IsConversionOperator (MethodDefinition self)
{
if (self == null)
throw new ArgumentNullException ("self");
return self.IsSpecialName
&& (self.Name == "op_Explicit" || self.Name == "op_Implicit");
}
void WriteReturnType (MethodDefinition method)
{
id.Append ('~');
WriteTypeSignature (method.ReturnType);
}
void WriteProperty (PropertyDefinition property)
{
WriteDefinition ('P', property);
if (property.HasParameters)
WriteParameters (property.Parameters);
}
void WriteParameters (IList<ParameterDefinition> parameters)
{
id.Append ('(');
WriteList (parameters, p => WriteTypeSignature (p.ParameterType));
id.Append (')');
}
void WriteTypeSignature (TypeReference type)
{
switch (type.MetadataType)
{
case MetadataType.Array:
WriteArrayTypeSignature ((ArrayType) type);
break;
case MetadataType.ByReference:
WriteTypeSignature (((ByReferenceType) type).ElementType);
id.Append ('@');
break;
case MetadataType.FunctionPointer:
WriteFunctionPointerTypeSignature ((FunctionPointerType) type);
break;
case MetadataType.GenericInstance:
WriteGenericInstanceTypeSignature ((GenericInstanceType) type);
break;
case MetadataType.Var:
id.Append ('`');
id.Append (((GenericParameter) type).Position);
break;
case MetadataType.MVar:
id.Append ('`').Append ('`');
id.Append (((GenericParameter) type).Position);
break;
case MetadataType.OptionalModifier:
WriteModiferTypeSignature ((RequiredModifierType) type, '!');
break;
case MetadataType.RequiredModifier:
WriteModiferTypeSignature ((RequiredModifierType) type, '|');
break;
case MetadataType.Pointer:
WriteTypeSignature (((PointerType) type).ElementType);
id.Append ('*');
break;
default:
WriteTypeFullName (type);
break;
}
}
void WriteGenericInstanceTypeSignature (GenericInstanceType type)
{
WriteTypeSignature (type.ElementType);
id.Append ('{');
WriteList (type.GenericArguments, WriteTypeSignature);
id.Append ('}');
}
void WriteList<T> (IList<T> list, Action<T> action)
{
for (int i = 0; i < list.Count; i++) {
if (i > 0)
id.Append (',');
action (list [i]);
}
}
void WriteModiferTypeSignature (IModifierType type, char id)
{
WriteTypeSignature (type.ElementType);
this.id.Append (id);
WriteTypeSignature (type.ModifierType);
}
void WriteFunctionPointerTypeSignature (FunctionPointerType type)
{
id.Append ("=FUNC:");
WriteTypeFullName (type.ReturnType);
if (type.HasParameters)
WriteParameters (type.Parameters);
}
void WriteArrayTypeSignature (ArrayType type)
{
WriteTypeSignature (type.ElementType);
if (type.IsVector) {
id.Append ("[]");
return;
}
id.Append ("[");
WriteList (type.Dimensions, dimension => {
if (dimension.LowerBound.HasValue)
id.Append (dimension.LowerBound.Value);
id.Append (':');
if (dimension.UpperBound.HasValue)
id.Append (dimension.UpperBound.Value - (dimension.LowerBound.GetValueOrDefault () + 1));
});
id.Append ("]");
}
void WriteDefinition (char id, IMemberDefinition member)
{
this.id.Append (id)
.Append (':');
WriteTypeFullName (member.DeclaringType);
this.id.Append ('.');
WriteItemName (member.Name);
}
void WriteTypeFullName (TypeReference type)
{
if (type.DeclaringType != null) {
WriteTypeFullName (type.DeclaringType);
id.Append ('.');
}
if (!string.IsNullOrEmpty (type.Namespace)) {
id.Append (type.Namespace);
id.Append ('.');
}
id.Append (type.Name);
}
void WriteItemName (string name)
{
id.Append (name.Replace ('.', '#'));
}
public override string ToString ()
{
return id.ToString ();
}
public static string GetDocCommentId (IMemberDefinition member)
{
if (member == null)
throw new ArgumentNullException ("member");
var documentId = new DocCommentId ();
switch (member.MetadataToken.TokenType)
{
case TokenType.Field:
documentId.WriteField ((FieldDefinition) member);
break;
case TokenType.Method:
documentId.WriteMethod ((MethodDefinition) member);
break;
case TokenType.TypeDef:
documentId.WriteType ((TypeDefinition) member);
break;
case TokenType.Event:
documentId.WriteEvent ((EventDefinition) member);
break;
case TokenType.Property:
documentId.WriteProperty ((PropertyDefinition) member);
break;
default:
throw new NotSupportedException (member.FullName);
}
return documentId.ToString ();
}
}
}
| |
// MIT License
//
// Copyright (c) 2009-2017 Luca Piccioni
//
// 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.
//
// This file is automatically generated
#pragma warning disable 649, 1572, 1573
// ReSharper disable RedundantUsingDirective
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using Khronos;
// ReSharper disable CheckNamespace
// ReSharper disable InconsistentNaming
// ReSharper disable JoinDeclarationAndInitializer
namespace OpenGL
{
public partial class Gl
{
/// <summary>
/// [GL] Value of GL_PER_GPU_STORAGE_BIT_NV symbol.
/// </summary>
[RequiredByFeature("GL_NV_gpu_multicast")]
[Log(BitmaskName = "GL")]
public const int PER_GPU_STORAGE_BIT_NV = 0x0800;
/// <summary>
/// [GL] Value of GL_MULTICAST_GPUS_NV symbol.
/// </summary>
[RequiredByFeature("GL_NV_gpu_multicast")]
public const int MULTICAST_GPUS_NV = 0x92BA;
/// <summary>
/// [GL] Value of GL_RENDER_GPU_MASK_NV symbol.
/// </summary>
[RequiredByFeature("GL_NV_gpu_multicast")]
public const int RENDER_GPU_MASK_NV = 0x9558;
/// <summary>
/// [GL] Value of GL_PER_GPU_STORAGE_NV symbol.
/// </summary>
[RequiredByFeature("GL_NV_gpu_multicast")]
public const int PER_GPU_STORAGE_NV = 0x9548;
/// <summary>
/// [GL] Value of GL_MULTICAST_PROGRAMMABLE_SAMPLE_LOCATION_NV symbol.
/// </summary>
[RequiredByFeature("GL_NV_gpu_multicast")]
public const int MULTICAST_PROGRAMMABLE_SAMPLE_LOCATION_NV = 0x9549;
/// <summary>
/// [GL] glRenderGpuMaskNV: Binding for glRenderGpuMaskNV.
/// </summary>
/// <param name="mask">
/// A <see cref="T:uint"/>.
/// </param>
[RequiredByFeature("GL_NV_gpu_multicast")]
public static void RenderGpuMaskNV(uint mask)
{
Debug.Assert(Delegates.pglRenderGpuMaskNV != null, "pglRenderGpuMaskNV not implemented");
Delegates.pglRenderGpuMaskNV(mask);
LogCommand("glRenderGpuMaskNV", null, mask );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glMulticastBufferSubDataNV: Binding for glMulticastBufferSubDataNV.
/// </summary>
/// <param name="gpuMask">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="buffer">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="offset">
/// A <see cref="T:IntPtr"/>.
/// </param>
/// <param name="size">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="data">
/// A <see cref="T:IntPtr"/>.
/// </param>
[RequiredByFeature("GL_NV_gpu_multicast")]
public static void MulticastBufferSubDataNV(uint gpuMask, uint buffer, IntPtr offset, uint size, IntPtr data)
{
unsafe {
{
Debug.Assert(Delegates.pglMulticastBufferSubDataNV != null, "pglMulticastBufferSubDataNV not implemented");
Delegates.pglMulticastBufferSubDataNV(gpuMask, buffer, offset, size, data.ToPointer());
LogCommand("glMulticastBufferSubDataNV", null, gpuMask, buffer, offset, size, data );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glMulticastBufferSubDataNV: Binding for glMulticastBufferSubDataNV.
/// </summary>
/// <param name="gpuMask">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="buffer">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="offset">
/// A <see cref="T:IntPtr"/>.
/// </param>
/// <param name="size">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="data">
/// A <see cref="T:object"/>.
/// </param>
[RequiredByFeature("GL_NV_gpu_multicast")]
public static void MulticastBufferSubDataNV(uint gpuMask, uint buffer, IntPtr offset, uint size, object data)
{
GCHandle pin_data = GCHandle.Alloc(data, GCHandleType.Pinned);
try {
MulticastBufferSubDataNV(gpuMask, buffer, offset, size, pin_data.AddrOfPinnedObject());
} finally {
pin_data.Free();
}
}
/// <summary>
/// [GL] glMulticastCopyBufferSubDataNV: Binding for glMulticastCopyBufferSubDataNV.
/// </summary>
/// <param name="readGpu">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="writeGpuMask">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="readBuffer">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="writeBuffer">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="readOffset">
/// A <see cref="T:IntPtr"/>.
/// </param>
/// <param name="writeOffset">
/// A <see cref="T:IntPtr"/>.
/// </param>
/// <param name="size">
/// A <see cref="T:uint"/>.
/// </param>
[RequiredByFeature("GL_NV_gpu_multicast")]
public static void MulticastCopyBufferSubDataNV(uint readGpu, uint writeGpuMask, uint readBuffer, uint writeBuffer, IntPtr readOffset, IntPtr writeOffset, uint size)
{
Debug.Assert(Delegates.pglMulticastCopyBufferSubDataNV != null, "pglMulticastCopyBufferSubDataNV not implemented");
Delegates.pglMulticastCopyBufferSubDataNV(readGpu, writeGpuMask, readBuffer, writeBuffer, readOffset, writeOffset, size);
LogCommand("glMulticastCopyBufferSubDataNV", null, readGpu, writeGpuMask, readBuffer, writeBuffer, readOffset, writeOffset, size );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glMulticastCopyImageSubDataNV: Binding for glMulticastCopyImageSubDataNV.
/// </summary>
/// <param name="srcGpu">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="dstGpuMask">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="srcName">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="srcTarget">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="srcLevel">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="srcX">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="srcY">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="srcZ">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="dstName">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="dstTarget">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="dstLevel">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="dstX">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="dstY">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="dstZ">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="srcWidth">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="srcHeight">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="srcDepth">
/// A <see cref="T:int"/>.
/// </param>
[RequiredByFeature("GL_NV_gpu_multicast")]
public static void MulticastCopyImageSubDataNV(uint srcGpu, uint dstGpuMask, uint srcName, int srcTarget, int srcLevel, int srcX, int srcY, int srcZ, uint dstName, int dstTarget, int dstLevel, int dstX, int dstY, int dstZ, int srcWidth, int srcHeight, int srcDepth)
{
Debug.Assert(Delegates.pglMulticastCopyImageSubDataNV != null, "pglMulticastCopyImageSubDataNV not implemented");
Delegates.pglMulticastCopyImageSubDataNV(srcGpu, dstGpuMask, srcName, srcTarget, srcLevel, srcX, srcY, srcZ, dstName, dstTarget, dstLevel, dstX, dstY, dstZ, srcWidth, srcHeight, srcDepth);
LogCommand("glMulticastCopyImageSubDataNV", null, srcGpu, dstGpuMask, srcName, srcTarget, srcLevel, srcX, srcY, srcZ, dstName, dstTarget, dstLevel, dstX, dstY, dstZ, srcWidth, srcHeight, srcDepth );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glMulticastBlitFramebufferNV: Binding for glMulticastBlitFramebufferNV.
/// </summary>
/// <param name="srcGpu">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="dstGpu">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="srcX0">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="srcY0">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="srcX1">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="srcY1">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="dstX0">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="dstY0">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="dstX1">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="dstY1">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="mask">
/// A <see cref="T:ClearBufferMask"/>.
/// </param>
/// <param name="filter">
/// A <see cref="T:int"/>.
/// </param>
[RequiredByFeature("GL_NV_gpu_multicast")]
public static void MulticastBlitFramebufferNV(uint srcGpu, uint dstGpu, int srcX0, int srcY0, int srcX1, int srcY1, int dstX0, int dstY0, int dstX1, int dstY1, ClearBufferMask mask, int filter)
{
Debug.Assert(Delegates.pglMulticastBlitFramebufferNV != null, "pglMulticastBlitFramebufferNV not implemented");
Delegates.pglMulticastBlitFramebufferNV(srcGpu, dstGpu, srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, (uint)mask, filter);
LogCommand("glMulticastBlitFramebufferNV", null, srcGpu, dstGpu, srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glMulticastFramebufferSampleLocationsfvNV: Binding for glMulticastFramebufferSampleLocationsfvNV.
/// </summary>
/// <param name="gpu">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="framebuffer">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="start">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="count">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="v">
/// A <see cref="T:float[]"/>.
/// </param>
[RequiredByFeature("GL_NV_gpu_multicast")]
public static void MulticastFramebufferSampleLocationsfvNV(uint gpu, uint framebuffer, uint start, int count, float[] v)
{
unsafe {
fixed (float* p_v = v)
{
Debug.Assert(Delegates.pglMulticastFramebufferSampleLocationsfvNV != null, "pglMulticastFramebufferSampleLocationsfvNV not implemented");
Delegates.pglMulticastFramebufferSampleLocationsfvNV(gpu, framebuffer, start, count, p_v);
LogCommand("glMulticastFramebufferSampleLocationsfvNV", null, gpu, framebuffer, start, count, v );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glMulticastBarrierNV: Binding for glMulticastBarrierNV.
/// </summary>
[RequiredByFeature("GL_NV_gpu_multicast")]
public static void MulticastBarrierNV()
{
Debug.Assert(Delegates.pglMulticastBarrierNV != null, "pglMulticastBarrierNV not implemented");
Delegates.pglMulticastBarrierNV();
LogCommand("glMulticastBarrierNV", null );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glMulticastWaitSyncNV: Binding for glMulticastWaitSyncNV.
/// </summary>
/// <param name="signalGpu">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="waitGpuMask">
/// A <see cref="T:uint"/>.
/// </param>
[RequiredByFeature("GL_NV_gpu_multicast")]
public static void MulticastWaitSyncNV(uint signalGpu, uint waitGpuMask)
{
Debug.Assert(Delegates.pglMulticastWaitSyncNV != null, "pglMulticastWaitSyncNV not implemented");
Delegates.pglMulticastWaitSyncNV(signalGpu, waitGpuMask);
LogCommand("glMulticastWaitSyncNV", null, signalGpu, waitGpuMask );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glMulticastGetQueryObjectivNV: Binding for glMulticastGetQueryObjectivNV.
/// </summary>
/// <param name="gpu">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="id">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="pname">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="params">
/// A <see cref="T:int[]"/>.
/// </param>
[RequiredByFeature("GL_NV_gpu_multicast")]
public static void MulticastGetQueryObjectivNV(uint gpu, uint id, int pname, int[] @params)
{
unsafe {
fixed (int* p_params = @params)
{
Debug.Assert(Delegates.pglMulticastGetQueryObjectivNV != null, "pglMulticastGetQueryObjectivNV not implemented");
Delegates.pglMulticastGetQueryObjectivNV(gpu, id, pname, p_params);
LogCommand("glMulticastGetQueryObjectivNV", null, gpu, id, pname, @params );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glMulticastGetQueryObjectuivNV: Binding for glMulticastGetQueryObjectuivNV.
/// </summary>
/// <param name="gpu">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="id">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="pname">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="params">
/// A <see cref="T:uint[]"/>.
/// </param>
[RequiredByFeature("GL_NV_gpu_multicast")]
public static void MulticastGetQueryObjectuivNV(uint gpu, uint id, int pname, uint[] @params)
{
unsafe {
fixed (uint* p_params = @params)
{
Debug.Assert(Delegates.pglMulticastGetQueryObjectuivNV != null, "pglMulticastGetQueryObjectuivNV not implemented");
Delegates.pglMulticastGetQueryObjectuivNV(gpu, id, pname, p_params);
LogCommand("glMulticastGetQueryObjectuivNV", null, gpu, id, pname, @params );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glMulticastGetQueryObjecti64vNV: Binding for glMulticastGetQueryObjecti64vNV.
/// </summary>
/// <param name="gpu">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="id">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="pname">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="params">
/// A <see cref="T:long[]"/>.
/// </param>
[RequiredByFeature("GL_NV_gpu_multicast")]
public static void MulticastGetQueryObjecti64vNV(uint gpu, uint id, int pname, long[] @params)
{
unsafe {
fixed (long* p_params = @params)
{
Debug.Assert(Delegates.pglMulticastGetQueryObjecti64vNV != null, "pglMulticastGetQueryObjecti64vNV not implemented");
Delegates.pglMulticastGetQueryObjecti64vNV(gpu, id, pname, p_params);
LogCommand("glMulticastGetQueryObjecti64vNV", null, gpu, id, pname, @params );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glMulticastGetQueryObjectui64vNV: Binding for glMulticastGetQueryObjectui64vNV.
/// </summary>
/// <param name="gpu">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="id">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="pname">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="params">
/// A <see cref="T:ulong[]"/>.
/// </param>
[RequiredByFeature("GL_NV_gpu_multicast")]
public static void MulticastGetQueryObjectui64vNV(uint gpu, uint id, int pname, ulong[] @params)
{
unsafe {
fixed (ulong* p_params = @params)
{
Debug.Assert(Delegates.pglMulticastGetQueryObjectui64vNV != null, "pglMulticastGetQueryObjectui64vNV not implemented");
Delegates.pglMulticastGetQueryObjectui64vNV(gpu, id, pname, p_params);
LogCommand("glMulticastGetQueryObjectui64vNV", null, gpu, id, pname, @params );
}
}
DebugCheckErrors(null);
}
internal static unsafe partial class Delegates
{
[RequiredByFeature("GL_NV_gpu_multicast")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glRenderGpuMaskNV(uint mask);
[RequiredByFeature("GL_NV_gpu_multicast")]
[ThreadStatic]
internal static glRenderGpuMaskNV pglRenderGpuMaskNV;
[RequiredByFeature("GL_NV_gpu_multicast")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glMulticastBufferSubDataNV(uint gpuMask, uint buffer, IntPtr offset, uint size, void* data);
[RequiredByFeature("GL_NV_gpu_multicast")]
[ThreadStatic]
internal static glMulticastBufferSubDataNV pglMulticastBufferSubDataNV;
[RequiredByFeature("GL_NV_gpu_multicast")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glMulticastCopyBufferSubDataNV(uint readGpu, uint writeGpuMask, uint readBuffer, uint writeBuffer, IntPtr readOffset, IntPtr writeOffset, uint size);
[RequiredByFeature("GL_NV_gpu_multicast")]
[ThreadStatic]
internal static glMulticastCopyBufferSubDataNV pglMulticastCopyBufferSubDataNV;
[RequiredByFeature("GL_NV_gpu_multicast")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glMulticastCopyImageSubDataNV(uint srcGpu, uint dstGpuMask, uint srcName, int srcTarget, int srcLevel, int srcX, int srcY, int srcZ, uint dstName, int dstTarget, int dstLevel, int dstX, int dstY, int dstZ, int srcWidth, int srcHeight, int srcDepth);
[RequiredByFeature("GL_NV_gpu_multicast")]
[ThreadStatic]
internal static glMulticastCopyImageSubDataNV pglMulticastCopyImageSubDataNV;
[RequiredByFeature("GL_NV_gpu_multicast")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glMulticastBlitFramebufferNV(uint srcGpu, uint dstGpu, int srcX0, int srcY0, int srcX1, int srcY1, int dstX0, int dstY0, int dstX1, int dstY1, uint mask, int filter);
[RequiredByFeature("GL_NV_gpu_multicast")]
[ThreadStatic]
internal static glMulticastBlitFramebufferNV pglMulticastBlitFramebufferNV;
[RequiredByFeature("GL_NV_gpu_multicast")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glMulticastFramebufferSampleLocationsfvNV(uint gpu, uint framebuffer, uint start, int count, float* v);
[RequiredByFeature("GL_NV_gpu_multicast")]
[ThreadStatic]
internal static glMulticastFramebufferSampleLocationsfvNV pglMulticastFramebufferSampleLocationsfvNV;
[RequiredByFeature("GL_NV_gpu_multicast")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glMulticastBarrierNV();
[RequiredByFeature("GL_NV_gpu_multicast")]
[ThreadStatic]
internal static glMulticastBarrierNV pglMulticastBarrierNV;
[RequiredByFeature("GL_NV_gpu_multicast")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glMulticastWaitSyncNV(uint signalGpu, uint waitGpuMask);
[RequiredByFeature("GL_NV_gpu_multicast")]
[ThreadStatic]
internal static glMulticastWaitSyncNV pglMulticastWaitSyncNV;
[RequiredByFeature("GL_NV_gpu_multicast")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glMulticastGetQueryObjectivNV(uint gpu, uint id, int pname, int* @params);
[RequiredByFeature("GL_NV_gpu_multicast")]
[ThreadStatic]
internal static glMulticastGetQueryObjectivNV pglMulticastGetQueryObjectivNV;
[RequiredByFeature("GL_NV_gpu_multicast")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glMulticastGetQueryObjectuivNV(uint gpu, uint id, int pname, uint* @params);
[RequiredByFeature("GL_NV_gpu_multicast")]
[ThreadStatic]
internal static glMulticastGetQueryObjectuivNV pglMulticastGetQueryObjectuivNV;
[RequiredByFeature("GL_NV_gpu_multicast")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glMulticastGetQueryObjecti64vNV(uint gpu, uint id, int pname, long* @params);
[RequiredByFeature("GL_NV_gpu_multicast")]
[ThreadStatic]
internal static glMulticastGetQueryObjecti64vNV pglMulticastGetQueryObjecti64vNV;
[RequiredByFeature("GL_NV_gpu_multicast")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glMulticastGetQueryObjectui64vNV(uint gpu, uint id, int pname, ulong* @params);
[RequiredByFeature("GL_NV_gpu_multicast")]
[ThreadStatic]
internal static glMulticastGetQueryObjectui64vNV pglMulticastGetQueryObjectui64vNV;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using FizzWare.NBuilder.Implementation;
using System.Linq;
using FizzWare.NBuilder.Extensions;
namespace FizzWare.NBuilder.PropertyNaming
{
public abstract class PropertyNamer : IPropertyNamer
{
protected readonly IReflectionUtil ReflectionUtil;
protected const BindingFlags FLAGS = (BindingFlags.Public | BindingFlags.Instance);
private BuilderSettings BuilderSettings;
protected PropertyNamer(IReflectionUtil reflectionUtil, BuilderSettings builderSettings)
{
this.ReflectionUtil = reflectionUtil;
BuilderSettings = builderSettings;
}
public abstract void SetValuesOfAllIn<T>(IList<T> objects);
public virtual void SetValuesOf<T>(T obj)
{
var type = typeof(T);
foreach (var propertyInfo in type.GetProperties(FLAGS).Where(p => p.CanWrite))
SetMemberValue(propertyInfo, obj);
foreach (var propertyInfo in type.GetFields(FLAGS).Where(f => !f.IsLiteral))
SetMemberValue(propertyInfo, obj);
}
protected static object GetCurrentValue<T>(MemberInfo memberInfo, T obj)
{
object currentValue = null;
if (memberInfo is FieldInfo)
{
currentValue = ((FieldInfo)memberInfo).GetValue(obj);
}
if (memberInfo is PropertyInfo)
{
try
{
if (((PropertyInfo)memberInfo).GetGetMethod() != null)
{
currentValue = ((PropertyInfo)memberInfo).GetValue(obj, null);
}
}
catch (Exception)
{
Debug.WriteLine(string.Format("NBuilder warning: {0} threw an exception when attempting to read its current value", memberInfo.Name));
}
}
return currentValue;
}
protected static Type GetMemberType(MemberInfo memberInfo)
{
Type type = null;
if (memberInfo is FieldInfo)
{
type = ((FieldInfo)memberInfo).FieldType;
}
if (memberInfo is PropertyInfo)
{
type = ((PropertyInfo)memberInfo).PropertyType;
}
if (type != null && IsNullableType(type))
{
type = Nullable.GetUnderlyingType(type);
}
return type;
}
private static bool IsNullableType(Type type)
{
return (type.IsGenericType() && type.GetGenericTypeDefinition() == typeof(Nullable<>));
}
protected virtual void SetValue<T>(MemberInfo memberInfo, T obj, object value)
{
if (value == null) return;
if (!IsMutable(memberInfo)) return;
switch (memberInfo)
{
case FieldInfo info:
info.SetValue(obj, value);
break;
case PropertyInfo info:
{
if (info.CanWrite)
info.SetValue(obj, value, null);
break;
}
}
}
protected virtual bool IsMutable(MemberInfo member)
{
var declaringType = member.DeclaringType;
switch (member.MemberType)
{
case MemberTypes.Constructor:
case MemberTypes.Event:
case MemberTypes.Method:
case MemberTypes.TypeInfo:
case MemberTypes.Custom:
case MemberTypes.NestedType:
case MemberTypes.All:
return false;
case MemberTypes.Field:
return !declaringType.GetFields().First(f => f.Name == member.Name).IsStatic;
case MemberTypes.Property:
return !declaringType.GetProperties().First(f => f.Name == member.Name).GetAccessors(true)
.Any(x => x.IsStatic);
default:
throw new ArgumentOutOfRangeException();
}
}
protected virtual void HandleUnknownType<T>(Type memberType, MemberInfo memberInfo, T obj)
{
}
protected abstract short GetInt16(MemberInfo memberInfo);
protected abstract int GetInt32(MemberInfo memberInfo);
protected abstract long GetInt64(MemberInfo memberInfo);
protected abstract decimal GetDecimal(MemberInfo memberInfo);
protected abstract float GetSingle(MemberInfo memberInfo);
protected abstract double GetDouble(MemberInfo memberInfo);
protected abstract ushort GetUInt16(MemberInfo memberInfo);
protected abstract uint GetUInt32(MemberInfo memberInfo);
protected abstract ulong GetUInt64(MemberInfo memberInfo);
protected abstract sbyte GetSByte(MemberInfo memberInfo);
protected abstract byte GetByte(MemberInfo memberInfo);
protected abstract DateTime GetDateTime(MemberInfo memberInfo, DateTimeKind kind = DateTimeKind.Unspecified);
protected abstract string GetString(MemberInfo memberInfo);
protected abstract bool GetBoolean(MemberInfo memberInfo);
protected abstract char GetChar(MemberInfo memberInfo);
protected abstract Enum GetEnum(MemberInfo memberInfo);
protected abstract Guid GetGuid(MemberInfo memberInfo);
protected abstract TimeSpan GetTimeSpan(MemberInfo memberInfo);
protected virtual bool ShouldIgnore(MemberInfo memberInfo)
{
if (memberInfo is PropertyInfo)
if (BuilderSettings.ShouldIgnoreProperty(((PropertyInfo)memberInfo)))
return true;
return false;
}
protected virtual void SetMemberValue<T>(MemberInfo memberInfo, T obj)
{
Type type = GetMemberType(memberInfo);
if (BuilderSettings.HasDisabledAutoNameProperties && ShouldIgnore(memberInfo))
return;
object currentValue = GetCurrentValue(memberInfo, obj);
if (!ReflectionUtil.IsDefaultValue(currentValue))
return;
object value = null;
if (type == typeof(short))
{
value = GetInt16(memberInfo);
}
else if (type == typeof(int))
{
value = GetInt32(memberInfo);
}
else if (type == typeof(long))
{
value = GetInt64(memberInfo);
}
else if (type == typeof(decimal))
{
value = GetDecimal(memberInfo);
}
else if (type == typeof(float))
{
value = GetSingle(memberInfo);
}
else if (type == typeof(double))
{
value = GetDouble(memberInfo);
}
else if (type == typeof(ushort))
{
value = GetUInt16(memberInfo);
}
else if (type == typeof(uint))
{
value = GetUInt32(memberInfo);
}
else if (type == typeof(ulong))
{
value = GetUInt64(memberInfo);
}
else if (type == typeof(char))
{
value = GetChar(memberInfo);
}
else if (type == typeof(byte))
{
value = GetByte(memberInfo);
}
else if (type == typeof(sbyte))
{
value = GetSByte(memberInfo);
}
else if (type == typeof(DateTime))
{
value = GetDateTime(memberInfo);
}
else if (type == typeof(string))
{
value = GetString(memberInfo);
}
else if (type == typeof(bool))
{
value = GetBoolean(memberInfo);
}
else if (type.BaseType() == typeof(Enum))
{
value = GetEnum(memberInfo);
}
else if (type == typeof(Guid))
{
value = GetGuid(memberInfo);
}
else if (type == typeof(TimeSpan))
{
value = GetTimeSpan(memberInfo);
}
else
{
HandleUnknownType(type, memberInfo, obj);
}
SetValue(memberInfo, obj, value);
}
protected static Array GetEnumValues(Type enumType)
{
var enumArray = EnumHelper.GetValues(enumType);
return enumArray;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Infrastructure;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Options;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.ApplicationModels
{
public class AuthorizationApplicationModelProviderTest
{
private readonly IOptions<MvcOptions> OptionsWithoutEndpointRouting = Options.Create(new MvcOptions { EnableEndpointRouting = false });
[Fact]
public void OnProvidersExecuting_AuthorizeAttribute_DoesNothing_WhenEnableRoutingIsEnabled()
{
// Arrange
var provider = new AuthorizationApplicationModelProvider(
new DefaultAuthorizationPolicyProvider(Options.Create(new AuthorizationOptions())),
Options.Create(new MvcOptions()));
var controllerType = typeof(AccountController);
var context = CreateProviderContext(controllerType);
// Act
provider.OnProvidersExecuting(context);
// Assert
var controller = Assert.Single(context.Result.Controllers);
Assert.Empty(controller.Filters);
}
[Fact]
public void OnProvidersExecuting_AllowAnonymousAttribute_DoesNothing_WhenEnableRoutingIsEnabled()
{
// Arrange
var provider = new AuthorizationApplicationModelProvider(
new DefaultAuthorizationPolicyProvider(Options.Create(new AuthorizationOptions())),
Options.Create(new MvcOptions()));
var controllerType = typeof(AnonymousController);
var context = CreateProviderContext(controllerType);
// Act
provider.OnProvidersExecuting(context);
// Assert
var controller = Assert.Single(context.Result.Controllers);
Assert.Empty(controller.Filters);
}
[Fact]
public void CreateControllerModel_AuthorizeAttributeAddsAuthorizeFilter()
{
// Arrange
var provider = new AuthorizationApplicationModelProvider(
new DefaultAuthorizationPolicyProvider(Options.Create(new AuthorizationOptions())),
OptionsWithoutEndpointRouting);
var controllerType = typeof(AccountController);
var context = CreateProviderContext(controllerType);
// Act
provider.OnProvidersExecuting(context);
// Assert
var controller = Assert.Single(context.Result.Controllers);
Assert.Single(controller.Filters, f => f is AuthorizeFilter);
}
[Fact]
public void BuildActionModels_BaseAuthorizeFiltersAreStillValidWhenOverriden()
{
// Arrange
var options = Options.Create(new AuthorizationOptions());
options.Value.AddPolicy("Base", policy => policy.RequireClaim("Basic").RequireClaim("Basic2"));
options.Value.AddPolicy("Derived", policy => policy.RequireClaim("Derived"));
var provider = new AuthorizationApplicationModelProvider(
new DefaultAuthorizationPolicyProvider(options),
OptionsWithoutEndpointRouting);
var context = CreateProviderContext(typeof(DerivedController));
// Act
provider.OnProvidersExecuting(context);
// Assert
var controller = Assert.Single(context.Result.Controllers);
var action = Assert.Single(controller.Actions);
Assert.Equal("Authorize", action.ActionName);
var attributeRoutes = action.Selectors.Where(sm => sm.AttributeRouteModel != null);
Assert.Empty(attributeRoutes);
var authorizeFilters = action.Filters.OfType<AuthorizeFilter>();
Assert.Single(authorizeFilters);
Assert.NotNull(authorizeFilters.First().Policy);
Assert.Equal(3, authorizeFilters.First().Policy.Requirements.Count()); // Basic + Basic2 + Derived authorize
}
[Fact]
public void CreateControllerModelAndActionModel_AllowAnonymousAttributeAddsAllowAnonymousFilter()
{
// Arrange
var provider = new AuthorizationApplicationModelProvider(
new DefaultAuthorizationPolicyProvider(Options.Create(new AuthorizationOptions())),
OptionsWithoutEndpointRouting);
var context = CreateProviderContext(typeof(AnonymousController));
// Act
provider.OnProvidersExecuting(context);
// Assert
var controller = Assert.Single(context.Result.Controllers);
Assert.Single(controller.Filters, f => f is AllowAnonymousFilter);
var action = Assert.Single(controller.Actions);
Assert.Single(action.Filters, f => f is AllowAnonymousFilter);
}
[Fact]
public void OnProvidersExecuting_DefaultPolicyProvider_NoAuthorizationData_NoFilterCreated()
{
// Arrange
var requirements = new IAuthorizationRequirement[]
{
new AssertionRequirement((con) => { return true; })
};
var authorizationPolicy = new AuthorizationPolicy(requirements, new string[] { "dingos" });
var authOptions = Options.Create(new AuthorizationOptions());
authOptions.Value.AddPolicy("Base", authorizationPolicy);
var policyProvider = new DefaultAuthorizationPolicyProvider(authOptions);
var provider = new AuthorizationApplicationModelProvider(policyProvider, OptionsWithoutEndpointRouting);
var context = CreateProviderContext(typeof(BaseController));
// Act
var action = GetBaseControllerActionModel(provider);
// Assert
var authorizationFilter = Assert.IsType<AuthorizeFilter>(Assert.Single(action.Filters));
Assert.NotNull(authorizationFilter.Policy);
Assert.Null(authorizationFilter.AuthorizeData);
Assert.Null(authorizationFilter.PolicyProvider);
}
[Fact]
public void OnProvidersExecuting_NonDefaultPolicyProvider_HasNoPolicy_HasPolicyProviderAndAuthorizeData()
{
// Arrange
var requirements = new IAuthorizationRequirement[]
{
new AssertionRequirement((con) => { return true; })
};
var authorizationPolicy = new AuthorizationPolicy(requirements, new string[] { "dingos" });
var authorizationPolicyProviderMock = new Mock<IAuthorizationPolicyProvider>();
authorizationPolicyProviderMock
.Setup(s => s.GetPolicyAsync(It.IsAny<string>()))
.Returns(Task.FromResult(authorizationPolicy))
.Verifiable();
var provider = new AuthorizationApplicationModelProvider(authorizationPolicyProviderMock.Object, OptionsWithoutEndpointRouting);
// Act
var action = GetBaseControllerActionModel(provider);
// Assert
var actionFilter = Assert.IsType<AuthorizeFilter>(Assert.Single(action.Filters));
Assert.Null(actionFilter.Policy);
Assert.NotNull(actionFilter.AuthorizeData);
Assert.NotNull(actionFilter.PolicyProvider);
}
[Fact]
public void CreateControllerModelAndActionModel_NoAuthNoFilter()
{
// Arrange
var provider = new AuthorizationApplicationModelProvider(
new DefaultAuthorizationPolicyProvider(Options.Create(new AuthorizationOptions())),
OptionsWithoutEndpointRouting);
var context = CreateProviderContext(typeof(NoAuthController));
// Act
provider.OnProvidersExecuting(context);
// Assert
var controller = Assert.Single(context.Result.Controllers);
Assert.Empty(controller.Filters);
var action = Assert.Single(controller.Actions);
Assert.Empty(action.Filters);
}
private ActionModel GetBaseControllerActionModel(AuthorizationApplicationModelProvider authorizationApplicationModelProvider)
{
var context = CreateProviderContext(typeof(BaseController));
authorizationApplicationModelProvider.OnProvidersExecuting(context);
var controller = Assert.Single(context.Result.Controllers);
Assert.Empty(controller.Filters);
var action = Assert.Single(controller.Actions);
return action;
}
private static ApplicationModelProviderContext CreateProviderContext(Type controllerType)
{
var defaultProvider = new DefaultApplicationModelProvider(
Options.Create(new MvcOptions()),
new EmptyModelMetadataProvider());
var context = new ApplicationModelProviderContext(new[] { controllerType.GetTypeInfo() });
defaultProvider.OnProvidersExecuting(context);
return context;
}
private class BaseController
{
[Authorize(Policy = "Base")]
public virtual void Authorize()
{
}
}
private class DerivedController : BaseController
{
[Authorize(Policy = "Derived")]
public override void Authorize()
{
}
}
[Authorize]
public class AccountController
{
}
public class NoAuthController
{
public void NoAuthAction()
{ }
}
[AllowAnonymous]
public class AnonymousController
{
[AllowAnonymous]
public void SomeAction()
{
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;
using pbd = global::Google.ProtocolBuffers.Descriptors;
using scg = global::System.Collections.Generic;
namespace Google.ProtocolBuffers.TestProtos {
public static partial class UnitTestCSharpOptionsProtoFile {
#region Extension registration
public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
}
#endregion
#region Static variables
internal static pbd::MessageDescriptor internal__static_protobuf_unittest_OptionsMessage__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.OptionsMessage, global::Google.ProtocolBuffers.TestProtos.OptionsMessage.Builder> internal__static_protobuf_unittest_OptionsMessage__FieldAccessorTable;
#endregion
#region Descriptor
public static pbd::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbd::FileDescriptor descriptor;
static UnitTestCSharpOptionsProtoFile() {
byte[] descriptorData = global::System.Convert.FromBase64String(
"Ci1nb29nbGUvcHJvdG9idWYvdW5pdHRlc3RfY3NoYXJwX29wdGlvbnMucHJv" +
"dG8SEXByb3RvYnVmX3VuaXR0ZXN0GiRnb29nbGUvcHJvdG9idWYvY3NoYXJw" +
"X29wdGlvbnMucHJvdG8iXgoOT3B0aW9uc01lc3NhZ2USDgoGbm9ybWFsGAEg" +
"ASgJEhcKD29wdGlvbnNfbWVzc2FnZRgCIAEoCRIjCgpjdXN0b21pemVkGAMg" +
"ASgJQg/CPgwKCkN1c3RvbU5hbWVCRsI+QwohR29vZ2xlLlByb3RvY29sQnVm" +
"ZmVycy5UZXN0UHJvdG9zEh5Vbml0VGVzdENTaGFycE9wdGlvbnNQcm90b0Zp" +
"bGU=");
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_protobuf_unittest_OptionsMessage__Descriptor = Descriptor.MessageTypes[0];
internal__static_protobuf_unittest_OptionsMessage__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.OptionsMessage, global::Google.ProtocolBuffers.TestProtos.OptionsMessage.Builder>(internal__static_protobuf_unittest_OptionsMessage__Descriptor,
new string[] { "Normal", "OptionsMessage_", "CustomName", });
pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance();
RegisterAllExtensions(registry);
global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.RegisterAllExtensions(registry);
return registry;
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.Descriptor,
}, assigner);
}
#endregion
}
#region Messages
public sealed partial class OptionsMessage : pb::GeneratedMessage<OptionsMessage, OptionsMessage.Builder> {
private static readonly OptionsMessage defaultInstance = new Builder().BuildPartial();
public static OptionsMessage DefaultInstance {
get { return defaultInstance; }
}
public override OptionsMessage DefaultInstanceForType {
get { return defaultInstance; }
}
protected override OptionsMessage ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::Google.ProtocolBuffers.TestProtos.UnitTestCSharpOptionsProtoFile.internal__static_protobuf_unittest_OptionsMessage__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<OptionsMessage, OptionsMessage.Builder> InternalFieldAccessors {
get { return global::Google.ProtocolBuffers.TestProtos.UnitTestCSharpOptionsProtoFile.internal__static_protobuf_unittest_OptionsMessage__FieldAccessorTable; }
}
public const int NormalFieldNumber = 1;
private bool hasNormal;
private string normal_ = "";
public bool HasNormal {
get { return hasNormal; }
}
public string Normal {
get { return normal_; }
}
public const int OptionsMessage_FieldNumber = 2;
private bool hasOptionsMessage_;
private string optionsMessage_ = "";
public bool HasOptionsMessage_ {
get { return hasOptionsMessage_; }
}
public string OptionsMessage_ {
get { return optionsMessage_; }
}
public const int CustomNameFieldNumber = 3;
private bool hasCustomName;
private string customized_ = "";
public bool HasCustomName {
get { return hasCustomName; }
}
public string CustomName {
get { return customized_; }
}
public override bool IsInitialized {
get {
return true;
}
}
public override void WriteTo(pb::CodedOutputStream output) {
int size = SerializedSize;
if (HasNormal) {
output.WriteString(1, Normal);
}
if (HasOptionsMessage_) {
output.WriteString(2, OptionsMessage_);
}
if (HasCustomName) {
output.WriteString(3, CustomName);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (HasNormal) {
size += pb::CodedOutputStream.ComputeStringSize(1, Normal);
}
if (HasOptionsMessage_) {
size += pb::CodedOutputStream.ComputeStringSize(2, OptionsMessage_);
}
if (HasCustomName) {
size += pb::CodedOutputStream.ComputeStringSize(3, CustomName);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
}
public static OptionsMessage ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static OptionsMessage ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static OptionsMessage ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static OptionsMessage ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static OptionsMessage ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static OptionsMessage ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static OptionsMessage ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static OptionsMessage ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static OptionsMessage ParseFrom(pb::CodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static OptionsMessage ParseFrom(pb::CodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
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(OptionsMessage prototype) {
return (Builder) new Builder().MergeFrom(prototype);
}
public sealed partial class Builder : pb::GeneratedBuilder<OptionsMessage, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {}
OptionsMessage result = new OptionsMessage();
protected override OptionsMessage MessageBeingBuilt {
get { return result; }
}
public override Builder Clear() {
result = new OptionsMessage();
return this;
}
public override Builder Clone() {
return new Builder().MergeFrom(result);
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::Google.ProtocolBuffers.TestProtos.OptionsMessage.Descriptor; }
}
public override OptionsMessage DefaultInstanceForType {
get { return global::Google.ProtocolBuffers.TestProtos.OptionsMessage.DefaultInstance; }
}
public override OptionsMessage BuildPartial() {
if (result == null) {
throw new global::System.InvalidOperationException("build() has already been called on this Builder");
}
OptionsMessage returnMe = result;
result = null;
return returnMe;
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is OptionsMessage) {
return MergeFrom((OptionsMessage) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(OptionsMessage other) {
if (other == global::Google.ProtocolBuffers.TestProtos.OptionsMessage.DefaultInstance) return this;
if (other.HasNormal) {
Normal = other.Normal;
}
if (other.HasOptionsMessage_) {
OptionsMessage_ = other.OptionsMessage_;
}
if (other.HasCustomName) {
CustomName = other.CustomName;
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::CodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::CodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
pb::UnknownFieldSet.Builder unknownFields = null;
while (true) {
uint tag = input.ReadTag();
switch (tag) {
case 0: {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
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);
break;
}
case 10: {
Normal = input.ReadString();
break;
}
case 18: {
OptionsMessage_ = input.ReadString();
break;
}
case 26: {
CustomName = input.ReadString();
break;
}
}
}
}
public bool HasNormal {
get { return result.HasNormal; }
}
public string Normal {
get { return result.Normal; }
set { SetNormal(value); }
}
public Builder SetNormal(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
result.hasNormal = true;
result.normal_ = value;
return this;
}
public Builder ClearNormal() {
result.hasNormal = false;
result.normal_ = "";
return this;
}
public bool HasOptionsMessage_ {
get { return result.HasOptionsMessage_; }
}
public string OptionsMessage_ {
get { return result.OptionsMessage_; }
set { SetOptionsMessage_(value); }
}
public Builder SetOptionsMessage_(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
result.hasOptionsMessage_ = true;
result.optionsMessage_ = value;
return this;
}
public Builder ClearOptionsMessage_() {
result.hasOptionsMessage_ = false;
result.optionsMessage_ = "";
return this;
}
public bool HasCustomName {
get { return result.HasCustomName; }
}
public string CustomName {
get { return result.CustomName; }
set { SetCustomName(value); }
}
public Builder SetCustomName(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
result.hasCustomName = true;
result.customized_ = value;
return this;
}
public Builder ClearCustomName() {
result.hasCustomName = false;
result.customized_ = "";
return this;
}
}
static OptionsMessage() {
object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.UnitTestCSharpOptionsProtoFile.Descriptor, null);
}
}
#endregion
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ApiManagement
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ApiOperationOperations operations.
/// </summary>
public partial interface IApiOperationOperations
{
/// <summary>
/// Lists a collection of the operations for the specified API.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='apiId'>
/// API identifier. Must be unique in the current API Management
/// service instance.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<OperationContract>>> ListByApiWithHttpMessagesAsync(string resourceGroupName, string serviceName, string apiId, ODataQuery<OperationContract> odataQuery = default(ODataQuery<OperationContract>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the details of the API Operation specified by its identifier.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='apiId'>
/// API identifier. Must be unique in the current API Management
/// service instance.
/// </param>
/// <param name='operationId'>
/// Operation identifier within an API. Must be unique in the current
/// API Management service instance.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<OperationContract,ApiOperationGetHeaders>> GetWithHttpMessagesAsync(string resourceGroupName, string serviceName, string apiId, string operationId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates a new operation in the API or updates an existing one.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='apiId'>
/// API identifier. Must be unique in the current API Management
/// service instance.
/// </param>
/// <param name='operationId'>
/// Operation identifier within an API. Must be unique in the current
/// API Management service instance.
/// </param>
/// <param name='parameters'>
/// Create parameters.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<OperationContract>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serviceName, string apiId, string operationId, OperationContract parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates the details of the operation in the API specified by its
/// identifier.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='apiId'>
/// API identifier. Must be unique in the current API Management
/// service instance.
/// </param>
/// <param name='operationId'>
/// Operation identifier within an API. Must be unique in the current
/// API Management service instance.
/// </param>
/// <param name='parameters'>
/// API Operation Update parameters.
/// </param>
/// <param name='ifMatch'>
/// ETag of the API Operation Entity. ETag should match the current
/// entity state from the header response of the GET request or it
/// should be * for unconditional update.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> UpdateWithHttpMessagesAsync(string resourceGroupName, string serviceName, string apiId, string operationId, OperationUpdateContract parameters, string ifMatch, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified operation in the API.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='apiId'>
/// API identifier. Must be unique in the current API Management
/// service instance.
/// </param>
/// <param name='operationId'>
/// Operation identifier within an API. Must be unique in the current
/// API Management service instance.
/// </param>
/// <param name='ifMatch'>
/// ETag of the API Operation Entity. ETag should match the current
/// entity state from the header response of the GET request or it
/// should be * for unconditional update.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string serviceName, string apiId, string operationId, string ifMatch, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists a collection of the operations for the specified API.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<OperationContract>>> ListByApiNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
namespace Aardvark.Base.Coder
{
// AUTO GENERATED CODE - DO NOT CHANGE!
public partial class StreamCodeReader
{
#region Vectors
public V2i ReadV2i()
{
return new V2i(ReadInt32(), ReadInt32());
}
public V2l ReadV2l()
{
return new V2l(ReadInt64(), ReadInt64());
}
public V2f ReadV2f()
{
return new V2f(ReadSingle(), ReadSingle());
}
public V2d ReadV2d()
{
return new V2d(ReadDouble(), ReadDouble());
}
public V3i ReadV3i()
{
return new V3i(ReadInt32(), ReadInt32(), ReadInt32());
}
public V3l ReadV3l()
{
return new V3l(ReadInt64(), ReadInt64(), ReadInt64());
}
public V3f ReadV3f()
{
return new V3f(ReadSingle(), ReadSingle(), ReadSingle());
}
public V3d ReadV3d()
{
return new V3d(ReadDouble(), ReadDouble(), ReadDouble());
}
public V4i ReadV4i()
{
return new V4i(ReadInt32(), ReadInt32(), ReadInt32(), ReadInt32());
}
public V4l ReadV4l()
{
return new V4l(ReadInt64(), ReadInt64(), ReadInt64(), ReadInt64());
}
public V4f ReadV4f()
{
return new V4f(ReadSingle(), ReadSingle(), ReadSingle(), ReadSingle());
}
public V4d ReadV4d()
{
return new V4d(ReadDouble(), ReadDouble(), ReadDouble(), ReadDouble());
}
#endregion
#region Matrices
public M22i ReadM22i()
{
return new M22i(
ReadInt32(), ReadInt32(),
ReadInt32(), ReadInt32()
);
}
public M22l ReadM22l()
{
return new M22l(
ReadInt64(), ReadInt64(),
ReadInt64(), ReadInt64()
);
}
public M22f ReadM22f()
{
return new M22f(
ReadSingle(), ReadSingle(),
ReadSingle(), ReadSingle()
);
}
public M22d ReadM22d()
{
return new M22d(
ReadDouble(), ReadDouble(),
ReadDouble(), ReadDouble()
);
}
public M23i ReadM23i()
{
return new M23i(
ReadInt32(), ReadInt32(), ReadInt32(),
ReadInt32(), ReadInt32(), ReadInt32()
);
}
public M23l ReadM23l()
{
return new M23l(
ReadInt64(), ReadInt64(), ReadInt64(),
ReadInt64(), ReadInt64(), ReadInt64()
);
}
public M23f ReadM23f()
{
return new M23f(
ReadSingle(), ReadSingle(), ReadSingle(),
ReadSingle(), ReadSingle(), ReadSingle()
);
}
public M23d ReadM23d()
{
return new M23d(
ReadDouble(), ReadDouble(), ReadDouble(),
ReadDouble(), ReadDouble(), ReadDouble()
);
}
public M33i ReadM33i()
{
return new M33i(
ReadInt32(), ReadInt32(), ReadInt32(),
ReadInt32(), ReadInt32(), ReadInt32(),
ReadInt32(), ReadInt32(), ReadInt32()
);
}
public M33l ReadM33l()
{
return new M33l(
ReadInt64(), ReadInt64(), ReadInt64(),
ReadInt64(), ReadInt64(), ReadInt64(),
ReadInt64(), ReadInt64(), ReadInt64()
);
}
public M33f ReadM33f()
{
return new M33f(
ReadSingle(), ReadSingle(), ReadSingle(),
ReadSingle(), ReadSingle(), ReadSingle(),
ReadSingle(), ReadSingle(), ReadSingle()
);
}
public M33d ReadM33d()
{
return new M33d(
ReadDouble(), ReadDouble(), ReadDouble(),
ReadDouble(), ReadDouble(), ReadDouble(),
ReadDouble(), ReadDouble(), ReadDouble()
);
}
public M34i ReadM34i()
{
return new M34i(
ReadInt32(), ReadInt32(), ReadInt32(), ReadInt32(),
ReadInt32(), ReadInt32(), ReadInt32(), ReadInt32(),
ReadInt32(), ReadInt32(), ReadInt32(), ReadInt32()
);
}
public M34l ReadM34l()
{
return new M34l(
ReadInt64(), ReadInt64(), ReadInt64(), ReadInt64(),
ReadInt64(), ReadInt64(), ReadInt64(), ReadInt64(),
ReadInt64(), ReadInt64(), ReadInt64(), ReadInt64()
);
}
public M34f ReadM34f()
{
return new M34f(
ReadSingle(), ReadSingle(), ReadSingle(), ReadSingle(),
ReadSingle(), ReadSingle(), ReadSingle(), ReadSingle(),
ReadSingle(), ReadSingle(), ReadSingle(), ReadSingle()
);
}
public M34d ReadM34d()
{
return new M34d(
ReadDouble(), ReadDouble(), ReadDouble(), ReadDouble(),
ReadDouble(), ReadDouble(), ReadDouble(), ReadDouble(),
ReadDouble(), ReadDouble(), ReadDouble(), ReadDouble()
);
}
public M44i ReadM44i()
{
return new M44i(
ReadInt32(), ReadInt32(), ReadInt32(), ReadInt32(),
ReadInt32(), ReadInt32(), ReadInt32(), ReadInt32(),
ReadInt32(), ReadInt32(), ReadInt32(), ReadInt32(),
ReadInt32(), ReadInt32(), ReadInt32(), ReadInt32()
);
}
public M44l ReadM44l()
{
return new M44l(
ReadInt64(), ReadInt64(), ReadInt64(), ReadInt64(),
ReadInt64(), ReadInt64(), ReadInt64(), ReadInt64(),
ReadInt64(), ReadInt64(), ReadInt64(), ReadInt64(),
ReadInt64(), ReadInt64(), ReadInt64(), ReadInt64()
);
}
public M44f ReadM44f()
{
return new M44f(
ReadSingle(), ReadSingle(), ReadSingle(), ReadSingle(),
ReadSingle(), ReadSingle(), ReadSingle(), ReadSingle(),
ReadSingle(), ReadSingle(), ReadSingle(), ReadSingle(),
ReadSingle(), ReadSingle(), ReadSingle(), ReadSingle()
);
}
public M44d ReadM44d()
{
return new M44d(
ReadDouble(), ReadDouble(), ReadDouble(), ReadDouble(),
ReadDouble(), ReadDouble(), ReadDouble(), ReadDouble(),
ReadDouble(), ReadDouble(), ReadDouble(), ReadDouble(),
ReadDouble(), ReadDouble(), ReadDouble(), ReadDouble()
);
}
#endregion
#region Ranges and Boxes
public Range1b ReadRange1b()
{
return new Range1b(ReadByte(), ReadByte());
}
public Range1sb ReadRange1sb()
{
return new Range1sb(ReadSByte(), ReadSByte());
}
public Range1s ReadRange1s()
{
return new Range1s(ReadInt16(), ReadInt16());
}
public Range1us ReadRange1us()
{
return new Range1us(ReadUInt16(), ReadUInt16());
}
public Range1i ReadRange1i()
{
return new Range1i(ReadInt32(), ReadInt32());
}
public Range1ui ReadRange1ui()
{
return new Range1ui(ReadUInt32(), ReadUInt32());
}
public Range1l ReadRange1l()
{
return new Range1l(ReadInt64(), ReadInt64());
}
public Range1ul ReadRange1ul()
{
return new Range1ul(ReadUInt64(), ReadUInt64());
}
public Range1f ReadRange1f()
{
return new Range1f(ReadSingle(), ReadSingle());
}
public Range1d ReadRange1d()
{
return new Range1d(ReadDouble(), ReadDouble());
}
public Box2i ReadBox2i()
{
return new Box2i(ReadV2i(), ReadV2i());
}
public Box2l ReadBox2l()
{
return new Box2l(ReadV2l(), ReadV2l());
}
public Box2f ReadBox2f()
{
return new Box2f(ReadV2f(), ReadV2f());
}
public Box2d ReadBox2d()
{
return new Box2d(ReadV2d(), ReadV2d());
}
public Box3i ReadBox3i()
{
return new Box3i(ReadV3i(), ReadV3i());
}
public Box3l ReadBox3l()
{
return new Box3l(ReadV3l(), ReadV3l());
}
public Box3f ReadBox3f()
{
return new Box3f(ReadV3f(), ReadV3f());
}
public Box3d ReadBox3d()
{
return new Box3d(ReadV3d(), ReadV3d());
}
#endregion
#region Colors
public C3b ReadC3b()
{
return new C3b(ReadByte(), ReadByte(), ReadByte());
}
public C3us ReadC3us()
{
return new C3us(ReadUInt16(), ReadUInt16(), ReadUInt16());
}
public C3ui ReadC3ui()
{
return new C3ui(ReadUInt32(), ReadUInt32(), ReadUInt32());
}
public C3f ReadC3f()
{
return new C3f(ReadSingle(), ReadSingle(), ReadSingle());
}
public C3d ReadC3d()
{
return new C3d(ReadDouble(), ReadDouble(), ReadDouble());
}
public C4b ReadC4b()
{
return new C4b(ReadByte(), ReadByte(), ReadByte(), ReadByte());
}
public C4us ReadC4us()
{
return new C4us(ReadUInt16(), ReadUInt16(), ReadUInt16(), ReadUInt16());
}
public C4ui ReadC4ui()
{
return new C4ui(ReadUInt32(), ReadUInt32(), ReadUInt32(), ReadUInt32());
}
public C4f ReadC4f()
{
return new C4f(ReadSingle(), ReadSingle(), ReadSingle(), ReadSingle());
}
public C4d ReadC4d()
{
return new C4d(ReadDouble(), ReadDouble(), ReadDouble(), ReadDouble());
}
#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.Diagnostics.Contracts;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Cryptography;
using System.Security.Principal;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Security;
using System.ServiceModel.Security.Tokens;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using SecurityUtils = System.ServiceModel.Security.SecurityUtils;
namespace System.ServiceModel.Channels
{
internal class HttpChannelFactory<TChannel>
: TransportChannelFactory<TChannel>,
IHttpTransportFactorySettings
{
private static CacheControlHeaderValue s_requestCacheHeader = new CacheControlHeaderValue { NoCache = true, MaxAge = new TimeSpan(0) };
protected readonly ClientWebSocketFactory _clientWebSocketFactory;
private bool _allowCookies;
private AuthenticationSchemes _authenticationScheme;
private HttpCookieContainerManager _httpCookieContainerManager;
private HttpClient _httpClient;
private volatile MruCache<string, string> _credentialHashCache;
private volatile MruCache<string, HttpClient> _httpClientCache;
private int _maxBufferSize;
private SecurityCredentialsManager _channelCredentials;
private SecurityTokenManager _securityTokenManager;
private TransferMode _transferMode;
private ISecurityCapabilities _securityCapabilities;
private WebSocketTransportSettings _webSocketSettings;
private bool _useDefaultWebProxy;
private Lazy<string> _webSocketSoapContentType;
private SHA512 _hashAlgorithm;
internal HttpChannelFactory(HttpTransportBindingElement bindingElement, BindingContext context)
: base(bindingElement, context, HttpTransportDefaults.GetDefaultMessageEncoderFactory())
{
// validate setting interactions
if (bindingElement.TransferMode == TransferMode.Buffered)
{
if (bindingElement.MaxReceivedMessageSize > int.MaxValue)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("bindingElement.MaxReceivedMessageSize",
SRServiceModel.MaxReceivedMessageSizeMustBeInIntegerRange));
}
if (bindingElement.MaxBufferSize != bindingElement.MaxReceivedMessageSize)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
SRServiceModel.MaxBufferSizeMustMatchMaxReceivedMessageSize);
}
}
else
{
if (bindingElement.MaxBufferSize > bindingElement.MaxReceivedMessageSize)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
SRServiceModel.MaxBufferSizeMustNotExceedMaxReceivedMessageSize);
}
}
if (TransferModeHelper.IsRequestStreamed(bindingElement.TransferMode) &&
bindingElement.AuthenticationScheme != AuthenticationSchemes.Anonymous)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
SRServiceModel.HttpAuthDoesNotSupportRequestStreaming);
}
_allowCookies = bindingElement.AllowCookies;
if (_allowCookies)
{
_httpCookieContainerManager = new HttpCookieContainerManager();
}
if (!bindingElement.AuthenticationScheme.IsSingleton())
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", string.Format(SRServiceModel.HttpRequiresSingleAuthScheme,
bindingElement.AuthenticationScheme));
}
_authenticationScheme = bindingElement.AuthenticationScheme;
_maxBufferSize = bindingElement.MaxBufferSize;
_transferMode = bindingElement.TransferMode;
_useDefaultWebProxy = bindingElement.UseDefaultWebProxy;
_channelCredentials = context.BindingParameters.Find<SecurityCredentialsManager>();
_securityCapabilities = bindingElement.GetProperty<ISecurityCapabilities>(context);
_webSocketSettings = WebSocketHelper.GetRuntimeWebSocketSettings(bindingElement.WebSocketSettings);
_clientWebSocketFactory = ClientWebSocketFactory.GetFactory();
_webSocketSoapContentType = new Lazy<string>(() => MessageEncoderFactory.CreateSessionEncoder().ContentType, LazyThreadSafetyMode.ExecutionAndPublication);
}
public bool AllowCookies
{
get
{
return _allowCookies;
}
}
public AuthenticationSchemes AuthenticationScheme
{
get
{
return _authenticationScheme;
}
}
public virtual bool IsChannelBindingSupportEnabled
{
get
{
return false;
}
}
public SecurityTokenManager SecurityTokenManager
{
get
{
return _securityTokenManager;
}
}
public int MaxBufferSize
{
get
{
return _maxBufferSize;
}
}
public TransferMode TransferMode
{
get
{
return _transferMode;
}
}
public override string Scheme
{
get
{
return UriEx.UriSchemeHttp;
}
}
public WebSocketTransportSettings WebSocketSettings
{
get
{
return _webSocketSettings;
}
}
internal string WebSocketSoapContentType
{
get
{
return _webSocketSoapContentType.Value;
}
}
private HashAlgorithm HashAlgorithm
{
[SecurityCritical]
get
{
if (_hashAlgorithm == null)
{
_hashAlgorithm = SHA512.Create();
}
else
{
_hashAlgorithm.Initialize();
}
return _hashAlgorithm;
}
}
protected ClientWebSocketFactory ClientWebSocketFactory
{
get
{
return _clientWebSocketFactory;
}
}
public override T GetProperty<T>()
{
if (typeof(T) == typeof(ISecurityCapabilities))
{
return (T)(object)_securityCapabilities;
}
if (typeof(T) == typeof(IHttpCookieContainerManager))
{
return (T)(object)GetHttpCookieContainerManager();
}
return base.GetProperty<T>();
}
private HttpCookieContainerManager GetHttpCookieContainerManager()
{
return _httpCookieContainerManager;
}
internal async Task<HttpClient> GetHttpClientAsync(EndpointAddress to, SecurityTokenProviderContainer tokenProvider,
SecurityTokenContainer clientCertificateToken, CancellationToken cancellationToken)
{
var impersonationLevelWrapper = new OutWrapper<TokenImpersonationLevel>();
var authenticationLevelWrapper = new OutWrapper<AuthenticationLevel>();
NetworkCredential credential = await HttpChannelUtilities.GetCredentialAsync(_authenticationScheme,
tokenProvider, impersonationLevelWrapper, authenticationLevelWrapper, cancellationToken);
return GetHttpClient(to, credential, impersonationLevelWrapper.Value, authenticationLevelWrapper.Value,
clientCertificateToken);
}
internal HttpClient GetHttpClient(EndpointAddress to, NetworkCredential credential,
TokenImpersonationLevel impersonationLevel, AuthenticationLevel authenticationLevel,
SecurityTokenContainer clientCertificateToken)
{
if (_httpClientCache == null)
{
lock (ThisLock)
{
if (_httpClientCache == null)
{
_httpClientCache = new MruCache<string, HttpClient>(10);
}
}
}
HttpClient httpClient;
string connectionGroupName = GetConnectionGroupName(credential, authenticationLevel, impersonationLevel,
clientCertificateToken);
X509CertificateEndpointIdentity remoteCertificateIdentity = to.Identity as X509CertificateEndpointIdentity;
if (remoteCertificateIdentity != null)
{
connectionGroupName = string.Format(CultureInfo.InvariantCulture, "{0}[{1}]", connectionGroupName,
remoteCertificateIdentity.Certificates[0].Thumbprint);
}
connectionGroupName = connectionGroupName == null ? string.Empty : connectionGroupName;
lock (_httpClientCache)
{
if (!_httpClientCache.TryGetValue(connectionGroupName, out httpClient))
{
var clientHandler = GetHttpMessageHandler(to, clientCertificateToken);
clientHandler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
clientHandler.UseCookies = _allowCookies;
clientHandler.PreAuthenticate = true;
if (clientHandler.SupportsProxy)
{
clientHandler.UseProxy = _useDefaultWebProxy;
}
clientHandler.UseDefaultCredentials = false;
if (credential == CredentialCache.DefaultCredentials)
{
clientHandler.UseDefaultCredentials = true;
}
else
{
clientHandler.Credentials = credential;
}
httpClient = new HttpClient(clientHandler);
_httpClientCache.Add(connectionGroupName, httpClient);
}
}
return httpClient;
}
internal virtual ServiceModelHttpMessageHandler GetHttpMessageHandler(EndpointAddress to, SecurityTokenContainer clientCertificateToken)
{
return new ServiceModelHttpMessageHandler();
}
internal ICredentials GetCredentials()
{
ICredentials creds = null;
if (_authenticationScheme != AuthenticationSchemes.Anonymous)
{
creds = CredentialCache.DefaultCredentials;
ClientCredentials credentials = _channelCredentials as ClientCredentials;
if (credentials != null)
{
switch (_authenticationScheme)
{
case AuthenticationSchemes.Basic:
if (credentials.UserName.UserName == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("userName");
}
if (credentials.UserName.UserName == string.Empty)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SRServiceModel.UserNameCannotBeEmpty);
}
creds = new NetworkCredential(credentials.UserName.UserName, credentials.UserName.Password);
break;
case AuthenticationSchemes.Digest:
if (credentials.HttpDigest.ClientCredential.UserName != string.Empty)
{
creds = credentials.HttpDigest.ClientCredential;
}
break;
case AuthenticationSchemes.Ntlm:
goto case AuthenticationSchemes.Negotiate;
case AuthenticationSchemes.Negotiate:
if (credentials.Windows.ClientCredential.UserName != string.Empty)
{
creds = credentials.Windows.ClientCredential;
}
break;
}
}
}
return creds;
}
internal Exception CreateToMustEqualViaException(Uri to, Uri via)
{
return new ArgumentException(string.Format(SRServiceModel.HttpToMustEqualVia, to, via));
}
public override int GetMaxBufferSize()
{
return MaxBufferSize;
}
private SecurityTokenProviderContainer CreateAndOpenTokenProvider(TimeSpan timeout, AuthenticationSchemes authenticationScheme,
EndpointAddress target, Uri via, ChannelParameterCollection channelParameters)
{
SecurityTokenProvider tokenProvider = null;
switch (authenticationScheme)
{
case AuthenticationSchemes.Anonymous:
break;
case AuthenticationSchemes.Basic:
tokenProvider = TransportSecurityHelpers.GetUserNameTokenProvider(SecurityTokenManager, target, via, Scheme, authenticationScheme, channelParameters);
break;
case AuthenticationSchemes.Negotiate:
case AuthenticationSchemes.Ntlm:
tokenProvider = TransportSecurityHelpers.GetSspiTokenProvider(SecurityTokenManager, target, via, Scheme, authenticationScheme, channelParameters);
break;
case AuthenticationSchemes.Digest:
tokenProvider = TransportSecurityHelpers.GetDigestTokenProvider(SecurityTokenManager, target, via, Scheme, authenticationScheme, channelParameters);
break;
default:
// The setter for this property should prevent this.
throw Fx.AssertAndThrow("CreateAndOpenTokenProvider: Invalid authentication scheme");
}
SecurityTokenProviderContainer result;
if (tokenProvider != null)
{
result = new SecurityTokenProviderContainer(tokenProvider);
result.Open(timeout);
}
else
{
result = null;
}
return result;
}
protected virtual void ValidateCreateChannelParameters(EndpointAddress remoteAddress, Uri via)
{
if (string.Compare(via.Scheme, "ws", StringComparison.OrdinalIgnoreCase) != 0)
{
ValidateScheme(via);
}
if (MessageVersion.Addressing == AddressingVersion.None && remoteAddress.Uri != via)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateToMustEqualViaException(remoteAddress.Uri, via));
}
}
protected override TChannel OnCreateChannel(EndpointAddress remoteAddress, Uri via)
{
if (typeof(TChannel) != typeof(IRequestChannel))
{
remoteAddress = remoteAddress != null && !WebSocketHelper.IsWebSocketUri(remoteAddress.Uri) ?
new EndpointAddress(WebSocketHelper.NormalizeHttpSchemeWithWsScheme(remoteAddress.Uri), remoteAddress) :
remoteAddress;
via = !WebSocketHelper.IsWebSocketUri(via) ? WebSocketHelper.NormalizeHttpSchemeWithWsScheme(via) : via;
}
return OnCreateChannelCore(remoteAddress, via);
}
protected virtual TChannel OnCreateChannelCore(EndpointAddress remoteAddress, Uri via)
{
ValidateCreateChannelParameters(remoteAddress, via);
ValidateWebSocketTransportUsage();
if (typeof(TChannel) == typeof(IRequestChannel))
{
return (TChannel)(object)new HttpClientRequestChannel((HttpChannelFactory<IRequestChannel>)(object)this, remoteAddress, via, ManualAddressing);
}
else
{
return (TChannel)(object)new ClientWebSocketTransportDuplexSessionChannel((HttpChannelFactory<IDuplexSessionChannel>)(object)this, _clientWebSocketFactory, remoteAddress, via);
}
}
protected void ValidateWebSocketTransportUsage()
{
Type channelType = typeof(TChannel);
if (channelType == typeof(IRequestChannel) && WebSocketSettings.TransportUsage == WebSocketTransportUsage.Always)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(string.Format(
SRServiceModel.WebSocketCannotCreateRequestClientChannelWithCertainWebSocketTransportUsage,
typeof(TChannel),
WebSocketTransportSettings.TransportUsageMethodName,
typeof(WebSocketTransportSettings).Name,
WebSocketSettings.TransportUsage)));
}
if (channelType == typeof(IDuplexSessionChannel))
{
if (WebSocketSettings.TransportUsage == WebSocketTransportUsage.Never)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(string.Format(
SRServiceModel.WebSocketCannotCreateRequestClientChannelWithCertainWebSocketTransportUsage,
typeof(TChannel),
WebSocketTransportSettings.TransportUsageMethodName,
typeof(WebSocketTransportSettings).Name,
WebSocketSettings.TransportUsage)));
}
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void InitializeSecurityTokenManager()
{
if (_channelCredentials == null)
{
_channelCredentials = ClientCredentials.CreateDefaultCredentials();
}
_securityTokenManager = _channelCredentials.CreateSecurityTokenManager();
}
protected virtual bool IsSecurityTokenManagerRequired()
{
return _authenticationScheme != AuthenticationSchemes.Anonymous;
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return OnOpenAsync(timeout).ToApm(callback, state);
}
protected override void OnEndOpen(IAsyncResult result)
{
result.ToApmEnd();
}
protected override void OnOpen(TimeSpan timeout)
{
if (IsSecurityTokenManagerRequired())
{
InitializeSecurityTokenManager();
}
if (AllowCookies &&
!_httpCookieContainerManager.IsInitialized) // We don't want to overwrite the CookieContainer if someone has set it already.
{
_httpCookieContainerManager.CookieContainer = new CookieContainer();
}
}
internal protected override Task OnOpenAsync(TimeSpan timeout)
{
OnOpen(timeout);
return TaskHelpers.CompletedTask();
}
protected internal override Task OnCloseAsync(TimeSpan timeout)
{
OnClose(timeout);
return TaskHelpers.CompletedTask();
}
protected override void OnClosed()
{
base.OnClosed();
var httpClientToDispose = _httpClient;
if (httpClientToDispose != null)
{
_httpClient = null;
httpClientToDispose.Dispose();
}
}
private string AppendWindowsAuthenticationInfo(string inputString, NetworkCredential credential,
AuthenticationLevel authenticationLevel, TokenImpersonationLevel impersonationLevel)
{
return SecurityUtils.AppendWindowsAuthenticationInfo(inputString, credential, authenticationLevel, impersonationLevel);
}
protected virtual string OnGetConnectionGroupPrefix(SecurityTokenContainer clientCertificateToken)
{
return string.Empty;
}
internal static bool IsWindowsAuth(AuthenticationSchemes authScheme)
{
Contract.Assert(authScheme.IsSingleton(), "authenticationScheme used in an Http(s)ChannelFactory must be a singleton value.");
return authScheme == AuthenticationSchemes.Negotiate ||
authScheme == AuthenticationSchemes.Ntlm;
}
private string GetConnectionGroupName(NetworkCredential credential, AuthenticationLevel authenticationLevel,
TokenImpersonationLevel impersonationLevel, SecurityTokenContainer clientCertificateToken)
{
if (_credentialHashCache == null)
{
lock (ThisLock)
{
if (_credentialHashCache == null)
{
_credentialHashCache = new MruCache<string, string>(5);
}
}
}
string inputString = TransferModeHelper.IsRequestStreamed(this.TransferMode) ? "streamed" : string.Empty;
if (IsWindowsAuth(_authenticationScheme))
{
inputString = AppendWindowsAuthenticationInfo(inputString, credential, authenticationLevel, impersonationLevel);
}
inputString = string.Concat(OnGetConnectionGroupPrefix(clientCertificateToken), inputString);
string credentialHash = null;
// we have to lock around each call to TryGetValue since the MruCache modifies the
// contents of it's mruList in a single-threaded manner underneath TryGetValue
if (!string.IsNullOrEmpty(inputString))
{
lock (_credentialHashCache)
{
if (!_credentialHashCache.TryGetValue(inputString, out credentialHash))
{
byte[] inputBytes = new UTF8Encoding().GetBytes(inputString);
byte[] digestBytes = HashAlgorithm.ComputeHash(inputBytes);
credentialHash = Convert.ToBase64String(digestBytes);
_credentialHashCache.Add(inputString, credentialHash);
}
}
}
return credentialHash;
}
internal HttpRequestMessage GetHttpRequestMessage(Uri via)
{
Uri httpRequestUri = via;
var requestMessage = new HttpRequestMessage(HttpMethod.Post, httpRequestUri);
if (TransferModeHelper.IsRequestStreamed(TransferMode))
{
requestMessage.Headers.TransferEncodingChunked = true;
}
requestMessage.Headers.CacheControl = s_requestCacheHeader;
return requestMessage;
}
private void ApplyManualAddressing(ref EndpointAddress to, ref Uri via, Message message)
{
if (ManualAddressing)
{
Uri toHeader = message.Headers.To;
if (toHeader == null)
{
throw TraceUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.ManualAddressingRequiresAddressedMessages), message);
}
to = new EndpointAddress(toHeader);
if (MessageVersion.Addressing == AddressingVersion.None)
{
via = toHeader;
}
}
// now apply query string property
object property;
if (message.Properties.TryGetValue(HttpRequestMessageProperty.Name, out property))
{
HttpRequestMessageProperty requestProperty = (HttpRequestMessageProperty)property;
if (!string.IsNullOrEmpty(requestProperty.QueryString))
{
UriBuilder uriBuilder = new UriBuilder(via);
if (requestProperty.QueryString.StartsWith("?", StringComparison.Ordinal))
{
uriBuilder.Query = requestProperty.QueryString.Substring(1);
}
else
{
uriBuilder.Query = requestProperty.QueryString;
}
via = uriBuilder.Uri;
}
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void CreateAndOpenTokenProvidersCore(EndpointAddress to, Uri via, ChannelParameterCollection channelParameters, TimeSpan timeout, out SecurityTokenProviderContainer tokenProvider)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
tokenProvider = CreateAndOpenTokenProvider(timeoutHelper.RemainingTime(), AuthenticationScheme, to, via, channelParameters);
}
internal void CreateAndOpenTokenProviders(EndpointAddress to, Uri via, ChannelParameterCollection channelParameters, TimeSpan timeout, out SecurityTokenProviderContainer tokenProvider)
{
if (!IsSecurityTokenManagerRequired())
{
tokenProvider = null;
}
else
{
CreateAndOpenTokenProvidersCore(to, via, channelParameters, timeout, out tokenProvider);
}
}
internal static bool MapIdentity(EndpointAddress target, AuthenticationSchemes authenticationScheme)
{
if (target.Identity == null)
{
return false;
}
return IsWindowsAuth(authenticationScheme);
}
private bool MapIdentity(EndpointAddress target)
{
return MapIdentity(target, AuthenticationScheme);
}
protected class HttpClientRequestChannel : RequestChannel
{
private HttpChannelFactory<IRequestChannel> _factory;
private SecurityTokenProviderContainer _tokenProvider;
private ChannelParameterCollection _channelParameters;
public HttpClientRequestChannel(HttpChannelFactory<IRequestChannel> factory, EndpointAddress to, Uri via, bool manualAddressing)
: base(factory, to, via, manualAddressing)
{
_factory = factory;
}
public HttpChannelFactory<IRequestChannel> Factory
{
get { return _factory; }
}
protected ChannelParameterCollection ChannelParameters
{
get
{
return _channelParameters;
}
}
public override T GetProperty<T>()
{
if (typeof(T) == typeof(ChannelParameterCollection))
{
if (State == CommunicationState.Created)
{
lock (ThisLock)
{
if (_channelParameters == null)
{
_channelParameters = new ChannelParameterCollection();
}
}
}
return (T)(object)_channelParameters;
}
return base.GetProperty<T>();
}
private void PrepareOpen()
{
Factory.MapIdentity(RemoteAddress);
}
private void CreateAndOpenTokenProviders(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
if (!ManualAddressing)
{
Factory.CreateAndOpenTokenProviders(RemoteAddress, Via, _channelParameters, timeoutHelper.RemainingTime(), out _tokenProvider);
}
}
private void CloseTokenProviders(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
if (_tokenProvider != null)
{
_tokenProvider.Close(timeoutHelper.RemainingTime());
}
}
private void AbortTokenProviders()
{
if (_tokenProvider != null)
{
_tokenProvider.Abort();
}
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return CommunicationObjectInternal.OnBeginOpen(this, timeout, callback, state);
}
protected override void OnEndOpen(IAsyncResult result)
{
CommunicationObjectInternal.OnEnd(result);
}
protected override void OnOpen(TimeSpan timeout)
{
CommunicationObjectInternal.OnOpen(this, timeout);
}
internal protected override Task OnOpenAsync(TimeSpan timeout)
{
PrepareOpen();
CreateAndOpenTokenProviders(timeout);
return TaskHelpers.CompletedTask();
}
private void PrepareClose(bool aborting)
{
}
protected override void OnAbort()
{
PrepareClose(true);
AbortTokenProviders();
base.OnAbort();
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return CommunicationObjectInternal.OnBeginClose(this, timeout, callback, state);
}
protected override void OnEndClose(IAsyncResult result)
{
CommunicationObjectInternal.OnEnd(result);
}
protected override void OnClose(TimeSpan timeout)
{
CommunicationObjectInternal.OnClose(this, timeout);
}
protected internal override async Task OnCloseAsync(TimeSpan timeout)
{
var timeoutHelper = new TimeoutHelper(timeout);
PrepareClose(false);
CloseTokenProviders(timeoutHelper.RemainingTime());
await WaitForPendingRequestsAsync(timeoutHelper.RemainingTime());
}
protected override IAsyncRequest CreateAsyncRequest(Message message)
{
return new HttpClientChannelAsyncRequest(this);
}
internal virtual Task<HttpClient> GetHttpClientAsync(EndpointAddress to, Uri via, TimeoutHelper timeoutHelper)
{
return GetHttpClientAsync(to, via, null, timeoutHelper);
}
protected async Task<HttpClient> GetHttpClientAsync(EndpointAddress to, Uri via, SecurityTokenContainer clientCertificateToken, TimeoutHelper timeoutHelper)
{
SecurityTokenProviderContainer requestTokenProvider;
if (ManualAddressing)
{
Factory.CreateAndOpenTokenProviders(to, via, _channelParameters, timeoutHelper.RemainingTime(),
out requestTokenProvider);
}
else
{
requestTokenProvider = _tokenProvider;
}
try
{
return await Factory.GetHttpClientAsync(to, requestTokenProvider, clientCertificateToken, await timeoutHelper.GetCancellationTokenAsync());
}
finally
{
if (ManualAddressing)
{
if (requestTokenProvider != null)
{
requestTokenProvider.Abort();
}
}
}
}
internal HttpRequestMessage GetHttpRequestMessage(Uri via)
{
return Factory.GetHttpRequestMessage(via);
}
internal virtual void OnHttpRequestCompleted(HttpRequestMessage request)
{
// empty
}
internal class HttpClientChannelAsyncRequest : IAsyncRequest
{
private static readonly Action<object> s_cancelCts = state =>
{
try
{
((CancellationTokenSource)state).Cancel();
}
catch (ObjectDisposedException)
{
// ignore
}
};
private HttpClientRequestChannel _channel;
private HttpChannelFactory<IRequestChannel> _factory;
private EndpointAddress _to;
private Uri _via;
private HttpRequestMessage _httpRequestMessage;
private HttpResponseMessage _httpResponseMessage;
private HttpAbortReason _abortReason;
private TimeoutHelper _timeoutHelper;
private int _httpRequestCompleted;
private HttpClient _httpClient;
private readonly CancellationTokenSource _httpSendCts;
public HttpClientChannelAsyncRequest(HttpClientRequestChannel channel)
{
_channel = channel;
_to = channel.RemoteAddress;
_via = channel.Via;
_factory = channel.Factory;
_httpSendCts = new CancellationTokenSource();
}
public async Task SendRequestAsync(Message message, TimeoutHelper timeoutHelper)
{
_timeoutHelper = timeoutHelper;
_factory.ApplyManualAddressing(ref _to, ref _via, message);
_httpClient = await _channel.GetHttpClientAsync(_to, _via, _timeoutHelper);
_httpRequestMessage = _channel.GetHttpRequestMessage(_via);
Message request = message;
try
{
if (_channel.State != CommunicationState.Opened)
{
// if we were aborted while getting our request or doing correlation,
// we need to abort the request and bail
Cleanup();
_channel.ThrowIfDisposedOrNotOpen();
}
bool suppressEntityBody = PrepareMessageHeaders(request);
if (!suppressEntityBody)
{
_httpRequestMessage.Content = MessageContent.Create(_factory, request, _timeoutHelper);
}
try
{
// There is a possibility that a HEAD pre-auth request might fail when the actual request
// will succeed. For example, when the web service refuses HEAD requests. We don't want
// to fail the actual request because of some subtlety which causes the HEAD request.
await SendPreauthenticationHeadRequestIfNeeded();
}
catch { /* ignored */ }
bool success = false;
var cancelTokenTask = _timeoutHelper.GetCancellationTokenAsync();
try
{
var timeoutToken = await cancelTokenTask;
timeoutToken.Register(s_cancelCts, _httpSendCts);
_httpResponseMessage = await _httpClient.SendAsync(_httpRequestMessage, HttpCompletionOption.ResponseHeadersRead, _httpSendCts.Token);
// As we have the response message and no exceptions have been thrown, the request message has completed it's job.
// Calling Dispose() on the request message to free up resources in HttpContent, but keeping the object around
// as we can still query properties once dispose'd.
_httpRequestMessage.Dispose();
success = true;
}
catch (HttpRequestException requestException)
{
HttpChannelUtilities.ProcessGetResponseWebException(requestException, _httpRequestMessage,
_abortReason);
}
catch (OperationCanceledException)
{
if (cancelTokenTask.Result.IsCancellationRequested)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(string.Format(
SRServiceModel.HttpRequestTimedOut, _httpRequestMessage.RequestUri, _timeoutHelper.OriginalTimeout)));
}
else
{
// Cancellation came from somewhere other than timeoutCts and needs to be handled differently.
throw;
}
}
finally
{
if (!success)
{
Abort(_channel);
}
}
}
finally
{
if (!ReferenceEquals(request, message))
{
request.Close();
}
}
}
private void Cleanup()
{
s_cancelCts(_httpSendCts);
if (_httpRequestMessage != null)
{
var httpRequestMessageSnapshot = _httpRequestMessage;
_httpRequestMessage = null;
TryCompleteHttpRequest(httpRequestMessageSnapshot);
httpRequestMessageSnapshot.Dispose();
}
}
public void Abort(RequestChannel channel)
{
Cleanup();
_abortReason = HttpAbortReason.Aborted;
}
public void Fault(RequestChannel channel)
{
Cleanup();
}
public async Task<Message> ReceiveReplyAsync(TimeoutHelper timeoutHelper)
{
try
{
_timeoutHelper = timeoutHelper;
var responseHelper = new HttpResponseMessageHelper(_httpResponseMessage, _factory);
var replyMessage = await responseHelper.ParseIncomingResponse();
TryCompleteHttpRequest(_httpRequestMessage);
return replyMessage;
}
catch (OperationCanceledException)
{
var cancelToken = _timeoutHelper.GetCancellationToken();
if (cancelToken.IsCancellationRequested)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(string.Format(
SRServiceModel.HttpResponseTimedOut, _httpRequestMessage.RequestUri, timeoutHelper.OriginalTimeout)));
}
else
{
// Cancellation came from somewhere other than timeoutCts and needs to be handled differently.
throw;
}
}
}
private bool PrepareMessageHeaders(Message message)
{
string action = message.Headers.Action;
if (action != null)
{
action = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", UrlUtility.UrlPathEncode(action));
}
if (message.Version.Addressing == AddressingVersion.None)
{
message.Headers.Action = null;
message.Headers.To = null;
}
bool suppressEntityBody = message is NullMessage;
object property;
if (message.Properties.TryGetValue(HttpRequestMessageProperty.Name, out property))
{
HttpRequestMessageProperty requestProperty = (HttpRequestMessageProperty)property;
_httpRequestMessage.Method = new HttpMethod(requestProperty.Method);
// Query string was applied in HttpChannelFactory.ApplyManualAddressing
WebHeaderCollection requestHeaders = requestProperty.Headers;
suppressEntityBody = suppressEntityBody || requestProperty.SuppressEntityBody;
var headerKeys = requestHeaders.AllKeys;
for (int i = 0; i < headerKeys.Length; i++)
{
string name = headerKeys[i];
string value = requestHeaders[name];
if (string.Compare(name, "accept", StringComparison.OrdinalIgnoreCase) == 0)
{
_httpRequestMessage.Headers.Accept.TryParseAdd(value);
}
else if (string.Compare(name, "connection", StringComparison.OrdinalIgnoreCase) == 0)
{
if (value.IndexOf("keep-alive", StringComparison.OrdinalIgnoreCase) != -1)
{
_httpRequestMessage.Headers.ConnectionClose = false;
}
else
{
_httpRequestMessage.Headers.Connection.TryParseAdd(value);
}
}
else if (string.Compare(name, "SOAPAction", StringComparison.OrdinalIgnoreCase) == 0)
{
if (action == null)
{
action = value;
}
else
{
if (!String.IsNullOrEmpty(value) && string.Compare(value, action, StringComparison.Ordinal) != 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ProtocolException(string.Format(SRServiceModel.HttpSoapActionMismatch, action, value)));
}
}
}
else if (string.Compare(name, "content-length", StringComparison.OrdinalIgnoreCase) == 0)
{
// this will be taken care of by System.Net when we write to the content
}
else if (string.Compare(name, "content-type", StringComparison.OrdinalIgnoreCase) == 0)
{
// Handled by MessageContent
}
else if (string.Compare(name, "expect", StringComparison.OrdinalIgnoreCase) == 0)
{
if (value.ToUpperInvariant().IndexOf("100-CONTINUE", StringComparison.OrdinalIgnoreCase) != -1)
{
_httpRequestMessage.Headers.ExpectContinue = true;
}
else
{
_httpRequestMessage.Headers.Expect.TryParseAdd(value);
}
}
else if (string.Compare(name, "host", StringComparison.OrdinalIgnoreCase) == 0)
{
// this should be controlled through Via
}
else if (string.Compare(name, "referer", StringComparison.OrdinalIgnoreCase) == 0)
{
// referrer is proper spelling, but referer is the what is in the protocol.
_httpRequestMessage.Headers.Referrer = new Uri(value);
}
else if (string.Compare(name, "transfer-encoding", StringComparison.OrdinalIgnoreCase) == 0)
{
if (value.ToUpperInvariant().IndexOf("CHUNKED", StringComparison.OrdinalIgnoreCase) != -1)
{
_httpRequestMessage.Headers.TransferEncodingChunked = true;
}
else
{
_httpRequestMessage.Headers.TransferEncoding.TryParseAdd(value);
}
}
else if (string.Compare(name, "user-agent", StringComparison.OrdinalIgnoreCase) == 0)
{
_httpRequestMessage.Headers.UserAgent.Add(ProductInfoHeaderValue.Parse(value));
}
else if (string.Compare(name, "if-modified-since", StringComparison.OrdinalIgnoreCase) == 0)
{
DateTimeOffset modifiedSinceDate;
if (DateTimeOffset.TryParse(value, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.AssumeLocal, out modifiedSinceDate))
{
_httpRequestMessage.Headers.IfModifiedSince = modifiedSinceDate;
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ProtocolException(string.Format(SRServiceModel.HttpIfModifiedSinceParseError, value)));
}
}
else if (string.Compare(name, "date", StringComparison.OrdinalIgnoreCase) == 0)
{
// this will be taken care of by System.Net when we make the request
}
else if (string.Compare(name, "proxy-connection", StringComparison.OrdinalIgnoreCase) == 0)
{
throw ExceptionHelper.PlatformNotSupported("proxy-connection");
}
else if (string.Compare(name, "range", StringComparison.OrdinalIgnoreCase) == 0)
{
// specifying a range doesn't make sense in the context of WCF
}
else
{
try
{
_httpRequestMessage.Headers.Add(name, value);
}
catch (Exception addHeaderException)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(string.Format(
SRServiceModel.CopyHttpHeaderFailed,
name,
value,
HttpChannelUtilities.HttpRequestHeadersTypeName),
addHeaderException));
}
}
}
}
if (action != null)
{
if (message.Version.Envelope == EnvelopeVersion.Soap11)
{
_httpRequestMessage.Headers.TryAddWithoutValidation("SOAPAction", action);
}
else if (message.Version.Envelope == EnvelopeVersion.Soap12)
{
// Handled by MessageContent
}
else if (message.Version.Envelope != EnvelopeVersion.None)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ProtocolException(string.Format(SRServiceModel.EnvelopeVersionUnknown,
message.Version.Envelope.ToString())));
}
}
// since we don't get the output stream in send when retVal == true,
// we need to disable chunking for some verbs (DELETE/PUT)
if (suppressEntityBody)
{
_httpRequestMessage.Headers.TransferEncodingChunked = false;
}
return suppressEntityBody;
}
public void OnReleaseRequest()
{
TryCompleteHttpRequest(_httpRequestMessage);
}
private void TryCompleteHttpRequest(HttpRequestMessage request)
{
if (request == null)
{
return;
}
if (Interlocked.CompareExchange(ref _httpRequestCompleted, 1, 0) == 0)
{
_channel.OnHttpRequestCompleted(request);
}
}
private async Task SendPreauthenticationHeadRequestIfNeeded()
{
if (!AuthenticationSchemeMayRequireResend())
{
return;
}
var requestUri = _httpRequestMessage.RequestUri;
// sends a HEAD request to the specificed requestUri for authentication purposes
Contract.Assert(requestUri != null);
HttpRequestMessage headHttpRequestMessage = new HttpRequestMessage()
{
Method = HttpMethod.Head,
RequestUri = requestUri
};
var cancelToken = await _timeoutHelper.GetCancellationTokenAsync();
await _httpClient.SendAsync(headHttpRequestMessage, cancelToken);
}
private bool AuthenticationSchemeMayRequireResend()
{
return _factory.AuthenticationScheme != AuthenticationSchemes.Anonymous;
}
}
}
}
}
| |
#region Copyright Information
// Sentience Lab Unity Framework
// (C) Sentience Lab (sentiencelab@aut.ac.nz), Auckland University of Technology, Auckland, New Zealand
#endregion Copyright Information
using UnityEngine;
namespace SentienceLab.MoCap
{
/// <summary>
/// Component for filtering MoCap data (e.g., smoothing).
/// </summary>
///
[DisallowMultipleComponent]
[AddComponentMenu("Motion Capture/Modifier/Filter")]
public class FilterModifier : MonoBehaviour, IMoCapDataModifier
{
[Tooltip("Filtering type")]
public FilterType filterType = FilterType.Rectangle;
[Tooltip("Filtering time in seconds")]
[Range(0, 10)]
public float filterTime = 1.0f;
[Tooltip("Maximum number of filter elements (0: calculate from filter size")]
[Range(0, 512)]
public int maximumFilterSize = 0;
public enum FilterType
{
Rectangle,
Gaussian,
LowPass
}
public void Start()
{
// calculate maximum filter size if necessary
if (maximumFilterSize <= 0)
{
maximumFilterSize = (int) (filterTime * MoCapManager.Instance.Framerate);
maximumFilterSize = Mathf.Max(maximumFilterSize, 1);
}
InitialiseFilter();
}
/// <summary>
/// Builds the FIR filter weights depending on size and filter type.
/// </summary>
///
private void InitialiseFilter()
{
float framerate = MoCapManager.Instance.Framerate;
int filterSize = Mathf.Clamp((int) (framerate * filterTime), 1, maximumFilterSize);
filter = new float[filterSize];
for (int i = 0; i < filterSize; i++)
{
float x = (i - (filterSize / 2.0f)) / framerate;
switch (filterType)
{
case FilterType.Rectangle:
filter[i] = 1.0f;
break;
case FilterType.Gaussian:
float d2 = 0.25f * 0.25f; // squared standard deviation range
filter[i] = 1.0f / (2.0f * Mathf.PI * d2) * Mathf.Exp(-(x * x) / (2.0f * d2));
break;
case FilterType.LowPass:
x *= Mathf.PI * 2;
x += 0.00001f; // avoid division by zero
filter[i] = Mathf.Sin(x)/x;
break;
}
}
oldFilterTime = filterTime;
}
/// <summary>
/// Filtering of mocap data with a somewhat crude approach to handling quaternions
/// as described in
/// </summary>
/// <param name="data">the MoCap data item to process</param>
///
public void _Process(ref MoCapData data)
{
if (!enabled) return;
// has the filter time changed?
if (filterTime != oldFilterTime) InitialiseFilter();
Vector3 pos = Vector3.zero;
float qx, qy, qz, qw; qx = qy = qz = qw = 0;
float length = 0;
MoCapData first = data;
float factorSum = 0;
bool firstEntry = true;
for ( int idx = 0; idx < filter.Length; idx++ )
{
MoCapData d = data.buffer.GetElement(idx);
if ( d.tracked )
{
// determine first valid entry
if (firstEntry)
{
first = d;
firstEntry = false;
}
// position and length: standard application of FIR filter
float factor = filter[idx];
factorSum += factor;
pos += d.pos * factor;
length += d.length * factor;
// quaternions: consider q = -q condition by checking dot product with first element
float dot = first.rot.x * d.rot.x + first.rot.y * d.rot.y + first.rot.z * d.rot.z + first.rot.w * d.rot.w;
if (dot < 0) { factor = -factor; }
qx += d.rot.x * factor;
qy += d.rot.y * factor;
qz += d.rot.z * factor;
qw += d.rot.w * factor;
}
}
// done adding up: now "normalize"
if (factorSum > 0)
{
pos /= factorSum;
float mag = Mathf.Sqrt(qx * qx + qy * qy + qz * qz + qw * qw);
qx /= mag; qy /= mag; qz /= mag; qw /= mag;
length /= factorSum;
}
// and write back into result
data.pos = pos;
data.rot.Set(qx, qy, qz, qw);
data.tracked = !firstEntry;
data.length = length;
}
/// <summary>
/// Filtering of MoCap data using the matrix eigenvalue approach described in
/// https://github.com/tolgabirdal/averaging_quaternions/blob/master/wavg_quaternion_markley.m
/// Eigenvalue calculation using the Power Iteration algorithm described in
/// http://www.bragitoff.com/2015/10/eigen-value-and-eigen-vector-of-a-matrix-by-iterative-method-c-program/
/// </summary>
/// <param name="data">the MoCap data item to process</param>
///
public void Process(ref MoCapData data)
{
if (!enabled) return;
// has the filter time changed?
if (filterTime != oldFilterTime) InitialiseFilter();
Vector3 pos = Vector3.zero;
Matrix4x4 rot = Matrix4x4.zero;
float length = 0;
MoCapData first = data;
Vector4 v = Vector4.zero;
float factorSum = 0;
bool firstEntry = true;
for (int idx = 0; idx < filter.Length; idx++)
{
MoCapData d = data.buffer.GetElement(idx);
if (d.tracked)
{
// determine first valid entry
if (firstEntry)
{
first = d;
firstEntry = false;
}
// position and length: standard application of FIR filter
float factor = filter[idx];
factorSum += factor;
pos += d.pos * factor;
length += d.length * factor;
// quaternions: build up matrix
Add(ref rot, ref d.rot, factor);
}
}
// done adding up: now "normalize"
if (factorSum > 0)
{
pos /= factorSum;
for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) rot[i, j] /= factorSum;
length /= factorSum;
}
// and write back into result
data.pos = pos;
data.tracked = !firstEntry;
data.length = length;
// average quaterion is eigenvector of accumulated matrix
v.Set(first.rot.x, first.rot.w, first.rot.z, first.rot.w);
v = FindEigenvector(rot, v);
data.rot.Set(v.x, v.y, v.z, v.w);
}
/// <summary>
/// Adds weight * (q * qT) to a matrix
/// </summary>
/// <param name="mtx">Matrix to add to</param>
/// <param name="q">Quaterion to add</param>
/// <param name="weight">weight</param>
///
public void Add(ref Matrix4x4 mtx, ref Quaternion q, float weight)
{
// diagonal
mtx.m00 += weight * q.x * q.x;
mtx.m11 += weight * q.y * q.y;
mtx.m22 += weight * q.z * q.z;
mtx.m33 += weight * q.w * q.w;
// corners and transpose
mtx.m01 += weight * q.x * q.y; mtx.m10 = mtx.m01;
mtx.m02 += weight * q.x * q.z; mtx.m20 = mtx.m02;
mtx.m03 += weight * q.x * q.w; mtx.m30 = mtx.m03;
mtx.m12 += weight * q.y * q.z; mtx.m21 = mtx.m12;
mtx.m13 += weight * q.y * q.w; mtx.m31 = mtx.m13;
mtx.m23 += weight * q.z * q.w; mtx.m32 = mtx.m23;
}
/// <summary>
/// Finds the primary eigenvector of a 4x4 matrix using Power Iteration.
/// https://en.wikipedia.org/wiki/Power_iteration
/// based on http://www.bragitoff.com/2015/10/eigen-value-and-eigen-vector-of-a-matrix-by-iterative-method-c-program/
/// </summary>
///
public Vector4 FindEigenvector(Matrix4x4 mtx, Vector4 startGuess, double epsilon = 0.0001f)
{
Vector4 eigen = startGuess;
float k = eigen.x;
float y;
do
{
y = k;
// c = mtx * eigen
Vector4 c = mtx * eigen;
// find larges element of c
k = Mathf.Max(
Mathf.Max(Mathf.Abs(c.x), Mathf.Abs(c.y)),
Mathf.Max(Mathf.Abs(c.z), Mathf.Abs(c.w)));
// calculate the new eigenvector
eigen = c / k;
} while (Mathf.Abs(k - y) > epsilon);
return eigen;
}
public int GetRequiredBufferSize()
{
return maximumFilterSize;
}
private float oldFilterTime;
private float[] filter;
}
}
| |
// 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;
namespace System.Runtime.Serialization
{
#if uapaot
public class XmlObjectSerializerReadContextComplex : XmlObjectSerializerReadContext
#else
internal class XmlObjectSerializerReadContextComplex : XmlObjectSerializerReadContext
#endif
{
private bool _preserveObjectReferences;
private SerializationMode _mode;
private ISerializationSurrogateProvider _serializationSurrogateProvider;
internal XmlObjectSerializerReadContextComplex(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver)
: base(serializer, rootTypeDataContract, dataContractResolver)
{
_mode = SerializationMode.SharedContract;
_preserveObjectReferences = serializer.PreserveObjectReferences;
_serializationSurrogateProvider = serializer.SerializationSurrogateProvider;
}
internal XmlObjectSerializerReadContextComplex(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject)
: base(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject)
{
}
internal override SerializationMode Mode
{
get { return _mode; }
}
internal override object InternalDeserialize(XmlReaderDelegator xmlReader, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle, string name, string ns)
{
if (_mode == SerializationMode.SharedContract)
{
if (_serializationSurrogateProvider == null)
return base.InternalDeserialize(xmlReader, declaredTypeID, declaredTypeHandle, name, ns);
else
return InternalDeserializeWithSurrogate(xmlReader, Type.GetTypeFromHandle(declaredTypeHandle), null /*surrogateDataContract*/, name, ns);
}
else
{
return InternalDeserializeInSharedTypeMode(xmlReader, declaredTypeID, Type.GetTypeFromHandle(declaredTypeHandle), name, ns);
}
}
internal override object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, string name, string ns)
{
if (_mode == SerializationMode.SharedContract)
{
if (_serializationSurrogateProvider == null)
return base.InternalDeserialize(xmlReader, declaredType, name, ns);
else
return InternalDeserializeWithSurrogate(xmlReader, declaredType, null /*surrogateDataContract*/, name, ns);
}
else
{
return InternalDeserializeInSharedTypeMode(xmlReader, -1, declaredType, name, ns);
}
}
internal override object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, string name, string ns)
{
if (_mode == SerializationMode.SharedContract)
{
if (_serializationSurrogateProvider == null)
return base.InternalDeserialize(xmlReader, declaredType, dataContract, name, ns);
else
return InternalDeserializeWithSurrogate(xmlReader, declaredType, dataContract, name, ns);
}
else
{
return InternalDeserializeInSharedTypeMode(xmlReader, -1, declaredType, name, ns);
}
}
private object InternalDeserializeInSharedTypeMode(XmlReaderDelegator xmlReader, int declaredTypeID, Type declaredType, string name, string ns)
{
object retObj = null;
if (TryHandleNullOrRef(xmlReader, declaredType, name, ns, ref retObj))
return retObj;
DataContract dataContract;
string assemblyName = attributes.ClrAssembly;
string typeName = attributes.ClrType;
if (assemblyName != null && typeName != null)
{
Assembly assembly;
Type type;
dataContract = ResolveDataContractInSharedTypeMode(assemblyName, typeName, out assembly, out type);
if (dataContract == null)
{
if (assembly == null)
throw XmlObjectSerializer.CreateSerializationException(SR.Format(SR.AssemblyNotFound, assemblyName));
if (type == null)
throw XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ClrTypeNotFound, assembly.FullName, typeName));
}
//Array covariance is not supported in XSD. If declared type is array, data is sent in format of base array
if (declaredType != null && declaredType.IsArray)
dataContract = (declaredTypeID < 0) ? GetDataContract(declaredType) : GetDataContract(declaredTypeID, declaredType.TypeHandle);
}
else
{
if (assemblyName != null)
throw XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.Format(SR.AttributeNotFound, Globals.SerializationNamespace, Globals.ClrTypeLocalName, xmlReader.NodeType, xmlReader.NamespaceURI, xmlReader.LocalName)));
else if (typeName != null)
throw XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.Format(SR.AttributeNotFound, Globals.SerializationNamespace, Globals.ClrAssemblyLocalName, xmlReader.NodeType, xmlReader.NamespaceURI, xmlReader.LocalName)));
else if (declaredType == null)
throw XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.Format(SR.AttributeNotFound, Globals.SerializationNamespace, Globals.ClrTypeLocalName, xmlReader.NodeType, xmlReader.NamespaceURI, xmlReader.LocalName)));
dataContract = (declaredTypeID < 0) ? GetDataContract(declaredType) : GetDataContract(declaredTypeID, declaredType.TypeHandle);
}
return ReadDataContractValue(dataContract, xmlReader);
}
private object InternalDeserializeWithSurrogate(XmlReaderDelegator xmlReader, Type declaredType, DataContract surrogateDataContract, string name, string ns)
{
DataContract dataContract = surrogateDataContract ??
GetDataContract(DataContractSurrogateCaller.GetDataContractType(_serializationSurrogateProvider, declaredType));
if (this.IsGetOnlyCollection && dataContract.UnderlyingType != declaredType)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.SurrogatesWithGetOnlyCollectionsNotSupportedSerDeser, DataContract.GetClrTypeFullName(declaredType))));
}
ReadAttributes(xmlReader);
string objectId = GetObjectId();
object oldObj = InternalDeserialize(xmlReader, name, ns, declaredType, ref dataContract);
object obj = DataContractSurrogateCaller.GetDeserializedObject(_serializationSurrogateProvider, oldObj, dataContract.UnderlyingType, declaredType);
ReplaceDeserializedObject(objectId, oldObj, obj);
return obj;
}
private Type ResolveDataContractTypeInSharedTypeMode(string assemblyName, string typeName, out Assembly assembly)
{
// The method is used only when _mode == SerializationMode.SharedType.
// _mode is set to SerializationMode.SharedType only when the context is for NetDataContractSerializer.
throw new PlatformNotSupportedException(SR.PlatformNotSupported_NetDataContractSerializer);
}
private DataContract ResolveDataContractInSharedTypeMode(string assemblyName, string typeName, out Assembly assembly, out Type type)
{
type = ResolveDataContractTypeInSharedTypeMode(assemblyName, typeName, out assembly);
if (type != null)
{
return GetDataContract(type);
}
return null;
}
protected override DataContract ResolveDataContractFromTypeName()
{
if (_mode == SerializationMode.SharedContract)
{
return base.ResolveDataContractFromTypeName();
}
else
{
if (attributes.ClrAssembly != null && attributes.ClrType != null)
{
Assembly assembly;
Type type;
return ResolveDataContractInSharedTypeMode(attributes.ClrAssembly, attributes.ClrType, out assembly, out type);
}
}
return null;
}
internal override void CheckIfTypeSerializable(Type memberType, bool isMemberTypeSerializable)
{
if (_serializationSurrogateProvider != null)
{
while (memberType.IsArray)
memberType = memberType.GetElementType();
memberType = DataContractSurrogateCaller.GetDataContractType(_serializationSurrogateProvider, memberType);
if (!DataContract.IsTypeSerializable(memberType))
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.TypeNotSerializable, memberType)));
return;
}
base.CheckIfTypeSerializable(memberType, isMemberTypeSerializable);
}
internal override Type GetSurrogatedType(Type type)
{
if (_serializationSurrogateProvider == null)
{
return base.GetSurrogatedType(type);
}
else
{
type = DataContract.UnwrapNullableType(type);
Type surrogateType = DataContractSerializer.GetSurrogatedType(_serializationSurrogateProvider, type);
if (this.IsGetOnlyCollection && surrogateType != type)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.SurrogatesWithGetOnlyCollectionsNotSupportedSerDeser,
DataContract.GetClrTypeFullName(type))));
}
else
{
return surrogateType;
}
}
}
#if USE_REFEMIT
public override int GetArraySize()
#else
internal override int GetArraySize()
#endif
{
return _preserveObjectReferences ? attributes.ArraySZSize : -1;
}
}
}
| |
using System;
using System.CodeDom;
using System.Collections;
using System.Xml;
namespace Stetic.Wrapper {
public class Button : Container {
ImageInfo imageInfo;
public override void Wrap (object obj, bool initialized)
{
base.Wrap (obj, initialized);
if (!initialized)
UseUnderline = true;
if (button.UseStock) {
type = ButtonType.StockItem;
StockId = button.Label;
} else if (!initialized) {
type = ButtonType.TextOnly;
Label = button.Name;
} else if (button.Child is Gtk.Label) {
type = ButtonType.TextOnly;
label = button.Label;
useUnderline = button.UseUnderline;
} else {
type = ButtonType.Custom;
FixupGladeChildren ();
}
}
public override void Read (ObjectReader reader, XmlElement elem)
{
base.Read (reader, elem);
if (reader.Format == FileFormat.Glade)
UseUnderline = true;
}
protected override ObjectWrapper ReadChild (ObjectReader reader, XmlElement child_elem)
{
ObjectWrapper ret = null;
if (Type == ButtonType.Custom || reader.Format == FileFormat.Glade) {
if (button.Child != null)
button.Remove (button.Child);
ret = base.ReadChild (reader, child_elem);
FixupGladeChildren ();
} else if (Type == ButtonType.TextAndIcon)
ConstructContents ();
return ret;
}
protected override XmlElement WriteChild (ObjectWriter writer, Widget wrapper)
{
if (writer.Format == FileFormat.Glade || Type == ButtonType.Custom)
return base.WriteChild (writer, wrapper);
else
return null;
}
void FixupGladeChildren ()
{
Gtk.Alignment alignment = button.Child as Gtk.Alignment;
if (alignment == null)
return;
Gtk.HBox box = alignment.Child as Gtk.HBox;
if (box == null)
return;
Gtk.Widget[] children = box.Children;
if (children == null || children.Length != 2)
return;
Gtk.Image image = children[0] as Gtk.Image;
Gtk.Label label = children[1] as Gtk.Label;
if (image == null || label == null)
return;
Stetic.Wrapper.Image iwrap = Stetic.ObjectWrapper.Lookup (image) as Stetic.Wrapper.Image;
if (iwrap == null)
return;
this.label = label.LabelProp;
button.UseUnderline = label.UseUnderline;
imageInfo = iwrap.Pixbuf;
Type = ButtonType.TextAndIcon;
}
protected override XmlElement WriteProperties (ObjectWriter writer)
{
XmlElement elem = base.WriteProperties (writer);
if (Type == ButtonType.StockItem)
GladeUtils.SetProperty (elem, "label", stockId);
return elem;
}
public override IEnumerable RealChildren {
get {
if (type == ButtonType.Custom)
return base.RealChildren;
else
return new Gtk.Widget[0];
}
}
public override IEnumerable GladeChildren {
get {
if (type == ButtonType.StockItem || type == ButtonType.TextOnly)
return new Gtk.Widget[0];
else
return base.GladeChildren;
}
}
private Gtk.Button button {
get {
return (Gtk.Button)Wrapped;
}
}
public enum ButtonType {
StockItem,
TextOnly,
TextAndIcon,
Custom
};
ButtonType type;
public ButtonType Type {
get {
return type;
}
set {
type = value;
EmitNotify ("Type");
switch (type) {
case ButtonType.StockItem:
button.UseStock = true;
StockId = stockId;
break;
case ButtonType.TextOnly:
labelWidget = null;
button.UseStock = false;
Label = label;
UseUnderline = useUnderline;
break;
case ButtonType.TextAndIcon:
button.UseStock = false;
Label = label;
UseUnderline = useUnderline;
Icon = imageInfo;
break;
case ButtonType.Custom:
button.UseStock = false;
if (button.Child != null)
ReplaceChild (button.Child, CreatePlaceholder (), true);
break;
}
}
}
public ImageInfo Icon {
get { return imageInfo; }
set {
imageInfo = value;
if (!Loading) {
ConstructContents ();
EmitNotify ("Image");
}
}
}
Gtk.Label labelWidget;
protected override void OnEndRead (FileFormat format)
{
base.OnEndRead (format);
if (format == FileFormat.Native && Type == ButtonType.TextAndIcon) {
Loading = true;
ConstructContents ();
Loading = false;
}
}
void ConstructContents ()
{
if (button.Child != null)
button.Remove (button.Child);
if (useUnderline) {
labelWidget = new Gtk.Label (label);
labelWidget.MnemonicWidget = button;
} else
labelWidget = Gtk.Label.New (label);
Gtk.Image imageWidget = (Gtk.Image)Registry.NewInstance ("Gtk.Image", proj);
Image imageWrapper = (Image)Widget.Lookup (imageWidget);
imageWrapper.Unselectable = true;
if (type != ButtonType.StockItem) {
imageWrapper.Pixbuf = imageInfo;
}
Gtk.HBox box = new Gtk.HBox (false, 2);
box.PackStart (imageWidget, false, false, 0);
box.PackEnd (labelWidget, false, false, 0);
Gtk.Alignment alignment = new Gtk.Alignment (button.Xalign, button.Yalign, 0.0f, 0.0f);
alignment.Add (box);
Widget wrapper = (Widget)ObjectWrapper.Create (proj, labelWidget);
wrapper.Unselectable = true;
wrapper = (Widget)ObjectWrapper.Create (proj, box);
wrapper.Unselectable = true;
wrapper = (Widget)ObjectWrapper.Create (proj, alignment);
wrapper.Unselectable = true;
alignment.ShowAll ();
button.Add (alignment);
}
string stockId = Gtk.Stock.Ok;
public string StockId {
get {
return stockId;
}
set {
if (responseId == ResponseIdForStockId (stockId))
responseId = 0;
if (value != null) {
string sid = value;
if (sid.StartsWith ("stock:"))
sid = sid.Substring (6);
button.Label = stockId = sid;
button.UseStock = true;
Gtk.StockItem item = Gtk.Stock.Lookup (sid);
if (item.StockId == sid) {
label = item.Label;
useUnderline = true;
}
} else {
stockId = value;
}
EmitNotify ("StockId");
if (responseId == 0)
ResponseId = ResponseIdForStockId (stockId);
}
}
string label;
public string Label {
get {
return label;
}
set {
label = value;
if (labelWidget != null)
labelWidget.LabelProp = value;
else
button.Label = value;
}
}
bool useUnderline;
public bool UseUnderline {
get {
return useUnderline;
}
set {
useUnderline = value;
if (labelWidget != null)
labelWidget.UseUnderline = value;
else
button.UseUnderline = value;
}
}
public bool IsDialogButton {
get {
ButtonBox box = this.ParentWrapper as ButtonBox;
return (box != null && box.InternalChildProperty != null && box.InternalChildProperty.Name == "ActionArea");
}
}
int responseId;
public int ResponseId {
get {
return responseId;
}
set {
responseId = value;
EmitNotify ("ResponseId");
}
}
int ResponseIdForStockId (string stockId)
{
if (stockId == Gtk.Stock.Ok)
return (int)Gtk.ResponseType.Ok;
else if (stockId == Gtk.Stock.Cancel)
return (int)Gtk.ResponseType.Cancel;
else if (stockId == Gtk.Stock.Close)
return (int)Gtk.ResponseType.Close;
else if (stockId == Gtk.Stock.Yes)
return (int)Gtk.ResponseType.Yes;
else if (stockId == Gtk.Stock.No)
return (int)Gtk.ResponseType.No;
else if (stockId == Gtk.Stock.Apply)
return (int)Gtk.ResponseType.Apply;
else if (stockId == Gtk.Stock.Help)
return (int)Gtk.ResponseType.Help;
else
return 0;
}
internal protected override void GenerateBuildCode (GeneratorContext ctx, CodeExpression var)
{
base.GenerateBuildCode (ctx, var);
if (Type != ButtonType.TextAndIcon) {
CodePropertyReferenceExpression cprop = new CodePropertyReferenceExpression (var, "Label");
PropertyDescriptor prop = (PropertyDescriptor) this.ClassDescriptor ["Label"];
bool trans = Type != ButtonType.StockItem && prop.IsTranslated (Wrapped);
CodeExpression val = ctx.GenerateValue (button.Label, typeof(string), trans);
ctx.Statements.Add (new CodeAssignStatement (cprop, val));
}
}
protected override void GeneratePropertySet (GeneratorContext ctx, CodeExpression var, PropertyDescriptor prop)
{
if (prop.Name != "Label")
base.GeneratePropertySet (ctx, var, prop);
}
}
}
| |
function VirtualKeyboard::create(%this)
{
%this.resetState();
}
function VirtualKeyboard::destroy(%this)
{
}
function VirtualKeyboard::resetState(%this)
{
%this.state = "toLower";
%this.dock = "bottom";
%this.targetGui ="";
%this.textBox = "";
}
function VirtualKeyboard::push(%this, %targetGui, %textBox, %showClose)
{
Sandbox.add( TamlRead("./gui/keyboardGui.taml") );
%textBox.setText("");
%this.targetGui = %targetGui;
%this.textBox = %textBox;
Canvas.pushDialog(%targetGui);
// resize to targetGui
%targetExtent = %targetGui.Extent;
KeyboardGui.resize(0, 0, %targetExtent._0, %targetExtent._1);
%this.targetGui.addGuiControl(KeyboardSet);
%textBox.setFirstResponder();
if (%showClose)
keyCloseBtn.setVisible(true);
else
keyCloseBtn.setVisible(false);
%this.toLower();
}
function VirtualKeyboard::Pop(%this)
{
KeyboardSet.delete();
KeyboardGui.delete();
Canvas.popDialog(%this.targetGui);
%this.resetState();
}
function VirtualKeyboard::toLower(%this)
{
%this.state = "toLower";
toLower_NumberBtn.visible = false;
toLowerBtn.visible = false;
toSymbolBtn.visible = false;
toNumber_symbolBtn.visible = false;
toLower_UpperLockBtn.visible = false;
toUpperLockBtn.visible =false;
toUpperBtn.visible = true;
toNumberBtn.visible = true;
keyboardSet.Image = "VirtualKeyboard:keyboardAlphaLower";
}
function VirtualKeyboard::toUpper(%this)
{
%this.state = "toUpper";
toUpperBtn.visible = false;
toLower_NumberBtn.visible = false;
toLowerBtn.visible = false;
toSymbolBtn.visible = false;
toNumber_symbolBtn.visible = false;
toLower_UpperLockBtn.visible = false;
toUpperLockBtn.visible =true;
toNumberBtn.visible = true;
keyboardSet.Image = "VirtualKeyboard:keyboardAlpha";
}
function VirtualKeyboard::toUpperLock(%this)
{
%this.state = "toUpperLock";
toUpperBtn.visible = false;
toUpperLockBtn.visible = false;
toLowerBtn.visible = false;
toLower_NumberBtn.visible = false;
toSymbolBtn.visible = false;
toNumber_symbolBtn.visible = false;
toLower_UpperLockBtn.visible = true;
toNumberBtn.visible = true;
keyboardSet.Image = "VirtualKeyboard:keyboardAlpha";
}
function VirtualKeyboard::toNumber(%this)
{
%this.state = "toNumber";
toNumberBtn.visible = false;
toLowerBtn.visible = false;
toUpperBtn.visible = false;
toNumber_symbolBtn.visible = false;
toLower_UpperLockBtn.visible = false;
toUpperLockBtn.visible =false;
toSymbolBtn.visible = true;
toLower_NumberBtn.visible = true;
keyboardSet.Image = "VirtualKeyboard:keyboardNumber";
}
function VirtualKeyboard::toSymbol(%this)
{
%this.state = "toSymbol";
toSymbolBtn.visible = false;
toUpperBtn.visible = false;
toLowerBtn.visible = false;
toNumberBtn.visible = false;
toLower_UpperLockBtn.visible = false;
toUpperLockBtn.visible =false;
toNumber_symbolBtn.visible = true;
toLower_NumberBtn.visible = true;
keyboardSet.Image = "VirtualKeyboard:keyboardSymbol";
}
function VirtualKeyboard::KeyPress(%this, %letter, %number, %symbol)
{
if (%letter $= "close")
%this.schedule(50, "Pop");
else if (%letter $= "delete")
%this.deleteCommand();
else if (%letter $= "space")
%this.insertChar(" ");
else
%this.insertChar(%letter, %number, %symbol);
}
function VirtualKeyboard::InsertChar(%this, %letter, %number, %symbol)
{
if (strlen(%this.textBox.getText()) >= %this.textBox.MaxLength)
return;
if (%letter $= " ")
{
%this.textBox.setText(%this.textBox.getText() @ " ");
}
else
{
if (%this.state $= "toLower")
%this.textBox.setText(%this.textBox.getText() @ strlwr(%letter));
else if (%this.state $= "toUpper")
{
%this.textBox.setText(%this.textBox.getText() @ strupr(%letter));
%this.toLower();
}
else if (%this.state $= "toUpperLock")
{
%this.textBox.setText(%this.textBox.getText() @ strupr(%letter));
}
else if (%this.state $= "toNumber")
{
if (%letter $= "B")
%number = "'";
else if (%letter $= "K")
%number = "&";
%this.textBox.setText(%this.textBox.getText() @ %number);
}
else if (%this.state $= "toSymbol")
{
if (%letter $= "B")
%symbol = "'";
%this.textBox.setText(%this.textBox.getText() @ %symbol);
}
}
}
function VirtualKeyboard::DeleteCommand(%this)
{
%len = strlen(%this.textBox.getText());
if (%len > 0)
%this.textBox.setText(getSubStr(%this.textBox.getText(), 0, %len - 1));
}
if(!isObject(GuiKeyboardProfile)) new GuiControlProfile (GuiKeyboardProfile)
{
tab = false;
canKeyFocus = false;
hasBitmapArray = false;
mouseOverSelected = false;
// fill color
opaque = false;
fillColor = "211 211 211";
fillColorHL = "244 244 244";
fillColorNA = "244 244 244";
// border color
border = 0;
borderColor = "100 100 100 255";
borderColorHL = "128 128 128";
borderColorNA = "64 64 64";
// font
fontType = $platformFontType;
fontSize = $platformFontSize;
fontColor = "0 0 0";
fontColorHL = "32 100 100";
fontColorNA = "0 0 0";
fontColorSEL= "10 10 10";
// used by guiTextControl
modal = true;
justify = "left";
autoSizeWidth = false;
autoSizeHeight = false;
returnTab = false;
numbersOnly = false;
cursorColor = "0 0 0 255";
// sounds
soundButtonDown = "VirtualKeyboard:keypress";
//soundButtonOver = "Sandbox:mouseOver";
};
| |
//------------------------------------------------------------------------------
// Microsoft Avalon
// Copyright (c) Microsoft Corporation, 2005
//
// File: UnsafeIndexingFilterStream.cs
//
// Description: The class UnsafeIndexingFilterStream uses an OLE IStream component
// passed on a indexing filter's IPersistStream interface to implement
// the System.IO.Stream functions necessary for filtering a document.
// In other words, it basically implements a seekable read-only stream.
//
// For a more complete example of an IStream adapter, see Listing 20.2
// in Adam Nathan's ".Net and COM".
//
// History: 02/15/05 - johnlarc - initial implementation
//------------------------------------------------------------------------------
using System;
using System.IO;
using System.Runtime.InteropServices; // For Marshal
using System.Windows; // for ExceptionStringTable
using MS.Win32; // For NativeMethods
using MS.Internal.Interop; // for IStream
using System.Security; // For SecurityCritical
namespace MS.Internal.IO.Packaging
{
/// <summary>
/// The class UnsafeIndexingFilterStream uses an OLE IStream component
/// passed on an indexing filter's IPersistStream interface to implement
/// the System.IO.Stream functions necessary for filtering a document.
/// In other words, it basically implements a seekable read-only stream.
/// </summary>
/// <remarks>
///
/// This class is used only by the Container filter, since the Xaml filter is not accessible directly
/// from unmanaged code and so can use System.IO.Stream natively.
///
/// This class does not own the process of closing the underlying stream. However,
/// This class does own a reference to a COM object that should be released as a part of the Dispose pattern,
/// so that the underlying unmanaged code doesn't keep the stream open indefinitely (or until GC gets to it)
///
/// The definition of IStream that is used is MS.Internal.Interop.IStream rather than the standard one
/// so as to allow efficient marshaling of arrays with specified offsets in Read.
/// </remarks>
/// <SecurityNote>
/// Critical: Marking this as Security Critical as this stream serves a very specific functionality
/// required for indexing content using unmanaged Indexing Services. We do not want managed
/// code to start using this Stream implementation.
/// This code is meant to be accessed only from unmanaged code. Currently there is one
/// unmanaged caller.
/// This stream- 1. Calls into unmanaged code.
/// 2. Implements a seekable read-only stream on an OLE IStream component.
/// 3. Behaves more like an unmanaged IStream as opposed to managed Stream.
/// 4. This class does not do any elevation of privilege.
/// </SecurityNote>
[SecurityCritical(SecurityCriticalScope.Everything)]
internal class UnsafeIndexingFilterStream : Stream
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
/// <summary>
/// Build a System.IO.Stream implementation around an IStream component.
/// </summary>
/// <remarks>
/// The client code is entirely responsible for the lifespan of the stream,
/// and there is no way it can tip us off for when to release it. Therefore,
/// its reference count is not incremented. The risk of the client
/// releasing the IStream component before we're done with it is no worse than
/// that of the client passing a pointer to garbage in the first place, and we
/// cannot protect against that either. After all, the client is unmanaged and
/// has endless possibilities of trashing the machine if she wishes to.
/// </remarks>
internal UnsafeIndexingFilterStream(IStream oleStream)
{
if (oleStream == null)
throw new ArgumentNullException("oleStream");
_oleStream = oleStream;
_disposed = false;
}
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
/// <summary>
/// Return the bytes requested.
/// </summary>
/// <param name="buffer">Destination buffer.</param>
/// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream.</param>
/// <param name="count">How many bytes requested.</param>
/// <returns>How many bytes were written into buffer.</returns>
public unsafe override int Read(byte[] buffer, int offset, int count)
{
ThrowIfStreamDisposed();
// Check arguments.
PackagingUtilities.VerifyStreamReadArgs(this, buffer, offset, count);
// Reading 0 bytes is a no-op.
if (count == 0)
return 0;
// Prepare location of return value and call the COM object.
int bytesRead;
IntPtr pBytesRead = new IntPtr(&bytesRead);
// Prepare to restore position in case the read fails.
long positionBeforeReadAttempt = this.Position;
try
{
// Pin the array wrt GC while using an address in it.
fixed (byte *bufferPointer = &buffer[offset])
{
_oleStream.Read(new IntPtr(bufferPointer), count, pBytesRead);
}
}
catch (COMException comException)
{
this.Position = positionBeforeReadAttempt;
throw new IOException("Read", comException);
}
catch (IOException ioException)
{
this.Position = positionBeforeReadAttempt;
throw new IOException("Read", ioException);
}
return bytesRead;
}
/// <summary>
/// Seek -unmanaged streams do not allow seeking beyond the end of the stream
/// and since we rely on the underlying stream to validate and return the seek
/// results, unlike managed streams where seeking beyond the end of the stream
/// is allowed we will get an exception.
/// </summary>
/// <param name="offset">Offset in byte.</param>
/// <param name="origin">Offset origin (start, current, or end).</param>
public unsafe override long Seek(long offset, SeekOrigin origin)
{
ThrowIfStreamDisposed();
long position = 0;
// The address of 'position' can be used without pinning the object, because it
// is a value and is therefore allocated on the stack rather than the heap.
IntPtr positionAddress = new IntPtr(&position);
// The enum values of SeekOrigin match the STREAM_SEEK_* values. This
// convention is as good as carved in stone, so there's no need for a switch here.
_oleStream.Seek(offset, (int)origin, positionAddress);
return position;
}
/// <summary>
/// SetLength
/// </summary>
/// <exception cref="NotSupportedException">not supported</exception>
/// <remarks>
/// Not supported. No indexing filter should require it.
/// </remarks>
public override void SetLength(long newLength)
{
ThrowIfStreamDisposed();
throw new NotSupportedException(SR.Get(SRID.StreamDoesNotSupportWrite));
}
/// <summary>
/// Write
/// </summary>
/// <exception cref="NotSupportedException">not supported</exception>
/// <remarks>
/// Not supported. No indexing filter should require it.
/// </remarks>
public override void Write(byte[] buf, int offset, int count)
{
ThrowIfStreamDisposed();
throw new NotSupportedException(SR.Get(SRID.StreamDoesNotSupportWrite));
}
/// <summary>
/// Flush
/// </summary>
public override void Flush()
{
ThrowIfStreamDisposed();
//This stream is always readonly, and calling this method is a no-op
//No IndexingFilter should require this method.
}
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
/// <summary>
/// Is stream readable?
/// </summary>
/// <remarks>
/// We always return true, because there's no way of checking whether the caller
/// has closed the stream.
/// </remarks>
public override bool CanRead
{
get
{
return !_disposed;
}
}
/// <summary>
/// Is stream seekable?
/// </summary>
public override bool CanSeek
{
get
{
// This information is not available from the underlying stream.
// So one assumption has to be made. True is the most common for indexable streams.
return !_disposed;
}
}
/// <summary>
/// Is stream writable?
/// </summary>
public override bool CanWrite
{
get
{
return false;
}
}
/// <summary>
/// Logical byte position in this stream
/// </summary>
public override long Position
{
get
{
ThrowIfStreamDisposed();
return Seek(0, SeekOrigin.Current);
}
set
{
ThrowIfStreamDisposed();
if (value < 0)
throw new ArgumentException(SR.Get(SRID.CannotSetNegativePosition));
Seek(value, SeekOrigin.Begin);
}
}
/// <summary>
/// Length.
/// </summary>
public override long Length
{
get
{
ThrowIfStreamDisposed();
// Retrieve stream stats. STATFLAG_NONAME means don't return the stream name.
System.Runtime.InteropServices.ComTypes.STATSTG statstg;
_oleStream.Stat(out statstg, NativeMethods.STATFLAG_NONAME);
return statstg.cbSize;
}
}
//------------------------------------------------------
//
// Protected methods.
//
//------------------------------------------------------
/// <summary>
/// <para>
/// Although UnsafeIndexingFilterStream does not close the underlying stream, it is responsible for releasing
/// the ComObject it holds, so that unmanaged code can properly close the stream.
/// </para> <para>
/// This method gets invoked as part of the base class's Dispose() or Close() implementation.
/// </para>
/// </summary>
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
if (_oleStream != null)
{
MS.Win32.UnsafeNativeMethods.SafeReleaseComObject(_oleStream);
}
}
}
finally
{
// Calls to Dispose(bool) are expected to bubble up through the class hierarchy.
_oleStream = null;
_disposed = true;
base.Dispose(disposing);
}
}
//------------------------------------------------------
//
// Private methods.
//
//------------------------------------------------------
private void ThrowIfStreamDisposed()
{
if (_disposed)
throw new ObjectDisposedException(null, SR.Get(SRID.StreamObjectDisposed));
}
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
private IStream _oleStream; // Underlying COM component.
private bool _disposed;
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gagr = Google.Api.Gax.ResourceNames;
using gcgv = Google.Cloud.GSuiteAddOns.V1;
using sys = System;
namespace Google.Cloud.GSuiteAddOns.V1
{
/// <summary>Resource name for the <c>Authorization</c> resource.</summary>
public sealed partial class AuthorizationName : gax::IResourceName, sys::IEquatable<AuthorizationName>
{
/// <summary>The possible contents of <see cref="AuthorizationName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>projects/{project}/authorization</c>.</summary>
Project = 1,
}
private static gax::PathTemplate s_project = new gax::PathTemplate("projects/{project}/authorization");
/// <summary>Creates a <see cref="AuthorizationName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="AuthorizationName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static AuthorizationName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new AuthorizationName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="AuthorizationName"/> with the pattern <c>projects/{project}/authorization</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="AuthorizationName"/> constructed from the provided ids.</returns>
public static AuthorizationName FromProject(string projectId) =>
new AuthorizationName(ResourceNameType.Project, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AuthorizationName"/> with pattern
/// <c>projects/{project}/authorization</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AuthorizationName"/> with pattern
/// <c>projects/{project}/authorization</c>.
/// </returns>
public static string Format(string projectId) => FormatProject(projectId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AuthorizationName"/> with pattern
/// <c>projects/{project}/authorization</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AuthorizationName"/> with pattern
/// <c>projects/{project}/authorization</c>.
/// </returns>
public static string FormatProject(string projectId) =>
s_project.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="AuthorizationName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>projects/{project}/authorization</c></description></item></list>
/// </remarks>
/// <param name="authorizationName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="AuthorizationName"/> if successful.</returns>
public static AuthorizationName Parse(string authorizationName) => Parse(authorizationName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="AuthorizationName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>projects/{project}/authorization</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="authorizationName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="AuthorizationName"/> if successful.</returns>
public static AuthorizationName Parse(string authorizationName, bool allowUnparsed) =>
TryParse(authorizationName, allowUnparsed, out AuthorizationName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AuthorizationName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>projects/{project}/authorization</c></description></item></list>
/// </remarks>
/// <param name="authorizationName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AuthorizationName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string authorizationName, out AuthorizationName result) =>
TryParse(authorizationName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AuthorizationName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>projects/{project}/authorization</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="authorizationName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AuthorizationName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string authorizationName, bool allowUnparsed, out AuthorizationName result)
{
gax::GaxPreconditions.CheckNotNull(authorizationName, nameof(authorizationName));
gax::TemplatedResourceName resourceName;
if (s_project.TryParseName(authorizationName, out resourceName))
{
result = FromProject(resourceName[0]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(authorizationName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private AuthorizationName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="AuthorizationName"/> class from the component parts of pattern
/// <c>projects/{project}/authorization</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
public AuthorizationName(string projectId) : this(ResourceNameType.Project, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.Project: return s_project.Expand(ProjectId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as AuthorizationName);
/// <inheritdoc/>
public bool Equals(AuthorizationName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(AuthorizationName a, AuthorizationName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(AuthorizationName a, AuthorizationName b) => !(a == b);
}
/// <summary>Resource name for the <c>InstallStatus</c> resource.</summary>
public sealed partial class InstallStatusName : gax::IResourceName, sys::IEquatable<InstallStatusName>
{
/// <summary>The possible contents of <see cref="InstallStatusName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/deployments/{deployment}/installStatus</c>.
/// </summary>
ProjectDeployment = 1,
}
private static gax::PathTemplate s_projectDeployment = new gax::PathTemplate("projects/{project}/deployments/{deployment}/installStatus");
/// <summary>Creates a <see cref="InstallStatusName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="InstallStatusName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static InstallStatusName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new InstallStatusName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="InstallStatusName"/> with the pattern
/// <c>projects/{project}/deployments/{deployment}/installStatus</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="InstallStatusName"/> constructed from the provided ids.</returns>
public static InstallStatusName FromProjectDeployment(string projectId, string deploymentId) =>
new InstallStatusName(ResourceNameType.ProjectDeployment, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), deploymentId: gax::GaxPreconditions.CheckNotNullOrEmpty(deploymentId, nameof(deploymentId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="InstallStatusName"/> with pattern
/// <c>projects/{project}/deployments/{deployment}/installStatus</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="InstallStatusName"/> with pattern
/// <c>projects/{project}/deployments/{deployment}/installStatus</c>.
/// </returns>
public static string Format(string projectId, string deploymentId) => FormatProjectDeployment(projectId, deploymentId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="InstallStatusName"/> with pattern
/// <c>projects/{project}/deployments/{deployment}/installStatus</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="InstallStatusName"/> with pattern
/// <c>projects/{project}/deployments/{deployment}/installStatus</c>.
/// </returns>
public static string FormatProjectDeployment(string projectId, string deploymentId) =>
s_projectDeployment.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(deploymentId, nameof(deploymentId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="InstallStatusName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/deployments/{deployment}/installStatus</c></description></item>
/// </list>
/// </remarks>
/// <param name="installStatusName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="InstallStatusName"/> if successful.</returns>
public static InstallStatusName Parse(string installStatusName) => Parse(installStatusName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="InstallStatusName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/deployments/{deployment}/installStatus</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="installStatusName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="InstallStatusName"/> if successful.</returns>
public static InstallStatusName Parse(string installStatusName, bool allowUnparsed) =>
TryParse(installStatusName, allowUnparsed, out InstallStatusName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="InstallStatusName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/deployments/{deployment}/installStatus</c></description></item>
/// </list>
/// </remarks>
/// <param name="installStatusName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="InstallStatusName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string installStatusName, out InstallStatusName result) =>
TryParse(installStatusName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="InstallStatusName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/deployments/{deployment}/installStatus</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="installStatusName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="InstallStatusName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string installStatusName, bool allowUnparsed, out InstallStatusName result)
{
gax::GaxPreconditions.CheckNotNull(installStatusName, nameof(installStatusName));
gax::TemplatedResourceName resourceName;
if (s_projectDeployment.TryParseName(installStatusName, out resourceName))
{
result = FromProjectDeployment(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(installStatusName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private InstallStatusName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string deploymentId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
DeploymentId = deploymentId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="InstallStatusName"/> class from the component parts of pattern
/// <c>projects/{project}/deployments/{deployment}/installStatus</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param>
public InstallStatusName(string projectId, string deploymentId) : this(ResourceNameType.ProjectDeployment, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), deploymentId: gax::GaxPreconditions.CheckNotNullOrEmpty(deploymentId, nameof(deploymentId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Deployment</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string DeploymentId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectDeployment: return s_projectDeployment.Expand(ProjectId, DeploymentId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as InstallStatusName);
/// <inheritdoc/>
public bool Equals(InstallStatusName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(InstallStatusName a, InstallStatusName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(InstallStatusName a, InstallStatusName b) => !(a == b);
}
/// <summary>Resource name for the <c>Deployment</c> resource.</summary>
public sealed partial class DeploymentName : gax::IResourceName, sys::IEquatable<DeploymentName>
{
/// <summary>The possible contents of <see cref="DeploymentName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>projects/{project}/deployments/{deployment}</c>.</summary>
ProjectDeployment = 1,
}
private static gax::PathTemplate s_projectDeployment = new gax::PathTemplate("projects/{project}/deployments/{deployment}");
/// <summary>Creates a <see cref="DeploymentName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="DeploymentName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static DeploymentName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new DeploymentName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="DeploymentName"/> with the pattern <c>projects/{project}/deployments/{deployment}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="DeploymentName"/> constructed from the provided ids.</returns>
public static DeploymentName FromProjectDeployment(string projectId, string deploymentId) =>
new DeploymentName(ResourceNameType.ProjectDeployment, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), deploymentId: gax::GaxPreconditions.CheckNotNullOrEmpty(deploymentId, nameof(deploymentId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="DeploymentName"/> with pattern
/// <c>projects/{project}/deployments/{deployment}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="DeploymentName"/> with pattern
/// <c>projects/{project}/deployments/{deployment}</c>.
/// </returns>
public static string Format(string projectId, string deploymentId) => FormatProjectDeployment(projectId, deploymentId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="DeploymentName"/> with pattern
/// <c>projects/{project}/deployments/{deployment}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="DeploymentName"/> with pattern
/// <c>projects/{project}/deployments/{deployment}</c>.
/// </returns>
public static string FormatProjectDeployment(string projectId, string deploymentId) =>
s_projectDeployment.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(deploymentId, nameof(deploymentId)));
/// <summary>Parses the given resource name string into a new <see cref="DeploymentName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/deployments/{deployment}</c></description></item>
/// </list>
/// </remarks>
/// <param name="deploymentName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="DeploymentName"/> if successful.</returns>
public static DeploymentName Parse(string deploymentName) => Parse(deploymentName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="DeploymentName"/> instance; optionally allowing
/// an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/deployments/{deployment}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="deploymentName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="DeploymentName"/> if successful.</returns>
public static DeploymentName Parse(string deploymentName, bool allowUnparsed) =>
TryParse(deploymentName, allowUnparsed, out DeploymentName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="DeploymentName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/deployments/{deployment}</c></description></item>
/// </list>
/// </remarks>
/// <param name="deploymentName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="DeploymentName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string deploymentName, out DeploymentName result) =>
TryParse(deploymentName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="DeploymentName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/deployments/{deployment}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="deploymentName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="DeploymentName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string deploymentName, bool allowUnparsed, out DeploymentName result)
{
gax::GaxPreconditions.CheckNotNull(deploymentName, nameof(deploymentName));
gax::TemplatedResourceName resourceName;
if (s_projectDeployment.TryParseName(deploymentName, out resourceName))
{
result = FromProjectDeployment(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(deploymentName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private DeploymentName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string deploymentId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
DeploymentId = deploymentId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="DeploymentName"/> class from the component parts of pattern
/// <c>projects/{project}/deployments/{deployment}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param>
public DeploymentName(string projectId, string deploymentId) : this(ResourceNameType.ProjectDeployment, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), deploymentId: gax::GaxPreconditions.CheckNotNullOrEmpty(deploymentId, nameof(deploymentId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Deployment</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string DeploymentId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectDeployment: return s_projectDeployment.Expand(ProjectId, DeploymentId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as DeploymentName);
/// <inheritdoc/>
public bool Equals(DeploymentName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(DeploymentName a, DeploymentName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(DeploymentName a, DeploymentName b) => !(a == b);
}
public partial class GetAuthorizationRequest
{
/// <summary>
/// <see cref="gcgv::AuthorizationName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcgv::AuthorizationName AuthorizationName
{
get => string.IsNullOrEmpty(Name) ? null : gcgv::AuthorizationName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class Authorization
{
/// <summary>
/// <see cref="gcgv::AuthorizationName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcgv::AuthorizationName AuthorizationName
{
get => string.IsNullOrEmpty(Name) ? null : gcgv::AuthorizationName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class CreateDeploymentRequest
{
/// <summary>
/// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::ProjectName ParentAsProjectName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::ProjectName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetDeploymentRequest
{
/// <summary>
/// <see cref="gcgv::DeploymentName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcgv::DeploymentName DeploymentName
{
get => string.IsNullOrEmpty(Name) ? null : gcgv::DeploymentName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListDeploymentsRequest
{
/// <summary>
/// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::ProjectName ParentAsProjectName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::ProjectName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class DeleteDeploymentRequest
{
/// <summary>
/// <see cref="gcgv::DeploymentName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcgv::DeploymentName DeploymentName
{
get => string.IsNullOrEmpty(Name) ? null : gcgv::DeploymentName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class InstallDeploymentRequest
{
/// <summary>
/// <see cref="gcgv::DeploymentName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcgv::DeploymentName DeploymentName
{
get => string.IsNullOrEmpty(Name) ? null : gcgv::DeploymentName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class UninstallDeploymentRequest
{
/// <summary>
/// <see cref="gcgv::DeploymentName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcgv::DeploymentName DeploymentName
{
get => string.IsNullOrEmpty(Name) ? null : gcgv::DeploymentName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class GetInstallStatusRequest
{
/// <summary>
/// <see cref="gcgv::InstallStatusName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcgv::InstallStatusName InstallStatusName
{
get => string.IsNullOrEmpty(Name) ? null : gcgv::InstallStatusName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class InstallStatus
{
/// <summary>
/// <see cref="gcgv::InstallStatusName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcgv::InstallStatusName InstallStatusName
{
get => string.IsNullOrEmpty(Name) ? null : gcgv::InstallStatusName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class Deployment
{
/// <summary>
/// <see cref="gcgv::DeploymentName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcgv::DeploymentName DeploymentName
{
get => string.IsNullOrEmpty(Name) ? null : gcgv::DeploymentName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.