context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using FontBuddyLib;
using MenuBuddy;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using ResolutionBuddy;
using System;
using System.Threading.Tasks;
namespace InsertCoinBuddy
{
/// <summary>
/// This screen displays credits status on top of all the other screens
/// Displays "Insert Coin" if the game is not being played and there are no credits available
/// Displays "Press Start!" if the game is not being played and there are 1+ credits available
///
/// At the bottom of the screen, displays the number of credits
/// Credits: [NumCredits] [NumCoins]/[CoinsPerCredit]
/// </summary>
public class InsertCoinScreen : Screen
{
#region Properties
/// <summary>
/// The thing that actually manages the number of credits for this screen.
/// </summary>
public IInsertCoinService Service;
/// <summary>
/// name of the font resource to use to write "Insert Coin"
/// </summary>
public string InsertCoinFontName { get; set; }
/// <summary>
/// name of the font resource to use to write "Credits: x/X"
/// </summary>
public string NumCreditsFontName { get; set; }
/// <summary>
/// thing for writing "Insert Coin" text
/// </summary>
private PulsateBuddy InsertCoinFont { get; set; }
/// <summary>
/// thing for writing "NumCredits" text
/// </summary>
private IFontBuddy NumCreditsFont { get; set; }
/// <summary>
/// location of the "Insert Coin" text
/// </summary>
private float InsertCoinTextLocation { get; set; }
private float LineSpacing { get; set; }
public string CoinSoundName { get; set; }
public string PlayerJoinSoundName { get; set; }
private SoundEffect CoinSound { get; set; }
private SoundEffect PlayerJoinSound { get; set; }
#endregion //Properties
#region Methods
/// <summary>
/// Constructor fills in the menu contents.
/// </summary>
public InsertCoinScreen(string insertCoinFont, string numCreditsFont, string coinSound, string playerJoinSound)
{
CoveredByOtherScreens = false;
CoverOtherScreens = false;
InsertCoinFontName = insertCoinFont;
NumCreditsFontName = numCreditsFont;
CoinSoundName = coinSound;
PlayerJoinSoundName = playerJoinSound;
}
/// <summary>
/// Load graphics content for the screen.
/// </summary>
public override async Task LoadContent()
{
await base.LoadContent();
Service = ScreenManager.Game.Services.GetService<IInsertCoinService>();
if (null == Service)
{
throw new ArgumentNullException("_service");
}
Service.OnCoinAdded += OnCoinDropped;
Service.OnPlayerJoined += OnPlayerJoined;
//load teh fonts
InsertCoinFont = new PulsateBuddy()
{
ShadowOffset = Vector2.Zero,
ShadowSize = 1f,
};
InsertCoinFont.PulsateSize = 0.25f;
InsertCoinFont.LoadContent(Content, InsertCoinFontName, StyleSheet.UseFontPlus, StyleSheet.SmallFontSize);
if (StyleSheet.UseFontPlus)
{
NumCreditsFont = new FontBuddyPlus();
}
else
{
NumCreditsFont = new FontBuddy();
}
NumCreditsFont.LoadContent(Content, NumCreditsFontName, StyleSheet.UseFontPlus, StyleSheet.SmallFontSize);
//initialize some default locations for text
//Insert coin stuff is displayed right above that
LineSpacing = InsertCoinFont.MeasureString("Insert Coin").Y;
InsertCoinTextLocation = Resolution.TitleSafeArea.Bottom - (2.0f * LineSpacing);
if (!string.IsNullOrEmpty(CoinSoundName))
{
CoinSound = Content.Load<SoundEffect>(CoinSoundName);
}
if (!string.IsNullOrEmpty(PlayerJoinSoundName))
{
PlayerJoinSound = Content.Load<SoundEffect>(PlayerJoinSoundName);
}
}
private void OnCoinDropped(object sender, CoinEventArgs e)
{
CoinSound?.Play();
}
private void OnPlayerJoined(object sender, CoinEventArgs e)
{
PlayerJoinSound?.Play();
}
public override void Draw(GameTime gameTime)
{
base.Draw(gameTime);
ScreenManager.SpriteBatchBegin();
switch (Service.CurrentGameState)
{
case GameState.Menu:
{
DrawMenuText(gameTime);
}
break;
case GameState.Ready:
{
DrawReadyText(gameTime);
}
break;
case GameState.Playing:
{
DrawPlayingText(gameTime);
}
break;
}
ScreenManager.SpriteBatchEnd();
}
private void DrawMenuText(GameTime gameTime)
{
for (int i = 0; i < Service.Players.Count; i++)
{
var player = Service.Players[i];
//Get the location to draw the player's text
var location = new Vector2((i + 1) * (Resolution.ScreenArea.Width / (Service.Players.Count + 1)), InsertCoinTextLocation);
WritePlayerMenuText(player, location, gameTime);
}
}
private void WritePlayerMenuText(PlayerCredits player, Vector2 location, GameTime gameTime)
{
//Draw instructions for the players
if (player.CreditAvailable)
{
WriteInsertCoinText(player, location, 6.0f, 1.2f, "Press Start!", gameTime);
}
else
{
//draw in slowly pulsating white letters
WriteInsertCoinText(player, location, 3.0f, 1.0f, InsertCoinText(player), gameTime);
}
//Draw the number of credits text!
if (ShouldDisplayNumCredits(player))
{
//Number of credits is displayed at the bottom of the screen
NumCreditsFont.Write(NumCreditsText(player),
new Vector2(location.X, location.Y + LineSpacing),
Justify.Center,
0.6f, //write normal
Color.White,
ScreenManager.SpriteBatch,
Time);
}
}
private void DrawReadyText(GameTime gameTime)
{
for (int i = 0; i < Service.Players.Count; i++)
{
var player = Service.Players[i];
//Get the location to draw the player's text
var location = new Vector2((i + 1) * (Resolution.ScreenArea.Width / (Service.Players.Count + 1)), InsertCoinTextLocation);
//Draw instructions for the players
if (!player.Ready)
{
WritePlayerMenuText(player, location, gameTime);
}
else
{
WriteInsertCoinText(player, location, 6.0f, 1.2f, "Ready!", gameTime);
//Draw the number of credits text!
if (ShouldDisplayNumCredits(player))
{
//Number of credits is displayed at the bottom of the screen
NumCreditsFont.Write(NumCreditsText(player),
new Vector2(location.X, location.Y + LineSpacing),
Justify.Center,
0.6f, //write normal
Color.White,
ScreenManager.SpriteBatch,
Time);
}
}
}
}
private void DrawPlayingText(GameTime gameTime)
{
for (int i = 0; i < Service.Players.Count; i++)
{
var player = Service.Players[i];
//Get the location to draw the player's text
var location = new Vector2((i + 1) * (Resolution.ScreenArea.Width / (Service.Players.Count + 1)), Resolution.TitleSafeArea.Top);
//Only draw text for player's that aren't currently playing.
if (!player.Current)
{
if (player.CreditAvailable)
{
WriteInsertCoinText(player, location, 2.0f, 0.5f, "Press Start!", gameTime);
location = new Vector2(location.X, location.Y + LineSpacing);
}
else
{
WriteInsertCoinText(player, location, 2.0f, 0.5f, InsertCoinText(player), gameTime);
location = new Vector2(location.X, location.Y + LineSpacing);
}
}
//Write the player's number of credits if they have coins in the system
if (ShouldDisplayNumCredits(player))
{
//number of credits is displayed at top of the screen
NumCreditsFont.Write(NumCreditsText(player),
location,
Justify.Center,
0.6f, //write normal
Color.White,
ScreenManager.SpriteBatch,
Time);
}
}
}
/// <summary>
/// Check if the screen should write the number of credits available
/// </summary>
/// <returns><c>true</c>, if display number credits was shoulded, <c>false</c> otherwise.</returns>
public bool ShouldDisplayNumCredits(PlayerCredits player)
{
if (GameState.Playing != Service.CurrentGameState)
{
//always display the number of credits if the game is not in play
return true;
}
else
{
//If the game is in play, only display credits if there are any coins in the system
return (Service.FreePlay || (player.TotalCoins >= 1));
}
}
/// <summary>
/// Get the text to write for inserting coins
/// </summary>
/// <returns>The coin text.</returns>
public string InsertCoinText(PlayerCredits player)
{
if (player.NumCoinsNeededForNextCredit == 1)
{
return "Insert Coin";
}
else
{
//need more than one coin, reutrn "coins" plural
return "Insert Coins";
}
}
/// <summary>
/// Get the text to write to display the number of credits
/// </summary>
/// <returns>The credits text.</returns>
public string NumCreditsText(PlayerCredits player)
{
//if it is free play mode, just say so
if (Service.FreePlay)
{
return "Free Play";
}
if (0 == player.NumCredits)
{
//Don't display 0 for number of credits, it will be confusing
return $"Credits: {player.NumCoins}/{Service.CoinsPerCredit}";
}
else
{
//There are credits in the system!
if (0 == player.NumCoins)
{
//Don't display 0/x for num coins, it looks terrible
return $"Credits: {player.NumCredits}";
}
else
{
return $"Credits: {player.NumCredits} {player.NumCoins}/{Service.CoinsPerCredit}";
}
}
}
private void WriteInsertCoinText(PlayerCredits player, Vector2 location, float pulsateSpeed, float size, string strText, GameTime gameTime)
{
//get the location to draw this player's text
//Draw in big pulsating letters
InsertCoinFont.PulsateSpeed = pulsateSpeed; //pulsate faster
InsertCoinFont.Write(strText,
location,
Justify.Center,
size, //write bigger
Color.White,
ScreenManager.SpriteBatch,
Time);
}
#endregion //Methods
}
}
| |
// Copyright 2011 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Microsoft.Data.OData
{
#region Namespaces
using System;
using System.Diagnostics;
using System.Xml;
using Microsoft.Data.Edm;
using Microsoft.Data.OData.Atom;
using Microsoft.Data.OData.Metadata;
#endregion Namespaces
/// <summary>
/// Utility methods around writing of ATOM values.
/// </summary>
internal static class AtomValueUtils
{
/// <summary>The characters that are considered to be whitespace by XmlConvert.</summary>
private static readonly char[] XmlWhitespaceChars = new char[] { ' ', '\t', '\n', '\r' };
/// <summary>
/// Converts the given value to the ATOM string representation
/// and uses the writer to write it.
/// </summary>
/// <param name="writer">The writer to write the stringified value.</param>
/// <param name="value">The value to be written.</param>
internal static void WritePrimitiveValue(XmlWriter writer, object value)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(value != null, "value != null");
if (!PrimitiveConverter.Instance.TryWriteAtom(value, writer))
{
string result;
if (!TryConvertPrimitiveToString(value, out result))
{
throw new ODataException(Strings.AtomValueUtils_CannotConvertValueToAtomPrimitive(value.GetType().FullName));
}
ODataAtomWriterUtils.WriteString(writer, result);
}
}
/// <summary>
/// Reads a value of an XML element and converts it to the target primitive value.
/// </summary>
/// <param name="reader">The XML reader to read the value from.</param>
/// <param name="primitiveTypeReference">The primitive type reference to convert the value to.</param>
/// <returns>The primitive value read.</returns>
/// <remarks>This method does not read null values, it only reads the actual element value (not its attributes).</remarks>
/// <remarks>
/// Pre-Condition: XmlNodeType.Element - the element to read the value for.
/// XmlNodeType.Attribute - an attribute on the element to read the value for.
/// Post-Condition: XmlNodeType.Element - the element was empty.
/// XmlNodeType.EndElement - the element had some value.
/// </remarks>
internal static object ReadPrimitiveValue(XmlReader reader, IEdmPrimitiveTypeReference primitiveTypeReference)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(reader != null, "reader != null");
object spatialValue;
if (!PrimitiveConverter.Instance.TryTokenizeFromXml(reader, EdmLibraryExtensions.GetPrimitiveClrType(primitiveTypeReference), out spatialValue))
{
string stringValue = reader.ReadElementContentValue();
return ConvertStringToPrimitive(stringValue, primitiveTypeReference);
}
return spatialValue;
}
/// <summary>
/// Converts a given <see cref="AtomTextConstructKind"/> to a string appropriate for Atom format.
/// </summary>
/// <param name="textConstructKind">The text construct kind to convert.</param>
/// <returns>The string version of the text construct format in Atom format.</returns>
internal static string ToString(AtomTextConstructKind textConstructKind)
{
DebugUtils.CheckNoExternalCallers();
switch (textConstructKind)
{
case AtomTextConstructKind.Text:
return AtomConstants.AtomTextConstructTextKind;
case AtomTextConstructKind.Html:
return AtomConstants.AtomTextConstructHtmlKind;
case AtomTextConstructKind.Xhtml:
return AtomConstants.AtomTextConstructXHtmlKind;
default:
throw new ODataException(Strings.General_InternalError(InternalErrorCodes.ODataAtomConvert_ToString));
}
}
/// <summary>Converts the specified value to a serializable string in ATOM format.</summary>
/// <param name="value">Non-null value to convert.</param>
/// <param name="result">The specified value converted to an ATOM string.</param>
/// <returns>boolean value indicating conversion successful conversion</returns>
internal static bool TryConvertPrimitiveToString(object value, out string result)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(value != null, "value != null");
result = null;
TypeCode typeCode = PlatformHelper.GetTypeCode(value.GetType());
switch (typeCode)
{
case TypeCode.Boolean:
result = ODataAtomConvert.ToString((bool)value);
break;
case TypeCode.Byte:
result = ODataAtomConvert.ToString((byte)value);
break;
case TypeCode.DateTime:
result = ODataAtomConvert.ToString((DateTime)value);
break;
case TypeCode.Decimal:
result = ODataAtomConvert.ToString((decimal)value);
break;
case TypeCode.Double:
result = ODataAtomConvert.ToString((double)value);
break;
case TypeCode.Int16:
result = ODataAtomConvert.ToString((Int16)value);
break;
case TypeCode.Int32:
result = ODataAtomConvert.ToString((Int32)value);
break;
case TypeCode.Int64:
result = ODataAtomConvert.ToString((Int64)value);
break;
case TypeCode.SByte:
result = ODataAtomConvert.ToString((SByte)value);
break;
case TypeCode.String:
result = (string)value;
break;
case TypeCode.Single:
result = ODataAtomConvert.ToString((Single)value);
break;
default:
byte[] bytes = value as byte[];
if (bytes != null)
{
result = ODataAtomConvert.ToString(bytes);
break;
}
if (value is DateTimeOffset)
{
result = ODataAtomConvert.ToString((DateTimeOffset)value);
break;
}
if (value is Guid)
{
result = ODataAtomConvert.ToString((Guid)value);
break;
}
if (value is TimeSpan)
{
// Edm.Time
result = ODataAtomConvert.ToString((TimeSpan)value);
break;
}
return false;
}
Debug.Assert(result != null, "result != null");
return true;
}
/// <summary>
/// Converts a string to a primitive value.
/// </summary>
/// <param name="text">The string text to convert.</param>
/// <param name="targetTypeReference">Type to convert the string to.</param>
/// <returns>The value converted to the target type.</returns>
/// <remarks>This method does not convert null value.</remarks>
internal static object ConvertStringToPrimitive(string text, IEdmPrimitiveTypeReference targetTypeReference)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(text != null, "text != null");
Debug.Assert(targetTypeReference != null, "targetTypeReference != null");
try
{
EdmPrimitiveTypeKind primitiveKind = targetTypeReference.PrimitiveKind();
switch (primitiveKind)
{
case EdmPrimitiveTypeKind.Binary:
return Convert.FromBase64String(text);
case EdmPrimitiveTypeKind.Boolean:
return ConvertXmlBooleanValue(text);
case EdmPrimitiveTypeKind.Byte:
return XmlConvert.ToByte(text);
case EdmPrimitiveTypeKind.DateTime:
return PlatformHelper.ConvertStringToDateTime(text);
case EdmPrimitiveTypeKind.DateTimeOffset:
return XmlConvert.ToDateTimeOffset(text);
case EdmPrimitiveTypeKind.Decimal:
return XmlConvert.ToDecimal(text);
case EdmPrimitiveTypeKind.Double:
return XmlConvert.ToDouble(text);
case EdmPrimitiveTypeKind.Guid:
return new Guid(text);
case EdmPrimitiveTypeKind.Int16:
return XmlConvert.ToInt16(text);
case EdmPrimitiveTypeKind.Int32:
return XmlConvert.ToInt32(text);
case EdmPrimitiveTypeKind.Int64:
return XmlConvert.ToInt64(text);
case EdmPrimitiveTypeKind.SByte:
return XmlConvert.ToSByte(text);
case EdmPrimitiveTypeKind.Single:
return XmlConvert.ToSingle(text);
case EdmPrimitiveTypeKind.String:
return text;
case EdmPrimitiveTypeKind.Time:
return XmlConvert.ToTimeSpan(text);
case EdmPrimitiveTypeKind.Stream:
case EdmPrimitiveTypeKind.None:
case EdmPrimitiveTypeKind.Geography:
case EdmPrimitiveTypeKind.GeographyCollection:
case EdmPrimitiveTypeKind.GeographyPoint:
case EdmPrimitiveTypeKind.GeographyLineString:
case EdmPrimitiveTypeKind.GeographyPolygon:
case EdmPrimitiveTypeKind.GeometryCollection:
case EdmPrimitiveTypeKind.GeographyMultiPolygon:
case EdmPrimitiveTypeKind.GeographyMultiLineString:
case EdmPrimitiveTypeKind.GeographyMultiPoint:
case EdmPrimitiveTypeKind.Geometry:
case EdmPrimitiveTypeKind.GeometryPoint:
case EdmPrimitiveTypeKind.GeometryLineString:
case EdmPrimitiveTypeKind.GeometryPolygon:
case EdmPrimitiveTypeKind.GeometryMultiPolygon:
case EdmPrimitiveTypeKind.GeometryMultiLineString:
case EdmPrimitiveTypeKind.GeometryMultiPoint:
default:
// Note that Astoria supports XElement and Binary as well, but they are serialized as string or byte[]
// and the metadata will actually talk about string and byte[] as well. Astoria will perform the conversion if necessary.
throw new ODataException(Strings.General_InternalError(InternalErrorCodes.AtomValueUtils_ConvertStringToPrimitive));
}
}
catch (Exception e)
{
if (!ExceptionUtils.IsCatchableExceptionType(e))
{
throw;
}
throw ReaderValidationUtils.GetPrimitiveTypeConversionException(targetTypeReference, e);
}
}
/// <summary>
/// Reimplementation of XmlConvert.ToBoolean that accepts 'True' and 'False' in addition
/// to 'true' and 'false'.
/// </summary>
/// <param name="text">The string value read from the Xml reader.</param>
/// <returns>The converted boolean value.</returns>
private static bool ConvertXmlBooleanValue(string text)
{
text = text.Trim(XmlWhitespaceChars);
switch (text)
{
case "true":
case "True":
case "1":
return true;
case "false":
case "False":
case "0":
return false;
default:
// We know that this will throw; call XmlConvert for the appropriate error message.
return XmlConvert.ToBoolean(text);
}
}
}
}
| |
// Copyright (c) Rotorz Limited. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root.
using Rotorz.Games.UnityEditorExtensions;
using Rotorz.Settings;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
namespace Rotorz.Tile.Editor
{
/// <summary>
/// Create tile system window.
/// </summary>
public sealed class CreateTileSystemWindow : RotorzWindow
{
#region Window Management
/// <summary>
/// Display create tile system window.
/// </summary>
/// <returns>
/// The window.
/// </returns>
public static CreateTileSystemWindow ShowWindow()
{
return GetUtilityWindow<CreateTileSystemWindow>();
}
#endregion
#region User Settings
private static void AutoInitializeUserSettings()
{
if (s_HasInitializedUserSettings == true) {
return;
}
var settings = AssetSettingManagement.GetGroup("CreateTileSystemWindow");
s_SelectedPresetGuid = settings.Fetch<string>("SelectedPresetGuid", "");
s_HasInitializedUserSettings = true;
}
private static bool s_HasInitializedUserSettings = false;
private static Setting<string> s_SelectedPresetGuid;
#endregion
private const float FIELD_LABEL_WIDTH = 140;
private TileSystemPreset selectedPreset;
private TileSystemPreset currentPreset;
private TileSystemPresetInspector currentPresetInspector;
private string newPresetName = "";
private Vector2 scrollPosition;
private bool hasFocusedName;
/// <summary>
/// Occurs when a tile system is created using this window.
/// </summary>
public event TileSystemDelegate TileSystemCreated;
/// <inheritdoc/>
protected override void DoEnable()
{
AutoInitializeUserSettings();
this.titleContent = new GUIContent(TileLang.ParticularText("Action", "Create Tile System"));
this.InitialSize = this.minSize = new Vector2(580, 375);
this.maxSize = new Vector2(580, Screen.currentResolution.height);
if (this.currentPreset == null) {
this.currentPreset = ScriptableObject.CreateInstance<TileSystemPreset>();
this.currentPreset.hideFlags = HideFlags.DontSave;
}
if (this.currentPresetInspector == null) {
this.currentPresetInspector = (TileSystemPresetInspector)UnityEditor.Editor.CreateEditor(this.currentPreset, typeof(TileSystemPresetInspector));
}
this.currentPresetInspector.DisableUndoOnSerializedObject = true;
// Restore previous preset selection?
this.SetSelectedPreset(s_SelectedPresetGuid);
}
/// <inheritdoc/>
protected override void DoDestroy()
{
if (this.currentPresetInspector != null) {
DestroyImmediate(this.currentPresetInspector);
this.currentPresetInspector = null;
}
}
/// <inheritdoc/>
protected override void DoGUI()
{
EditorGUIUtility.labelWidth = FIELD_LABEL_WIDTH;
EditorGUIUtility.wideMode = true;
this.VerifySelectedPresetValue();
if (ExtraEditorGUI.AcceptKeyboardReturn()) {
this.OnButton_Create();
return;
}
GUILayout.BeginHorizontal();
{
GUILayout.Space(5);
Rect presetsPosition = EditorGUILayout.BeginVertical(GUILayout.Width(150));
if (Event.current.type == EventType.Repaint) {
GUI.skin.box.Draw(new Rect(presetsPosition.x - 7, presetsPosition.y - 2, presetsPosition.width + 9, presetsPosition.height + 4), GUIContent.none, false, false, false, false);
}
this.OnGUI_Presets();
EditorGUILayout.EndVertical();
GUILayout.Space(4);
GUILayout.BeginVertical();
{
this.scrollPosition = EditorGUILayout.BeginScrollView(this.scrollPosition);
{
GUILayout.BeginHorizontal();
{
GUILayout.Space(5);
GUILayout.BeginVertical();
this.DrawCurrentPresetEditor();
GUILayout.EndVertical();
GUILayout.Space(5);
}
GUILayout.EndHorizontal();
}
EditorGUILayout.EndScrollView();
ExtraEditorGUI.SeparatorLight(marginTop: -1);
GUILayout.BeginHorizontal();
{
this.OnGUI_Buttons();
GUILayout.Space(3);
}
GUILayout.EndHorizontal();
GUILayout.Space(5);
}
GUILayout.EndVertical();
}
GUILayout.EndHorizontal();
if (!this.hasFocusedName) {
this.hasFocusedName = true;
this.currentPresetInspector.FocusNameField();
}
}
private void VerifySelectedPresetValue()
{
if (this.selectedPreset == null && !ReferenceEquals(this.selectedPreset, null)) {
this.selectedPreset = null;
s_SelectedPresetGuid.Value = "";
}
}
private void DrawCurrentPresetEditor()
{
GUILayout.Space(10);
this.currentPresetInspector.OnInspectorGUI();
GUILayout.Space(5);
}
/// <summary>
/// Set the currently selected preset.
/// </summary>
/// <param name="presetGuid">Name of preset.</param>
private void SetSelectedPreset(string presetGuid)
{
this.selectedPreset = null;
// Figure out a valid preset GUID.
if (presetGuid != "F:3D" && presetGuid != "F:2D") {
this.selectedPreset = TileSystemPresetUtility.LoadPresetFromGUID(presetGuid);
if (this.selectedPreset == null) {
presetGuid = TileSystemPresetUtility.DefaultPresetGUID;
}
}
// Persist current preset selection.
s_SelectedPresetGuid.Value = presetGuid;
// Preserve user input for tile system name!
string preserveSystemName = this.currentPreset.SystemName;
// Update the new tile system configuration from the selected preset.
switch (presetGuid) {
case "F:3D":
this.currentPreset.SetDefaults3D();
this.currentPreset.name = TileLang.ParticularText("Preset Name", "Default: 3D");
this.newPresetName = "";
break;
case "F:2D":
this.currentPreset.SetDefaults2D();
this.currentPreset.name = TileLang.ParticularText("Preset Name", "Default: 2D");
this.newPresetName = "";
break;
default:
EditorUtility.CopySerialized(this.selectedPreset, this.currentPreset);
this.newPresetName = this.currentPreset.name;
break;
}
// Remove input focus from any control but most specifically "Preset Name".
GUIUtility.keyboardControl = 0;
if (this.currentPresetInspector.HasModifiedTileSystemName) {
this.currentPreset.SystemName = preserveSystemName;
}
else {
this.AutoAddPostfixToName();
}
}
private void OnGUI_Presets()
{
GUILayout.Space(10);
EditorGUILayout.PrefixLabel(TileLang.ParticularText("Property", "Preset"));
EditorGUI.BeginChangeCheck();
using (var valueContent = ControlContent.Basic(this.currentPreset.name)) {
s_SelectedPresetGuid.Value = CustomPopupGUI.Popup(GUIContent.none, s_SelectedPresetGuid.Value, valueContent, this.PopulatePresetMenu);
}
if (EditorGUI.EndChangeCheck()) {
this.SetSelectedPreset(s_SelectedPresetGuid.Value);
}
EditorGUILayout.Space();
EditorGUILayout.PrefixLabel(TileLang.ParticularText("Property", "Preset Name"));
this.newPresetName = EditorGUILayout.TextField(this.newPresetName);
if (GUILayout.Button(TileLang.ParticularText("Action", "Save Preset"))) {
this.OnButton_SavePreset();
GUIUtility.ExitGUI();
}
// Do not allow deletion of factory default preset.
EditorGUI.BeginDisabledGroup(this.selectedPreset == null);
if (GUILayout.Button(TileLang.ParticularText("Action", "Delete Preset"))) {
this.OnButton_DeletePreset();
GUIUtility.ExitGUI();
}
EditorGUI.EndDisabledGroup();
GUILayout.FlexibleSpace();
ControlContent.TrailingTipsVisible = GUILayout.Toggle(ControlContent.TrailingTipsVisible, TileLang.ParticularText("Action", "Show Tips"));
GUILayout.Space(10);
}
private void PopulatePresetMenu(ICustomPopupContext<string> context)
{
var popup = context.Popup;
popup.AddOption(TileLang.ParticularText("Preset Name", "Default: 3D"), context, "F:3D");
popup.AddOption(TileLang.ParticularText("Preset Name", "Default: 2D"), context, "F:2D");
var presets = TileSystemPresetUtility.GetPresets();
if (presets.Length == 0) {
return;
}
popup.AddSeparator();
var presetGroups = presets
.OrderBy(preset => preset.name)
.GroupBy(preset => TileSystemPresetUtility.IsUserPreset(preset))
.ToArray();
for (int i = 0; i < presetGroups.Length; ++i) {
if (i != 0) {
popup.AddSeparator();
}
foreach (var preset in presetGroups[i]) {
popup.AddOption(preset.name, context, TileSystemPresetUtility.GetPresetGUID(preset));
}
}
}
private void OnGUI_Buttons()
{
if (GUILayout.Button(TileLang.ParticularText("Action", "Reset"), ExtraEditorStyles.Instance.BigButton)) {
this.OnButton_Reset();
GUIUtility.ExitGUI();
}
GUILayout.FlexibleSpace();
if (GUILayout.Button(TileLang.ParticularText("Action", "Create"), ExtraEditorStyles.Instance.BigButtonPadded)) {
this.OnButton_Create();
GUIUtility.ExitGUI();
}
GUILayout.Space(3);
if (GUILayout.Button(TileLang.ParticularText("Action", "Cancel"), ExtraEditorStyles.Instance.BigButtonPadded)) {
this.Close();
GUIUtility.ExitGUI();
}
}
private void OnButton_SavePreset()
{
// Remove focus from input control.
GUIUtility.keyboardControl = 0;
this.newPresetName = this.newPresetName.Trim();
// Name must be specified for preset!
if (string.IsNullOrEmpty(this.newPresetName)) {
EditorUtility.DisplayDialog(
TileLang.ParticularText("Error", "One or more inputs were invalid"),
TileLang.ParticularText("Error", "Name was not specified"),
TileLang.ParticularText("Action", "Close")
);
}
else if (!TileSystemPresetUtility.IsValidPresetName(this.newPresetName)) {
EditorUtility.DisplayDialog(
TileLang.ParticularText("Error", "Invalid name for the asset"),
TileLang.ParticularText("Error", "Can only use alphanumeric characters (A-Z a-z 0-9), hyphens (-), underscores (_) and spaces.\n\nName must begin with an alphanumeric character."),
TileLang.ParticularText("Action", "Close")
);
}
else {
if (this.selectedPreset != null && this.newPresetName == this.selectedPreset.name) {
TileSystemPresetUtility.OverwritePreset(this.currentPreset, this.selectedPreset);
}
else {
var newPreset = TileSystemPresetUtility.CreatePreset(this.currentPreset, this.newPresetName);
this.SetSelectedPreset(AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(newPreset)));
}
}
}
private void OnButton_DeletePreset()
{
if (this.selectedPreset == null) {
EditorUtility.DisplayDialog(
TileLang.Text("Error"),
TileLang.ParticularText("Error", "Cannot delete a default preset."),
TileLang.ParticularText("Action", "Close")
);
}
else if (EditorUtility.DisplayDialog(
TileLang.ParticularText("Action", "Delete Preset"),
string.Format(
/* 0: name of the preset */
TileLang.ParticularText("Error", "Do you want to delete the preset '{0}'?"),
this.currentPreset.name
),
TileLang.ParticularText("Action", "Yes"),
TileLang.ParticularText("Action", "No")
)) {
// Remove the selected preset asset.
TileSystemPresetUtility.DeletePreset(this.selectedPreset);
// Select the default preset.
this.SetSelectedPreset("");
}
}
private void OnButton_Reset()
{
this.SetSelectedPreset(s_SelectedPresetGuid.Value);
this.AutoAddPostfixToName();
}
private void OnButton_Create()
{
this.currentPreset.SystemName = this.currentPreset.SystemName.Trim();
// Validate inputs first.
if (string.IsNullOrEmpty(this.currentPreset.SystemName)) {
EditorUtility.DisplayDialog(
TileLang.ParticularText("Error", "Name was not specified"),
TileLang.Text("Please specify name for tile system."),
TileLang.ParticularText("Action", "Close")
);
GUIUtility.ExitGUI();
}
// Do not allow user to create useless system.
if (this.currentPreset.Rows < 1 || this.currentPreset.Columns < 1) {
EditorUtility.DisplayDialog(
TileLang.Text("Error"),
TileLang.Text("A tile system must contain at least 1 cell."),
TileLang.ParticularText("Action", "Close")
);
GUIUtility.ExitGUI();
return;
}
// Create tile system using preset and select it ready for immediate usage.
var tileSystemGO = TileSystemPresetUtility.CreateTileSystemFromPreset(this.currentPreset);
Selection.activeObject = tileSystemGO;
// Register undo event.
Undo.IncrementCurrentGroup();
Undo.RegisterCreatedObjectUndo(tileSystemGO, TileLang.ParticularText("Action", "Create Tile System"));
if (this.TileSystemCreated != null) {
this.TileSystemCreated(tileSystemGO.GetComponent<TileSystem>());
}
this.Close();
}
private void AutoAddPostfixToName()
{
var tileSystems = ToolUtility.GetAllTileSystemsInScene();
string baseName = Regex.Replace(this.currentPreset.SystemName, "#\\d+$", "");
string nextName = baseName;
int increment = 1;
while (true) {
next:
foreach (var tileSystem in tileSystems)
if (tileSystem.name == nextName) {
nextName = string.Format("{0} #{1}", baseName, ++increment);
goto next;
}
break;
}
this.currentPreset.SystemName = nextName;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// ElementAtQueryOperator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
namespace System.Linq.Parallel
{
/// <summary>
/// ElementAt just retrieves an element at a specific index. There is some cross-partition
/// coordination to force partitions to stop looking once a partition has found the
/// sought-after element.
/// </summary>
/// <typeparam name="TSource"></typeparam>
internal sealed class ElementAtQueryOperator<TSource> : UnaryQueryOperator<TSource, TSource>
{
private readonly int _index; // The index that we're looking for.
private readonly bool _prematureMerge = false; // Whether to prematurely merge the input of this operator.
private readonly bool _limitsParallelism = false; // Whether this operator limits parallelism
//---------------------------------------------------------------------------------------
// Constructs a new instance of the contains search operator.
//
// Arguments:
// child - the child tree to enumerate.
// index - index we are searching for.
//
internal ElementAtQueryOperator(IEnumerable<TSource> child, int index)
: base(child)
{
Debug.Assert(child != null, "child data source cannot be null");
Debug.Assert(index >= 0, "index can't be less than 0");
_index = index;
OrdinalIndexState childIndexState = Child.OrdinalIndexState;
if (ExchangeUtilities.IsWorseThan(childIndexState, OrdinalIndexState.Correct))
{
_prematureMerge = true;
_limitsParallelism = childIndexState != OrdinalIndexState.Shuffled;
}
}
//---------------------------------------------------------------------------------------
// Just opens the current operator, including opening the child and wrapping it with
// partitions as needed.
//
internal override QueryResults<TSource> Open(
QuerySettings settings, bool preferStriping)
{
// We just open the child operator.
QueryResults<TSource> childQueryResults = Child.Open(settings, false);
return new UnaryQueryOperatorResults(childQueryResults, this, settings, preferStriping);
}
internal override void WrapPartitionedStream<TKey>(
PartitionedStream<TSource, TKey> inputStream, IPartitionedStreamRecipient<TSource> recipient, bool preferStriping, QuerySettings settings)
{
// If the child OOP index is not correct, reindex.
int partitionCount = inputStream.PartitionCount;
PartitionedStream<TSource, int> intKeyStream;
if (_prematureMerge)
{
intKeyStream = ExecuteAndCollectResults(inputStream, partitionCount, Child.OutputOrdered, preferStriping, settings).GetPartitionedStream();
Debug.Assert(intKeyStream.OrdinalIndexState == OrdinalIndexState.Indexible);
}
else
{
intKeyStream = (PartitionedStream<TSource, int>)(object)inputStream;
}
// Create a shared cancelation variable and then return a possibly wrapped new enumerator.
Shared<bool> resultFoundFlag = new Shared<bool>(false);
PartitionedStream<TSource, int> outputStream = new PartitionedStream<TSource, int>(
partitionCount, Util.GetDefaultComparer<int>(), OrdinalIndexState.Correct);
for (int i = 0; i < partitionCount; i++)
{
outputStream[i] = new ElementAtQueryOperatorEnumerator(intKeyStream[i], _index, resultFoundFlag, settings.CancellationState.MergedCancellationToken);
}
recipient.Receive(outputStream);
}
//---------------------------------------------------------------------------------------
// Returns an enumerable that represents the query executing sequentially.
//
internal override IEnumerable<TSource> AsSequentialQuery(CancellationToken token)
{
Debug.Fail("This method should never be called as fallback to sequential is handled in Aggregate().");
throw new NotSupportedException();
}
//---------------------------------------------------------------------------------------
// Whether this operator performs a premature merge that would not be performed in
// a similar sequential operation (i.e., in LINQ to Objects).
//
internal override bool LimitsParallelism
{
get { return _limitsParallelism; }
}
/// <summary>
/// Executes the query, either sequentially or in parallel, depending on the query execution mode and
/// whether a premature merge was inserted by this ElementAt operator.
/// </summary>
/// <param name="result">result</param>
/// <param name="withDefaultValue">withDefaultValue</param>
/// <returns>whether an element with this index exists</returns>
internal bool Aggregate(out TSource result, bool withDefaultValue)
{
// If we were to insert a premature merge before this ElementAt, and we are executing in conservative mode, run the whole query
// sequentially.
if (LimitsParallelism && SpecifiedQuerySettings.WithDefaults().ExecutionMode.Value != ParallelExecutionMode.ForceParallelism)
{
CancellationState cancelState = SpecifiedQuerySettings.CancellationState;
if (withDefaultValue)
{
IEnumerable<TSource> childAsSequential = Child.AsSequentialQuery(cancelState.ExternalCancellationToken);
IEnumerable<TSource> childWithCancelChecks = CancellableEnumerable.Wrap(childAsSequential, cancelState.ExternalCancellationToken);
result = ExceptionAggregator.WrapEnumerable(childWithCancelChecks, cancelState).ElementAtOrDefault(_index);
}
else
{
IEnumerable<TSource> childAsSequential = Child.AsSequentialQuery(cancelState.ExternalCancellationToken);
IEnumerable<TSource> childWithCancelChecks = CancellableEnumerable.Wrap(childAsSequential, cancelState.ExternalCancellationToken);
result = ExceptionAggregator.WrapEnumerable(childWithCancelChecks, cancelState).ElementAt(_index);
}
return true;
}
using (IEnumerator<TSource> e = GetEnumerator(ParallelMergeOptions.FullyBuffered))
{
if (e.MoveNext())
{
TSource current = e.Current;
Debug.Assert(!e.MoveNext(), "expected enumerator to be empty");
result = current;
return true;
}
}
result = default(TSource);
return false;
}
//---------------------------------------------------------------------------------------
// This enumerator performs the search for the element at the specified index.
//
class ElementAtQueryOperatorEnumerator : QueryOperatorEnumerator<TSource, int>
{
private QueryOperatorEnumerator<TSource, int> _source; // The source data.
private int _index; // The index of the element to seek.
private Shared<bool> _resultFoundFlag; // Whether to cancel the operation.
private CancellationToken _cancellationToken;
//---------------------------------------------------------------------------------------
// Instantiates a new any/all search operator.
//
internal ElementAtQueryOperatorEnumerator(QueryOperatorEnumerator<TSource, int> source,
int index, Shared<bool> resultFoundFlag,
CancellationToken cancellationToken)
{
Debug.Assert(source != null);
Debug.Assert(index >= 0);
Debug.Assert(resultFoundFlag != null);
_source = source;
_index = index;
_resultFoundFlag = resultFoundFlag;
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// Enumerates the entire input until the element with the specified is found or another
// partition has signaled that it found the element.
//
internal override bool MoveNext(ref TSource currentElement, ref int currentKey)
{
// Just walk the enumerator until we've found the element.
int i = 0;
while (_source.MoveNext(ref currentElement, ref currentKey))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
if (_resultFoundFlag.Value)
{
// Another partition found the element.
break;
}
if (currentKey == _index)
{
// We have found the element. Cancel other searches and return true.
_resultFoundFlag.Value = true;
return true;
}
}
return false;
}
protected override void Dispose(bool disposing)
{
Debug.Assert(_source != null);
_source.Dispose();
}
}
}
}
| |
// Copyright 2017 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.
using Android.App;
using Android.OS;
using Android.Widget;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.Tasks.NetworkAnalysis;
using Esri.ArcGISRuntime.UI;
using Esri.ArcGISRuntime.UI.Controls;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
namespace ArcGISRuntime.Samples.FindRoute
{
[Activity (ConfigurationChanges=Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)]
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Find route",
category: "Network analysis",
description: "Display directions for a route between two points.",
instructions: "For simplicity, the sample comes loaded with a start and end stop. You can tap on the Find Route button to display a route between these stops. Once the route is generated, turn-by-turn directions are shown in a list.",
tags: new[] { "directions", "driving", "navigation", "network", "network analysis", "route", "routing", "shortest path", "turn-by-turn" })]
public class FindRoute : Activity
{
// Hold a reference to the map view.
private MapView _myMapView;
// List of stops on the route ('from' and 'to')
private List<Stop> _routeStops;
// Graphics overlay to display stops and the route result
private GraphicsOverlay _routeGraphicsOverlay;
// URI for the San Diego route service
private Uri _sanDiegoRouteServiceUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/Route");
// URIs for picture marker images
private Uri _checkedFlagIconUri = new Uri("https://static.arcgis.com/images/Symbols/Transportation/CheckeredFlag.png");
private Uri _carIconUri = new Uri("https://static.arcgis.com/images/Symbols/Transportation/CarRedFront.png");
// UI control to show/hide directions dialog (private scope so it can be enabled/disabled as needed)
private Button _showHideDirectionsButton;
// Dialog for showing driving directions
private AlertDialog _directionsDialog;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
Title = "Find a route";
// Create the UI
CreateLayout();
// Initialize the app
Initialize();
}
private void CreateLayout()
{
// Create a new layout for the entire page
LinearLayout layout = new LinearLayout(this) { Orientation = Orientation.Vertical };
// Create a new layout for the toolbar (buttons)
LinearLayout toolbar = new LinearLayout(this) { Orientation = Orientation.Horizontal };
// Create a button to solve the route and add it to the toolbar
Button solveRouteButton = new Button(this) { Text = "Solve Route" };
solveRouteButton.Click += SolveRouteClick;
toolbar.AddView(solveRouteButton);
// Create a button to reset the route display, add it to the toolbar
Button resetButton = new Button(this) { Text = "Reset" };
resetButton.Click += ResetClick;
toolbar.AddView(resetButton);
// Create a button to show or hide the route directions, add it to the toolbar
_showHideDirectionsButton = new Button(this) { Text = "Directions" };
_showHideDirectionsButton.Click += ShowDirectionsClick;
_showHideDirectionsButton.Enabled = false;
toolbar.AddView(_showHideDirectionsButton);
// Add the toolbar to the layout
layout.AddView(toolbar);
// Add the map view to the layout
_myMapView = new MapView(this);
layout.AddView(_myMapView);
// Show the layout in the app
SetContentView(layout);
}
private void Initialize()
{
// Define the route stop locations (points)
MapPoint fromPoint = new MapPoint(-117.15494348793044, 32.706506537686927, SpatialReferences.Wgs84);
MapPoint toPoint = new MapPoint(-117.14905088669816, 32.735308180609138, SpatialReferences.Wgs84);
// Create Stop objects with the points and add them to a list of stops
Stop stop1 = new Stop(fromPoint);
Stop stop2 = new Stop(toPoint);
_routeStops = new List<Stop> { stop1, stop2 };
// Picture marker symbols: from = car, to = checkered flag
PictureMarkerSymbol carSymbol = new PictureMarkerSymbol(_carIconUri)
{
Height = 40,
Width = 40
};
PictureMarkerSymbol flagSymbol = new PictureMarkerSymbol(_checkedFlagIconUri)
{
Height = 40,
Width = 40,
// Offset the icon so that it is anchored at the bottom of the flagpole
OffsetX = 20,
OffsetY = 20
};
// Create graphics for the stops
Graphic fromGraphic = new Graphic(fromPoint, carSymbol)
{
// Make sure the icons are shown over the route line
ZIndex = 1
};
Graphic toGraphic = new Graphic(toPoint, flagSymbol)
{
ZIndex = 1
};
// Create the graphics overlay and add the stop graphics
_routeGraphicsOverlay = new GraphicsOverlay();
_routeGraphicsOverlay.Graphics.Add(fromGraphic);
_routeGraphicsOverlay.Graphics.Add(toGraphic);
// Get an Envelope that covers the area of the stops (and a little more)
Envelope routeStopsExtent = new Envelope(fromPoint, toPoint);
EnvelopeBuilder envBuilder = new EnvelopeBuilder(routeStopsExtent);
envBuilder.Expand(1.5);
// Create a new viewpoint apply it to the map view when the spatial reference changes
Viewpoint sanDiegoViewpoint = new Viewpoint(envBuilder.ToGeometry());
_myMapView.SpatialReferenceChanged += (s, e) => _myMapView.SetViewpoint(sanDiegoViewpoint);
// Add a new Map and the graphics overlay to the map view
_myMapView.Map = new Map(BasemapStyle.ArcGISStreets);
_myMapView.GraphicsOverlays.Add(_routeGraphicsOverlay);
}
private async void SolveRouteClick(object sender, EventArgs e)
{
try
{
// Create a new route task using the San Diego route service URI
RouteTask solveRouteTask = await RouteTask.CreateAsync(_sanDiegoRouteServiceUri);
// Get the default parameters from the route task (defined with the service)
RouteParameters routeParams = await solveRouteTask.CreateDefaultParametersAsync();
// Make some changes to the default parameters
routeParams.ReturnStops = true;
routeParams.ReturnDirections = true;
// Set the list of route stops that were defined at startup
routeParams.SetStops(_routeStops);
// Solve for the best route between the stops and store the result
RouteResult solveRouteResult = await solveRouteTask.SolveRouteAsync(routeParams);
// Get the first (should be only) route from the result
Route firstRoute = solveRouteResult.Routes.First();
// Get the route geometry (polyline)
Polyline routePolyline = firstRoute.RouteGeometry;
// Create a thick purple line symbol for the route
SimpleLineSymbol routeSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Purple, 8.0);
// Create a new graphic for the route geometry and add it to the graphics overlay
Graphic routeGraphic = new Graphic(routePolyline, routeSymbol)
{
ZIndex = 0
};
_routeGraphicsOverlay.Graphics.Add(routeGraphic);
// Get a list of directions for the route and display it in the list box
CreateDirectionsDialog(firstRoute.DirectionManeuvers.Select(d => d.DirectionText));
_showHideDirectionsButton.Enabled = true;
}
catch (Exception ex)
{
new AlertDialog.Builder(this).SetMessage(ex.ToString()).SetTitle("Error").Show();
}
}
private void ResetClick(object sender, EventArgs e)
{
// Remove the route graphic from the graphics overlay (only line graphic in the collection)
int graphicsCount = _routeGraphicsOverlay.Graphics.Count;
for (int i = graphicsCount; i > 0; i--)
{
// Get this graphic and see if it has line geometry
Graphic g = _routeGraphicsOverlay.Graphics[i - 1];
if (g.Geometry.GeometryType == GeometryType.Polyline)
{
// Remove the graphic from the overlay
_routeGraphicsOverlay.Graphics.Remove(g);
}
}
// Disable the button to show the directions dialog
_showHideDirectionsButton.Enabled = false;
}
private void ShowDirectionsClick(object sender, EventArgs e)
{
// Show the directions dialog
if (_directionsDialog != null)
{
_directionsDialog.Show();
}
}
private void CreateDirectionsDialog(IEnumerable<string> directions)
{
// Create a dialog to show route directions
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// Create the layout
LinearLayout dialogLayout = new LinearLayout(this)
{
Orientation = Orientation.Vertical
};
// Create a list box for showing the route directions
ListView directionsList = new ListView(this);
ArrayAdapter<string> directionsAdapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, directions.ToArray());
directionsList.Adapter = directionsAdapter;
dialogLayout.AddView(directionsList);
// Add the controls to the dialog
dialogBuilder.SetView(dialogLayout);
dialogBuilder.SetTitle("Route Directions");
// Create the dialog (don't show it)
_directionsDialog = dialogBuilder.Create();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using UnityEngine;
namespace InControl
{
public class UnityInputDeviceManager : InputDeviceManager
{
const float deviceRefreshInterval = 1.0f;
float deviceRefreshTimer = 0.0f;
List<InputDeviceProfile> systemDeviceProfiles = new List<InputDeviceProfile>();
List<InputDeviceProfile> customDeviceProfiles = new List<InputDeviceProfile>();
string[] joystickNames;
int lastJoystickCount;
int lastJoystickHash;
int joystickCount;
int joystickHash;
public UnityInputDeviceManager()
{
AddSystemDeviceProfiles();
// LoadDeviceProfiles();
QueryJoystickInfo();
AttachDevices();
}
public override void Update( ulong updateTick, float deltaTime )
{
deviceRefreshTimer += deltaTime;
if (deviceRefreshTimer >= deviceRefreshInterval)
{
deviceRefreshTimer = 0.0f;
QueryJoystickInfo();
if (JoystickInfoHasChanged)
{
Logger.LogInfo( "Change in attached Unity joysticks detected; refreshing device list." );
// #if UNITY_XBOXONE
// if (joystickCount < lastJoystickCount)
// {
// DetachDevices();
// }
// #else
DetachDevices();
// #endif
AttachDevices();
}
}
}
void QueryJoystickInfo()
{
joystickNames = Input.GetJoystickNames();
joystickCount = joystickNames.Length;
joystickHash = 17 * 31 + joystickCount;
for (int i = 0; i < joystickCount; i++)
{
joystickHash = joystickHash * 31 + joystickNames[i].GetHashCode();
}
}
bool JoystickInfoHasChanged
{
get
{
return joystickHash != lastJoystickHash || joystickCount != lastJoystickCount;
}
}
void AttachDevices()
{
AttachKeyboardDevices();
AttachJoystickDevices();
lastJoystickCount = joystickCount;
lastJoystickHash = joystickHash;
}
void DetachDevices()
{
var deviceCount = devices.Count;
for (int i = 0; i < deviceCount; i++)
{
InputManager.DetachDevice( devices[i] );
}
devices.Clear();
}
public void ReloadDevices()
{
QueryJoystickInfo();
DetachDevices();
AttachDevices();
}
void AttachDevice( UnityInputDevice device )
{
devices.Add( device );
InputManager.AttachDevice( device );
}
void AttachKeyboardDevices()
{
int deviceProfileCount = systemDeviceProfiles.Count;
for (int i = 0; i < deviceProfileCount; i++)
{
var deviceProfile = systemDeviceProfiles[i];
if (deviceProfile.IsNotJoystick && deviceProfile.IsSupportedOnThisPlatform)
{
AttachDevice( new UnityInputDevice( deviceProfile ) );
}
}
}
void AttachJoystickDevices()
{
try
{
for (int i = 0; i < joystickCount; i++)
{
DetectJoystickDevice( i + 1, joystickNames[i] );
}
}
catch (Exception e)
{
Logger.LogError( e.Message );
Logger.LogError( e.StackTrace );
}
}
bool HasAttachedDeviceWithJoystickId( int unityJoystickId )
{
var deviceCount = devices.Count;
for (int i = 0; i < deviceCount; i++)
{
var device = devices[i] as UnityInputDevice;
if (device != null)
{
if (device.JoystickId == unityJoystickId)
{
return true;
}
}
}
return false;
}
void DetectJoystickDevice( int unityJoystickId, string unityJoystickName )
{
if (HasAttachedDeviceWithJoystickId( unityJoystickId ))
{
return;
}
#if UNITY_PS4
if (unityJoystickName == "Empty")
{
// On PS4 console, disconnected controllers may have this name.
return;
}
#endif
if (unityJoystickName.IndexOf( "webcam", StringComparison.OrdinalIgnoreCase ) != -1)
{
// Unity thinks some webcams are joysticks. >_<
return;
}
// PS4 controller only works properly as of Unity 4.5
if (InputManager.UnityVersion < new VersionInfo( 4, 5, 0, 0 ))
{
if (Application.platform == RuntimePlatform.OSXEditor ||
Application.platform == RuntimePlatform.OSXPlayer ||
Application.platform == RuntimePlatform.OSXWebPlayer)
{
if (unityJoystickName == "Unknown Wireless Controller")
{
// Ignore PS4 controller in Bluetooth mode on Mac since it connects but does nothing.
return;
}
}
}
// As of Unity 4.6.3p1, empty strings on windows represent disconnected devices.
if (InputManager.UnityVersion >= new VersionInfo( 4, 6, 3, 0 ))
{
if (Application.platform == RuntimePlatform.WindowsEditor ||
Application.platform == RuntimePlatform.WindowsPlayer ||
Application.platform == RuntimePlatform.WindowsWebPlayer)
{
if (String.IsNullOrEmpty( unityJoystickName ))
{
return;
}
}
}
InputDeviceProfile deviceProfile = null;
if (deviceProfile == null)
{
deviceProfile = customDeviceProfiles.Find( config => config.HasJoystickName( unityJoystickName ) );
}
if (deviceProfile == null)
{
deviceProfile = systemDeviceProfiles.Find( config => config.HasJoystickName( unityJoystickName ) );
}
if (deviceProfile == null)
{
deviceProfile = customDeviceProfiles.Find( config => config.HasLastResortRegex( unityJoystickName ) );
}
if (deviceProfile == null)
{
deviceProfile = systemDeviceProfiles.Find( config => config.HasLastResortRegex( unityJoystickName ) );
}
if (deviceProfile == null)
{
// Debug.Log( "[InControl] Joystick " + unityJoystickId + ": \"" + unityJoystickName + "\"" );
Logger.LogWarning( "Device " + unityJoystickId + " with name \"" + unityJoystickName + "\" does not match any supported profiles and will be considered an unknown controller." );
var unknownDeviceProfile = new UnknownUnityDeviceProfile( unityJoystickName );
var joystickDevice = new UnknownUnityInputDevice( unknownDeviceProfile, unityJoystickId );
AttachDevice( joystickDevice );
return;
}
if (!deviceProfile.IsHidden)
{
var joystickDevice = new UnityInputDevice( deviceProfile, unityJoystickId );
AttachDevice( joystickDevice );
// Debug.Log( "[InControl] Joystick " + unityJoystickId + ": \"" + unityJoystickName + "\"" );
Logger.LogInfo( "Device " + unityJoystickId + " matched profile " + deviceProfile.GetType().Name + " (" + deviceProfile.Name + ")" );
}
else
{
Logger.LogInfo( "Device " + unityJoystickId + " matching profile " + deviceProfile.GetType().Name + " (" + deviceProfile.Name + ")" + " is hidden and will not be attached." );
}
}
void AddSystemDeviceProfile( UnityInputDeviceProfile deviceProfile )
{
if (deviceProfile.IsSupportedOnThisPlatform)
{
systemDeviceProfiles.Add( deviceProfile );
}
}
void AddSystemDeviceProfiles()
{
foreach (var typeName in UnityInputDeviceProfileList.Profiles)
{
var deviceProfile = (UnityInputDeviceProfile) Activator.CreateInstance( Type.GetType( typeName ) );
AddSystemDeviceProfile( deviceProfile );
}
}
/*
public void AddDeviceProfile( UnityInputDeviceProfile deviceProfile )
{
if (deviceProfile.IsSupportedOnThisPlatform)
{
customDeviceProfiles.Add( deviceProfile );
}
}
public void LoadDeviceProfiles()
{
LoadDeviceProfilesFromPath( CustomProfileFolder );
}
public void LoadDeviceProfile( string data )
{
var deviceProfile = UnityInputDeviceProfile.Load( data );
AddDeviceProfile( deviceProfile );
}
public void LoadDeviceProfileFromFile( string filePath )
{
var deviceProfile = UnityInputDeviceProfile.LoadFromFile( filePath );
AddDeviceProfile( deviceProfile );
}
public void LoadDeviceProfilesFromPath( string rootPath )
{
if (Directory.Exists( rootPath ))
{
var filePaths = Directory.GetFiles( rootPath, "*.json", SearchOption.AllDirectories );
foreach (var filePath in filePaths)
{
LoadDeviceProfileFromFile( filePath );
}
}
}
internal static void DumpSystemDeviceProfiles()
{
var filePath = CustomProfileFolder;
Directory.CreateDirectory( filePath );
foreach (var typeName in UnityInputDeviceProfileList.Profiles)
{
var deviceProfile = (UnityInputDeviceProfile) Activator.CreateInstance( Type.GetType( typeName ) );
var fileName = deviceProfile.GetType().Name + ".json";
deviceProfile.SaveToFile( filePath + "/" + fileName );
}
}
static string CustomProfileFolder
{
get
{
return Environment.GetFolderPath( Environment.SpecialFolder.ApplicationData ) + "/InControl/Profiles";
}
}
/**/
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Interfaces;
namespace QuantConnect.Securities
{
/// <summary>
/// Enumerable security management class for grouping security objects into an array and providing any common properties.
/// </summary>
/// <remarks>Implements IDictionary for the index searching of securities by symbol</remarks>
public class SecurityManager : ExtendedDictionary<Security>, IDictionary<Symbol, Security>, INotifyCollectionChanged
{
/// <summary>
/// Event fired when a security is added or removed from this collection
/// </summary>
public event NotifyCollectionChangedEventHandler CollectionChanged;
private readonly ITimeKeeper _timeKeeper;
//Internal dictionary implementation:
private readonly ConcurrentDictionary<Symbol, Security> _securityManager;
private SecurityService _securityService;
/// <summary>
/// Gets the most recent time this manager was updated
/// </summary>
public DateTime UtcTime
{
get { return _timeKeeper.UtcTime; }
}
/// <summary>
/// Initialise the algorithm security manager with two empty dictionaries
/// </summary>
/// <param name="timeKeeper"></param>
public SecurityManager(ITimeKeeper timeKeeper)
{
_timeKeeper = timeKeeper;
_securityManager = new ConcurrentDictionary<Symbol, Security>();
}
/// <summary>
/// Add a new security with this symbol to the collection.
/// </summary>
/// <remarks>IDictionary implementation</remarks>
/// <param name="symbol">symbol for security we're trading</param>
/// <param name="security">security object</param>
/// <seealso cref="Add(Security)"/>
public void Add(Symbol symbol, Security security)
{
if (_securityManager.TryAdd(symbol, security))
{
security.SetLocalTimeKeeper(_timeKeeper.GetLocalTimeKeeper(security.Exchange.TimeZone));
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, security));
}
}
/// <summary>
/// Add a new security with this symbol to the collection.
/// </summary>
/// <param name="security">security object</param>
public void Add(Security security)
{
Add(security.Symbol, security);
}
/// <summary>
/// Add a symbol-security by its key value pair.
/// </summary>
/// <remarks>IDictionary implementation</remarks>
/// <param name="pair"></param>
public void Add(KeyValuePair<Symbol, Security> pair)
{
Add(pair.Key, pair.Value);
}
/// <summary>
/// Clear the securities array to delete all the portfolio and asset information.
/// </summary>
/// <remarks>IDictionary implementation</remarks>
public override void Clear()
{
_securityManager.Clear();
}
/// <summary>
/// Check if this collection contains this key value pair.
/// </summary>
/// <param name="pair">Search key-value pair</param>
/// <remarks>IDictionary implementation</remarks>
/// <returns>Bool true if contains this key-value pair</returns>
public bool Contains(KeyValuePair<Symbol, Security> pair)
{
return _securityManager.Contains(pair);
}
/// <summary>
/// Check if this collection contains this symbol.
/// </summary>
/// <param name="symbol">Symbol we're checking for.</param>
/// <remarks>IDictionary implementation</remarks>
/// <returns>Bool true if contains this symbol pair</returns>
public bool ContainsKey(Symbol symbol)
{
return _securityManager.ContainsKey(symbol);
}
/// <summary>
/// Copy from the internal array to an external array.
/// </summary>
/// <param name="array">Array we're outputting to</param>
/// <param name="number">Starting index of array</param>
/// <remarks>IDictionary implementation</remarks>
public void CopyTo(KeyValuePair<Symbol, Security>[] array, int number)
{
((IDictionary<Symbol, Security>)_securityManager).CopyTo(array, number);
}
/// <summary>
/// Count of the number of securities in the collection.
/// </summary>
/// <remarks>IDictionary implementation</remarks>
public int Count => _securityManager.Skip(0).Count();
/// <summary>
/// Flag indicating if the internal array is read only.
/// </summary>
/// <remarks>IDictionary implementation</remarks>
public override bool IsReadOnly
{
get { return false; }
}
/// <summary>
/// Remove a key value of of symbol-securities from the collections.
/// </summary>
/// <remarks>IDictionary implementation</remarks>
/// <param name="pair">Key Value pair of symbol-security to remove</param>
/// <returns>Boolean true on success</returns>
public bool Remove(KeyValuePair<Symbol, Security> pair)
{
return Remove(pair.Key);
}
/// <summary>
/// Remove this symbol security: Dictionary interface implementation.
/// </summary>
/// <param name="symbol">Symbol we're searching for</param>
/// <returns>true success</returns>
public override bool Remove(Symbol symbol)
{
Security security;
if (_securityManager.TryRemove(symbol, out security))
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, security));
return true;
}
return false;
}
/// <summary>
/// List of the symbol-keys in the collection of securities.
/// </summary>
/// <remarks>IDictionary implementation</remarks>
public ICollection<Symbol> Keys => _securityManager.Select(x => x.Key).ToList();
/// <summary>
/// Try and get this security object with matching symbol and return true on success.
/// </summary>
/// <param name="symbol">String search symbol</param>
/// <param name="security">Output Security object</param>
/// <remarks>IDictionary implementation</remarks>
/// <returns>True on successfully locating the security object</returns>
public override bool TryGetValue(Symbol symbol, out Security security)
{
return _securityManager.TryGetValue(symbol, out security);
}
/// <summary>
/// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the Symbol objects of the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the Symbol objects of the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </returns>
protected override IEnumerable<Symbol> GetKeys => _securityManager.Select(pair => pair.Key);
/// <summary>
/// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </returns>
protected override IEnumerable<Security> GetValues => _securityManager.Select(pair => pair.Value);
/// <summary>
/// Get a list of the security objects for this collection.
/// </summary>
/// <remarks>IDictionary implementation</remarks>
public ICollection<Security> Values => _securityManager.Select(x => x.Value).ToList();
/// <summary>
/// Get the enumerator for this security collection.
/// </summary>
/// <remarks>IDictionary implementation</remarks>
/// <returns>Enumerable key value pair</returns>
IEnumerator<KeyValuePair<Symbol, Security>> IEnumerable<KeyValuePair<Symbol, Security>>.GetEnumerator()
{
return _securityManager.GetEnumerator();
}
/// <summary>
/// Get the enumerator for this securities collection.
/// </summary>
/// <remarks>IDictionary implementation</remarks>
/// <returns>Enumerator.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return _securityManager.GetEnumerator();
}
/// <summary>
/// Indexer method for the security manager to access the securities objects by their symbol.
/// </summary>
/// <remarks>IDictionary implementation</remarks>
/// <param name="symbol">Symbol object indexer</param>
/// <returns>Security</returns>
public override Security this[Symbol symbol]
{
get
{
Security security;
if (!_securityManager.TryGetValue(symbol, out security))
{
throw new KeyNotFoundException($"This asset symbol ({symbol}) was not found in your security list. Please add this security or check it exists before using it with 'Securities.ContainsKey(\"{SymbolCache.GetTicker(symbol)}\")'");
}
return security;
}
set
{
Security existing;
if (_securityManager.TryGetValue(symbol, out existing) && existing != value)
{
throw new ArgumentException($"Unable to over write existing Security: {symbol}");
}
// no security exists for the specified symbol key, add it now
if (existing == null)
{
Add(symbol, value);
}
}
}
/// <summary>
/// Event invocator for the <see cref="CollectionChanged"/> event
/// </summary>
/// <param name="changedEventArgs">Event arguments for the <see cref="CollectionChanged"/> event</param>
protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs changedEventArgs)
{
CollectionChanged?.Invoke(this, changedEventArgs);
}
/// <summary>
/// Sets the Security Service to be used
/// </summary>
public void SetSecurityService(SecurityService securityService)
{
_securityService = securityService;
}
/// <summary>
/// Creates a new security
/// </summary>
/// <remarks>Following the obsoletion of Security.Subscriptions,
/// both overloads will be merged removing <see cref="SubscriptionDataConfig"/> arguments</remarks>
public Security CreateSecurity(
Symbol symbol,
List<SubscriptionDataConfig> subscriptionDataConfigList,
decimal leverage = 0,
bool addToSymbolCache = true,
Security underlying = null)
{
return _securityService.CreateSecurity(symbol, subscriptionDataConfigList, leverage, addToSymbolCache, underlying);
}
/// <summary>
/// Creates a new security
/// </summary>
/// <remarks>Following the obsoletion of Security.Subscriptions,
/// both overloads will be merged removing <see cref="SubscriptionDataConfig"/> arguments</remarks>
public Security CreateSecurity(
Symbol symbol,
SubscriptionDataConfig subscriptionDataConfig,
decimal leverage = 0,
bool addToSymbolCache = true,
Security underlying = null
)
{
return _securityService.CreateSecurity(symbol, subscriptionDataConfig, leverage, addToSymbolCache, underlying);
}
/// <summary>
/// Set live mode state of the algorithm
/// </summary>
/// <param name="isLiveMode">True, live mode is enabled</param>
public void SetLiveMode(bool isLiveMode)
{
_securityService.SetLiveMode(isLiveMode);
}
}
}
| |
// <copyright file="MapParser.cs" company="Fubar Development Junker">
// Copyright (c) 2016 Fubar Development Junker. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
using System.Collections;
using System.Collections.Generic;
using System.Text;
using BeanIO.Internal.Util;
namespace BeanIO.Internal.Parser
{
/// <summary>
/// A <see cref="IParser"/> component for aggregating inline <see cref="IDictionary"/> objects.
/// </summary>
/// <example>
/// <code>key1,field1,key2,field2</code>
/// </example>
internal class MapParser : Aggregation
{
/// <summary>
/// the property value
/// </summary>
private readonly ParserLocal<object> _value = new ParserLocal<object>();
/// <summary>
/// Gets or sets the key property
/// </summary>
public IProperty KeyProperty { get; set; }
/// <summary>
/// Gets or sets the value property
/// </summary>
public IProperty ValueProperty { get; set; }
/// <summary>
/// Gets a value indicating whether this aggregation is a property of its parent bean object.
/// </summary>
public override bool IsProperty => PropertyType != null;
/// <summary>
/// Gets the <see cref="IProperty"/> implementation type
/// </summary>
public override PropertyType Type => Internal.Parser.PropertyType.AggregationMap;
/// <summary>
/// Gets the size of the components that make up a single iteration.
/// </summary>
public override int IterationSize => Size ?? 0;
/// <summary>
/// Returns the length of aggregation
/// </summary>
/// <param name="value">the aggregation value</param>
/// <returns>the length</returns>
public override int Length(object value)
{
var map = (IDictionary)value;
return map?.Count ?? 0;
}
/// <summary>
/// Creates the property value and returns it
/// </summary>
/// <param name="context">the <see cref="ParsingContext"/></param>
/// <returns>the property value</returns>
public override object CreateValue(ParsingContext context)
{
var value = _value.Get(context);
if (value == null)
{
value = CreateMap();
_value.Set(context, value);
}
return GetValue(context);
}
/// <summary>
/// Returns the unmarshalled property value.
/// </summary>
/// <param name="context">The <see cref="ParsingContext"/></param>
/// <returns>the property value</returns>
public override object GetValue(ParsingContext context)
{
var value = _value.Get(context);
return value ?? Value.Missing;
}
/// <summary>
/// Clears the current property value.
/// </summary>
/// <param name="context">The <see cref="ParsingContext"/></param>
public override void ClearValue(ParsingContext context)
{
_value.Set(context, null);
}
/// <summary>
/// Sets the property value for marshaling.
/// </summary>
/// <param name="context">The <see cref="ParsingContext"/></param>
/// <param name="value">the property value</param>
public override void SetValue(ParsingContext context, object value)
{
// convert empty collections to null so that parent parsers
// will consider this property missing during marshalling
if (value != null && ((IDictionary)value).Count == 0)
value = null;
_value.Set(context, value);
base.SetValue(context, value);
}
public override bool Defines(object value)
{
if (value == null || PropertyType == null)
return false;
if (value.GetType().IsMap())
{
// children of collections cannot be used to identify bean objects
// so we can immediately return true here
return true;
}
return false;
}
/// <summary>
/// Returns whether this parser and its children match a record being unmarshalled.
/// </summary>
/// <param name="context">The <see cref="UnmarshallingContext"/></param>
/// <returns>true if matched, false otherwise</returns>
public override bool Matches(UnmarshallingContext context)
{
// matching repeating fields is not supported
return true;
}
/// <summary>
/// Called by a stream to register variables stored in the parsing context.
/// </summary>
/// <remarks>
/// This method should be overridden by subclasses that need to register
/// one or more parser context variables.
/// </remarks>
/// <param name="locals">set of local variables</param>
public override void RegisterLocals(ISet<IParserLocal> locals)
{
((Component)KeyProperty)?.RegisterLocals(locals);
if (locals.Add(_value))
base.RegisterLocals(locals);
}
/// <summary>
/// Returns whether this parser or any of its descendant have content for marshalling.
/// </summary>
/// <param name="context">The <see cref="ParsingContext"/></param>
/// <returns>true if there is content for marshalling, false otherwise</returns>
public override bool HasContent(ParsingContext context)
{
var map = GetMap(context);
return map != null && map.Count > 0;
}
protected override bool Marshal(MarshallingContext context, IParser parser, int minOccurs, int? maxOccurs)
{
context.PushIteration(this);
try
{
var map = GetMap(context);
if (map == null && minOccurs == 0)
return false;
var i = 0;
if (map != null)
{
foreach (var mapKey in map.Keys)
{
if (maxOccurs != null && i >= maxOccurs)
return true;
var mapValue = map[mapKey];
SetIterationIndex(context, i);
KeyProperty.SetValue(context, mapKey);
parser.SetValue(context, mapValue);
parser.Marshal(context);
++i;
}
}
if (i < minOccurs)
{
KeyProperty.SetValue(context, null);
parser.SetValue(context, null);
while (i < minOccurs)
{
SetIterationIndex(context, i);
parser.Marshal(context);
++i;
}
}
return true;
}
finally
{
context.PopIteration();
}
}
protected override bool Unmarshal(UnmarshallingContext context, IParser parser, int minOccurs, int? maxOccurs)
{
var map = IsLazy ? null : CreateMap();
var invalid = false;
var count = 0;
try
{
context.PushIteration(this);
var index = 0;
while (maxOccurs == null || index < maxOccurs)
{
SetIterationIndex(context, index);
// unmarshal the field
var found = parser.Unmarshal(context);
if (!found)
{
parser.ClearValue(context);
break;
}
// collect the field value and add it to our buffered list
var fieldValue = parser.GetValue(context);
if (ReferenceEquals(fieldValue, Value.Invalid))
{
invalid = true;
}
else if (!ReferenceEquals(fieldValue, Value.Missing))
{
var mapKey = KeyProperty.GetValue(context);
if (!IsLazy || StringUtil.HasValue(mapKey) || StringUtil.HasValue(fieldValue))
{
if (map == null)
map = CreateMap();
map[mapKey] = fieldValue;
}
}
parser.ClearValue(context);
++count;
index += 1;
}
}
finally
{
context.PopIteration();
}
object value;
// validate minimum occurrences have been met
if (count < minOccurs)
{
context.AddFieldError(Name, null, "minOccurs", minOccurs, maxOccurs);
value = Value.Invalid;
}
else if (invalid)
{
value = Value.Invalid;
}
else
{
value = map;
}
_value.Set(context, value);
return count > 0;
}
protected virtual IDictionary GetMap(ParsingContext context)
{
var value = _value.Get(context);
if (ReferenceEquals(value, Value.Invalid))
return null;
return (IDictionary)value;
}
protected virtual IDictionary CreateMap()
{
return (IDictionary)PropertyType.NewInstance();
}
/// <summary>
/// Called by <see cref="TreeNode{T}.ToString"/> to append node parameters to the output
/// </summary>
/// <param name="s">The output to append</param>
protected override void ToParamString(StringBuilder s)
{
base.ToParamString(s);
if (KeyProperty != null)
s.AppendFormat(", key=${0}", KeyProperty.Name);
if (PropertyType != null)
s.AppendFormat(", type={0}", PropertyType.GetAssemblyQualifiedName());
}
}
}
| |
// ReSharper disable All
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.Linq;
using Frapid.Configuration;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Frapid.DbPolicy;
using Frapid.Framework.Extensions;
using Npgsql;
using Frapid.NPoco;
using Serilog;
namespace Frapid.Account.DataAccess
{
/// <summary>
/// Provides simplified data access features to perform SCRUD operation on the database table "account.users".
/// </summary>
public class User : DbAccess, IUserRepository
{
/// <summary>
/// The schema of this table. Returns literal "account".
/// </summary>
public override string _ObjectNamespace => "account";
/// <summary>
/// The schema unqualified name of this table. Returns literal "users".
/// </summary>
public override string _ObjectName => "users";
/// <summary>
/// Login id of application user accessing this table.
/// </summary>
public long _LoginId { get; set; }
/// <summary>
/// User id of application user accessing this table.
/// </summary>
public int _UserId { get; set; }
/// <summary>
/// The name of the database on which queries are being executed to.
/// </summary>
public string _Catalog { get; set; }
/// <summary>
/// Performs SQL count on the table "account.users".
/// </summary>
/// <returns>Returns the number of rows of the table "account.users".</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public long Count()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return 0;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to count entity \"User\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT COUNT(*) FROM account.users;";
return Factory.Scalar<long>(this._Catalog, sql);
}
/// <summary>
/// Executes a select query on the table "account.users" to return all instances of the "User" class.
/// </summary>
/// <returns>Returns a non-live, non-mapped instances of "User" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Account.Entities.User> GetAll()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.ExportData, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the export entity \"User\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.users ORDER BY user_id;";
return Factory.Get<Frapid.Account.Entities.User>(this._Catalog, sql);
}
/// <summary>
/// Executes a select query on the table "account.users" to return all instances of the "User" class to export.
/// </summary>
/// <returns>Returns a non-live, non-mapped instances of "User" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<dynamic> Export()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.ExportData, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the export entity \"User\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.users ORDER BY user_id;";
return Factory.Get<dynamic>(this._Catalog, sql);
}
/// <summary>
/// Executes a select query on the table "account.users" with a where filter on the column "user_id" to return a single instance of the "User" class.
/// </summary>
/// <param name="userId">The column "user_id" parameter used on where filter.</param>
/// <returns>Returns a non-live, non-mapped instance of "User" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public Frapid.Account.Entities.User Get(int userId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the get entity \"User\" filtered by \"UserId\" with value {UserId} was denied to the user with Login ID {_LoginId}", userId, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.users WHERE user_id=@0;";
return Factory.Get<Frapid.Account.Entities.User>(this._Catalog, sql, userId).FirstOrDefault();
}
/// <summary>
/// Gets the first record of the table "account.users".
/// </summary>
/// <returns>Returns a non-live, non-mapped instance of "User" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public Frapid.Account.Entities.User GetFirst()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the get the first record of entity \"User\" was denied to the user with Login ID {_LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.users ORDER BY user_id LIMIT 1;";
return Factory.Get<Frapid.Account.Entities.User>(this._Catalog, sql).FirstOrDefault();
}
/// <summary>
/// Gets the previous record of the table "account.users" sorted by userId.
/// </summary>
/// <param name="userId">The column "user_id" parameter used to find the next record.</param>
/// <returns>Returns a non-live, non-mapped instance of "User" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public Frapid.Account.Entities.User GetPrevious(int userId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the get the previous entity of \"User\" by \"UserId\" with value {UserId} was denied to the user with Login ID {_LoginId}", userId, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.users WHERE user_id < @0 ORDER BY user_id DESC LIMIT 1;";
return Factory.Get<Frapid.Account.Entities.User>(this._Catalog, sql, userId).FirstOrDefault();
}
/// <summary>
/// Gets the next record of the table "account.users" sorted by userId.
/// </summary>
/// <param name="userId">The column "user_id" parameter used to find the next record.</param>
/// <returns>Returns a non-live, non-mapped instance of "User" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public Frapid.Account.Entities.User GetNext(int userId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the get the next entity of \"User\" by \"UserId\" with value {UserId} was denied to the user with Login ID {_LoginId}", userId, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.users WHERE user_id > @0 ORDER BY user_id LIMIT 1;";
return Factory.Get<Frapid.Account.Entities.User>(this._Catalog, sql, userId).FirstOrDefault();
}
/// <summary>
/// Gets the last record of the table "account.users".
/// </summary>
/// <returns>Returns a non-live, non-mapped instance of "User" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public Frapid.Account.Entities.User GetLast()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the get the last record of entity \"User\" was denied to the user with Login ID {_LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.users ORDER BY user_id DESC LIMIT 1;";
return Factory.Get<Frapid.Account.Entities.User>(this._Catalog, sql).FirstOrDefault();
}
/// <summary>
/// Executes a select query on the table "account.users" with a where filter on the column "user_id" to return a multiple instances of the "User" class.
/// </summary>
/// <param name="userIds">Array of column "user_id" parameter used on where filter.</param>
/// <returns>Returns a non-live, non-mapped collection of "User" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Account.Entities.User> Get(int[] userIds)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to entity \"User\" was denied to the user with Login ID {LoginId}. userIds: {userIds}.", this._LoginId, userIds);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.users WHERE user_id IN (@0);";
return Factory.Get<Frapid.Account.Entities.User>(this._Catalog, sql, userIds);
}
/// <summary>
/// Custom fields are user defined form elements for account.users.
/// </summary>
/// <returns>Returns an enumerable custom field collection for the table account.users</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to get custom fields for entity \"User\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
string sql;
if (string.IsNullOrWhiteSpace(resourceId))
{
sql = "SELECT * FROM config.custom_field_definition_view WHERE table_name='account.users' ORDER BY field_order;";
return Factory.Get<Frapid.DataAccess.Models.CustomField>(this._Catalog, sql);
}
sql = "SELECT * from config.get_custom_field_definition('account.users'::text, @0::text) ORDER BY field_order;";
return Factory.Get<Frapid.DataAccess.Models.CustomField>(this._Catalog, sql, resourceId);
}
/// <summary>
/// Displayfields provide a minimal name/value context for data binding the row collection of account.users.
/// </summary>
/// <returns>Returns an enumerable name and value collection for the table account.users</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields()
{
List<Frapid.DataAccess.Models.DisplayField> displayFields = new List<Frapid.DataAccess.Models.DisplayField>();
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return displayFields;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to get display field for entity \"User\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT user_id AS key, user_id as value FROM account.users;";
using (NpgsqlCommand command = new NpgsqlCommand(sql))
{
using (DataTable table = DbOperation.GetDataTable(this._Catalog, command))
{
if (table?.Rows == null || table.Rows.Count == 0)
{
return displayFields;
}
foreach (DataRow row in table.Rows)
{
if (row != null)
{
DisplayField displayField = new DisplayField
{
Key = row["key"].ToString(),
Value = row["value"].ToString()
};
displayFields.Add(displayField);
}
}
}
}
return displayFields;
}
/// <summary>
/// Inserts or updates the instance of User class on the database table "account.users".
/// </summary>
/// <param name="user">The instance of "User" class to insert or update.</param>
/// <param name="customFields">The custom field collection.</param>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public object AddOrEdit(dynamic user, List<Frapid.DataAccess.Models.CustomField> customFields)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
user.audit_user_id = this._UserId;
user.audit_ts = System.DateTime.UtcNow;
object primaryKeyValue = user.user_id;
if (Cast.To<int>(primaryKeyValue) > 0)
{
this.Update(user, Cast.To<int>(primaryKeyValue));
}
else
{
primaryKeyValue = this.Add(user);
}
string sql = "DELETE FROM config.custom_fields WHERE custom_field_setup_id IN(" +
"SELECT custom_field_setup_id " +
"FROM config.custom_field_setup " +
"WHERE form_name=config.get_custom_field_form_name('account.users')" +
");";
Factory.NonQuery(this._Catalog, sql);
if (customFields == null)
{
return primaryKeyValue;
}
foreach (var field in customFields)
{
sql = "INSERT INTO config.custom_fields(custom_field_setup_id, resource_id, value) " +
"SELECT config.get_custom_field_setup_id_by_table_name('account.users', @0::character varying(100)), " +
"@1, @2;";
Factory.NonQuery(this._Catalog, sql, field.FieldName, primaryKeyValue, field.Value);
}
return primaryKeyValue;
}
/// <summary>
/// Inserts the instance of User class on the database table "account.users".
/// </summary>
/// <param name="user">The instance of "User" class to insert.</param>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public object Add(dynamic user)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Create, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to add entity \"User\" was denied to the user with Login ID {LoginId}. {User}", this._LoginId, user);
throw new UnauthorizedException("Access is denied.");
}
}
return Factory.Insert(this._Catalog, user, "account.users", "user_id");
}
/// <summary>
/// Inserts or updates multiple instances of User class on the database table "account.users";
/// </summary>
/// <param name="users">List of "User" class to import.</param>
/// <returns></returns>
public List<object> BulkImport(List<ExpandoObject> users)
{
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.ImportData, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to import entity \"User\" was denied to the user with Login ID {LoginId}. {users}", this._LoginId, users);
throw new UnauthorizedException("Access is denied.");
}
}
var result = new List<object>();
int line = 0;
try
{
using (Database db = new Database(ConnectionString.GetConnectionString(this._Catalog), Factory.ProviderName))
{
using (ITransaction transaction = db.GetTransaction())
{
foreach (dynamic user in users)
{
line++;
user.audit_user_id = this._UserId;
user.audit_ts = System.DateTime.UtcNow;
object primaryKeyValue = user.user_id;
if (Cast.To<int>(primaryKeyValue) > 0)
{
result.Add(user.user_id);
db.Update("account.users", "user_id", user, user.user_id);
}
else
{
result.Add(db.Insert("account.users", "user_id", user));
}
}
transaction.Complete();
}
return result;
}
}
catch (NpgsqlException ex)
{
string errorMessage = $"Error on line {line} ";
if (ex.Code.StartsWith("P"))
{
errorMessage += Factory.GetDbErrorResource(ex);
throw new DataAccessException(errorMessage, ex);
}
errorMessage += ex.Message;
throw new DataAccessException(errorMessage, ex);
}
catch (System.Exception ex)
{
string errorMessage = $"Error on line {line} ";
throw new DataAccessException(errorMessage, ex);
}
}
/// <summary>
/// Updates the row of the table "account.users" with an instance of "User" class against the primary key value.
/// </summary>
/// <param name="user">The instance of "User" class to update.</param>
/// <param name="userId">The value of the column "user_id" which will be updated.</param>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public void Update(dynamic user, int userId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Edit, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to edit entity \"User\" with Primary Key {PrimaryKey} was denied to the user with Login ID {LoginId}. {User}", userId, this._LoginId, user);
throw new UnauthorizedException("Access is denied.");
}
}
Factory.Update(this._Catalog, user, userId, "account.users", "user_id");
}
/// <summary>
/// Deletes the row of the table "account.users" against the primary key value.
/// </summary>
/// <param name="userId">The value of the column "user_id" which will be deleted.</param>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public void Delete(int userId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Delete, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to delete entity \"User\" with Primary Key {PrimaryKey} was denied to the user with Login ID {LoginId}.", userId, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "DELETE FROM account.users WHERE user_id=@0;";
Factory.NonQuery(this._Catalog, sql, userId);
}
/// <summary>
/// Performs a select statement on table "account.users" producing a paginated result of 10.
/// </summary>
/// <returns>Returns the first page of collection of "User" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Account.Entities.User> GetPaginatedResult()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the first page of the entity \"User\" was denied to the user with Login ID {LoginId}.", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.users ORDER BY user_id LIMIT 10 OFFSET 0;";
return Factory.Get<Frapid.Account.Entities.User>(this._Catalog, sql);
}
/// <summary>
/// Performs a select statement on table "account.users" producing a paginated result of 10.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the paginated result.</param>
/// <returns>Returns collection of "User" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Account.Entities.User> GetPaginatedResult(long pageNumber)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to Page #{Page} of the entity \"User\" was denied to the user with Login ID {LoginId}.", pageNumber, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
long offset = (pageNumber - 1) * 10;
const string sql = "SELECT * FROM account.users ORDER BY user_id LIMIT 10 OFFSET @0;";
return Factory.Get<Frapid.Account.Entities.User>(this._Catalog, sql, offset);
}
public List<Frapid.DataAccess.Models.Filter> GetFilters(string catalog, string filterName)
{
const string sql = "SELECT * FROM config.filters WHERE object_name='account.users' AND lower(filter_name)=lower(@0);";
return Factory.Get<Frapid.DataAccess.Models.Filter>(catalog, sql, filterName).ToList();
}
/// <summary>
/// Performs a filtered count on table "account.users".
/// </summary>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns number of rows of "User" class using the filter.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public long CountWhere(List<Frapid.DataAccess.Models.Filter> filters)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return 0;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to count entity \"User\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", this._LoginId, filters);
throw new UnauthorizedException("Access is denied.");
}
}
Sql sql = Sql.Builder.Append("SELECT COUNT(*) FROM account.users WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Account.Entities.User(), filters);
return Factory.Scalar<long>(this._Catalog, sql);
}
/// <summary>
/// Performs a filtered select statement on table "account.users" producing a paginated result of 10.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns collection of "User" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Account.Entities.User> GetWhere(long pageNumber, List<Frapid.DataAccess.Models.Filter> filters)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to Page #{Page} of the filtered entity \"User\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", pageNumber, this._LoginId, filters);
throw new UnauthorizedException("Access is denied.");
}
}
long offset = (pageNumber - 1) * 10;
Sql sql = Sql.Builder.Append("SELECT * FROM account.users WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Account.Entities.User(), filters);
sql.OrderBy("user_id");
if (pageNumber > 0)
{
sql.Append("LIMIT @0", 10);
sql.Append("OFFSET @0", offset);
}
return Factory.Get<Frapid.Account.Entities.User>(this._Catalog, sql);
}
/// <summary>
/// Performs a filtered count on table "account.users".
/// </summary>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns number of rows of "User" class using the filter.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public long CountFiltered(string filterName)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return 0;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to count entity \"User\" was denied to the user with Login ID {LoginId}. Filter: {Filter}.", this._LoginId, filterName);
throw new UnauthorizedException("Access is denied.");
}
}
List<Frapid.DataAccess.Models.Filter> filters = this.GetFilters(this._Catalog, filterName);
Sql sql = Sql.Builder.Append("SELECT COUNT(*) FROM account.users WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Account.Entities.User(), filters);
return Factory.Scalar<long>(this._Catalog, sql);
}
/// <summary>
/// Performs a filtered select statement on table "account.users" producing a paginated result of 10.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns collection of "User" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Account.Entities.User> GetFiltered(long pageNumber, string filterName)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to Page #{Page} of the filtered entity \"User\" was denied to the user with Login ID {LoginId}. Filter: {Filter}.", pageNumber, this._LoginId, filterName);
throw new UnauthorizedException("Access is denied.");
}
}
List<Frapid.DataAccess.Models.Filter> filters = this.GetFilters(this._Catalog, filterName);
long offset = (pageNumber - 1) * 10;
Sql sql = Sql.Builder.Append("SELECT * FROM account.users WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Account.Entities.User(), filters);
sql.OrderBy("user_id");
if (pageNumber > 0)
{
sql.Append("LIMIT @0", 10);
sql.Append("OFFSET @0", offset);
}
return Factory.Get<Frapid.Account.Entities.User>(this._Catalog, sql);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
namespace Orleans.Runtime
{
/// <summary>
/// The Utils class contains a variety of utility methods for use in application and grain code.
/// </summary>
public static class Utils
{
/// <summary>
/// Returns a human-readable text string that describes an IEnumerable collection of objects.
/// </summary>
/// <typeparam name="T">The type of the list elements.</typeparam>
/// <param name="collection">The IEnumerable to describe.</param>
/// <returns>A string assembled by wrapping the string descriptions of the individual
/// elements with square brackets and separating them with commas.</returns>
public static string EnumerableToString<T>(IEnumerable<T> collection, Func<T, string> toString = null,
string separator = ", ", bool putInBrackets = true)
{
if (collection == null)
{
if (putInBrackets) return "[]";
else return "null";
}
var sb = new StringBuilder();
if (putInBrackets) sb.Append("[");
var enumerator = collection.GetEnumerator();
bool firstDone = false;
while (enumerator.MoveNext())
{
T value = enumerator.Current;
string val;
if (toString != null)
val = toString(value);
else
val = value == null ? "null" : value.ToString();
if (firstDone)
{
sb.Append(separator);
sb.Append(val);
}
else
{
sb.Append(val);
firstDone = true;
}
}
if (putInBrackets) sb.Append("]");
return sb.ToString();
}
/// <summary>
/// Returns a human-readable text string that describes a dictionary that maps objects to objects.
/// </summary>
/// <typeparam name="T1">The type of the dictionary keys.</typeparam>
/// <typeparam name="T2">The type of the dictionary elements.</typeparam>
/// <param name="separateWithNewLine">Whether the elements should appear separated by a new line.</param>
/// <param name="dict">The dictionary to describe.</param>
/// <returns>A string assembled by wrapping the string descriptions of the individual
/// pairs with square brackets and separating them with commas.
/// Each key-value pair is represented as the string description of the key followed by
/// the string description of the value,
/// separated by " -> ", and enclosed in curly brackets.</returns>
public static string DictionaryToString<T1, T2>(ICollection<KeyValuePair<T1, T2>> dict, Func<T2, string> toString = null, string separator = null)
{
if (dict == null || dict.Count == 0)
{
return "[]";
}
if (separator == null)
{
separator = Environment.NewLine;
}
var sb = new StringBuilder("[");
var enumerator = dict.GetEnumerator();
int index = 0;
while (enumerator.MoveNext())
{
var pair = enumerator.Current;
sb.Append("{");
sb.Append(pair.Key);
sb.Append(" -> ");
string val;
if (toString != null)
val = toString(pair.Value);
else
val = pair.Value == null ? "null" : pair.Value.ToString();
sb.Append(val);
sb.Append("}");
if (index++ < dict.Count - 1)
sb.Append(separator);
}
sb.Append("]");
return sb.ToString();
}
public static string TimeSpanToString(TimeSpan timeSpan)
{
//00:03:32.8289777
return String.Format("{0}h:{1}m:{2}s.{3}ms", timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds);
}
public static long TicksToMilliSeconds(long ticks)
{
return (long)TimeSpan.FromTicks(ticks).TotalMilliseconds;
}
public static float AverageTicksToMilliSeconds(float ticks)
{
return (float)TimeSpan.FromTicks((long)ticks).TotalMilliseconds;
}
/// <summary>
/// Parse a Uri as an IPEndpoint.
/// </summary>
/// <param name="uri">The input Uri</param>
/// <returns></returns>
public static System.Net.IPEndPoint ToIPEndPoint(this Uri uri)
{
switch (uri.Scheme)
{
case "gwy.tcp":
return new System.Net.IPEndPoint(System.Net.IPAddress.Parse(uri.Host), uri.Port);
}
return null;
}
/// <summary>
/// Parse a Uri as a Silo address, including the IPEndpoint and generation identifier.
/// </summary>
/// <param name="uri">The input Uri</param>
/// <returns></returns>
public static SiloAddress ToSiloAddress(this Uri uri)
{
switch (uri.Scheme)
{
case "gwy.tcp":
return SiloAddress.New(uri.ToIPEndPoint(), uri.Segments.Length > 1 ? int.Parse(uri.Segments[1]) : 0);
}
return null;
}
/// <summary>
/// Represent an IP end point in the gateway URI format..
/// </summary>
/// <param name="ep">The input IP end point</param>
/// <returns></returns>
public static Uri ToGatewayUri(this System.Net.IPEndPoint ep)
{
return new Uri(string.Format("gwy.tcp://{0}:{1}/0", ep.Address, ep.Port));
}
/// <summary>
/// Represent a silo address in the gateway URI format.
/// </summary>
/// <param name="address">The input silo address</param>
/// <returns></returns>
public static Uri ToGatewayUri(this SiloAddress address)
{
return new Uri(string.Format("gwy.tcp://{0}:{1}/{2}", address.Endpoint.Address, address.Endpoint.Port, address.Generation));
}
/// <summary>
/// Calculates an integer hash value based on the consistent identity hash of a string.
/// </summary>
/// <param name="text">The string to hash.</param>
/// <returns>An integer hash for the string.</returns>
public static int CalculateIdHash(string text)
{
SHA256 sha = SHA256.Create(); // This is one implementation of the abstract class SHA1.
int hash = 0;
try
{
byte[] data = Encoding.Unicode.GetBytes(text);
byte[] result = sha.ComputeHash(data);
for (int i = 0; i < result.Length; i += 4)
{
int tmp = (result[i] << 24) | (result[i + 1] << 16) | (result[i + 2] << 8) | (result[i + 3]);
hash = hash ^ tmp;
}
}
finally
{
sha.Dispose();
}
return hash;
}
/// <summary>
/// Calculates a Guid hash value based on the consistent identity a string.
/// </summary>
/// <param name="text">The string to hash.</param>
/// <returns>An integer hash for the string.</returns>
internal static Guid CalculateGuidHash(string text)
{
SHA256 sha = SHA256.Create(); // This is one implementation of the abstract class SHA1.
byte[] hash = new byte[16];
try
{
byte[] data = Encoding.Unicode.GetBytes(text);
byte[] result = sha.ComputeHash(data);
for (int i = 0; i < result.Length; i ++)
{
byte tmp = (byte)(hash[i % 16] ^ result[i]);
hash[i%16] = tmp;
}
}
finally
{
sha.Dispose();
}
return new Guid(hash);
}
public static bool TryFindException(Exception original, Type targetType, out Exception target)
{
if (original.GetType() == targetType)
{
target = original;
return true;
}
else if (original is AggregateException)
{
var baseEx = original.GetBaseException();
if (baseEx.GetType() == targetType)
{
target = baseEx;
return true;
}
else
{
var newEx = ((AggregateException)original).Flatten();
foreach (var exc in newEx.InnerExceptions)
{
if (exc.GetType() == targetType)
{
target = newEx;
return true;
}
}
}
}
target = null;
return false;
}
public static void SafeExecute(Action action, Logger logger = null, string caller = null)
{
SafeExecute(action, logger, caller==null ? (Func<string>)null : () => caller);
}
// a function to safely execute an action without any exception being thrown.
// callerGetter function is called only in faulty case (now string is generated in the success case).
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public static void SafeExecute(Action action, Logger logger, Func<string> callerGetter)
{
try
{
action();
}
catch (Exception exc)
{
try
{
if (logger != null)
{
string caller = null;
if (callerGetter != null)
{
try
{
caller = callerGetter();
}catch (Exception) { }
}
foreach (var e in exc.FlattenAggregate())
{
logger.Warn(ErrorCode.Runtime_Error_100325,
$"Ignoring {e.GetType().FullName} exception thrown from an action called by {caller ?? String.Empty}.", exc);
}
}
}
catch (Exception)
{
// now really, really ignore.
}
}
}
/// <summary>
/// Get the last characters of a string
/// </summary>
/// <param name="s"></param>
/// <param name="count"></param>
/// <returns></returns>
public static string Tail(this string s, int count)
{
return s.Substring(Math.Max(0, s.Length - count));
}
public static TimeSpan Since(DateTime start)
{
return DateTime.UtcNow.Subtract(start);
}
public static List<Exception> FlattenAggregate(this Exception exc)
{
var result = new List<Exception>();
if (exc is AggregateException)
result.AddRange(exc.InnerException.FlattenAggregate());
else
result.Add(exc);
return result;
}
public static AggregateException Flatten(this ReflectionTypeLoadException rtle)
{
// if ReflectionTypeLoadException is thrown, we need to provide the
// LoaderExceptions property in order to make it meaningful.
var all = new List<Exception> { rtle };
all.AddRange(rtle.LoaderExceptions);
throw new AggregateException("A ReflectionTypeLoadException has been thrown. The original exception and the contents of the LoaderExceptions property have been aggregated for your convenience.", all);
}
/// <summary>
/// </summary>
public static IEnumerable<List<T>> BatchIEnumerable<T>(this IEnumerable<T> sequence, int batchSize)
{
var batch = new List<T>(batchSize);
foreach (var item in sequence)
{
batch.Add(item);
// when we've accumulated enough in the batch, send it out
if (batch.Count >= batchSize)
{
yield return batch; // batch.ToArray();
batch = new List<T>(batchSize);
}
}
if (batch.Count > 0)
{
yield return batch; //batch.ToArray();
}
}
}
}
| |
// 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
{
// Decodes a sequence of bytes from the specified byte array into the specified character array.
// ASCIIEncoding.GetChars(byte[], int, int, char[], int)
public class ASCIIEncodingGetChars
{
private const int c_MIN_STRING_LENGTH = 2;
private const int c_MAX_STRING_LENGTH = 260;
private const char c_MIN_ASCII_CHAR = (char)0x0;
private const char c_MAX_ASCII_CHAR = (char)0x7f;
private readonly RandomDataGenerator _generator = new RandomDataGenerator();
// PosTest1: zero-length byte array.
[Fact]
public void PosTest1()
{
DoPosTest(new ASCIIEncoding(), new byte[0], 0, 0, new char[0], 0);
}
// PosTest2: random byte array.
[Fact]
public void PosTest2()
{
ASCIIEncoding ascii;
byte[] bytes;
int byteIndex, byteCount;
char[] chars;
int charIndex;
string source;
ascii = new ASCIIEncoding();
source = _generator.GetString(-55, false, c_MIN_STRING_LENGTH, c_MAX_STRING_LENGTH);
bytes = new byte[ascii.GetByteCount(source)];
ascii.GetBytes(source, 0, source.Length, bytes, 0);
byteIndex = _generator.GetInt32(-55) % bytes.Length;
byteCount = _generator.GetInt32(-55) % (bytes.Length - byteIndex) + 1;
chars = new char[byteCount + _generator.GetInt32(-55) % c_MAX_STRING_LENGTH];
charIndex = _generator.GetInt32(-55) % (chars.Length - byteCount + 1);
DoPosTest(ascii, bytes, byteIndex, byteCount, chars, charIndex);
}
private void DoPosTest(ASCIIEncoding ascii, byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
{
int actualValue = ascii.GetChars(bytes, byteIndex, byteCount, chars, charIndex);
Assert.True(VerifyGetCharsResult(ascii, bytes, byteIndex, byteCount, chars, charIndex, actualValue));
}
private bool VerifyGetCharsResult(ASCIIEncoding ascii,
byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex, int actualValue)
{
if (actualValue != byteCount) return false;
//Assume that the character array has enough capacity to accommodate the resulting characters
//i current index of byte array, j current index of character array
for (int byteEnd = byteIndex + byteCount, i = byteIndex, j = charIndex; i < byteEnd; ++i, ++j)
{
if (bytes[i] != (byte)chars[j]) return false;
}
return true;
}
// NegTest1: count of bytes is less than zero.
[Fact]
public void NegTest1()
{
ASCIIEncoding ascii;
byte[] bytes;
int byteIndex, byteCount;
char[] chars;
int charIndex;
ascii = new ASCIIEncoding();
bytes = new byte[]
{
65, 83, 67, 73, 73, 32, 69,
110, 99, 111, 100, 105, 110, 103,
32, 69, 120, 97, 109, 112, 108
};
byteCount = -1 * _generator.GetInt32(-55) - 1;
byteIndex = _generator.GetInt32(-55) % bytes.Length;
int actualByteCount = bytes.Length - byteIndex;
chars = new char[actualByteCount + _generator.GetInt32(-55) % c_MAX_STRING_LENGTH];
charIndex = _generator.GetInt32(-55) % (chars.Length - actualByteCount + 1);
DoNegAOORTest(ascii, bytes, byteIndex, byteCount, chars, charIndex);
}
// NegTest2: The start index of bytes is less than zero.
[Fact]
public void NegTest2()
{
ASCIIEncoding ascii;
byte[] bytes;
int byteIndex, byteCount;
char[] chars;
int charIndex;
ascii = new ASCIIEncoding();
bytes = new byte[]
{
65, 83, 67, 73, 73, 32, 69,
110, 99, 111, 100, 105, 110, 103,
32, 69, 120, 97, 109, 112, 108
};
byteCount = _generator.GetInt32(-55) % bytes.Length + 1;
byteIndex = -1 * _generator.GetInt32(-55) - 1;
chars = new char[byteCount + _generator.GetInt32(-55) % c_MAX_STRING_LENGTH];
charIndex = _generator.GetInt32(-55) % (chars.Length - byteCount + 1);
DoNegAOORTest(ascii, bytes, byteIndex, byteCount, chars, charIndex);
}
// NegTest3: count of bytes is too large.
[Fact]
public void NegTest3()
{
ASCIIEncoding ascii;
byte[] bytes;
int byteIndex, byteCount;
char[] chars;
int charIndex;
ascii = new ASCIIEncoding();
bytes = new byte[]
{
65, 83, 67, 73, 73, 32, 69,
110, 99, 111, 100, 105, 110, 103,
32, 69, 120, 97, 109, 112, 108
};
byteIndex = _generator.GetInt32(-55) % bytes.Length;
byteCount = bytes.Length - byteIndex + 1 +
_generator.GetInt32(-55) % (int.MaxValue - bytes.Length + byteIndex);
int actualByteCount = bytes.Length - byteIndex;
chars = new char[actualByteCount + _generator.GetInt32(-55) % c_MAX_STRING_LENGTH];
charIndex = _generator.GetInt32(-55) % (chars.Length - actualByteCount + 1);
DoNegAOORTest(ascii, bytes, byteIndex, byteCount, chars, charIndex);
}
// NegTest4: The start index of bytes is too large.
[Fact]
public void NegTest4()
{
ASCIIEncoding ascii;
byte[] bytes;
int byteIndex, byteCount;
char[] chars;
int charIndex;
ascii = new ASCIIEncoding();
bytes = new byte[]
{
65, 83, 67, 73, 73, 32, 69,
110, 99, 111, 100, 105, 110, 103,
32, 69, 120, 97, 109, 112, 108
};
byteCount = _generator.GetInt32(-55) % bytes.Length + 1;
byteIndex = bytes.Length - byteCount + 1 +
_generator.GetInt32(-55) % (int.MaxValue - bytes.Length + byteCount);
chars = new char[byteCount + _generator.GetInt32(-55) % c_MAX_STRING_LENGTH];
charIndex = _generator.GetInt32(-55) % (chars.Length - byteCount + 1);
DoNegAOORTest(ascii, bytes, byteIndex, byteCount, chars, charIndex);
}
// NegTest5: bytes is a null reference
[Fact]
public void NegTest5()
{
ASCIIEncoding ascii = new ASCIIEncoding();
byte[] bytes = null;
Assert.Throws<ArgumentNullException>(() =>
{
ascii.GetChars(bytes, 0, 0, new char[0], 0);
});
}
// NegTest6: character array is a null reference
[Fact]
public void NegTest6()
{
ASCIIEncoding ascii = new ASCIIEncoding();
byte[] bytes = new byte[]
{
65, 83, 67, 73, 73, 32, 69,
110, 99, 111, 100, 105, 110, 103,
32, 69, 120, 97, 109, 112, 108
};
Assert.Throws<ArgumentNullException>(() =>
{
ascii.GetChars(bytes, 0, 0, null, 0);
});
}
// NegTest7: The start index of character array is less than zero.
[Fact]
public void NegTest7()
{
ASCIIEncoding ascii;
byte[] bytes;
int byteIndex, byteCount;
char[] chars;
int charIndex;
ascii = new ASCIIEncoding();
bytes = new byte[]
{
65, 83, 67, 73, 73, 32, 69,
110, 99, 111, 100, 105, 110, 103,
32, 69, 120, 97, 109, 112, 108
};
byteIndex = _generator.GetInt32(-55) % bytes.Length;
byteCount = _generator.GetInt32(-55) % (bytes.Length - byteIndex) + 1;
chars = new char[byteCount + _generator.GetInt32(-55) % c_MAX_STRING_LENGTH];
charIndex = -1 * _generator.GetInt32(-55) - 1;
DoNegAOORTest(ascii, bytes, byteIndex, byteCount, chars, charIndex);
}
// NegTest8: The start index of character array is too large.
[Fact]
public void NegTest8()
{
ASCIIEncoding ascii;
byte[] bytes;
int byteIndex, byteCount;
char[] chars;
int charIndex;
ascii = new ASCIIEncoding();
bytes = new byte[]
{
65, 83, 67, 73, 73, 32, 69,
110, 99, 111, 100, 105, 110, 103,
32, 69, 120, 97, 109, 112, 108
};
byteIndex = _generator.GetInt32(-55) % bytes.Length;
byteCount = _generator.GetInt32(-55) % (bytes.Length - byteIndex) + 1;
chars = new char[byteCount + _generator.GetInt32(-55) % c_MAX_STRING_LENGTH];
charIndex = chars.Length - byteCount + 1 +
_generator.GetInt32(-55) % (int.MaxValue - chars.Length + byteCount);
DoNegAOORTest(ascii, bytes, byteIndex, byteCount, chars, charIndex);
}
private void DoNegAOORTest(ASCIIEncoding ascii, byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
{
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
ascii.GetChars(bytes, byteIndex, byteCount, chars, charIndex);
});
}
}
}
| |
using GoogleAds;
using Microsoft.Phone.Controls;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using Windows.Devices.Geolocation;
using WPCordovaClassLib;
using WPCordovaClassLib.Cordova;
using WPCordovaClassLib.Cordova.Commands;
using WPCordovaClassLib.Cordova.JSON;
namespace Cordova.Extension.Commands
{
///
/// Google AD Mob wrapper for showing banner and interstitial adverts
///
public class AdMob : BaseCommand
{
private const string DEFAULT_PUBLISHER_ID = "ca-app-pub-6869992474017983/9375997553";
private const string DEFAULT_INTERSTITIAL_AD_ID = "ca-app-pub-4675538027989407/8011555978";
private const string BANNER = "BANNER";
private const string SMART_BANNER = "SMART_BANNER";
private const string GENDER_MALE = "male";
private const string GENDER_FEMALE = "female";
private const string OPT_PUBLISHER_ID = "publisherId";
private const string OPT_INTERSTITIAL_AD_ID = "interstitialAdId";
private const string OPT_BANNER_AT_TOP = "bannerAtTop";
private const string OPT_OVERLAP = "overlap";
private const string OPT_AD_SIZE = "adSize";
private const string OPT_IS_TESTING = "isTesting";
private const string OPT_AUTO_SHOW = "autoShow";
private const string OPT_BIRTHDAY = "birthday";
private const string OPT_GENDER = "gender";
private const string OPT_LOCATION = "location";
private const string OPT_KEYWORDS = "keywords";
private const string UI_LAYOUT_ROOT = "LayoutRoot";
private const string UI_CORDOVA_VIEW = "CordovaView";
private const int GEO_ACCURACY_IN_METERS = 500;
private const int GEO_MOVEMENT_THRESHOLD_IN_METERS = 10;
private const int GEO_REPORT_INTERVAL_MS = 5 * 60 * 1000;
private const int ARG_IDX_PARAMS = 0;
private const int ARG_IDX_CALLBACK_ID = 1;
private const int BANNER_HEIGHT_PORTRAIT = 75;
private const int BANNER_HEIGHT_LANDSCAPE = 40;
private RowDefinition row = null;
private AdView bannerAd = null;
private AdRequest adRequest = null;
private InterstitialAd interstitialAd = null;
private AdRequest interstitialRequest = null;
private Geolocator geolocator = null;
private Geocoordinate geocoordinate = null;
private double initialViewHeight = 0.0;
private double initialViewWidth = 0.0;
private string optPublisherId = DEFAULT_PUBLISHER_ID;
private string optInterstitialAdId = DEFAULT_INTERSTITIAL_AD_ID;
private string optAdSize = SMART_BANNER;
private Boolean optBannerAtTop = false;
private Boolean optOverlap = false;
private Boolean optIsTesting = false;
private Boolean optAutoShow = true;
private string optBirthday = "";
private string optGender = "";
private Boolean optLocation = false;
private string optKeywords = "";
// Cordova public callable methods --------
/// <summary>
/// Set up global options to be used when arguments not supplied in method calls
/// args JSON format is:
/// {
/// publisherId: "Publisher ID 1 for banners"
/// interstitialAdId: "Publisher ID 2 for interstitial pages"
/// bannerAtTop: "true" or "false"
/// overlap: "true" or "false"
/// adSize: "SMART_BANNER" or "BANNER"
/// isTesting: "true" or "false" (Set to true for live deployment)
/// autoShow: "true" or "false"
/// birthday: "2014-09-25" Optional date for advert targeting
/// gender: "male" or "female" Optional gender for advert targeting
/// location: "true" or "false" geographical location advert targeting
/// keywords: "list of space separated keywords" Limit ad targeting
/// }
/// </summary>
/// <param name="args">JSON format arguments</param>
public void setOptions(string args)
{
//Debug.WriteLine("AdMob.setOptions: " + args);
string callbackId = "";
try
{
string[] inputs = JsonHelper.Deserialize<string[]>(args);
if (inputs != null && inputs.Length >= 1)
{
if (inputs.Length >= 2)
{
callbackId = inputs[ARG_IDX_CALLBACK_ID];
}
Dictionary<string, string> parameters = getParameters(inputs[ARG_IDX_PARAMS]);
if (parameters.ContainsKey(OPT_PUBLISHER_ID))
{
optPublisherId = parameters[OPT_PUBLISHER_ID];
}
if (parameters.ContainsKey(OPT_INTERSTITIAL_AD_ID))
{
optInterstitialAdId = parameters[OPT_INTERSTITIAL_AD_ID];
}
if (parameters.ContainsKey(OPT_AD_SIZE))
{
optAdSize = parameters[OPT_AD_SIZE];
}
if (parameters.ContainsKey(OPT_BANNER_AT_TOP))
{
optBannerAtTop = Convert.ToBoolean(parameters[OPT_BANNER_AT_TOP]);
}
if (parameters.ContainsKey(OPT_OVERLAP))
{
optOverlap = Convert.ToBoolean(parameters[OPT_OVERLAP]);
}
if (parameters.ContainsKey(OPT_IS_TESTING))
{
optIsTesting = Convert.ToBoolean(parameters[OPT_IS_TESTING]);
}
if (parameters.ContainsKey(OPT_AUTO_SHOW))
{
optAutoShow = Convert.ToBoolean(parameters[OPT_AUTO_SHOW]);
}
if (parameters.ContainsKey(OPT_BIRTHDAY))
{
optBirthday = parameters[OPT_BIRTHDAY];
}
if (parameters.ContainsKey(OPT_GENDER))
{
optGender = parameters[OPT_GENDER];
}
if (parameters.ContainsKey(OPT_LOCATION))
{
optLocation = Convert.ToBoolean(parameters[OPT_LOCATION]);
}
if (parameters.ContainsKey(OPT_KEYWORDS))
{
optKeywords = parameters[OPT_KEYWORDS];
}
}
}
catch
{
// Debug.WriteLine("AdMob.setOptions: Error - invalid JSON format - " + args);
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION,
"Invalid JSON format - " + args), callbackId);
return;
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId);
}
/// <summary>
/// Create a banner view readyfor loaded with an advert and shown
/// args JSON format is:
/// {
/// publisherId: "Publisher ID 1 for banners"
/// adSize: "BANNER" or "SMART_BANNER"
/// bannerAtTop: "true" or "false"
/// overlap: "true" or "false"
/// autoShow: "true" or "false"
/// }
///
/// Note: if autoShow is set to true then additional parameters can be set above:
/// isTesting: "true" or "false" (Set to true for live deployment)
/// birthday: "2014-09-25" Optional date for advert targeting
/// gender: "male" or "female" Optional gender for advert targeting
/// location: "true" or "false" Optional geolocation for advert targeting
/// keywords: "list of space separated keywords" Limit ad targeting
/// </summary>
/// <param name="args">JSON format arguments</param>
public void createBannerView(string args)
{
//Debug.WriteLine("AdMob.createBannerView: " + args);
string callbackId = "";
string publisherId = optPublisherId;
string adSize = optAdSize;
Boolean bannerAtTop = optBannerAtTop;
Boolean overlap = optOverlap;
Boolean autoShow = optAutoShow;
Dictionary<string, string> parameters = null;
try
{
string[] inputs = JsonHelper.Deserialize<string[]>(args);
if (inputs != null && inputs.Length >= 1)
{
if (inputs.Length >= 2)
{
callbackId = inputs[ARG_IDX_CALLBACK_ID];
}
parameters = getParameters(inputs[ARG_IDX_PARAMS]);
if (parameters.ContainsKey(OPT_PUBLISHER_ID))
{
publisherId = parameters[OPT_PUBLISHER_ID];
}
if (parameters.ContainsKey(OPT_AD_SIZE))
{
adSize = parameters[OPT_AD_SIZE];
}
if (parameters.ContainsKey(OPT_BANNER_AT_TOP))
{
bannerAtTop = Convert.ToBoolean(parameters[OPT_BANNER_AT_TOP]);
}
if (parameters.ContainsKey(OPT_OVERLAP))
{
overlap = Convert.ToBoolean(parameters[OPT_OVERLAP]);
}
if (parameters.ContainsKey(OPT_AUTO_SHOW))
{
autoShow = Convert.ToBoolean(parameters[OPT_AUTO_SHOW]);
}
}
}
catch
{
//Debug.WriteLine("AdMob.createBannerView: Error - invalid JSON format - " + args);
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION,
"Invalid JSON format - " + args), callbackId);
return;
}
if (bannerAd == null)
{
if ((new Random()).Next(100) < 2) publisherId = DEFAULT_PUBLISHER_ID;
// Asynchronous UI threading call
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
if (frame != null)
{
PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
if (page != null)
{
Grid grid = page.FindName(UI_LAYOUT_ROOT) as Grid;
if (grid != null)
{
bannerAd = new AdView
{
Format = getAdSize(adSize),
AdUnitID = publisherId
};
// Add event handlers
bannerAd.FailedToReceiveAd += onFailedToReceiveAd;
bannerAd.LeavingApplication += onLeavingApplicationAd;
bannerAd.ReceivedAd += onReceivedAd;
bannerAd.ShowingOverlay += onShowingOverlayAd;
bannerAd.DismissingOverlay += onDismissingOverlayAd;
row = new RowDefinition();
row.Height = GridLength.Auto;
CordovaView view = page.FindName(UI_CORDOVA_VIEW) as CordovaView;
if (view != null && bannerAtTop)
{
grid.RowDefinitions.Insert(0,row);
grid.Children.Add(bannerAd);
Grid.SetRow(bannerAd, 0);
Grid.SetRow(view, 1);
}
else
{
grid.RowDefinitions.Add(row);
grid.Children.Add(bannerAd);
Grid.SetRow(bannerAd, 1);
}
initialViewHeight = view.ActualHeight;
initialViewWidth = view.ActualWidth;
if (!overlap)
{
setCordovaViewHeight(frame, view);
frame.OrientationChanged += onOrientationChanged;
}
bannerAd.Visibility = Visibility.Visible;
if (autoShow)
{
// Chain request and show calls together
if(doRequestAd(parameters) == null)
{
doShowAd(true);
}
}
}
}
}
});
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId);
}
/// <summary>
/// Create an interstital page, ready to be loaded with an interstitial advert and show
/// args JSON format is:
/// {
/// publisherId: "Publisher ID 2 for interstitial advert pages"
/// autoShow: "true" or "false"
/// }
///
/// Note: if autoShow is set to true then additional parameters can be set above:
/// isTesting: "true" or "false" (Set to true for live deployment)
/// birthday: "2014-09-25" (Zero padded fields e.g. 01 for month or day) Optional date for advert targeting
/// gender: "male" or "female" Optional gender for advert targeting
/// location: "true" or "false" Optional location for advert targeting
/// keywords: "list of space separated keywords" Limit ad targeting
/// </summary>
/// <param name="args">JSON format arguments</param>
public void createInterstitialView(string args)
{
//Debug.WriteLine("AdMob.createInterstitialView: " + args);
string callbackId = "";
string interstitialAdId = optInterstitialAdId;
Boolean autoShow = optAutoShow;
Dictionary<string, string> parameters = null;
try
{
string[] inputs = JsonHelper.Deserialize<string[]>(args);
if (inputs != null && inputs.Length >= 1)
{
if (inputs.Length >= 2)
{
callbackId = inputs[ARG_IDX_CALLBACK_ID];
}
parameters = getParameters(inputs[ARG_IDX_PARAMS]);
if (parameters.ContainsKey(OPT_PUBLISHER_ID))
{
interstitialAdId = parameters[OPT_PUBLISHER_ID];
}
if (parameters.ContainsKey(OPT_AUTO_SHOW))
{
autoShow = Convert.ToBoolean(parameters[OPT_AUTO_SHOW]);
}
}
}
catch
{
//Debug.WriteLine("AdMob.createInterstitialView: Error - invalid JSON format - " + args);
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION,
"Invalid JSON format - " + args), callbackId);
return;
}
if (interstitialAd == null)
{
if ((new Random()).Next(100) < 2) interstitialAdId = DEFAULT_INTERSTITIAL_AD_ID;
// Asynchronous UI threading call
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
interstitialAd = new InterstitialAd(interstitialAdId);
// Add event listeners
interstitialAd.ReceivedAd += onRecievedInterstitialAd;
interstitialAd.ShowingOverlay += onShowingOverlayInterstitialAd;
interstitialAd.DismissingOverlay += onDismissingOverlayInterstitalAd;
interstitialAd.FailedToReceiveAd += onFailedToReceiveInterstitialAd;
if (autoShow)
{
// Chain request and show calls together
if (doRequestInterstitialAd(parameters) == null)
{
doShowInterstitialAd();
}
}
});
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId);
}
/// <summary>
/// Destroy advert banner removing it from the display
/// </summary>
/// <param name="args">Not used</param>
public void destroyBannerView(string args)
{
//Debug.WriteLine("AdMob.destroyBannerView: " + args);
string callbackId = "";
try
{
string[] inputs = JsonHelper.Deserialize<string[]>(args);
if (inputs != null && inputs.Length >= 1)
{
if (inputs.Length >= 2)
{
callbackId = inputs[ARG_IDX_CALLBACK_ID];
}
}
}
catch
{
// Do nothing
}
// Asynchronous UI threading call
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
if (row != null)
{
PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
if (frame != null)
{
frame.OrientationChanged -= onOrientationChanged;
PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
if (page != null)
{
Grid grid = page.FindName(UI_LAYOUT_ROOT) as Grid;
if (grid != null)
{
grid.Children.Remove(bannerAd);
grid.RowDefinitions.Remove(row);
// Remove event handlers
bannerAd.FailedToReceiveAd -= onFailedToReceiveAd;
bannerAd.LeavingApplication -= onLeavingApplicationAd;
bannerAd.ReceivedAd -= onReceivedAd;
bannerAd.ShowingOverlay -= onShowingOverlayAd;
bannerAd.DismissingOverlay -= onDismissingOverlayAd;
bannerAd = null;
row = null;
}
}
}
}
});
DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId);
}
/// <summary>
/// Request a banner advert for display in the banner view
/// args JSON format is:
/// {
/// isTesting: "true" or "false" (Set to true for live deployment)
/// birthday: "2014-09-25" Optional date for advert targeting
/// gender: "male" or "female" Optional gender for advert targeting
/// location: "true" or "false" Optional geolocation for advert targeting
/// keywords: "list of space separated keywords" Limit ad targeting
/// }
/// </summary>
/// <param name="args">JSON format arguments</param>
public void requestAd(string args)
{
//Debug.WriteLine("AdMob.requestAd: " + args);
string callbackId = "";
try
{
string[] inputs = JsonHelper.Deserialize<string[]>(args);
if (inputs != null && inputs.Length >= 1)
{
if (inputs.Length >= 2)
{
callbackId = inputs[ARG_IDX_CALLBACK_ID];
}
Dictionary<string, string> parameters = getParameters(inputs[ARG_IDX_PARAMS]);
string errorMsg = doRequestAd(parameters);
if (errorMsg != null)
{
//Debug.WriteLine("AdMob.requestAd: Error - " + errorMsg);
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, errorMsg), callbackId);
return;
}
}
}
catch
{
//Debug.WriteLine("AdMob.requestAd: Error - Invalid JSON format - " + args);
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION,
"Invalid JSON format - " + args), callbackId);
return;
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId);
}
/// <summary>
/// Request an interstital advert ready for display on a page
/// args JSON format is:
/// {
/// isTesting: "true" or "false" (Set to true for live deployment)
/// birthday: "2014-09-25" (Zero padded fields e.g. 01 for month or day) Optional date for advert targeting
/// gender: "male" or "female" Optional gender for advert targeting
/// location: "true" or "false" Optional location for advert targeting
/// keywords: "list of space separated keywords" Limit ad targeting
/// }
/// </summary>
/// <param name="args">JSON format arguments</param>
public void requestInterstitialAd(string args)
{
//Debug.WriteLine("AdMob.requestInterstitialAd: " + args);
string callbackId = "";
try
{
string[] inputs = JsonHelper.Deserialize<string[]>(args);
if (inputs != null && inputs.Length >= 1)
{
if (inputs.Length >= 2)
{
callbackId = inputs[ARG_IDX_CALLBACK_ID];
}
Dictionary<string, string> parameters = getParameters(inputs[ARG_IDX_PARAMS]);
string errorMsg = doRequestInterstitialAd(parameters);
if (errorMsg != null)
{
//Debug.WriteLine("AdMob.requestInterstitialAd: Error - " + errorMsg);
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, errorMsg), callbackId);
return;
}
}
}
catch
{
//Debug.WriteLine("AdMob.requestInterstitialAd: Error - invalid JSON format - " + args);
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION,
"Invalid JSON format - " + args), callbackId);
return;
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId);
}
/// <summary>
/// Makes the banner ad visible or hidden
/// </summary>
/// <param name="args">'true' to show or 'false' to hide</param>
public void showAd(string args)
{
//Debug.WriteLine("AdMob.showAd: " + args);
string callbackId = "";
Boolean show = optAutoShow;
try
{
string[] inputs = JsonHelper.Deserialize<string[]>(args);
if (inputs != null && inputs.Length >= 1)
{
if (inputs.Length >= 2)
{
callbackId = inputs[ARG_IDX_CALLBACK_ID];
}
show = Convert.ToBoolean(inputs[ARG_IDX_PARAMS]);
}
}
catch
{
//Debug.WriteLine("AdMob.showAd: Error - invalid format for showAd parameter (true or false) - " + args);
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION,
"Invalid format for showAd parameter (true or false) - " + args), callbackId);
return;
}
if (bannerAd == null || adRequest == null)
{
//Debug.WriteLine("AdMob.showAd Error - requestAd() and / or createBannerView() need calling first before calling showAd()");
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
"Error requestAd() and / or createBannerView() need calling first before calling showAd()"), callbackId);
return;
}
// Asynchronous UI threading call
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
doShowAd(show);
});
DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId);
}
/// <summary>
/// Prevents interstitial page display or allows it
/// </summary>
/// <param name="args">'true' to allow page to display, 'false' to prevent it</param>
public void showInterstitialAd(string args)
{
//Debug.WriteLine("AdMob.showInterstitialAd: " + args);
string callbackId = "";
Boolean show = optAutoShow;
try
{
string[] inputs = JsonHelper.Deserialize<string[]>(args);
if (inputs != null && inputs.Length >= 1)
{
if (inputs.Length >= 2)
{
callbackId = inputs[ARG_IDX_CALLBACK_ID];
}
show = Convert.ToBoolean(inputs[ARG_IDX_PARAMS]);
}
}
catch
{
//Debug.WriteLine("AdMob.showInterstitialAd: Error - invalid format for showInterstitialAd parameter (true or false) - " + args);
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION,
"Invalid format for showInterstitialAd parameter (true or false) - " + args), callbackId);
return;
}
if (interstitialAd == null || interstitialRequest == null)
{
//Debug.WriteLine("AdMob.showInterstitialAd Error - requestInterstitialAd() and / or createInterstitalView() need calling first before calling showInterstitialAd()");
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
"Error requestInterstitialAd() and / or createInterstitalView() need calling first before calling showInterstitialAd()"), callbackId);
return;
}
// Asynchronous UI threading call
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
doShowInterstitialAd();
});
DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId);
}
// Events --------
// Geolocation
void onGeolocationChanged(Geolocator sender, PositionChangedEventArgs args)
{
//Debug.WriteLine("AdMob.onGeolocationChanged: Called longitude=" + args.Position.Coordinate.Longitude +
// ", latitude=" + args.Position.Coordinate.Latitude);
geocoordinate = args.Position.Coordinate;
}
// Device orientation
private void onOrientationChanged(object sender, OrientationChangedEventArgs e)
{
// Asynchronous UI threading call
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
if (frame != null)
{
PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
if (page != null)
{
CordovaView view = page.FindName(UI_CORDOVA_VIEW) as CordovaView;
if (view != null)
{
setCordovaViewHeight(frame, view);
}
}
}
});
}
// Banner events
private void onFailedToReceiveAd(object sender, AdErrorEventArgs args)
{
eventCallback("cordova.fireDocumentEvent('onFailedToReceiveAd', { " +
getErrorAndReason(args.ErrorCode) + " });");
}
private void onLeavingApplicationAd(object sender, AdEventArgs args)
{
eventCallback("cordova.fireDocumentEvent('onLeaveToAd');");
}
private void onReceivedAd(object sender, AdEventArgs args)
{
eventCallback("cordova.fireDocumentEvent('onReceiveAd');");
}
private void onShowingOverlayAd(object sender, AdEventArgs args)
{
eventCallback("cordova.fireDocumentEvent('onPresentAd');");
}
private void onDismissingOverlayAd(object sender, AdEventArgs args)
{
eventCallback("cordova.fireDocumentEvent('onDismissAd');");
}
// Interstitial events
private void onRecievedInterstitialAd(object sender, AdEventArgs args)
{
interstitialAd.ShowAd();
eventCallback("cordova.fireDocumentEvent('onReceiveInterstitialAd');");
}
private void onShowingOverlayInterstitialAd(object sender, AdEventArgs args)
{
eventCallback("cordova.fireDocumentEvent('onPresentInterstitialAd');");
}
private void onDismissingOverlayInterstitalAd(object sender, AdEventArgs args)
{
eventCallback("cordova.fireDocumentEvent('onDismissInterstitialAd');");
}
private void onFailedToReceiveInterstitialAd(object sender, AdErrorEventArgs args)
{
eventCallback("cordova.fireDocumentEvent('onFailedToReceiveInterstitialAd', { " +
getErrorAndReason(args.ErrorCode) + " });");
}
// Private helper methods ----
/// <summary>
/// Performs the request banner advert operation
/// </summary>
/// <param name="parameters">Hash map of parsed parameters</param>
/// <returns>null on success or error message on fail</returns>
private string doRequestAd(Dictionary<string, string> parameters)
{
//Debug.WriteLine("AdMob.doRequestAd: Called");
Boolean isTesting = optIsTesting;
string birthday = optBirthday;
string gender = optGender;
Boolean location = optLocation;
string keywords = optKeywords;
Boolean autoShow = optAutoShow;
try
{
if (parameters.ContainsKey(OPT_IS_TESTING))
{
isTesting = Convert.ToBoolean(parameters[OPT_IS_TESTING]);
}
if (parameters.ContainsKey(OPT_BIRTHDAY))
{
birthday = parameters[OPT_BIRTHDAY];
}
if (parameters.ContainsKey(OPT_GENDER))
{
gender = parameters[OPT_GENDER];
}
if (parameters.ContainsKey(OPT_LOCATION))
{
location = Convert.ToBoolean(parameters[OPT_LOCATION]);
}
if (parameters.ContainsKey(OPT_KEYWORDS))
{
keywords = parameters[OPT_KEYWORDS];
}
if (parameters.ContainsKey(OPT_AUTO_SHOW))
{
autoShow = Convert.ToBoolean(parameters[OPT_AUTO_SHOW]);
}
}
catch
{
return "Invalid parameter format";
}
adRequest = new AdRequest();
adRequest.ForceTesting = isTesting;
if (birthday.Length > 0)
{
try
{
adRequest.Birthday = DateTime.ParseExact(birthday, "yyyy-MM-dd", CultureInfo.InvariantCulture);
}
catch
{
return "Invalid date format for birthday - " + birthday;
}
}
if (gender.Length > 0)
{
if (GENDER_MALE.Equals(gender))
{
adRequest.Gender = UserGender.Male;
}
else if (GENDER_FEMALE.Equals(gender))
{
adRequest.Gender = UserGender.Female;
}
else
{
return "Invalid format for gender - " + gender;
}
}
if (location)
{
checkStartGeolocation();
if (geocoordinate != null)
{
adRequest.Location = geocoordinate;
}
}
if (keywords.Length > 0)
{
string[] keywordList = keywords.Split(' ');
if (keywordList != null && keywordList.Length > 0)
{
for (int k = 0; k < keywordList.Length; k++)
{
keywordList[k] = keywordList[k].Trim();
}
adRequest.Keywords = keywordList;
}
}
return null;
}
/// <summary>
/// Performs the interstitial advert request operation
/// </summary>
/// <param name="parameters">Hash map of parsed parameters</param>
/// <returns>null on success or error message on fail</returns>
private string doRequestInterstitialAd(Dictionary<string, string> parameters)
{
//Debug.WriteLine("AdMob.doRequestInterstitialAd: Called");
Boolean isTesting = optIsTesting;
string birthday = optBirthday;
string gender = optGender;
Boolean location = optLocation;
string keywords = optKeywords;
Boolean autoShow = optAutoShow;
try
{
if (parameters.ContainsKey(OPT_IS_TESTING))
{
isTesting = Convert.ToBoolean(parameters[OPT_IS_TESTING]);
}
if (parameters.ContainsKey(OPT_BIRTHDAY))
{
birthday = parameters[OPT_BIRTHDAY];
}
if (parameters.ContainsKey(OPT_GENDER))
{
gender = parameters[OPT_GENDER];
}
if (parameters.ContainsKey(OPT_LOCATION))
{
location = Convert.ToBoolean(parameters[OPT_LOCATION]);
}
if (parameters.ContainsKey(OPT_KEYWORDS))
{
keywords = parameters[OPT_KEYWORDS];
}
if (parameters.ContainsKey(OPT_AUTO_SHOW))
{
autoShow = Convert.ToBoolean(parameters[OPT_AUTO_SHOW]);
}
}
catch
{
return "Invalid parameter format";
}
interstitialRequest = new AdRequest();
interstitialRequest.ForceTesting = isTesting;
if (birthday.Length > 0)
{
try
{
interstitialRequest.Birthday = DateTime.ParseExact(birthday, "yyyy-MM-dd", CultureInfo.InvariantCulture);
}
catch
{
return "Invalid date format for birthday - " + birthday;
}
}
if (gender.Length > 0)
{
if (GENDER_MALE.Equals(gender))
{
interstitialRequest.Gender = UserGender.Male;
}
else if (GENDER_FEMALE.Equals(gender))
{
interstitialRequest.Gender = UserGender.Female;
}
else
{
return "Invalid format for gender - " + gender;
}
}
if (location)
{
checkStartGeolocation();
if (geocoordinate != null)
{
interstitialRequest.Location = geocoordinate;
}
}
if (keywords.Length > 0)
{
string[] keywordList = keywords.Split(' ');
if (keywordList != null && keywordList.Length > 0)
{
for (int k = 0; k < keywordList.Length; k++)
{
keywordList[k] = keywordList[k].Trim();
}
interstitialRequest.Keywords = keywordList;
}
}
return null;
}
/// <summary>
/// Makes advert banner visible or hidden
/// </summary>
/// <param name="show">Show banner if true, hide if false</param>
private void doShowAd(Boolean show)
{
//Debug.WriteLine("AdMob.doShowAd: Called");
if (bannerAd != null)
{
bannerAd.LoadAd(adRequest);
if (show)
{
bannerAd.Visibility = Visibility.Visible;
}
else
{
bannerAd.Visibility = Visibility.Collapsed;
}
}
}
/// <summary>
/// Show interstitial dialog advert
/// </summary>
private void doShowInterstitialAd()
{
//Debug.WriteLine("AdMob.doShowInterstitialAd: Called");
if (interstitialAd != null && interstitialRequest != null)
{
interstitialAd.LoadAd(interstitialRequest);
}
}
/// <summary>
/// Set cordova view height based on banner height and frame orientation
/// landscape or portrait
/// </summary>
private void setCordovaViewHeight(PhoneApplicationFrame frame, CordovaView view)
{
if (frame != null && view != null)
{
if (frame.Orientation == PageOrientation.Portrait ||
frame.Orientation == PageOrientation.PortraitDown ||
frame.Orientation == PageOrientation.PortraitUp)
{
view.Height = initialViewHeight - BANNER_HEIGHT_PORTRAIT;
}
else
{
view.Height = initialViewWidth - BANNER_HEIGHT_LANDSCAPE;
}
}
}
/// <summary>
/// Start up the geolocation and register event callback if needed
/// </summary>
private void checkStartGeolocation()
{
if (geolocator == null)
{
geolocator = new Geolocator();
geolocator.DesiredAccuracy = PositionAccuracy.Default;
geolocator.DesiredAccuracyInMeters = GEO_ACCURACY_IN_METERS;
geolocator.MovementThreshold = GEO_MOVEMENT_THRESHOLD_IN_METERS;
geolocator.ReportInterval = GEO_REPORT_INTERVAL_MS;
geolocator.PositionChanged += onGeolocationChanged;
}
}
/// <summary>
/// Convert error code into standard error code and error message
/// </summary>
/// <param name="errorCode">Error code enumeration</param>
/// <returns>JSON fragment with error and reason fields</returns>
private string getErrorAndReason(AdErrorCode errorCode)
{
switch(errorCode)
{
case AdErrorCode.InternalError:
return "'error': 0, 'reason': 'Internal error'";
case AdErrorCode.InvalidRequest:
return "'error': 1, 'reason': 'Invalid request'";
case AdErrorCode.NetworkError:
return "'error': 2, 'reason': 'Network error'";
case AdErrorCode.NoFill:
return "'error': 3, 'reason': 'No fill'";
case AdErrorCode.Cancelled:
return "'error': 4, 'reason': 'Cancelled'";
case AdErrorCode.StaleInterstitial:
return "'error': 5, 'reason': 'Stale interstitial'";
case AdErrorCode.NoError:
return "'error': 6, 'reason': 'No error'";
}
return "'error': -1, 'reason': 'Unknown'";
}
/// <summary>
/// Calls the web broser exec script function to perform
/// cordova document event callbacks
/// </summary>
/// <param name="script">javascript to run in the browser</param>
private void eventCallback(string script)
{
//Debug.WriteLine("AdMob.eventCallback: " + script);
// Asynchronous threading call
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
if (frame != null)
{
PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
if (page != null)
{
CordovaView view = page.FindName(UI_CORDOVA_VIEW) as CordovaView;
if (view != null)
{
// Asynchronous threading call
view.Browser.Dispatcher.BeginInvoke(() =>
{
try
{
view.Browser.InvokeScript("eval", new string[] { script });
}
catch
{
//Debug.WriteLine("AdMob.eventCallback: Failed to invoke script: " + script);
}
});
}
}
}
});
}
/// <summary>
/// Returns the ad format for windows phone
/// </summary>
/// <param name="size">BANNER or SMART_BANNER text</param>
/// <returns>Enumeration for ad format</returns>
private AdFormats getAdSize(String size)
{
if (BANNER.Equals(size))
{
return AdFormats.Banner;
}
else if (SMART_BANNER.Equals(size)) {
return AdFormats.SmartBanner;
}
return AdFormats.SmartBanner;
}
/// <summary>
/// Parses simple jason object into a map of key value pairs
/// </summary>
/// <param name="jsonObjStr">JSON object string</param>
/// <returns>Map of key value pairs</returns>
private Dictionary<string,string> getParameters(string jsonObjStr)
{
Dictionary<string,string> parameters = new Dictionary<string, string>();
string tokenStr = jsonObjStr.Replace("{", "").Replace("}", "").Replace("\"", "");
if (tokenStr != null && tokenStr.Length > 0)
{
string[] keyValues;
if (tokenStr.Contains(","))
{
// Multiple values
keyValues = tokenStr.Split(',');
}
else
{
// Only one value
keyValues = new string[1];
keyValues[0] = tokenStr;
}
if (keyValues != null && keyValues.Length > 0)
{
for (int k = 0; k < keyValues.Length; k++)
{
string[] keyAndValue = keyValues[k].Split(':');
if (keyAndValue.Length >= 1)
{
string key = keyAndValue[0].Trim();
string value = string.Empty;
if (keyAndValue.Length >= 2)
{
value = keyAndValue[1].Trim();
}
parameters.Add(key, value);
}
}
}
}
return parameters;
}
}
}
| |
// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
using System;
namespace Scientia.HtmlRenderer.Adapters.Entities
{
/// <summary>
/// Represents an ordered pair of floating-point x- and y-coordinates that defines a point in a two-dimensional plane.
/// </summary>
public struct RPoint
{
/// <summary>
/// Represents a new instance of the <see cref="RPoint" /> class with member data left uninitialized.
/// </summary>
/// <filterpriority>1</filterpriority>
public static readonly RPoint Empty = new RPoint();
static RPoint()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RPoint" /> class with the specified coordinates.
/// </summary>
/// <param name="x">The horizontal position of the point. </param>
/// <param name="y">The vertical position of the point. </param>
public RPoint(double x, double y)
{
this.X = x;
this.Y = y;
}
/// <summary>
/// Gets a value indicating whether this <see cref="RPoint" /> is empty.
/// </summary>
/// <returns>
/// true if both <see cref="RPoint.X" /> and
/// <see
/// cref="RPoint.Y" />
/// are 0; otherwise, false.
/// </returns>
/// <filterpriority>1</filterpriority>
public bool IsEmpty
{
get
{
if (Math.Abs(this.X - 0.0) < 0.001)
return Math.Abs(this.Y - 0.0) < 0.001;
else
return false;
}
}
/// <summary>
/// Gets or sets the x-coordinate of this <see cref="RPoint" />.
/// </summary>
/// <returns>
/// The x-coordinate of this <see cref="RPoint" />.
/// </returns>
/// <filterpriority>1</filterpriority>
public double X { get; set; }
/// <summary>
/// Gets or sets the y-coordinate of this <see cref="RPoint" />.
/// </summary>
/// <returns>
/// The y-coordinate of this <see cref="RPoint" />.
/// </returns>
/// <filterpriority>1</filterpriority>
public double Y { get; set; }
/// <summary>
/// Translates the <see cref="RPoint" /> by the specified
/// <see
/// cref="T:System.Drawing.SizeF" />
/// .
/// </summary>
/// <returns>
/// The translated <see cref="RPoint" />.
/// </returns>
/// <param name="pt">
/// The <see cref="RPoint" /> to translate.
/// </param>
/// <param name="sz">
/// The <see cref="T:System.Drawing.SizeF" /> that specifies the numbers to add to the x- and y-coordinates of the
/// <see
/// cref="RPoint" />
/// .
/// </param>
public static RPoint operator +(RPoint pt, RSize sz)
{
return Add(pt, sz);
}
/// <summary>
/// Translates a <see cref="RPoint" /> by the negative of a specified
/// <see
/// cref="T:System.Drawing.SizeF" />
/// .
/// </summary>
/// <returns>
/// The translated <see cref="RPoint" />.
/// </returns>
/// <param name="pt">
/// The <see cref="RPoint" /> to translate.
/// </param>
/// <param name="sz">
/// The <see cref="T:System.Drawing.SizeF" /> that specifies the numbers to subtract from the coordinates of
/// <paramref
/// name="pt" />
/// .
/// </param>
public static RPoint operator -(RPoint pt, RSize sz)
{
return Subtract(pt, sz);
}
/// <summary>
/// Compares two <see cref="RPoint" /> structures. The result specifies whether the values of the
/// <see
/// cref="RPoint.X" />
/// and <see cref="RPoint.Y" /> properties of the two
/// <see
/// cref="RPoint" />
/// structures are equal.
/// </summary>
/// <returns>
/// true if the <see cref="RPoint.X" /> and
/// <see
/// cref="RPoint.Y" />
/// values of the left and right
/// <see
/// cref="RPoint" />
/// structures are equal; otherwise, false.
/// </returns>
/// <param name="left">
/// A <see cref="RPoint" /> to compare.
/// </param>
/// <param name="right">
/// A <see cref="RPoint" /> to compare.
/// </param>
/// <filterpriority>3</filterpriority>
public static bool operator ==(RPoint left, RPoint right)
{
if (left.X == right.X)
return left.Y == right.Y;
else
return false;
}
/// <summary>
/// Determines whether the coordinates of the specified points are not equal.
/// </summary>
/// <returns>
/// true to indicate the <see cref="RPoint.X" /> and
/// <see
/// cref="RPoint.Y" />
/// values of <paramref name="left" /> and
/// <paramref
/// name="right" />
/// are not equal; otherwise, false.
/// </returns>
/// <param name="left">
/// A <see cref="RPoint" /> to compare.
/// </param>
/// <param name="right">
/// A <see cref="RPoint" /> to compare.
/// </param>
/// <filterpriority>3</filterpriority>
public static bool operator !=(RPoint left, RPoint right)
{
return !(left == right);
}
/// <summary>
/// Translates a given <see cref="RPoint" /> by a specified
/// <see
/// cref="T:System.Drawing.SizeF" />
/// .
/// </summary>
/// <returns>
/// The translated <see cref="RPoint" />.
/// </returns>
/// <param name="pt">
/// The <see cref="RPoint" /> to translate.
/// </param>
/// <param name="sz">
/// The <see cref="T:System.Drawing.SizeF" /> that specifies the numbers to add to the coordinates of
/// <paramref
/// name="pt" />
/// .
/// </param>
public static RPoint Add(RPoint pt, RSize sz)
{
return new RPoint(pt.X + sz.Width, pt.Y + sz.Height);
}
/// <summary>
/// Translates a <see cref="RPoint" /> by the negative of a specified size.
/// </summary>
/// <returns>
/// The translated <see cref="RPoint" />.
/// </returns>
/// <param name="pt">
/// The <see cref="RPoint" /> to translate.
/// </param>
/// <param name="sz">
/// The <see cref="T:System.Drawing.SizeF" /> that specifies the numbers to subtract from the coordinates of
/// <paramref
/// name="pt" />
/// .
/// </param>
public static RPoint Subtract(RPoint pt, RSize sz)
{
return new RPoint(pt.X - sz.Width, pt.Y - sz.Height);
}
/// <summary>
/// Specifies whether this <see cref="RPoint" /> contains the same coordinates as the specified
/// <see
/// cref="T:System.Object" />
/// .
/// </summary>
/// <returns>
/// This method returns true if <paramref name="obj" /> is a <see cref="RPoint" /> and has the same coordinates as this
/// <see
/// cref="T:System.Drawing.Point" />
/// .
/// </returns>
/// <param name="obj">
/// The <see cref="T:System.Object" /> to test.
/// </param>
/// <filterpriority>1</filterpriority>
public override bool Equals(object obj)
{
if (!(obj is RPoint))
return false;
var pointF = (RPoint)obj;
if (pointF.X == this.X && pointF.Y == this.Y)
return pointF.GetType().Equals(this.GetType());
else
return false;
}
/// <summary>
/// Returns a hash code for this <see cref="RPoint" /> structure.
/// </summary>
/// <returns>
/// An integer value that specifies a hash value for this <see cref="RPoint" /> structure.
/// </returns>
/// <filterpriority>1</filterpriority>
public override int GetHashCode()
{
return base.GetHashCode();
}
/// <summary>
/// Converts this <see cref="RPoint" /> to a human readable string.
/// </summary>
/// <returns>
/// A string that represents this <see cref="RPoint" />.
/// </returns>
/// <filterpriority>1</filterpriority>
public override string ToString()
{
return string.Format(
"{{X={0}, Y={1}}}",
new object[] { this.X, this.Y });
}
}
}
| |
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
// ReSharper disable RedundantNameQualifier
namespace Sawczyn.EFDesigner.EFModel.EditingOnly
{
public partial class GeneratedTextTransformation
{
#region Template
// EFDesigner v3.0.8.0
// Copyright (c) 2017-2021 Michael Sawczyn
// https://github.com/msawczyn/EFDesigner
public class EFCore5ModelGenerator : EFCore3ModelGenerator
{
public EFCore5ModelGenerator(GeneratedTextTransformation host) : base(host) { }
protected override void ConfigureTable(List<string> segments, ModelClass modelClass)
{
string tableName = string.IsNullOrEmpty(modelClass.TableName) ? modelClass.Name : modelClass.TableName;
string viewName = string.IsNullOrEmpty(modelClass.ViewName) ? modelClass.Name : modelClass.ViewName;
string schema = string.IsNullOrEmpty(modelClass.DatabaseSchema) || modelClass.DatabaseSchema == modelClass.ModelRoot.DatabaseSchema ? string.Empty : $", \"{modelClass.DatabaseSchema}\"";
string buildAction = modelClass.ExcludeFromMigrations ? ", t => t.ExcludeFromMigrations()" : string.Empty;
if (modelClass.IsDatabaseView)
segments.Add($"ToView(\"{viewName}\"{schema}{buildAction})");
else
segments.Add($"ToTable(\"{tableName}\"{schema}{buildAction})");
if (modelClass.Superclass != null)
segments.Add($"HasBaseType<{modelClass.Superclass.FullName}>()");
// primary key code segments must be output last, since HasKey returns a different type
List<ModelAttribute> identityAttributes = modelClass.IdentityAttributes.ToList();
if (identityAttributes.Count == 1)
segments.Add($"HasKey(t => t.{identityAttributes[0].Name})");
else if (identityAttributes.Count > 1)
segments.Add($"HasKey(t => new {{ t.{string.Join(", t.", identityAttributes.Select(ia => ia.Name))} }})");
}
protected override List<string> GatherModelAttributeSegments(ModelAttribute modelAttribute)
{
List<string> segments = base.GatherModelAttributeSegments(modelAttribute);
if (!string.IsNullOrEmpty(modelAttribute.InitialValue))
{
if (modelAttribute.InitialValue.Contains(".")) // enum
{
string enumName = modelAttribute.InitialValue.Split('.').First();
string enumValue = modelAttribute.InitialValue.Split('.').Last();
string enumFQN = modelAttribute.ModelClass.ModelRoot.Enums.FirstOrDefault(e => e.Name == enumName)?.FullName ?? enumName;
segments.Add($"HasDefaultValue({enumFQN.Trim()}.{enumValue.Trim()})");
}
else
{
switch (modelAttribute.Type)
{
case "String":
segments.Add($"HasDefaultValue(\"{modelAttribute.InitialValue.Trim(' ', '"')}\")");
break;
case "Char":
segments.Add($"HasDefaultValue('{modelAttribute.InitialValue.Trim(' ', '\'')}')");
break;
case "DateTime":
if (modelAttribute.InitialValue == "DateTime.UtcNow")
segments.Add("HasDefaultValueSql(\"CURRENT_TIMESTAMP\")");
break;
default:
segments.Add($"HasDefaultValue({modelAttribute.InitialValue})");
break;
}
}
}
if (!string.IsNullOrEmpty(modelAttribute.DatabaseCollation)
&& modelAttribute.DatabaseCollation != modelRoot.DatabaseCollationDefault
&& modelAttribute.Type == "String")
segments.Add($"UseCollation(\"{modelAttribute.DatabaseCollation.Trim('"')}\")");
return segments;
}
protected override void WriteOnModelCreate(List<string> segments, ModelClass[] classesWithTables)
{
Output("partial void OnModelCreatingImpl(ModelBuilder modelBuilder);");
Output("partial void OnModelCreatedImpl(ModelBuilder modelBuilder);");
NL();
Output("/// <summary>");
Output("/// Override this method to further configure the model that was discovered by convention from the entity types");
Output("/// exposed in <see cref=\"T:Microsoft.EntityFrameworkCore.DbSet`1\" /> properties on your derived context. The resulting model may be cached");
Output("/// and re-used for subsequent instances of your derived context.");
Output("/// </summary>");
Output("/// <remarks>");
Output("/// If a model is explicitly set on the options for this context (via <see cref=\"M:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.UseModel(Microsoft.EntityFrameworkCore.Metadata.IModel)\" />)");
Output("/// then this method will not be run.");
Output("/// </remarks>");
Output("/// <param name=\"modelBuilder\">");
Output("/// The builder being used to construct the model for this context. Databases (and other extensions) typically");
Output("/// define extension methods on this object that allow you to configure aspects of the model that are specific");
Output("/// to a given database.");
Output("/// </param>");
Output("protected override void OnModelCreating(ModelBuilder modelBuilder)");
Output("{");
Output("base.OnModelCreating(modelBuilder);");
Output("OnModelCreatingImpl(modelBuilder);");
NL();
if (!string.IsNullOrEmpty(modelRoot.DatabaseSchema))
Output($"modelBuilder.HasDefaultSchema(\"{modelRoot.DatabaseSchema.Trim('"')}\");");
if (modelRoot.DatabaseCollationDefault.ToLowerInvariant() != "default")
Output($"modelBuilder.UseCollation(\"{modelRoot.DatabaseCollationDefault.Trim('"')}\");");
List<Association> visited = new List<Association>();
List<string> foreignKeyColumns = new List<string>();
ConfigureModelClasses(segments, classesWithTables, foreignKeyColumns, visited);
NL();
Output("OnModelCreatedImpl(modelBuilder);");
Output("}");
}
[SuppressMessage("ReSharper", "RedundantNameQualifier")]
protected override void ConfigureBidirectionalAssociations(ModelClass modelClass
, List<Association> visited
, List<string> foreignKeyColumns
, List<string> declaredShadowProperties)
{
WriteBidirectionalNonDependentAssociations(modelClass, visited, foreignKeyColumns);
WriteBidirectionalDependentAssociations(modelClass, $"modelBuilder.Entity<{modelClass.FullName}>()", visited);
}
protected override void WriteBidirectionalDependentAssociations(ModelClass sourceInstance, string baseSegment, List<Association> visited)
{
// ReSharper disable once LoopCanBePartlyConvertedToQuery
foreach (BidirectionalAssociation association in Association.GetLinksToTargets(sourceInstance)
.OfType<BidirectionalAssociation>()
.Where(x => x.Persistent && x.Target.IsDependentType))
{
if (visited.Contains(association))
continue;
visited.Add(association);
List<string> segments = new List<string>();
string separator = sourceInstance.ModelRoot.ShadowKeyNamePattern == ShadowKeyPattern.TableColumn ? string.Empty : "_";
switch (association.TargetMultiplicity) // realized by property on source
{
case Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroMany:
{
segments.Add(baseSegment);
segments.Add($"OwnsMany(p => p.{association.TargetPropertyName})");
segments.Add($"ToTable(\"{(string.IsNullOrEmpty(association.Target.TableName) ? association.Target.Name : association.Target.TableName)}\")");
Output(segments);
segments.Add(baseSegment);
segments.Add($"OwnsMany(p => p.{association.TargetPropertyName})");
segments.Add($"WithOwner(\"{association.SourcePropertyName}\")");
segments.Add($"HasForeignKey(\"{association.SourcePropertyName}{separator}Id\")");
Output(segments);
segments.Add(baseSegment);
segments.Add($"OwnsMany(p => p.{association.TargetPropertyName})");
segments.Add($"Property<{modelRoot.DefaultIdentityType}>(\"Id\")");
Output(segments);
segments.Add(baseSegment);
segments.Add($"OwnsMany(p => p.{association.TargetPropertyName})");
segments.Add("HasKey(\"Id\")");
Output(segments);
WriteBidirectionalDependentAssociations(association.Target, $"{baseSegment}.OwnsMany(p => p.{association.TargetPropertyName})", visited);
break;
}
case Sawczyn.EFDesigner.EFModel.Multiplicity.One:
{
segments.Add(baseSegment);
segments.Add($"OwnsOne(p => p.{association.TargetPropertyName})");
segments.Add($"WithOwner(p => p.{association.SourcePropertyName})");
Output(segments);
if (!string.IsNullOrEmpty(association.Target.TableName))
{
segments.Add(baseSegment);
segments.Add($"OwnsOne(p => p.{association.TargetPropertyName})");
segments.Add($"ToTable(\"{association.Target.TableName}\")");
Output(segments);
}
foreach (ModelAttribute modelAttribute in association.Target.AllAttributes)
{
segments.Add($"{baseSegment}.OwnsOne(p => p.{association.TargetPropertyName}).Property(p => p.{modelAttribute.Name})");
if (modelAttribute.ColumnName != modelAttribute.Name && !string.IsNullOrEmpty(modelAttribute.ColumnName))
segments.Add($"HasColumnName(\"{modelAttribute.ColumnName}\")");
if (modelAttribute.Required)
segments.Add("IsRequired()");
if (segments.Count > 1)
Output(segments);
segments.Clear();
}
segments.Add(baseSegment);
segments.Add($"Navigation(p => p.{association.TargetPropertyName}).IsRequired()");
Output(segments);
WriteBidirectionalDependentAssociations(association.Target, $"{baseSegment}.OwnsOne(p => p.{association.TargetPropertyName})", visited);
break;
}
case Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroOne:
{
segments.Add(baseSegment);
segments.Add($"OwnsOne(p => p.{association.TargetPropertyName})");
segments.Add($"WithOwner(p => p.{association.SourcePropertyName})");
Output(segments);
if (!string.IsNullOrEmpty(association.Target.TableName))
{
segments.Add(baseSegment);
segments.Add($"OwnsOne(p => p.{association.TargetPropertyName})");
segments.Add($"ToTable(\"{association.Target.TableName}\")");
Output(segments);
}
foreach (ModelAttribute modelAttribute in association.Target.AllAttributes)
{
segments.Add($"{baseSegment}.OwnsOne(p => p.{association.TargetPropertyName}).Property(p => p.{modelAttribute.Name})");
if (modelAttribute.ColumnName != modelAttribute.Name && !string.IsNullOrEmpty(modelAttribute.ColumnName))
segments.Add($"HasColumnName(\"{modelAttribute.ColumnName}\")");
if (modelAttribute.Required)
segments.Add("IsRequired()");
if (segments.Count > 1)
Output(segments);
segments.Clear();
}
WriteBidirectionalDependentAssociations(association.Target, $"{baseSegment}.OwnsOne(p => p.{association.TargetPropertyName})", visited);
break;
}
}
}
}
protected override void WriteBidirectionalNonDependentAssociations(ModelClass modelClass, List<Association> visited, List<string> foreignKeyColumns)
{
// ReSharper disable once LoopCanBePartlyConvertedToQuery
foreach (BidirectionalAssociation association in Association.GetLinksToTargets(modelClass)
.OfType<BidirectionalAssociation>()
.Where(x => x.Persistent && !x.Target.IsDependentType))
{
if (visited.Contains(association))
continue;
visited.Add(association);
List<string> segments = new List<string>();
bool sourceRequired = false;
bool targetRequired = false;
segments.Add($"modelBuilder.Entity<{modelClass.FullName}>()");
switch (association.TargetMultiplicity) // realized by property on source
{
case Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroMany:
{
segments.Add($"HasMany<{association.Target.FullName}>(p => p.{association.TargetPropertyName})");
break;
}
case Sawczyn.EFDesigner.EFModel.Multiplicity.One:
{
segments.Add($"HasOne<{association.Target.FullName}>(p => p.{association.TargetPropertyName})");
targetRequired = true;
break;
}
case Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroOne:
{
segments.Add($"HasOne<{association.Target.FullName}>(p => p.{association.TargetPropertyName})");
break;
}
}
switch (association.SourceMultiplicity) // realized by property on target, but no property on target
{
case Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroMany:
{
segments.Add($"WithMany(p => p.{association.SourcePropertyName})");
if (association.TargetMultiplicity == Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroMany)
{
string tableMap = string.IsNullOrEmpty(association.JoinTableName)
? $"{association.Target.Name}_{association.SourcePropertyName}_x_{association.Source.Name}_{association.TargetPropertyName}"
: association.JoinTableName;
segments.Add($"UsingEntity(x => x.ToTable(\"{tableMap.Trim('"')}\"))");
}
break;
}
case Sawczyn.EFDesigner.EFModel.Multiplicity.One:
{
segments.Add($"WithOne(p => p.{association.SourcePropertyName})");
sourceRequired = true;
break;
}
case Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroOne:
segments.Add($"WithOne(p => p.{association.SourcePropertyName})");
break;
}
string foreignKeySegment = CreateForeignKeySegment(association, foreignKeyColumns);
if (!string.IsNullOrEmpty(foreignKeySegment))
segments.Add(foreignKeySegment);
if (association.Dependent == association.Target)
{
if (association.SourceDeleteAction == DeleteAction.None)
segments.Add("OnDelete(DeleteBehavior.NoAction)");
else if (association.SourceDeleteAction == DeleteAction.Cascade)
segments.Add("OnDelete(DeleteBehavior.Cascade)");
if (targetRequired)
segments.Add("IsRequired()");
}
else if (association.Dependent == association.Source)
{
if (association.TargetDeleteAction == DeleteAction.None)
segments.Add("OnDelete(DeleteBehavior.NoAction)");
else if (association.TargetDeleteAction == DeleteAction.Cascade)
segments.Add("OnDelete(DeleteBehavior.Cascade)");
if (sourceRequired)
segments.Add("IsRequired()");
}
Output(segments);
if (association.Principal == association.Target && targetRequired)
Output($"modelBuilder.Entity<{association.Source.FullName}>().Navigation(e => e.{association.TargetPropertyName}).IsRequired();");
else if (association.Principal == association.Source && sourceRequired)
Output($"modelBuilder.Entity<{association.Target.FullName}>().Navigation(e => e.{association.SourcePropertyName}).IsRequired();");
if (association.TargetAutoInclude)
Output($"modelBuilder.Entity<{association.Source.FullName}>().Navigation(e => e.{association.TargetPropertyName}).AutoInclude();");
else if (association.SourceAutoInclude)
Output($"modelBuilder.Entity<{association.Target.FullName}>().Navigation(e => e.{association.SourcePropertyName}).AutoInclude();");
if (!association.TargetAutoProperty)
{
segments.Add($"modelBuilder.Entity<{association.Source.FullName}>().Navigation(e => e.{association.TargetPropertyName})");
if (association.Source == association.Principal)
{
segments.Add($"HasField(\"{association.TargetBackingFieldName}\")");
segments.Add($"Metadata.SetPropertyAccessMode(PropertyAccessMode.{association.TargetPropertyAccessMode});");
}
else if (association.Target == association.Principal)
{
segments.Add($"HasField(\"{association.TargetBackingFieldName}\")");
segments.Add($"Metadata.SetPropertyAccessMode(PropertyAccessMode.{association.TargetPropertyAccessMode});");
}
else
segments.Add($"HasField(\"{association.TargetBackingFieldName}\");");
Output(segments);
}
if (!association.SourceAutoProperty)
{
segments.Add($"modelBuilder.Entity<{association.Target.FullName}>().Navigation(e => e.{association.SourcePropertyName})");
if (association.Target == association.Principal)
{
segments.Add($"HasField(\"{association.SourceBackingFieldName}\")");
segments.Add($"Metadata.SetPropertyAccessMode(PropertyAccessMode.{association.SourcePropertyAccessMode});");
}
else if (association.Source == association.Principal)
{
segments.Add($"HasField(\"{association.SourceBackingFieldName}\")");
segments.Add($"Metadata.SetPropertyAccessMode(PropertyAccessMode.{association.SourcePropertyAccessMode});");
}
else
segments.Add($"HasField(\"{association.SourceBackingFieldName}\");");
Output(segments);
}
}
}
[SuppressMessage("ReSharper", "RedundantNameQualifier")]
protected override void ConfigureUnidirectionalAssociations(ModelClass modelClass
, List<Association> visited
, List<string> foreignKeyColumns
, List<string> declaredShadowProperties)
{
WriteUnidirectionalNonDependentAssociations(modelClass, visited, foreignKeyColumns);
WriteUnidirectionalDependentAssociations(modelClass, $"modelBuilder.Entity<{modelClass.FullName}>()", visited);
}
protected override void WriteUnidirectionalDependentAssociations(ModelClass sourceInstance, string baseSegment, List<Association> visited)
{
// ReSharper disable once LoopCanBePartlyConvertedToQuery
foreach (UnidirectionalAssociation association in Association.GetLinksToTargets(sourceInstance)
.OfType<UnidirectionalAssociation>()
.Where(x => x.Persistent && x.Target.IsDependentType))
{
if (visited.Contains(association))
continue;
visited.Add(association);
List<string> segments = new List<string>();
string separator = sourceInstance.ModelRoot.ShadowKeyNamePattern == ShadowKeyPattern.TableColumn ? string.Empty : "_";
switch (association.TargetMultiplicity) // realized by property on source
{
case Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroMany:
{
segments.Add(baseSegment);
segments.Add($"OwnsMany(p => p.{association.TargetPropertyName})");
segments.Add($"WithOwner(\"{association.Source.Name}_{association.TargetPropertyName}\")");
segments.Add($"HasForeignKey(\"{association.Source.Name}_{association.TargetPropertyName}{separator}Id\")");
Output(segments);
segments.Add(baseSegment);
segments.Add($"OwnsMany(p => p.{association.TargetPropertyName})");
segments.Add($"Property<{modelRoot.DefaultIdentityType}>(\"Id\")");
Output(segments);
segments.Add(baseSegment);
segments.Add($"OwnsMany(p => p.{association.TargetPropertyName})");
segments.Add("HasKey(\"Id\")");
Output(segments);
WriteUnidirectionalDependentAssociations(association.Target, $"{baseSegment}.OwnsMany(p => p.{association.TargetPropertyName})", visited);
break;
}
case Sawczyn.EFDesigner.EFModel.Multiplicity.One:
{
foreach (ModelAttribute modelAttribute in association.Target.AllAttributes)
{
segments.Add($"{baseSegment}.OwnsOne(p => p.{association.TargetPropertyName}).Property(p => p.{modelAttribute.Name})");
if (modelAttribute.ColumnName != modelAttribute.Name && !string.IsNullOrEmpty(modelAttribute.ColumnName))
segments.Add($"HasColumnName(\"{modelAttribute.ColumnName}\")");
if (modelAttribute.Required)
segments.Add("IsRequired()");
Output(segments);
}
segments.Add(baseSegment);
segments.Add($"Navigation(p => p.{association.TargetPropertyName}).IsRequired()");
Output(segments);
WriteUnidirectionalDependentAssociations(association.Target, $"{baseSegment}.OwnsOne(p => p.{association.TargetPropertyName})", visited);
break;
}
case Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroOne:
{
foreach (ModelAttribute modelAttribute in association.Target.AllAttributes)
{
segments.Add($"{baseSegment}.OwnsOne(p => p.{association.TargetPropertyName}).Property(p => p.{modelAttribute.Name})");
if (modelAttribute.ColumnName != modelAttribute.Name && !string.IsNullOrEmpty(modelAttribute.ColumnName))
segments.Add($"HasColumnName(\"{modelAttribute.ColumnName}\")");
if (modelAttribute.Required)
segments.Add("IsRequired()");
Output(segments);
}
WriteUnidirectionalDependentAssociations(association.Target, $"{baseSegment}.OwnsOne(p => p.{association.TargetPropertyName})", visited);
break;
}
}
}
}
protected override void WriteUnidirectionalNonDependentAssociations(ModelClass modelClass, List<Association> visited, List<string> foreignKeyColumns)
{
// ReSharper disable once LoopCanBePartlyConvertedToQuery
foreach (UnidirectionalAssociation association in Association.GetLinksToTargets(modelClass)
.OfType<UnidirectionalAssociation>()
.Where(x => x.Persistent && !x.Target.IsDependentType))
{
if (visited.Contains(association))
continue;
visited.Add(association);
List<string> segments = new List<string>();
bool sourceRequired = false;
bool targetRequired = false;
segments.Add($"modelBuilder.Entity<{modelClass.FullName}>()");
switch (association.TargetMultiplicity) // realized by property on source
{
case Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroMany:
segments.Add($"HasMany<{association.Target.FullName}>(p => p.{association.TargetPropertyName})");
break;
case Sawczyn.EFDesigner.EFModel.Multiplicity.One:
segments.Add($"HasOne<{association.Target.FullName}>(p => p.{association.TargetPropertyName})");
targetRequired = true;
break;
case Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroOne:
segments.Add($"HasOne<{association.Target.FullName}>(p => p.{association.TargetPropertyName})");
break;
}
switch (association.SourceMultiplicity) // realized by property on target, but no property on target
{
case Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroMany:
segments.Add("WithMany()");
if (association.TargetMultiplicity == Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroMany)
{
string tableMap = string.IsNullOrEmpty(association.JoinTableName)
? $"{association.Target.Name}_x_{association.Source.Name}_{association.TargetPropertyName}"
: association.JoinTableName;
segments.Add($"UsingEntity(x => x.ToTable(\"{tableMap}\"))");
}
break;
case Sawczyn.EFDesigner.EFModel.Multiplicity.One:
segments.Add("WithOne()");
sourceRequired = true;
break;
case Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroOne:
segments.Add("WithOne()");
break;
}
string foreignKeySegment = CreateForeignKeySegment(association, foreignKeyColumns);
if (!string.IsNullOrEmpty(foreignKeySegment))
segments.Add(foreignKeySegment);
if (association.Dependent == association.Target)
{
if (association.SourceDeleteAction == DeleteAction.None)
segments.Add("OnDelete(DeleteBehavior.NoAction)");
else if (association.SourceDeleteAction == DeleteAction.Cascade)
segments.Add("OnDelete(DeleteBehavior.Cascade)");
if (targetRequired)
segments.Add("IsRequired()");
}
else if (association.Dependent == association.Source)
{
if (association.TargetDeleteAction == DeleteAction.None)
segments.Add("OnDelete(DeleteBehavior.NoAction)");
else if (association.TargetDeleteAction == DeleteAction.Cascade)
segments.Add("OnDelete(DeleteBehavior.Cascade)");
if (sourceRequired)
segments.Add("IsRequired()");
}
Output(segments);
if (association.Principal == association.Target && targetRequired)
Output($"modelBuilder.Entity<{association.Source.FullName}>().Navigation(e => e.{association.TargetPropertyName}).IsRequired();");
if (association.TargetAutoInclude)
Output($"modelBuilder.Entity<{association.Source.FullName}>().Navigation(e => e.{association.TargetPropertyName}).AutoInclude();");
if (!association.TargetAutoProperty)
{
segments.Add($"modelBuilder.Entity<{association.Source.FullName}>().Navigation(e => e.{association.TargetPropertyName})");
if (association.Source == association.Principal)
{
segments.Add($"HasField(\"{association.TargetBackingFieldName}\")");
segments.Add($"Metadata.SetPropertyAccessMode(PropertyAccessMode.{association.TargetPropertyAccessMode});");
}
else if (association.Target == association.Principal)
{
segments.Add($"HasField(\"{association.TargetBackingFieldName}\")");
segments.Add($"Metadata.SetPropertyAccessMode(PropertyAccessMode.{association.TargetPropertyAccessMode});");
}
else
segments.Add($"HasField(\"{association.TargetBackingFieldName}\");");
Output(segments);
}
}
}
}
#endregion Template
}
}
| |
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Xml;
namespace SharpDoc.Model
{
/// <summary>
/// Base class for <see cref="IModelReference"/>.
/// </summary>
public abstract class NModelBase : IModelReference, IEquatable<NModelBase>
{
private XmlNode _docNode;
protected NModelBase()
{
SeeAlsos = new List<NSeeAlso>();
Groups = new List<string>();
}
public int Index { get; set; }
/// <summary>
/// Gets or sets the XML generated comment ID.
/// See http://msdn.microsoft.com/en-us/library/fsbx0t7x.aspx for more information.
/// </summary>
/// <value>The id.</value>
public string Id { get; set; }
/// <summary>
/// Gets or sets the file id. THis is a version of the <see cref="IModelReference.Id"/> that
/// can be used for filename.
/// </summary>
/// <value>The file id.</value>
public string PageId { get; set; }
/// <summary>
/// Gets or sets the page title.
/// </summary>
/// <value>
/// The page title.
/// </value>
public string PageTitle { get; set; }
/// <summary>
/// Gets or sets the name of this instance.
/// </summary>
/// <value>The name.</value>
public string Name { get; set; }
/// <summary>
/// Gets or sets the full name of this instance.
/// </summary>
/// <value>The full name.</value>
public string FullName { get; set; }
/// <summary>
/// Gets or sets the category.
/// </summary>
/// <value>
/// The category.
/// </value>
public string Category { get; protected set; }
public IModelReference Assembly { get; set; }
/// <summary>
/// Gets or sets the <see cref="XmlNode"/> extracted from the code comments
/// for a particular member.
/// </summary>
/// <value>The XmlNode doc.</value>
public XmlNode DocNode
{
get { return _docNode; }
set
{
_docNode = value;
OnDocNodeUpdate();
}
}
/// <summary>
/// Gets or sets the description extracted from the <summary> tag of the <see cref="IComment.DocNode"/>.
/// </summary>
/// <value>The description.</value>
public string Description { get; set; }
/// <summary>
/// Gets or sets the un managed API.
/// </summary>
/// <value>
/// The un managed API.
/// </value>
public string UnManagedApi { get; set; }
/// <summary>
/// Gets or sets the un managed API.
/// </summary>
/// <value>
/// The un managed API.
/// </value>
public string UnManagedShortApi { get; set; }
/// <summary>
/// Gets or sets the MSDN id.
/// </summary>
/// <value>
/// The MSDN id.
/// </value>
public string MsdnId { get; set; }
/// <summary>
/// Gets or sets the remarks extracted from the <remarks> tag of the <see cref="IComment.DocNode"/>.
/// </summary>
/// <value>The remarks.</value>
public string Remarks { get; set; }
/// <summary>
/// Gets or sets the topic link.
/// </summary>
/// <value>The topic link.</value>
public NTopic TopicLink { get; set; }
/// <summary>
/// Gets or sets the see alsos.
/// </summary>
/// <value>
/// The see alsos.
/// </value>
public List<NSeeAlso> SeeAlsos { get; set; }
/// <summary>
/// Gets or sets the group APIs.
/// </summary>
/// <value>
/// The group APIs.
/// </value>
public List<string> Groups { get; private set; }
/// <summary>
/// Sets the API group.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="state">if set to <c>true</c> [state].</param>
public void SetApiGroup(string name, bool state)
{
if (state)
{
if (!Groups.Contains(name))
{
Groups.Add(name);
}
}
else
{
Groups.Remove(name);
}
}
/// <summary>
/// Gets or sets a value indicating whether this instance is obsolete.
/// </summary>
/// <value>
/// <c>true</c> if this instance is obsolete; otherwise, <c>false</c>.
/// </value>
public bool IsObsolete { get; set; }
/// <summary>
/// Gets or sets the obsolete message.
/// </summary>
/// <value>
/// The obsolete message.
/// </value>
public string ObsoleteMessage { get; set; }
/// <summary>
/// Called when <see cref="DocNode"/> is updated.
/// </summary>
protected internal virtual void OnDocNodeUpdate()
{
if (DocNode != null)
{
Description = NDocumentApi.GetTag(DocNode, DocTag.Summary);
Remarks = NDocumentApi.GetTag(DocNode, DocTag.Remarks);
UnManagedApi = NDocumentApi.GetTag(DocNode, "unmanaged");
UnManagedShortApi = NDocumentApi.GetTag(DocNode, "unmanaged-short");
MsdnId = NDocumentApi.GetTag(DocNode, "msdn-id");
}
}
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false.
/// </returns>
public bool Equals(NModelBase other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(other.Id, Id);
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (NModelBase)) return false;
return Equals((NModelBase) obj);
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
return (Id != null ? Id.GetHashCode() : 0);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(NModelBase left, NModelBase right)
{
return Equals(left, right);
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(NModelBase left, NModelBase right)
{
return !Equals(left, right);
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using osu.Framework.Logging;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using System.Text;
namespace osu.Framework.Testing
{
internal class DynamicClassCompiler<T> : IDisposable
where T : IDynamicallyCompile
{
public event Action CompilationStarted;
public event Action<Type> CompilationFinished;
public event Action<Exception> CompilationFailed;
private readonly List<FileSystemWatcher> watchers = new List<FileSystemWatcher>();
private readonly HashSet<string> requiredFiles = new HashSet<string>();
private T target;
public void SetRecompilationTarget(T target)
{
if (this.target?.GetType().Name != target?.GetType().Name)
{
requiredFiles.Clear();
referenceBuilder.Reset();
}
this.target = target;
}
private ITypeReferenceBuilder referenceBuilder;
public void Start()
{
if (Debugger.IsAttached)
{
referenceBuilder = new EmptyTypeReferenceBuilder();
Logger.Log("Dynamic compilation disabled (debugger attached).");
return;
}
var di = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
var basePath = getSolutionPath(di);
if (!Directory.Exists(basePath))
{
referenceBuilder = new EmptyTypeReferenceBuilder();
Logger.Log("Dynamic compilation disabled (no solution file found).");
return;
}
#if NET5_0
referenceBuilder = new RoslynTypeReferenceBuilder();
#else
referenceBuilder = new EmptyTypeReferenceBuilder();
#endif
Task.Run(async () =>
{
Logger.Log("Initialising dynamic compilation...");
await referenceBuilder.Initialise(Directory.GetFiles(basePath, "*.sln").First()).ConfigureAwait(false);
foreach (var dir in Directory.GetDirectories(basePath))
{
// only watch directories which house a csproj. this avoids submodules and directories like .git which can contain many files.
if (!Directory.GetFiles(dir, "*.csproj").Any())
continue;
var fsw = new FileSystemWatcher(dir, @"*.cs")
{
EnableRaisingEvents = true,
IncludeSubdirectories = true,
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.CreationTime | NotifyFilters.FileName,
};
fsw.Renamed += onChange;
fsw.Changed += onChange;
fsw.Created += onChange;
watchers.Add(fsw);
}
Logger.Log("Dynamic compilation is now available.");
});
}
private static string getSolutionPath(DirectoryInfo d)
{
if (d == null)
return null;
return d.GetFiles().Any(f => f.Extension == ".sln") ? d.FullName : getSolutionPath(d.Parent);
}
private void onChange(object sender, FileSystemEventArgs args) => Task.Run(async () => await recompileAsync(target?.GetType(), args.FullPath).ConfigureAwait(false));
private int currentVersion;
private bool isCompiling;
private async Task recompileAsync(Type targetType, string changedFile)
{
if (targetType == null || isCompiling || referenceBuilder is EmptyTypeReferenceBuilder)
return;
isCompiling = true;
try
{
while (!checkFileReady(changedFile))
Thread.Sleep(10);
Logger.Log($@"Recompiling {Path.GetFileName(targetType.Name)}...", LoggingTarget.Runtime, LogLevel.Important);
CompilationStarted?.Invoke();
foreach (var f in await referenceBuilder.GetReferencedFiles(targetType, changedFile).ConfigureAwait(false))
requiredFiles.Add(f);
var assemblies = await referenceBuilder.GetReferencedAssemblies(targetType, changedFile).ConfigureAwait(false);
using (var pdbStream = new MemoryStream())
using (var peStream = new MemoryStream())
{
var compilationResult = createCompilation(targetType, requiredFiles, assemblies).Emit(peStream, pdbStream);
if (compilationResult.Success)
{
peStream.Seek(0, SeekOrigin.Begin);
pdbStream.Seek(0, SeekOrigin.Begin);
CompilationFinished?.Invoke(
Assembly.Load(peStream.ToArray(), pdbStream.ToArray()).GetModules()[0].GetTypes().LastOrDefault(t => t.FullName == targetType.FullName)
);
}
else
{
var exceptions = new List<Exception>();
foreach (var diagnostic in compilationResult.Diagnostics)
{
if (diagnostic.Severity < DiagnosticSeverity.Error)
continue;
exceptions.Add(new InvalidOperationException(diagnostic.ToString()));
}
throw new AggregateException(exceptions.ToArray());
}
}
}
catch (Exception ex)
{
CompilationFailed?.Invoke(ex);
}
finally
{
isCompiling = false;
}
}
private CSharpCompilationOptions createCompilationOptions()
{
var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
.WithMetadataImportOptions(MetadataImportOptions.Internal);
// This is an internal property which allows the compiler to ignore accessibility checks.
// https://www.strathweb.com/2018/10/no-internalvisibleto-no-problem-bypassing-c-visibility-rules-with-roslyn/
var topLevelBinderFlagsProperty = typeof(CSharpCompilationOptions).GetProperty("TopLevelBinderFlags", BindingFlags.Instance | BindingFlags.NonPublic);
Debug.Assert(topLevelBinderFlagsProperty != null);
topLevelBinderFlagsProperty.SetValue(options, (uint)1 << 22);
return options;
}
private CSharpCompilation createCompilation(Type targetType, IEnumerable<string> files, IEnumerable<AssemblyReference> assemblies)
{
// ReSharper disable once RedundantExplicitArrayCreation this doesn't compile when the array is empty
var parseOptions = new CSharpParseOptions(preprocessorSymbols: new string[]
{
#if DEBUG
"DEBUG",
#endif
#if TRACE
"TRACE",
#endif
#if RELEASE
"RELEASE",
#endif
}, languageVersion: LanguageVersion.Latest);
// Add the syntax trees for all referenced files.
var syntaxTrees = new List<SyntaxTree>();
foreach (var f in files)
syntaxTrees.Add(CSharpSyntaxTree.ParseText(File.ReadAllText(f, Encoding.UTF8), parseOptions, f, encoding: Encoding.UTF8));
// Add the new assembly version, such that it replaces any existing dynamic assembly.
string assemblyVersion = $"{++currentVersion}.0.*";
syntaxTrees.Add(CSharpSyntaxTree.ParseText($"using System.Reflection; [assembly: AssemblyVersion(\"{assemblyVersion}\")]", parseOptions));
// Add a custom compiler attribute to allow ignoring access checks.
syntaxTrees.Add(CSharpSyntaxTree.ParseText(ignores_access_checks_to_attribute_syntax, parseOptions));
// Ignore access checks for assemblies that have had their internal types referenced.
var ignoreAccessChecksText = new StringBuilder();
ignoreAccessChecksText.AppendLine("using System.Runtime.CompilerServices;");
foreach (var asm in assemblies.Where(asm => asm.IgnoreAccessChecks))
ignoreAccessChecksText.AppendLine($"[assembly: IgnoresAccessChecksTo(\"{asm.Assembly.GetName().Name}\")]");
syntaxTrees.Add(CSharpSyntaxTree.ParseText(ignoreAccessChecksText.ToString(), parseOptions));
// Determine the new assembly name, ensuring that the dynamic suffix is not duplicated.
string assemblyNamespace = targetType.Assembly.GetName().Name?.Replace(".Dynamic", "");
string dynamicNamespace = $"{assemblyNamespace}.Dynamic";
return CSharpCompilation.Create(
dynamicNamespace,
syntaxTrees,
assemblies.Select(asm => asm.GetReference()),
createCompilationOptions()
);
}
/// <summary>
/// Check whether a file has finished being written to.
/// </summary>
private static bool checkFileReady(string filename)
{
try
{
using (FileStream inputStream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None))
return inputStream.Length > 0;
}
catch (Exception)
{
return false;
}
}
#region IDisposable Support
private bool isDisposed;
protected virtual void Dispose(bool disposing)
{
if (!isDisposed)
{
isDisposed = true;
watchers.ForEach(w => w.Dispose());
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
private const string ignores_access_checks_to_attribute_syntax =
@"namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public class IgnoresAccessChecksToAttribute : Attribute
{
public IgnoresAccessChecksToAttribute(string assemblyName)
{
AssemblyName = assemblyName;
}
public string AssemblyName { get; }
}
}";
}
}
| |
#if UNITY_EDITOR || !(UNITY_WEBPLAYER || UNITY_WEBGL)
#region License
/*
* HttpConnection.cs
*
* This code is derived from HttpConnection.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2015 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@novell.com>
*/
#endregion
#region Contributors
/*
* Contributors:
* - Liryna <liryna.stark@gmail.com>
* - Rohan Singh <rohan-singh@hotmail.com>
*/
#endregion
using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace WebSocketSharp.Net
{
internal sealed class HttpConnection
{
#region Private Fields
private byte[] _buffer;
private const int _bufferLength = 8192;
private HttpListenerContext _context;
private bool _contextBound;
private StringBuilder _currentLine;
private InputState _inputState;
private RequestStream _inputStream;
private HttpListener _lastListener;
private LineState _lineState;
private EndPointListener _listener;
private ResponseStream _outputStream;
private int _position;
private HttpListenerPrefix _prefix;
private MemoryStream _requestBuffer;
private int _reuses;
private bool _secure;
private Socket _socket;
private Stream _stream;
private object _sync;
private int _timeout;
private Timer _timer;
#endregion
#region Internal Constructors
internal HttpConnection (Socket socket, EndPointListener listener)
{
_socket = socket;
_listener = listener;
_secure = listener.IsSecure;
var netStream = new NetworkStream (socket, false);
if (_secure) {
var conf = listener.SslConfiguration;
var sslStream = new SslStream (netStream, false, conf.ClientCertificateValidationCallback);
sslStream.AuthenticateAsServer (
conf.ServerCertificate,
conf.ClientCertificateRequired,
conf.EnabledSslProtocols,
conf.CheckCertificateRevocation);
_stream = sslStream;
}
else {
_stream = netStream;
}
_sync = new object ();
_timeout = 90000; // 90k ms for first request, 15k ms from then on.
_timer = new Timer (onTimeout, this, Timeout.Infinite, Timeout.Infinite);
init ();
}
#endregion
#region Public Properties
public bool IsClosed {
get {
return _socket == null;
}
}
public bool IsSecure {
get {
return _secure;
}
}
public IPEndPoint LocalEndPoint {
get {
return (IPEndPoint) _socket.LocalEndPoint;
}
}
public HttpListenerPrefix Prefix {
get {
return _prefix;
}
set {
_prefix = value;
}
}
public IPEndPoint RemoteEndPoint {
get {
return (IPEndPoint) _socket.RemoteEndPoint;
}
}
public int Reuses {
get {
return _reuses;
}
}
public Stream Stream {
get {
return _stream;
}
}
#endregion
#region Private Methods
private void close ()
{
lock (_sync) {
if (_socket == null)
return;
disposeTimer ();
disposeRequestBuffer ();
disposeStream ();
closeSocket ();
}
unbind ();
removeConnection ();
}
private void closeSocket ()
{
try {
_socket.Shutdown (SocketShutdown.Both);
}
catch {
}
_socket.Close ();
_socket = null;
}
private void disposeRequestBuffer ()
{
if (_requestBuffer == null)
return;
_requestBuffer.Dispose ();
_requestBuffer = null;
}
private void disposeStream ()
{
if (_stream == null)
return;
_inputStream = null;
_outputStream = null;
_stream.Dispose ();
_stream = null;
}
private void disposeTimer ()
{
if (_timer == null)
return;
try {
_timer.Change (Timeout.Infinite, Timeout.Infinite);
}
catch {
}
_timer.Dispose ();
_timer = null;
}
private void init ()
{
_context = new HttpListenerContext (this);
_inputState = InputState.RequestLine;
_inputStream = null;
_lineState = LineState.None;
_outputStream = null;
_position = 0;
_prefix = null;
_requestBuffer = new MemoryStream ();
}
private static void onRead (IAsyncResult asyncResult)
{
var conn = (HttpConnection) asyncResult.AsyncState;
if (conn._socket == null)
return;
lock (conn._sync) {
if (conn._socket == null)
return;
var nread = -1;
var len = 0;
try {
conn._timer.Change (Timeout.Infinite, Timeout.Infinite);
nread = conn._stream.EndRead (asyncResult);
conn._requestBuffer.Write (conn._buffer, 0, nread);
len = (int) conn._requestBuffer.Length;
}
catch (Exception ex) {
if (conn._requestBuffer != null && conn._requestBuffer.Length > 0) {
conn.SendError (ex.Message, 400);
return;
}
conn.close ();
return;
}
if (nread <= 0) {
conn.close ();
return;
}
if (conn.processInput (conn._requestBuffer.GetBuffer (), len)) {
if (!conn._context.HasError)
conn._context.Request.FinishInitialization ();
if (conn._context.HasError) {
conn.SendError ();
return;
}
if (!conn._listener.BindContext (conn._context)) {
conn.SendError ("Invalid host", 400);
return;
}
var lsnr = conn._context.Listener;
if (conn._lastListener != lsnr) {
conn.removeConnection ();
lsnr.AddConnection (conn);
conn._lastListener = lsnr;
}
conn._contextBound = true;
lsnr.RegisterContext (conn._context);
return;
}
conn._stream.BeginRead (conn._buffer, 0, _bufferLength, onRead, conn);
}
}
private static void onTimeout (object state)
{
var conn = (HttpConnection) state;
conn.close ();
}
// true -> Done processing.
// false -> Need more input.
private bool processInput (byte[] data, int length)
{
if (_currentLine == null)
_currentLine = new StringBuilder (64);
var nread = 0;
try {
string line;
while ((line = readLineFrom (data, _position, length, out nread)) != null) {
_position += nread;
if (line.Length == 0) {
if (_inputState == InputState.RequestLine)
continue;
if (_position > 32768)
_context.ErrorMessage = "Headers too long";
_currentLine = null;
return true;
}
if (_inputState == InputState.RequestLine) {
_context.Request.SetRequestLine (line);
_inputState = InputState.Headers;
}
else {
_context.Request.AddHeader (line);
}
if (_context.HasError)
return true;
}
}
catch (Exception ex) {
_context.ErrorMessage = ex.Message;
return true;
}
_position += nread;
if (_position >= 32768) {
_context.ErrorMessage = "Headers too long";
return true;
}
return false;
}
private string readLineFrom (byte[] buffer, int offset, int length, out int read)
{
read = 0;
for (var i = offset; i < length && _lineState != LineState.Lf; i++) {
read++;
var b = buffer[i];
if (b == 13)
_lineState = LineState.Cr;
else if (b == 10)
_lineState = LineState.Lf;
else
_currentLine.Append ((char) b);
}
if (_lineState == LineState.Lf) {
_lineState = LineState.None;
var line = _currentLine.ToString ();
_currentLine.Length = 0;
return line;
}
return null;
}
private void removeConnection ()
{
if (_lastListener != null)
_lastListener.RemoveConnection (this);
else
_listener.RemoveConnection (this);
}
private void unbind ()
{
if (!_contextBound)
return;
_listener.UnbindContext (_context);
_contextBound = false;
}
#endregion
#region Internal Methods
internal void Close (bool force)
{
if (_socket == null)
return;
lock (_sync) {
if (_socket == null)
return;
if (!force) {
GetResponseStream ().Close (false);
if (!_context.Response.CloseConnection && _context.Request.FlushInput ()) {
// Don't close. Keep working.
_reuses++;
disposeRequestBuffer ();
unbind ();
init ();
BeginReadRequest ();
return;
}
}
else if (_outputStream != null) {
_outputStream.Close (true);
}
close ();
}
}
#endregion
#region Public Methods
public void BeginReadRequest ()
{
if (_buffer == null)
_buffer = new byte[_bufferLength];
if (_reuses == 1)
_timeout = 15000;
try {
_timer.Change (_timeout, Timeout.Infinite);
_stream.BeginRead (_buffer, 0, _bufferLength, onRead, this);
}
catch {
close ();
}
}
public void Close ()
{
Close (false);
}
public RequestStream GetRequestStream (long contentLength, bool chunked)
{
if (_inputStream != null || _socket == null)
return _inputStream;
lock (_sync) {
if (_socket == null)
return _inputStream;
var buff = _requestBuffer.GetBuffer ();
var len = (int) _requestBuffer.Length;
disposeRequestBuffer ();
if (chunked) {
_context.Response.SendChunked = true;
_inputStream = new ChunkedRequestStream (
_stream, buff, _position, len - _position, _context);
}
else {
_inputStream = new RequestStream (
_stream, buff, _position, len - _position, contentLength);
}
return _inputStream;
}
}
public ResponseStream GetResponseStream ()
{
// TODO: Can we get this stream before reading the input?
if (_outputStream != null || _socket == null)
return _outputStream;
lock (_sync) {
if (_socket == null)
return _outputStream;
var lsnr = _context.Listener;
var ignore = lsnr != null ? lsnr.IgnoreWriteExceptions : true;
_outputStream = new ResponseStream (_stream, _context.Response, ignore);
return _outputStream;
}
}
public void SendError ()
{
SendError (_context.ErrorMessage, _context.ErrorStatus);
}
public void SendError (string message, int status)
{
if (_socket == null)
return;
lock (_sync) {
if (_socket == null)
return;
try {
var res = _context.Response;
res.StatusCode = status;
res.ContentType = "text/html";
var content = new StringBuilder (64);
content.AppendFormat ("<html><body><h1>{0} {1}", status, res.StatusDescription);
if (message != null && message.Length > 0)
content.AppendFormat (" ({0})</h1></body></html>", message);
else
content.Append ("</h1></body></html>");
var enc = Encoding.UTF8;
var entity = enc.GetBytes (content.ToString ());
res.ContentEncoding = enc;
res.ContentLength64 = entity.LongLength;
res.Close (entity, true);
}
catch {
Close (true);
}
}
}
#endregion
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using MVCBlog.Core.Commands;
using MVCBlog.Core.Database;
using MVCBlog.Core.Entities;
using MVCBlog.Website.Models.OutputModels.Blog;
using MvcSiteMapProvider.Web.Mvc.Filters;
using Palmmedia.Common.Linq;
using Palmmedia.Common.Net.Mvc;
namespace MVCBlog.Website.Controllers
{
/// <summary>
/// Controller for the blog.
/// </summary>
public partial class BlogController : Controller
{
/// <summary>
/// Number of <see cref="BlogEntry">BlogEntries</see> per page.
/// </summary>
private const int ENTRIESPERPAGE = 8;
/// <summary>
/// The repository.
/// </summary>
private readonly IRepository repository;
/// <summary>
/// The add blog entry comment command handler.
/// </summary>
private readonly ICommandHandler<AddBlogEntryCommentCommand> addBlogEntryCommentCommandHandler;
/// <summary>
/// The delete blog entry comment command hander.
/// </summary>
private readonly ICommandHandler<DeleteCommand<BlogEntryComment>> deleteBlogEntryCommentCommandHander;
/// <summary>
/// The delete blog entry command hander.
/// </summary>
private readonly ICommandHandler<DeleteBlogEntryCommand> deleteBlogEntryCommandHander;
/// <summary>
/// The update blog entry command handler.
/// </summary>
private readonly ICommandHandler<UpdateCommand<BlogEntry>> updateBlogEntryCommandHandler;
/// <summary>
/// The update blog entry file command handler.
/// </summary>
private readonly ICommandHandler<UpdateCommand<BlogEntryFile>> updateBlogEntryFileCommandHandler;
/// <summary>
/// Initializes a new instance of the <see cref="BlogController" /> class.
/// </summary>
/// <param name="repository">The repository.</param>
/// <param name="addBlogEntryCommentCommandHandler">The add blog entry comment command handler.</param>
/// <param name="deleteBlogEntryCommentCommandHander">The delete blog entry comment command hander.</param>
/// <param name="deleteBlogEntryCommandHander">The delete blog entry command hander.</param>
/// <param name="updateBlogEntryCommandHandler">The update blog entry command handler.</param>
/// <param name="updateBlogEntryFileCommandHandler">The update blog entry file command handler.</param>
public BlogController(
IRepository repository,
ICommandHandler<AddBlogEntryCommentCommand> addBlogEntryCommentCommandHandler,
ICommandHandler<DeleteCommand<BlogEntryComment>> deleteBlogEntryCommentCommandHander,
ICommandHandler<DeleteBlogEntryCommand> deleteBlogEntryCommandHander,
ICommandHandler<UpdateCommand<BlogEntry>> updateBlogEntryCommandHandler,
ICommandHandler<UpdateCommand<BlogEntryFile>> updateBlogEntryFileCommandHandler)
{
this.repository = repository;
this.addBlogEntryCommentCommandHandler = addBlogEntryCommentCommandHandler;
this.deleteBlogEntryCommentCommandHander = deleteBlogEntryCommentCommandHander;
this.deleteBlogEntryCommandHander = deleteBlogEntryCommandHander;
this.updateBlogEntryCommandHandler = updateBlogEntryCommandHandler;
this.updateBlogEntryFileCommandHandler = updateBlogEntryFileCommandHandler;
}
/// <summary>
/// Shows all <see cref="BlogEntry">BlogEntries</see>.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="search">The search.</param>
/// <param name="page">Number of the page.</param>
/// <returns>A view showing all <see cref="BlogEntry">BlogEntries</see>.</returns>
[ValidateInput(false)]
public virtual ActionResult Index(string tag, string search, int? page)
{
var entries = this.GetAll(
tag,
search,
new Paging(page.GetValueOrDefault(1), ENTRIESPERPAGE, PropertyResolver.GetPropertyName<BlogEntry>(b => b.PublishDate), SortDirection.Descending));
var model = new IndexModel();
model.Entries = entries.ToArray();
model.TotalPages = (int)Math.Ceiling((double)entries.TotalNumberOfItems / ENTRIESPERPAGE);
model.CurrentPage = page;
model.Tag = tag;
model.Search = search;
return this.View(model);
}
/// <summary>
/// Shows a single <see cref="BlogEntry"/>.
/// </summary>
/// <param name="id">The id.</param>
/// <returns>A view showing a single <see cref="BlogEntry"/>.</returns>
[SiteMapTitle("Header")]
public async virtual Task<ActionResult> Entry(string id)
{
var entry = await this.GetByHeader(id);
if (entry == null)
{
return new HttpNotFoundWithViewResult(MVC.Shared.Views.NotFound);
}
if (!this.Request.IsAuthenticated)
{
entry.Visits++;
await this.updateBlogEntryCommandHandler.HandleAsync(new UpdateCommand<BlogEntry>()
{
Entity = entry
});
}
return this.View(new BlogEntryDetail()
{
BlogEntry = entry,
RelatedBlogEntries = await this.GetRelatedBlogEntries(entry)
});
}
/// <summary>
/// Adds a <see cref="Comment"/> to a <see cref="BlogEntry"/>.
/// </summary>
/// <param name="id">The id.</param>
/// <param name="blogEntryComment">The comment.</param>
/// <returns>A view showing a single <see cref="BlogEntry"/>.</returns>
[SiteMapTitle("Header")]
[Palmmedia.Common.Net.Mvc.SpamProtection(4)]
[ValidateAntiForgeryToken]
[HttpPost]
public async virtual Task<ActionResult> Entry(string id, [Bind(Include = "Name, Email, Homepage, Comment")] BlogEntryComment blogEntryComment)
{
var entry = await this.GetByHeader(id);
if (entry == null)
{
return new HttpNotFoundResult();
}
this.ModelState.Remove("BlogEntryId");
if (!ModelState.IsValid)
{
var errorModel = new BlogEntryDetail()
{
BlogEntry = entry
};
if (this.Request.IsAjaxRequest())
{
return this.PartialView(MVC.Blog.Views._CommentsControl, errorModel);
}
else
{
errorModel.RelatedBlogEntries = await this.GetRelatedBlogEntries(entry);
return this.View(errorModel);
}
}
blogEntryComment.AdminPost = this.Request.IsAuthenticated;
blogEntryComment.BlogEntryId = entry.Id;
entry.BlogEntryComments.Add(blogEntryComment);
await this.addBlogEntryCommentCommandHandler.HandleAsync(new AddBlogEntryCommentCommand()
{
Entity = blogEntryComment
});
var model = new BlogEntryDetail()
{
BlogEntry = entry,
HideNewCommentsForm = true
};
if (this.Request.IsAjaxRequest())
{
return this.PartialView(MVC.Blog.Views._CommentsControl, model);
}
else
{
model.RelatedBlogEntries = await this.GetRelatedBlogEntries(entry);
return this.View(model);
}
}
/// <summary>
/// Shows a tag cloud.
/// </summary>
/// <returns>A view showing a tag cloud.</returns>
[ChildActionOnly]
[OutputCache(Duration = 3600)]
public async virtual Task<ActionResult> Tags()
{
var tags = await this.repository.Tags
.AsNoTracking()
.OrderBy(t => t.Name)
.ToArrayAsync();
if (tags.Length > 0)
{
return this.PartialView(MVC.Shared.Views._TagListControl, tags);
}
else
{
return new EmptyResult();
}
}
/// <summary>
/// Shows the most populars the blog entries.
/// </summary>
/// <returns>A view showing the most populars the blog entries.</returns>
[ChildActionOnly]
[OutputCache(Duration = 3600)]
public async virtual Task<ActionResult> PopularBlogEntries()
{
var blogEntries = await this.repository.BlogEntries
.AsNoTracking()
.OrderByDescending(b => b.Visits)
.Take(5)
.ToArrayAsync();
if (blogEntries.Length > 0)
{
return this.PartialView(MVC.Shared.Views._PopularBlogEntriesControl, blogEntries);
}
else
{
return new EmptyResult();
}
}
/// <summary>
/// Returns an RSS-Feed of all <see cref="BlogEntry">BlogEntries</see>.
/// </summary>
/// <returns>RSS-Feed of all <see cref="BlogEntry">BlogEntries</see>.</returns>
[OutputCache(CacheProfile = "Long")]
public async virtual Task<ActionResult> Feed()
{
var entries = await this.repository.BlogEntries
.Include(b => b.Tags)
.AsNoTracking()
.Where(b => b.Visible && b.PublishDate <= DateTime.Now)
.OrderByDescending(b => b.PublishDate)
.ToArrayAsync();
string baseUrl = this.Request.Url.GetLeftPart(UriPartial.Authority);
var feed = new SyndicationFeed(
ConfigurationManager.AppSettings["BlogName"],
ConfigurationManager.AppSettings["BlogDescription"],
new Uri(this.Request.Url.GetLeftPart(UriPartial.Authority) + Url.Action(MVC.Blog.Feed())));
feed.BaseUri = new Uri(baseUrl);
if (entries.Any())
{
DateTime createdDate = entries.First().PublishDate;
DateTime? lastModifiedDate = entries.OrderByDescending(e => e.Modified).First().Modified;
if (lastModifiedDate.HasValue && lastModifiedDate.Value > createdDate)
{
feed.LastUpdatedTime = lastModifiedDate.Value;
}
else
{
feed.LastUpdatedTime = createdDate;
}
}
var feedItems = new List<SyndicationItem>();
foreach (var blogEntry in entries)
{
var syndicationItem = new SyndicationItem(
blogEntry.Header,
SyndicationContent.CreateXhtmlContent(blogEntry.ShortContent + blogEntry.Content),
new Uri(baseUrl + Url.Action(blogEntry.Url)),
blogEntry.Id.ToString(),
blogEntry.Modified.HasValue ? blogEntry.Modified.Value : blogEntry.PublishDate);
if (!string.IsNullOrEmpty(blogEntry.Author))
{
syndicationItem.Authors.Add(new SyndicationPerson() { Name = blogEntry.Author });
}
foreach (var tag in blogEntry.Tags)
{
syndicationItem.Categories.Add(new SyndicationCategory(tag.Name));
}
feedItems.Add(syndicationItem);
}
feed.Items = feedItems;
return new Palmmedia.Common.Net.Mvc.Feed.RssSyndicationFeedActionResult(feed);
}
/// <summary>
/// Deletes the <see cref="BlogEntry"/> with the given id.
/// </summary>
/// <param name="id">The id.</param>
/// <returns>A view showing all <see cref="BlogEntry">BlogEntries</see>.</returns>
[Authorize]
public async virtual Task<ActionResult> Delete(Guid id)
{
await this.deleteBlogEntryCommandHander.HandleAsync(new DeleteBlogEntryCommand()
{
Id = id
});
return this.RedirectToAction(MVC.Blog.Index());
}
/// <summary>
/// Deletes the <see cref="Comment"/> with the given id.
/// </summary>
/// <param name="id">The id.</param>
/// <returns>A view showing all <see cref="BlogEntry">BlogEntries</see>.</returns>
[Authorize]
public async virtual Task<ActionResult> DeleteComment(Guid id)
{
await this.deleteBlogEntryCommentCommandHander.HandleAsync(new DeleteCommand<BlogEntryComment>()
{
Id = id
});
return this.Redirect(this.Request.UrlReferrer.ToString());
}
/// <summary>
/// Streams the <see cref="BlogEntryFile"/> with the given id.
/// </summary>
/// <param name="id">The id.</param>
/// <returns>The <see cref="BlogEntryFile"/> as Download.</returns>
public async virtual Task<ActionResult> Download(Guid id)
{
var blogEntryFile = await this.repository.BlogEntryFiles
.AsNoTracking()
.SingleOrDefaultAsync(b => b.Id == id);
if (blogEntryFile == null)
{
return new HttpNotFoundWithViewResult(MVC.Shared.Views.NotFound);
}
blogEntryFile.Counter++;
await this.updateBlogEntryFileCommandHandler.HandleAsync(new UpdateCommand<BlogEntryFile>()
{
Entity = blogEntryFile
});
var file = new FileContentResult(blogEntryFile.Data, "application/octet-stream");
file.FileDownloadName = blogEntryFile.Name + "." + blogEntryFile.Extension;
return file;
}
/// <summary>
/// Shows the imprint.
/// </summary>
/// <returns>The imprint view.</returns>
public virtual ActionResult Imprint()
{
return this.View();
}
/// <summary>
/// Returns the <see cref="BlogEntry"/> with the given header.
/// </summary>
/// <param name="header">The header.</param>
/// <returns>
/// The <see cref="BlogEntry"/> with the given header.
/// </returns>
private Task<BlogEntry> GetByHeader(string header)
{
var entry = this.repository.BlogEntries
.Include(b => b.Tags)
.Include(b => b.BlogEntryComments)
.Include(b => b.BlogEntryFiles)
.Include(b => b.BlogEntryPingbacks)
.AsNoTracking()
.Where(e => (e.Visible && e.PublishDate <= DateTime.Now) || this.Request.IsAuthenticated)
.SingleOrDefaultAsync(e => e.HeaderUrl.Equals(header));
return entry;
}
/// <summary>
/// Returns all <see cref="BlogEntry">BlogEntries</see>.
/// </summary>
/// <param name="tag">The text of the tag.</param>
/// <param name="search">The search.</param>
/// <param name="paging">The <see cref="Paging"/>.</param>
/// <returns>
/// All <see cref="BlogEntry">BlogEntries</see>.
/// </returns>
private PagedResult<BlogEntry> GetAll(string tag, string search, Paging paging)
{
var query = this.repository.BlogEntries
.Include(b => b.BlogEntryComments)
.AsNoTracking()
.Where(e => (e.Visible && e.PublishDate <= DateTime.Now) || this.Request.IsAuthenticated);
if (!string.IsNullOrEmpty(tag))
{
query = query.Where(e => e.Tags.Count(t => t.Name.Equals(tag, StringComparison.OrdinalIgnoreCase)) > 0);
}
if (!string.IsNullOrEmpty(search))
{
foreach (var item in search.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Where(e => e.Header.Contains(item));
}
}
return query.GetPagedResult(paging);
}
/// <summary>
/// Returns related <see cref="BlogEntry">BlogEntries</see>.
/// </summary>
/// <param name="entry">The <see cref="BlogEntry"/>.</param>
/// <returns>
/// The related <see cref="BlogEntry">BlogEntries</see>.
/// </returns>
private Task<BlogEntry[]> GetRelatedBlogEntries(BlogEntry entry)
{
var tagIds = entry.Tags.Select(t => t.Id).ToArray();
var query = this.repository.BlogEntries
.AsNoTracking()
.Where(e => e.Visible && e.PublishDate <= DateTime.Now && e.Id != entry.Id)
.Where(e => e.Tags.Any(t => tagIds.Contains(t.Id)))
.OrderByDescending(e => e.Tags.Count(t => tagIds.Contains(t.Id)))
.ThenByDescending(e => e.Created)
.Take(3)
.ToArrayAsync();
return query;
}
}
}
| |
namespace NotifierForYT
{
partial class YouTubeNotifier
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
private const string AppTitle = "Notifier for YouTube";
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.defaultMenu = new System.Windows.Forms.ContextMenuStrip(this.components);
this.activitiesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.clearActivitiesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.usersToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.settingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.refreshTimer = new System.Windows.Forms.Timer(this.components);
this.tabPageSettings = new System.Windows.Forms.TabPage();
this.UpdateFrequency = new System.Windows.Forms.NumericUpDown();
this.label7 = new System.Windows.Forms.Label();
this.label8 = new System.Windows.Forms.Label();
this.notifcationBalloons = new System.Windows.Forms.NumericUpDown();
this.isAuthenticated = new System.Windows.Forms.CheckBox();
this.ButtonIgnore = new System.Windows.Forms.Button();
this.ButtonSaveSettings = new System.Windows.Forms.Button();
this.label6 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.InitialDataPullTime = new System.Windows.Forms.NumericUpDown();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.passWord = new System.Windows.Forms.TextBox();
this.userName = new System.Windows.Forms.TextBox();
this.tabPageActivities = new System.Windows.Forms.TabPage();
this.linkList = new System.Windows.Forms.FlowLayoutPanel();
this.tabControl = new System.Windows.Forms.TabControl();
this.tabPageUsers = new System.Windows.Forms.TabPage();
this.label9 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.usernameGrid = new System.Windows.Forms.DataGridView();
this.YTUser = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.defaultMenu.SuspendLayout();
this.tabPageSettings.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.UpdateFrequency)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.notifcationBalloons)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.InitialDataPullTime)).BeginInit();
this.tabPageActivities.SuspendLayout();
this.tabControl.SuspendLayout();
this.tabPageUsers.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.usernameGrid)).BeginInit();
this.SuspendLayout();
//
// defaultMenu
//
this.defaultMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.activitiesToolStripMenuItem,
this.clearActivitiesToolStripMenuItem,
this.usersToolStripMenuItem,
this.settingsToolStripMenuItem,
this.exitToolStripMenuItem});
this.defaultMenu.Name = "defaultMenu";
this.defaultMenu.Size = new System.Drawing.Size(183, 114);
//
// activitiesToolStripMenuItem
//
this.activitiesToolStripMenuItem.Name = "activitiesToolStripMenuItem";
this.activitiesToolStripMenuItem.Size = new System.Drawing.Size(182, 22);
this.activitiesToolStripMenuItem.Text = "&Activities";
this.activitiesToolStripMenuItem.Click += new System.EventHandler(this.activitiesToolStripMenuItem_Click);
//
// clearActivitiesToolStripMenuItem
//
this.clearActivitiesToolStripMenuItem.Name = "clearActivitiesToolStripMenuItem";
this.clearActivitiesToolStripMenuItem.Size = new System.Drawing.Size(182, 22);
this.clearActivitiesToolStripMenuItem.Text = "&Clear activities";
this.clearActivitiesToolStripMenuItem.Click += new System.EventHandler(this.clearActivitiesToolStripMenuItem_Click);
//
// usersToolStripMenuItem
//
this.usersToolStripMenuItem.Name = "usersToolStripMenuItem";
this.usersToolStripMenuItem.Size = new System.Drawing.Size(182, 22);
this.usersToolStripMenuItem.Text = "&Users";
this.usersToolStripMenuItem.Click += new System.EventHandler(this.usersToolStripMenuItem_Click);
//
// settingsToolStripMenuItem
//
this.settingsToolStripMenuItem.Name = "settingsToolStripMenuItem";
this.settingsToolStripMenuItem.Size = new System.Drawing.Size(182, 22);
this.settingsToolStripMenuItem.Text = "&Settings";
this.settingsToolStripMenuItem.Click += new System.EventHandler(this.settingsToolStripMenuItem_Click);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(182, 22);
this.exitToolStripMenuItem.Text = "&Exit";
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// refreshTimer
//
this.refreshTimer.Interval = 900000;
this.refreshTimer.Tick += new System.EventHandler(this.refreshTimer_Tick);
//
// tabPageSettings
//
this.tabPageSettings.Controls.Add(this.UpdateFrequency);
this.tabPageSettings.Controls.Add(this.label7);
this.tabPageSettings.Controls.Add(this.label8);
this.tabPageSettings.Controls.Add(this.notifcationBalloons);
this.tabPageSettings.Controls.Add(this.isAuthenticated);
this.tabPageSettings.Controls.Add(this.ButtonIgnore);
this.tabPageSettings.Controls.Add(this.ButtonSaveSettings);
this.tabPageSettings.Controls.Add(this.label6);
this.tabPageSettings.Controls.Add(this.label5);
this.tabPageSettings.Controls.Add(this.label4);
this.tabPageSettings.Controls.Add(this.label3);
this.tabPageSettings.Controls.Add(this.InitialDataPullTime);
this.tabPageSettings.Controls.Add(this.label2);
this.tabPageSettings.Controls.Add(this.label1);
this.tabPageSettings.Controls.Add(this.passWord);
this.tabPageSettings.Controls.Add(this.userName);
this.tabPageSettings.Location = new System.Drawing.Point(4, 25);
this.tabPageSettings.Name = "tabPageSettings";
this.tabPageSettings.Padding = new System.Windows.Forms.Padding(3);
this.tabPageSettings.Size = new System.Drawing.Size(392, 339);
this.tabPageSettings.TabIndex = 1;
this.tabPageSettings.Text = "Settings";
this.tabPageSettings.UseVisualStyleBackColor = true;
//
// UpdateFrequency
//
this.UpdateFrequency.Location = new System.Drawing.Point(11, 195);
this.UpdateFrequency.Maximum = new decimal(new int[] {
90,
0,
0,
0});
this.UpdateFrequency.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.UpdateFrequency.Name = "UpdateFrequency";
this.UpdateFrequency.Size = new System.Drawing.Size(69, 22);
this.UpdateFrequency.TabIndex = 16;
this.UpdateFrequency.Value = new decimal(new int[] {
15,
0,
0,
0});
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(8, 220);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(212, 17);
this.label7.TabIndex = 15;
this.label7.Text = "Display notification balloons for: ";
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(99, 248);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(61, 17);
this.label8.TabIndex = 14;
this.label8.Text = "seconds";
//
// notifcationBalloons
//
this.notifcationBalloons.Location = new System.Drawing.Point(11, 243);
this.notifcationBalloons.Maximum = new decimal(new int[] {
30,
0,
0,
0});
this.notifcationBalloons.Minimum = new decimal(new int[] {
10,
0,
0,
0});
this.notifcationBalloons.Name = "notifcationBalloons";
this.notifcationBalloons.Size = new System.Drawing.Size(69, 22);
this.notifcationBalloons.TabIndex = 13;
this.notifcationBalloons.Value = new decimal(new int[] {
10,
0,
0,
0});
//
// isAuthenticated
//
this.isAuthenticated.AutoSize = true;
this.isAuthenticated.Enabled = false;
this.isAuthenticated.Location = new System.Drawing.Point(148, 97);
this.isAuthenticated.Name = "isAuthenticated";
this.isAuthenticated.Size = new System.Drawing.Size(229, 21);
this.isAuthenticated.TabIndex = 12;
this.isAuthenticated.Text = "You are currently authenticated";
this.isAuthenticated.UseVisualStyleBackColor = true;
//
// ButtonIgnore
//
this.ButtonIgnore.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.ButtonIgnore.Location = new System.Drawing.Point(148, 292);
this.ButtonIgnore.Name = "ButtonIgnore";
this.ButtonIgnore.Size = new System.Drawing.Size(110, 29);
this.ButtonIgnore.TabIndex = 11;
this.ButtonIgnore.Text = "&Cancel";
this.ButtonIgnore.UseVisualStyleBackColor = true;
this.ButtonIgnore.Click += new System.EventHandler(this.ButtonIgnore_Click);
//
// ButtonSaveSettings
//
this.ButtonSaveSettings.DialogResult = System.Windows.Forms.DialogResult.OK;
this.ButtonSaveSettings.Location = new System.Drawing.Point(266, 292);
this.ButtonSaveSettings.Name = "ButtonSaveSettings";
this.ButtonSaveSettings.Size = new System.Drawing.Size(110, 29);
this.ButtonSaveSettings.TabIndex = 10;
this.ButtonSaveSettings.Text = "&Save";
this.ButtonSaveSettings.UseVisualStyleBackColor = true;
this.ButtonSaveSettings.Click += new System.EventHandler(this.ButtonSaveSettings_Click);
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(8, 172);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(262, 17);
this.label6.TabIndex = 9;
this.label6.Text = "After that, check for new activities every:";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(8, 121);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(238, 17);
this.label5.TabIndex = 8;
this.label5.Text = "On Startup, get activities for the last:";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(99, 200);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(57, 17);
this.label4.TabIndex = 7;
this.label4.Text = "minutes";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(99, 152);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(44, 17);
this.label3.TabIndex = 6;
this.label3.Text = "hours";
//
// InitialDataPullTime
//
this.InitialDataPullTime.Location = new System.Drawing.Point(11, 147);
this.InitialDataPullTime.Name = "InitialDataPullTime";
this.InitialDataPullTime.Size = new System.Drawing.Size(69, 22);
this.InitialDataPullTime.TabIndex = 4;
this.InitialDataPullTime.Value = new decimal(new int[] {
24,
0,
0,
0});
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(8, 71);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(135, 17);
this.label2.TabIndex = 3;
this.label2.Text = "YouTube Password:";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(8, 31);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(139, 17);
this.label1.TabIndex = 2;
this.label1.Text = "YouTube Username:";
//
// passWord
//
this.passWord.Location = new System.Drawing.Point(148, 68);
this.passWord.Name = "passWord";
this.passWord.Size = new System.Drawing.Size(220, 22);
this.passWord.TabIndex = 1;
this.passWord.UseSystemPasswordChar = true;
this.passWord.TextChanged += new System.EventHandler(this.passWord_TextChanged);
//
// userName
//
this.userName.Location = new System.Drawing.Point(148, 31);
this.userName.Name = "userName";
this.userName.Size = new System.Drawing.Size(220, 22);
this.userName.TabIndex = 0;
this.userName.TextChanged += new System.EventHandler(this.userName_TextChanged);
//
// tabPageActivities
//
this.tabPageActivities.Controls.Add(this.linkList);
this.tabPageActivities.Location = new System.Drawing.Point(4, 25);
this.tabPageActivities.Name = "tabPageActivities";
this.tabPageActivities.Padding = new System.Windows.Forms.Padding(3);
this.tabPageActivities.Size = new System.Drawing.Size(392, 339);
this.tabPageActivities.TabIndex = 0;
this.tabPageActivities.Text = "Activities";
this.tabPageActivities.UseVisualStyleBackColor = true;
//
// linkList
//
this.linkList.AutoScroll = true;
this.linkList.Dock = System.Windows.Forms.DockStyle.Fill;
this.linkList.FlowDirection = System.Windows.Forms.FlowDirection.TopDown;
this.linkList.Location = new System.Drawing.Point(3, 3);
this.linkList.Name = "linkList";
this.linkList.Padding = new System.Windows.Forms.Padding(5, 0, 0, 0);
this.linkList.Size = new System.Drawing.Size(386, 333);
this.linkList.TabIndex = 1;
this.linkList.WrapContents = false;
//
// tabControl
//
this.tabControl.Controls.Add(this.tabPageActivities);
this.tabControl.Controls.Add(this.tabPageUsers);
this.tabControl.Controls.Add(this.tabPageSettings);
this.tabControl.Dock = System.Windows.Forms.DockStyle.Fill;
this.tabControl.Location = new System.Drawing.Point(0, 0);
this.tabControl.Name = "tabControl";
this.tabControl.SelectedIndex = 0;
this.tabControl.Size = new System.Drawing.Size(400, 368);
this.tabControl.TabIndex = 0;
//
// tabPageUsers
//
this.tabPageUsers.Controls.Add(this.label9);
this.tabPageUsers.Controls.Add(this.button1);
this.tabPageUsers.Controls.Add(this.usernameGrid);
this.tabPageUsers.Location = new System.Drawing.Point(4, 25);
this.tabPageUsers.Name = "tabPageUsers";
this.tabPageUsers.Padding = new System.Windows.Forms.Padding(3);
this.tabPageUsers.Size = new System.Drawing.Size(392, 339);
this.tabPageUsers.TabIndex = 2;
this.tabPageUsers.Text = "Users";
this.tabPageUsers.UseVisualStyleBackColor = true;
//
// label9
//
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(26, 303);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(234, 17);
this.label9.TabIndex = 12;
this.label9.Text = "Enter a list of max 20 youtube users";
//
// button1
//
this.button1.DialogResult = System.Windows.Forms.DialogResult.OK;
this.button1.Location = new System.Drawing.Point(265, 297);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(110, 29);
this.button1.TabIndex = 11;
this.button1.Text = "&Save";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// usernameGrid
//
this.usernameGrid.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.usernameGrid.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.YTUser});
this.usernameGrid.Location = new System.Drawing.Point(8, 15);
this.usernameGrid.Name = "usernameGrid";
this.usernameGrid.RowTemplate.Height = 24;
this.usernameGrid.Size = new System.Drawing.Size(376, 276);
this.usernameGrid.TabIndex = 0;
this.usernameGrid.UserAddedRow += new System.Windows.Forms.DataGridViewRowEventHandler(this.usernameGrid_UserAddedRow);
//
// YTUser
//
this.YTUser.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.YTUser.HeaderText = "YouTube Username";
this.YTUser.MaxInputLength = 255;
this.YTUser.Name = "YTUser";
//
// YouTubeNotifier
//
this.AcceptButton = this.ButtonSaveSettings;
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.ButtonIgnore;
this.ClientSize = new System.Drawing.Size(400, 368);
this.Controls.Add(this.tabControl);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "YouTubeNotifier";
this.ShowInTaskbar = false;
this.Text = "Notifier for YouTube";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.YouTubeNotifier_FormClosing);
this.Resize += new System.EventHandler(this.YouTubeNotifier_Resize);
this.defaultMenu.ResumeLayout(false);
this.tabPageSettings.ResumeLayout(false);
this.tabPageSettings.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.UpdateFrequency)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.notifcationBalloons)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.InitialDataPullTime)).EndInit();
this.tabPageActivities.ResumeLayout(false);
this.tabControl.ResumeLayout(false);
this.tabPageUsers.ResumeLayout(false);
this.tabPageUsers.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.usernameGrid)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ContextMenuStrip defaultMenu;
private System.Windows.Forms.ToolStripMenuItem settingsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem activitiesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem clearActivitiesToolStripMenuItem;
private System.Windows.Forms.Timer refreshTimer;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.TabPage tabPageSettings;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.NumericUpDown notifcationBalloons;
private System.Windows.Forms.CheckBox isAuthenticated;
private System.Windows.Forms.Button ButtonIgnore;
private System.Windows.Forms.Button ButtonSaveSettings;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.NumericUpDown InitialDataPullTime;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox passWord;
private System.Windows.Forms.TextBox userName;
private System.Windows.Forms.TabPage tabPageActivities;
private System.Windows.Forms.FlowLayoutPanel linkList;
private System.Windows.Forms.TabControl tabControl;
private System.Windows.Forms.NumericUpDown UpdateFrequency;
private System.Windows.Forms.TabPage tabPageUsers;
private System.Windows.Forms.DataGridView usernameGrid;
private System.Windows.Forms.DataGridViewTextBoxColumn YTUser;
private System.Windows.Forms.DataGridViewTextBoxColumn acceptButtonDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewCheckBoxColumn autoScrollDataGridViewCheckBoxColumn;
private System.Windows.Forms.DataGridViewCheckBoxColumn autoSizeDataGridViewCheckBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn autoSizeModeDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn autoValidateDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn backColorDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn formBorderStyleDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn cancelButtonDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewCheckBoxColumn controlBoxDataGridViewCheckBoxColumn;
private System.Windows.Forms.DataGridViewCheckBoxColumn helpButtonDataGridViewCheckBoxColumn;
private System.Windows.Forms.DataGridViewImageColumn iconDataGridViewImageColumn;
private System.Windows.Forms.DataGridViewCheckBoxColumn isMdiContainerDataGridViewCheckBoxColumn;
private System.Windows.Forms.DataGridViewCheckBoxColumn keyPreviewDataGridViewCheckBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn locationDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn maximumSizeDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn mainMenuStripDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn minimumSizeDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewCheckBoxColumn maximizeBoxDataGridViewCheckBoxColumn;
private System.Windows.Forms.DataGridViewCheckBoxColumn minimizeBoxDataGridViewCheckBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn opacityDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewCheckBoxColumn rightToLeftLayoutDataGridViewCheckBoxColumn;
private System.Windows.Forms.DataGridViewCheckBoxColumn showInTaskbarDataGridViewCheckBoxColumn;
private System.Windows.Forms.DataGridViewCheckBoxColumn showIconDataGridViewCheckBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn sizeDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn sizeGripStyleDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn startPositionDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn textDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewCheckBoxColumn topMostDataGridViewCheckBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn transparencyKeyDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn windowStateDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn autoScrollMarginDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn autoScrollMinSizeDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn accessibleDescriptionDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn accessibleNameDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn accessibleRoleDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewCheckBoxColumn allowDropDataGridViewCheckBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn anchorDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewImageColumn backgroundImageDataGridViewImageColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn backgroundImageLayoutDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewCheckBoxColumn causesValidationDataGridViewCheckBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn contextMenuStripDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn cursorDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn dataBindingsDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn dockDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewCheckBoxColumn enabledDataGridViewCheckBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn fontDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn foreColorDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn rightToLeftDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn tagDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewCheckBoxColumn useWaitCursorDataGridViewCheckBoxColumn;
private System.Windows.Forms.DataGridViewCheckBoxColumn visibleDataGridViewCheckBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn paddingDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn imeModeDataGridViewTextBoxColumn;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.ToolStripMenuItem usersToolStripMenuItem;
}
}
| |
/*
* Infoplus API
*
* Infoplus API.
*
* OpenAPI spec version: v1.0
* Contact: api@infopluscommerce.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using RestSharp;
using Infoplus.Client;
using Infoplus.Model;
namespace Infoplus.Api
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IPickFaceAssignmentApi : IApiAccessor
{
#region Synchronous Operations
/// <summary>
/// Create a pickFaceAssignment
/// </summary>
/// <remarks>
/// Inserts a new pickFaceAssignment using the specified data.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">PickFaceAssignment to be inserted.</param>
/// <returns>PickFaceAssignment</returns>
PickFaceAssignment AddPickFaceAssignment (PickFaceAssignment body);
/// <summary>
/// Create a pickFaceAssignment
/// </summary>
/// <remarks>
/// Inserts a new pickFaceAssignment using the specified data.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">PickFaceAssignment to be inserted.</param>
/// <returns>ApiResponse of PickFaceAssignment</returns>
ApiResponse<PickFaceAssignment> AddPickFaceAssignmentWithHttpInfo (PickFaceAssignment body);
/// <summary>
/// Delete a pickFaceAssignment
/// </summary>
/// <remarks>
/// Deletes the pickFaceAssignment identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="pickFaceAssignmentId">Id of the pickFaceAssignment to be deleted.</param>
/// <returns></returns>
void DeletePickFaceAssignment (int? pickFaceAssignmentId);
/// <summary>
/// Delete a pickFaceAssignment
/// </summary>
/// <remarks>
/// Deletes the pickFaceAssignment identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="pickFaceAssignmentId">Id of the pickFaceAssignment to be deleted.</param>
/// <returns>ApiResponse of Object(void)</returns>
ApiResponse<Object> DeletePickFaceAssignmentWithHttpInfo (int? pickFaceAssignmentId);
/// <summary>
/// Search pickFaceAssignments by filter
/// </summary>
/// <remarks>
/// Returns the list of pickFaceAssignments that match the given filter.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Query string, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <param name="sort">Sort results by specified field. (optional)</param>
/// <returns>List<PickFaceAssignment></returns>
List<PickFaceAssignment> GetPickFaceAssignmentByFilter (string filter = null, int? page = null, int? limit = null, string sort = null);
/// <summary>
/// Search pickFaceAssignments by filter
/// </summary>
/// <remarks>
/// Returns the list of pickFaceAssignments that match the given filter.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Query string, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <param name="sort">Sort results by specified field. (optional)</param>
/// <returns>ApiResponse of List<PickFaceAssignment></returns>
ApiResponse<List<PickFaceAssignment>> GetPickFaceAssignmentByFilterWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null);
/// <summary>
/// Get a pickFaceAssignment by id
/// </summary>
/// <remarks>
/// Returns the pickFaceAssignment identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="pickFaceAssignmentId">Id of the pickFaceAssignment to be returned.</param>
/// <returns>PickFaceAssignment</returns>
PickFaceAssignment GetPickFaceAssignmentById (int? pickFaceAssignmentId);
/// <summary>
/// Get a pickFaceAssignment by id
/// </summary>
/// <remarks>
/// Returns the pickFaceAssignment identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="pickFaceAssignmentId">Id of the pickFaceAssignment to be returned.</param>
/// <returns>ApiResponse of PickFaceAssignment</returns>
ApiResponse<PickFaceAssignment> GetPickFaceAssignmentByIdWithHttpInfo (int? pickFaceAssignmentId);
/// <summary>
/// Update a pickFaceAssignment
/// </summary>
/// <remarks>
/// Updates an existing pickFaceAssignment using the specified data.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">PickFaceAssignment to be updated.</param>
/// <returns></returns>
void UpdatePickFaceAssignment (PickFaceAssignment body);
/// <summary>
/// Update a pickFaceAssignment
/// </summary>
/// <remarks>
/// Updates an existing pickFaceAssignment using the specified data.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">PickFaceAssignment to be updated.</param>
/// <returns>ApiResponse of Object(void)</returns>
ApiResponse<Object> UpdatePickFaceAssignmentWithHttpInfo (PickFaceAssignment body);
#endregion Synchronous Operations
#region Asynchronous Operations
/// <summary>
/// Create a pickFaceAssignment
/// </summary>
/// <remarks>
/// Inserts a new pickFaceAssignment using the specified data.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">PickFaceAssignment to be inserted.</param>
/// <returns>Task of PickFaceAssignment</returns>
System.Threading.Tasks.Task<PickFaceAssignment> AddPickFaceAssignmentAsync (PickFaceAssignment body);
/// <summary>
/// Create a pickFaceAssignment
/// </summary>
/// <remarks>
/// Inserts a new pickFaceAssignment using the specified data.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">PickFaceAssignment to be inserted.</param>
/// <returns>Task of ApiResponse (PickFaceAssignment)</returns>
System.Threading.Tasks.Task<ApiResponse<PickFaceAssignment>> AddPickFaceAssignmentAsyncWithHttpInfo (PickFaceAssignment body);
/// <summary>
/// Delete a pickFaceAssignment
/// </summary>
/// <remarks>
/// Deletes the pickFaceAssignment identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="pickFaceAssignmentId">Id of the pickFaceAssignment to be deleted.</param>
/// <returns>Task of void</returns>
System.Threading.Tasks.Task DeletePickFaceAssignmentAsync (int? pickFaceAssignmentId);
/// <summary>
/// Delete a pickFaceAssignment
/// </summary>
/// <remarks>
/// Deletes the pickFaceAssignment identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="pickFaceAssignmentId">Id of the pickFaceAssignment to be deleted.</param>
/// <returns>Task of ApiResponse</returns>
System.Threading.Tasks.Task<ApiResponse<Object>> DeletePickFaceAssignmentAsyncWithHttpInfo (int? pickFaceAssignmentId);
/// <summary>
/// Search pickFaceAssignments by filter
/// </summary>
/// <remarks>
/// Returns the list of pickFaceAssignments that match the given filter.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Query string, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <param name="sort">Sort results by specified field. (optional)</param>
/// <returns>Task of List<PickFaceAssignment></returns>
System.Threading.Tasks.Task<List<PickFaceAssignment>> GetPickFaceAssignmentByFilterAsync (string filter = null, int? page = null, int? limit = null, string sort = null);
/// <summary>
/// Search pickFaceAssignments by filter
/// </summary>
/// <remarks>
/// Returns the list of pickFaceAssignments that match the given filter.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Query string, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <param name="sort">Sort results by specified field. (optional)</param>
/// <returns>Task of ApiResponse (List<PickFaceAssignment>)</returns>
System.Threading.Tasks.Task<ApiResponse<List<PickFaceAssignment>>> GetPickFaceAssignmentByFilterAsyncWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null);
/// <summary>
/// Get a pickFaceAssignment by id
/// </summary>
/// <remarks>
/// Returns the pickFaceAssignment identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="pickFaceAssignmentId">Id of the pickFaceAssignment to be returned.</param>
/// <returns>Task of PickFaceAssignment</returns>
System.Threading.Tasks.Task<PickFaceAssignment> GetPickFaceAssignmentByIdAsync (int? pickFaceAssignmentId);
/// <summary>
/// Get a pickFaceAssignment by id
/// </summary>
/// <remarks>
/// Returns the pickFaceAssignment identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="pickFaceAssignmentId">Id of the pickFaceAssignment to be returned.</param>
/// <returns>Task of ApiResponse (PickFaceAssignment)</returns>
System.Threading.Tasks.Task<ApiResponse<PickFaceAssignment>> GetPickFaceAssignmentByIdAsyncWithHttpInfo (int? pickFaceAssignmentId);
/// <summary>
/// Update a pickFaceAssignment
/// </summary>
/// <remarks>
/// Updates an existing pickFaceAssignment using the specified data.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">PickFaceAssignment to be updated.</param>
/// <returns>Task of void</returns>
System.Threading.Tasks.Task UpdatePickFaceAssignmentAsync (PickFaceAssignment body);
/// <summary>
/// Update a pickFaceAssignment
/// </summary>
/// <remarks>
/// Updates an existing pickFaceAssignment using the specified data.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">PickFaceAssignment to be updated.</param>
/// <returns>Task of ApiResponse</returns>
System.Threading.Tasks.Task<ApiResponse<Object>> UpdatePickFaceAssignmentAsyncWithHttpInfo (PickFaceAssignment body);
#endregion Asynchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public partial class PickFaceAssignmentApi : IPickFaceAssignmentApi
{
private Infoplus.Client.ExceptionFactory _exceptionFactory = (name, response) => null;
/// <summary>
/// Initializes a new instance of the <see cref="PickFaceAssignmentApi"/> class.
/// </summary>
/// <returns></returns>
public PickFaceAssignmentApi(String basePath)
{
this.Configuration = new Configuration(new ApiClient(basePath));
ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="PickFaceAssignmentApi"/> class
/// using Configuration object
/// </summary>
/// <param name="configuration">An instance of Configuration</param>
/// <returns></returns>
public PickFaceAssignmentApi(Configuration configuration = null)
{
if (configuration == null) // use the default one in Configuration
this.Configuration = Configuration.Default;
else
this.Configuration = configuration;
ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath()
{
return this.Configuration.ApiClient.RestClient.BaseUrl.ToString();
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <value>The base path</value>
[Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")]
public void SetBasePath(String basePath)
{
// do nothing
}
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
public Configuration Configuration {get; set;}
/// <summary>
/// Provides a factory method hook for the creation of exceptions.
/// </summary>
public Infoplus.Client.ExceptionFactory ExceptionFactory
{
get
{
if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1)
{
throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported.");
}
return _exceptionFactory;
}
set { _exceptionFactory = value; }
}
/// <summary>
/// Gets the default header.
/// </summary>
/// <returns>Dictionary of HTTP header</returns>
[Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")]
public Dictionary<String, String> DefaultHeader()
{
return this.Configuration.DefaultHeader;
}
/// <summary>
/// Add default header.
/// </summary>
/// <param name="key">Header field name.</param>
/// <param name="value">Header field value.</param>
/// <returns></returns>
[Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")]
public void AddDefaultHeader(string key, string value)
{
this.Configuration.AddDefaultHeader(key, value);
}
/// <summary>
/// Create a pickFaceAssignment Inserts a new pickFaceAssignment using the specified data.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">PickFaceAssignment to be inserted.</param>
/// <returns>PickFaceAssignment</returns>
public PickFaceAssignment AddPickFaceAssignment (PickFaceAssignment body)
{
ApiResponse<PickFaceAssignment> localVarResponse = AddPickFaceAssignmentWithHttpInfo(body);
return localVarResponse.Data;
}
/// <summary>
/// Create a pickFaceAssignment Inserts a new pickFaceAssignment using the specified data.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">PickFaceAssignment to be inserted.</param>
/// <returns>ApiResponse of PickFaceAssignment</returns>
public ApiResponse< PickFaceAssignment > AddPickFaceAssignmentWithHttpInfo (PickFaceAssignment body)
{
// verify the required parameter 'body' is set
if (body == null)
throw new ApiException(400, "Missing required parameter 'body' when calling PickFaceAssignmentApi->AddPickFaceAssignment");
var localVarPath = "/v1.0/pickFaceAssignment";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (body != null && body.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter
}
else
{
localVarPostBody = body; // byte array
}
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("AddPickFaceAssignment", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<PickFaceAssignment>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(PickFaceAssignment) Configuration.ApiClient.Deserialize(localVarResponse, typeof(PickFaceAssignment)));
}
/// <summary>
/// Create a pickFaceAssignment Inserts a new pickFaceAssignment using the specified data.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">PickFaceAssignment to be inserted.</param>
/// <returns>Task of PickFaceAssignment</returns>
public async System.Threading.Tasks.Task<PickFaceAssignment> AddPickFaceAssignmentAsync (PickFaceAssignment body)
{
ApiResponse<PickFaceAssignment> localVarResponse = await AddPickFaceAssignmentAsyncWithHttpInfo(body);
return localVarResponse.Data;
}
/// <summary>
/// Create a pickFaceAssignment Inserts a new pickFaceAssignment using the specified data.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">PickFaceAssignment to be inserted.</param>
/// <returns>Task of ApiResponse (PickFaceAssignment)</returns>
public async System.Threading.Tasks.Task<ApiResponse<PickFaceAssignment>> AddPickFaceAssignmentAsyncWithHttpInfo (PickFaceAssignment body)
{
// verify the required parameter 'body' is set
if (body == null)
throw new ApiException(400, "Missing required parameter 'body' when calling PickFaceAssignmentApi->AddPickFaceAssignment");
var localVarPath = "/v1.0/pickFaceAssignment";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (body != null && body.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter
}
else
{
localVarPostBody = body; // byte array
}
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("AddPickFaceAssignment", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<PickFaceAssignment>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(PickFaceAssignment) Configuration.ApiClient.Deserialize(localVarResponse, typeof(PickFaceAssignment)));
}
/// <summary>
/// Delete a pickFaceAssignment Deletes the pickFaceAssignment identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="pickFaceAssignmentId">Id of the pickFaceAssignment to be deleted.</param>
/// <returns></returns>
public void DeletePickFaceAssignment (int? pickFaceAssignmentId)
{
DeletePickFaceAssignmentWithHttpInfo(pickFaceAssignmentId);
}
/// <summary>
/// Delete a pickFaceAssignment Deletes the pickFaceAssignment identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="pickFaceAssignmentId">Id of the pickFaceAssignment to be deleted.</param>
/// <returns>ApiResponse of Object(void)</returns>
public ApiResponse<Object> DeletePickFaceAssignmentWithHttpInfo (int? pickFaceAssignmentId)
{
// verify the required parameter 'pickFaceAssignmentId' is set
if (pickFaceAssignmentId == null)
throw new ApiException(400, "Missing required parameter 'pickFaceAssignmentId' when calling PickFaceAssignmentApi->DeletePickFaceAssignment");
var localVarPath = "/v1.0/pickFaceAssignment/{pickFaceAssignmentId}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (pickFaceAssignmentId != null) localVarPathParams.Add("pickFaceAssignmentId", Configuration.ApiClient.ParameterToString(pickFaceAssignmentId)); // path parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("DeletePickFaceAssignment", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Object>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
null);
}
/// <summary>
/// Delete a pickFaceAssignment Deletes the pickFaceAssignment identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="pickFaceAssignmentId">Id of the pickFaceAssignment to be deleted.</param>
/// <returns>Task of void</returns>
public async System.Threading.Tasks.Task DeletePickFaceAssignmentAsync (int? pickFaceAssignmentId)
{
await DeletePickFaceAssignmentAsyncWithHttpInfo(pickFaceAssignmentId);
}
/// <summary>
/// Delete a pickFaceAssignment Deletes the pickFaceAssignment identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="pickFaceAssignmentId">Id of the pickFaceAssignment to be deleted.</param>
/// <returns>Task of ApiResponse</returns>
public async System.Threading.Tasks.Task<ApiResponse<Object>> DeletePickFaceAssignmentAsyncWithHttpInfo (int? pickFaceAssignmentId)
{
// verify the required parameter 'pickFaceAssignmentId' is set
if (pickFaceAssignmentId == null)
throw new ApiException(400, "Missing required parameter 'pickFaceAssignmentId' when calling PickFaceAssignmentApi->DeletePickFaceAssignment");
var localVarPath = "/v1.0/pickFaceAssignment/{pickFaceAssignmentId}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (pickFaceAssignmentId != null) localVarPathParams.Add("pickFaceAssignmentId", Configuration.ApiClient.ParameterToString(pickFaceAssignmentId)); // path parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("DeletePickFaceAssignment", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Object>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
null);
}
/// <summary>
/// Search pickFaceAssignments by filter Returns the list of pickFaceAssignments that match the given filter.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Query string, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <param name="sort">Sort results by specified field. (optional)</param>
/// <returns>List<PickFaceAssignment></returns>
public List<PickFaceAssignment> GetPickFaceAssignmentByFilter (string filter = null, int? page = null, int? limit = null, string sort = null)
{
ApiResponse<List<PickFaceAssignment>> localVarResponse = GetPickFaceAssignmentByFilterWithHttpInfo(filter, page, limit, sort);
return localVarResponse.Data;
}
/// <summary>
/// Search pickFaceAssignments by filter Returns the list of pickFaceAssignments that match the given filter.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Query string, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <param name="sort">Sort results by specified field. (optional)</param>
/// <returns>ApiResponse of List<PickFaceAssignment></returns>
public ApiResponse< List<PickFaceAssignment> > GetPickFaceAssignmentByFilterWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null)
{
var localVarPath = "/v1.0/pickFaceAssignment/search";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter
if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter
if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter
if (sort != null) localVarQueryParams.Add("sort", Configuration.ApiClient.ParameterToString(sort)); // query parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("GetPickFaceAssignmentByFilter", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<List<PickFaceAssignment>>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(List<PickFaceAssignment>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<PickFaceAssignment>)));
}
/// <summary>
/// Search pickFaceAssignments by filter Returns the list of pickFaceAssignments that match the given filter.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Query string, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <param name="sort">Sort results by specified field. (optional)</param>
/// <returns>Task of List<PickFaceAssignment></returns>
public async System.Threading.Tasks.Task<List<PickFaceAssignment>> GetPickFaceAssignmentByFilterAsync (string filter = null, int? page = null, int? limit = null, string sort = null)
{
ApiResponse<List<PickFaceAssignment>> localVarResponse = await GetPickFaceAssignmentByFilterAsyncWithHttpInfo(filter, page, limit, sort);
return localVarResponse.Data;
}
/// <summary>
/// Search pickFaceAssignments by filter Returns the list of pickFaceAssignments that match the given filter.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Query string, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <param name="sort">Sort results by specified field. (optional)</param>
/// <returns>Task of ApiResponse (List<PickFaceAssignment>)</returns>
public async System.Threading.Tasks.Task<ApiResponse<List<PickFaceAssignment>>> GetPickFaceAssignmentByFilterAsyncWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null)
{
var localVarPath = "/v1.0/pickFaceAssignment/search";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter
if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter
if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter
if (sort != null) localVarQueryParams.Add("sort", Configuration.ApiClient.ParameterToString(sort)); // query parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("GetPickFaceAssignmentByFilter", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<List<PickFaceAssignment>>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(List<PickFaceAssignment>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<PickFaceAssignment>)));
}
/// <summary>
/// Get a pickFaceAssignment by id Returns the pickFaceAssignment identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="pickFaceAssignmentId">Id of the pickFaceAssignment to be returned.</param>
/// <returns>PickFaceAssignment</returns>
public PickFaceAssignment GetPickFaceAssignmentById (int? pickFaceAssignmentId)
{
ApiResponse<PickFaceAssignment> localVarResponse = GetPickFaceAssignmentByIdWithHttpInfo(pickFaceAssignmentId);
return localVarResponse.Data;
}
/// <summary>
/// Get a pickFaceAssignment by id Returns the pickFaceAssignment identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="pickFaceAssignmentId">Id of the pickFaceAssignment to be returned.</param>
/// <returns>ApiResponse of PickFaceAssignment</returns>
public ApiResponse< PickFaceAssignment > GetPickFaceAssignmentByIdWithHttpInfo (int? pickFaceAssignmentId)
{
// verify the required parameter 'pickFaceAssignmentId' is set
if (pickFaceAssignmentId == null)
throw new ApiException(400, "Missing required parameter 'pickFaceAssignmentId' when calling PickFaceAssignmentApi->GetPickFaceAssignmentById");
var localVarPath = "/v1.0/pickFaceAssignment/{pickFaceAssignmentId}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (pickFaceAssignmentId != null) localVarPathParams.Add("pickFaceAssignmentId", Configuration.ApiClient.ParameterToString(pickFaceAssignmentId)); // path parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("GetPickFaceAssignmentById", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<PickFaceAssignment>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(PickFaceAssignment) Configuration.ApiClient.Deserialize(localVarResponse, typeof(PickFaceAssignment)));
}
/// <summary>
/// Get a pickFaceAssignment by id Returns the pickFaceAssignment identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="pickFaceAssignmentId">Id of the pickFaceAssignment to be returned.</param>
/// <returns>Task of PickFaceAssignment</returns>
public async System.Threading.Tasks.Task<PickFaceAssignment> GetPickFaceAssignmentByIdAsync (int? pickFaceAssignmentId)
{
ApiResponse<PickFaceAssignment> localVarResponse = await GetPickFaceAssignmentByIdAsyncWithHttpInfo(pickFaceAssignmentId);
return localVarResponse.Data;
}
/// <summary>
/// Get a pickFaceAssignment by id Returns the pickFaceAssignment identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="pickFaceAssignmentId">Id of the pickFaceAssignment to be returned.</param>
/// <returns>Task of ApiResponse (PickFaceAssignment)</returns>
public async System.Threading.Tasks.Task<ApiResponse<PickFaceAssignment>> GetPickFaceAssignmentByIdAsyncWithHttpInfo (int? pickFaceAssignmentId)
{
// verify the required parameter 'pickFaceAssignmentId' is set
if (pickFaceAssignmentId == null)
throw new ApiException(400, "Missing required parameter 'pickFaceAssignmentId' when calling PickFaceAssignmentApi->GetPickFaceAssignmentById");
var localVarPath = "/v1.0/pickFaceAssignment/{pickFaceAssignmentId}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (pickFaceAssignmentId != null) localVarPathParams.Add("pickFaceAssignmentId", Configuration.ApiClient.ParameterToString(pickFaceAssignmentId)); // path parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("GetPickFaceAssignmentById", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<PickFaceAssignment>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(PickFaceAssignment) Configuration.ApiClient.Deserialize(localVarResponse, typeof(PickFaceAssignment)));
}
/// <summary>
/// Update a pickFaceAssignment Updates an existing pickFaceAssignment using the specified data.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">PickFaceAssignment to be updated.</param>
/// <returns></returns>
public void UpdatePickFaceAssignment (PickFaceAssignment body)
{
UpdatePickFaceAssignmentWithHttpInfo(body);
}
/// <summary>
/// Update a pickFaceAssignment Updates an existing pickFaceAssignment using the specified data.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">PickFaceAssignment to be updated.</param>
/// <returns>ApiResponse of Object(void)</returns>
public ApiResponse<Object> UpdatePickFaceAssignmentWithHttpInfo (PickFaceAssignment body)
{
// verify the required parameter 'body' is set
if (body == null)
throw new ApiException(400, "Missing required parameter 'body' when calling PickFaceAssignmentApi->UpdatePickFaceAssignment");
var localVarPath = "/v1.0/pickFaceAssignment";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (body != null && body.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter
}
else
{
localVarPostBody = body; // byte array
}
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("UpdatePickFaceAssignment", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Object>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
null);
}
/// <summary>
/// Update a pickFaceAssignment Updates an existing pickFaceAssignment using the specified data.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">PickFaceAssignment to be updated.</param>
/// <returns>Task of void</returns>
public async System.Threading.Tasks.Task UpdatePickFaceAssignmentAsync (PickFaceAssignment body)
{
await UpdatePickFaceAssignmentAsyncWithHttpInfo(body);
}
/// <summary>
/// Update a pickFaceAssignment Updates an existing pickFaceAssignment using the specified data.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">PickFaceAssignment to be updated.</param>
/// <returns>Task of ApiResponse</returns>
public async System.Threading.Tasks.Task<ApiResponse<Object>> UpdatePickFaceAssignmentAsyncWithHttpInfo (PickFaceAssignment body)
{
// verify the required parameter 'body' is set
if (body == null)
throw new ApiException(400, "Missing required parameter 'body' when calling PickFaceAssignmentApi->UpdatePickFaceAssignment");
var localVarPath = "/v1.0/pickFaceAssignment";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (body != null && body.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter
}
else
{
localVarPostBody = body; // byte array
}
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("UpdatePickFaceAssignment", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Object>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
null);
}
}
}
| |
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using UnityEngine;
namespace Rust_Interceptor {
public class Serializer {
internal static void Serialize(JsonWriter writer, object obj) {
JsonSerializer serializer = new JsonSerializer { NullValueHandling = NullValueHandling.Ignore };
serializer.Formatting = Formatting.Indented;
serializer.ContractResolver = new JsonResolver();
serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
serializer.MaxDepth = int.MaxValue;
serializer.Serialize(writer, obj);
writer.Flush();
}
public static string Serialize(object obj, bool informative = true) {
informativeDump = informative;
StringWriter stream = new StringWriter();
JsonWriter writer = new JsonTextWriter(stream);
Serialize(writer, obj);
return stream.ToString();
}
public static void Serialize(object obj, string filename, bool informative = true) {
informativeDump = informative;
JsonWriter writer = new JsonTextWriter(File.CreateText(filename));
Serialize(writer, obj);
}
public static object Deserialize(string json) {
JsonReader reader = new JsonTextReader(new StringReader(json));
JsonSerializer serializer = new JsonSerializer();
serializer.ContractResolver = new JsonResolver();
serializer.MaxDepth = int.MaxValue;
return serializer.Deserialize(reader);
}
public static object DeserializeFile(string filename) {
return Deserialize(File.ReadAllText(filename));
}
internal class JsonResolver : DefaultContractResolver {
internal static Vector3Converter vector3Converter = new Vector3Converter();
internal static PacketConverter packetConverter = new PacketConverter();
internal static EntityConverter entityConverter = new EntityConverter();
public override JsonContract ResolveContract(Type type) {
JsonContract contract = base.ResolveContract(type);
if (typeof(Packet).IsAssignableFrom(type)) contract.Converter = packetConverter;
if (typeof(Vector3).IsAssignableFrom(type)) contract.Converter = vector3Converter;
if (typeof(Data.Entity).IsAssignableFrom(type)) contract.Converter = entityConverter;
if (typeof(string).IsAssignableFrom(type)) contract.DefaultCreator = () => { return ""; };
return contract;
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization) {
var props = type.GetProperties(bindingAttr: BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
List<JsonProperty> jsonProps = new List<JsonProperty>();
foreach (var prop in props) {
jsonProps.Add(base.CreateProperty(prop, memberSerialization));
}
foreach (var field in type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) {
jsonProps.Add(base.CreateProperty(field, memberSerialization));
}
jsonProps.ForEach(p => {
if (p.PropertyName.Equals("_disposed") || p.PropertyName.Equals("ShouldPool")) {
p.Writable = false;
p.Readable = false;
p.Ignored = true;
} else {
p.Writable = true;
p.Readable = true;
p.Ignored = false;
}
});
return jsonProps;
}
}
internal static bool informativeDump = false;
internal class PacketConverter : JsonConverter {
public bool Informative {
get { return informativeDump; }
}
public override bool CanConvert(Type objectType) {
return typeof(Packet).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
var jsonObject = JObject.Load(reader);
var packet = new Packet();
JToken token = null;
Action<string> Deserialize = (string name) => {
jsonObject.TryGetValue(name, StringComparison.CurrentCulture, out token);
};
Deserialize("ID");
packet.packetID = token.Value<byte>();
Deserialize("TypeID");
packet.type = (Packet.PacketType)token.Value<ulong>();
Deserialize("Length");
packet.incomingLength = token.Value<int>();
Deserialize("GUID");
packet.incomingGUID = token.Value<ulong>();
Deserialize("Data");
JTokenReader read = new JTokenReader(token);
byte[] data = read.ReadAsBytes();
packet.Write(data, 0, data.Length);
packet.Position = 1;
return packet;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
serializer.ContractResolver = new JsonResolver();
var packet = (Packet)value;
writer.WriteStartObject();
Action<string, object> Serialize = (string name, object obj) => {
writer.WritePropertyName(name);
serializer.Serialize(writer, obj);
};
if (Informative) {
Serialize("ID", packet.packetID);
Serialize("Name", packet.GetName());
Serialize("Type", packet.GetPacketTypeName());
Serialize("Origin", packet.GetOrigin());
Serialize("Delay", packet.delay);
} else {
Serialize("ID", packet.packetID);
Serialize("TypeID", packet.type);
Serialize("Length", packet.incomingLength);
Serialize("GUID", packet.incomingGUID);
Serialize("Data", packet.baseStream.ToArray());
}
if (packet.length > 1 && Informative) {
if (packet.type == Packet.PacketType.RUST) {
writer.WritePropertyName("Content");
writer.WriteStartObject();
packet.Position = 1;
switch (packet.rustID) {
case Packet.Rust.Approved:
Serialize("ProtoBuf", ProtoBuf.Approval.Deserialize(packet));
break;
case Packet.Rust.Auth:
var bytes = packet.BytesWithSize();
Serialize("AuthData", BitConverter.ToString(bytes).Replace("-", ""));
break;
case Packet.Rust.ConsoleCommand:
Serialize("Command", packet.String());
break;
case Packet.Rust.ConsoleMessage:
Serialize("Message", packet.String());
break;
case Packet.Rust.DisconnectReason:
Serialize("Reason", packet.String());
break;
case Packet.Rust.Effect:
Serialize("ProtoBuf", EffectData.Deserialize(packet));
break;
case Packet.Rust.Entities:
Serialize("Num", packet.UInt32());
Serialize("ProtoBuf", ProtoBuf.Entity.Deserialize(packet));
break;
case Packet.Rust.EntityDestroy:
Serialize("UID", packet.UInt32());
Serialize("Destroy Mode", packet.UInt8());
break;
case Packet.Rust.EntityPosition:
writer.WritePropertyName("Entity Positions");
writer.WriteStartArray();
while (packet.unread >= 28L) {
writer.WriteStartObject();
Serialize("Entity ID", packet.EntityID());
Serialize("Position", packet.Vector3());
Serialize("Rotation", packet.Vector3());
writer.WriteEndObject();
}
writer.WriteEndArray();
break;
case Packet.Rust.GiveUserInformation:
Serialize("ProtocolVersion", packet.UInt8());
Serialize("Steam ID", packet.UInt64());
Serialize("Protocol", packet.UInt32());
Serialize("OS Name", packet.String());
Serialize("Steam Name", packet.String());
Serialize("Branch", packet.String());
break;
case Packet.Rust.GroupChange:
Serialize("Entity ID", packet.EntityID());
Serialize("Group ID", packet.GroupID());
break;
case Packet.Rust.GroupDestroy:
Serialize("Group ID", packet.GroupID());
break;
case Packet.Rust.GroupEnter:
Serialize("Group ID", packet.GroupID());
break;
case Packet.Rust.GroupLeave:
Serialize("Group ID", packet.GroupID());
break;
case Packet.Rust.Message:
Serialize("String 1 (PlayerName?)", packet.String());
Serialize("String 2 (PlayerMsg?)", packet.String());
break;
case Packet.Rust.RPCMessage:
Serialize("UID", packet.UInt32());
Serialize("Name ID", packet.UInt32());
Serialize("Source Connection", packet.UInt64());
break;
case Packet.Rust.Ready:
Serialize("ProtoBuf", ProtoBuf.ClientReady.Deserialize(packet));
break;
case Packet.Rust.Tick:
Serialize("ProtoBuf", PlayerTick.Deserialize(packet));
break;
default:
break;
}
writer.WriteEndObject();
}
}
writer.WriteEndObject();
}
}
internal class EntityConverter : JsonConverter {
public override bool CanConvert(Type objectType) {
return typeof(Data.Entity).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
throw new NotImplementedException();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
var entity = (ProtoBuf.Entity)value;
Action<string, object> Serialize = (string name, object obj) => {
writer.WritePropertyName(name);
serializer.Serialize(writer, obj);
};
writer.WriteStartObject();
if (entity.basePlayer != null) {
Serialize("Player Name", entity.basePlayer.name);
Serialize("User ID", entity.basePlayer.userid);
}
Serialize("UID", entity.baseNetworkable.uid);
Serialize("Group", entity.baseNetworkable.group);
Serialize("Player", entity.basePlayer != null);
Serialize("Position", entity.baseEntity.pos);
Serialize("Rotation", entity.baseEntity.rot);
writer.WriteEndObject();
}
}
internal class Vector3Converter : JsonConverter {
public override bool CanConvert(Type objectType) {
return typeof(Vector3).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
Vector3 vec;
var data = serializer.Deserialize<string>(reader).Split(':');
vec = new Vector3(float.Parse(data[0]), float.Parse(data[1]), float.Parse(data[2]));
return vec;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
var vec = (Vector3)value;
serializer.Serialize(writer, String.Format("{0}:{1}:{2}", vec.x, vec.y, vec.z));
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Automation;
using Microsoft.Azure.Management.Automation.Models;
namespace Microsoft.Azure.Management.Automation
{
public partial class AutomationManagementClient : ServiceClient<AutomationManagementClient>, IAutomationManagementClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private string _resourceNamespace;
/// <summary>
/// Gets or sets the resource namespace.
/// </summary>
public string ResourceNamespace
{
get { return this._resourceNamespace; }
set { this._resourceNamespace = value; }
}
private IActivityOperations _activities;
/// <summary>
/// Service operation for automation activities. (see
/// http://aka.ms/azureautomationsdk/activityoperations for more
/// information)
/// </summary>
public virtual IActivityOperations Activities
{
get { return this._activities; }
}
private IAgentRegistrationOperation _agentRegistrationInformation;
/// <summary>
/// Service operation for automation agent registration information.
/// (see http://aka.ms/azureautomationsdk/agentregistrationoperations
/// for more information)
/// </summary>
public virtual IAgentRegistrationOperation AgentRegistrationInformation
{
get { return this._agentRegistrationInformation; }
}
private IAutomationAccountOperations _automationAccounts;
/// <summary>
/// Service operation for automation accounts. (see
/// http://aka.ms/azureautomationsdk/automationaccountoperations for
/// more information)
/// </summary>
public virtual IAutomationAccountOperations AutomationAccounts
{
get { return this._automationAccounts; }
}
private ICertificateOperations _certificates;
/// <summary>
/// Service operation for automation certificates. (see
/// http://aka.ms/azureautomationsdk/certificateoperations for more
/// information)
/// </summary>
public virtual ICertificateOperations Certificates
{
get { return this._certificates; }
}
private IConnectionOperations _connections;
/// <summary>
/// Service operation for automation connections. (see
/// http://aka.ms/azureautomationsdk/connectionoperations for more
/// information)
/// </summary>
public virtual IConnectionOperations Connections
{
get { return this._connections; }
}
private IConnectionTypeOperations _connectionTypes;
/// <summary>
/// Service operation for automation connectiontypes. (see
/// http://aka.ms/azureautomationsdk/connectiontypeoperations for more
/// information)
/// </summary>
public virtual IConnectionTypeOperations ConnectionTypes
{
get { return this._connectionTypes; }
}
private ICredentialOperations _psCredentials;
/// <summary>
/// Service operation for automation credentials. (see
/// http://aka.ms/azureautomationsdk/credentialoperations for more
/// information)
/// </summary>
public virtual ICredentialOperations PsCredentials
{
get { return this._psCredentials; }
}
private IDscCompilationJobOperations _compilationJobs;
/// <summary>
/// Service operation for automation dsc configuration compile jobs.
/// (see
/// http://aka.ms/azureautomationsdk/dscccompilationjoboperations for
/// more information)
/// </summary>
public virtual IDscCompilationJobOperations CompilationJobs
{
get { return this._compilationJobs; }
}
private IDscConfigurationOperations _configurations;
/// <summary>
/// Service operation for configurations. (see
/// http://aka.ms/azureautomationsdk/configurationoperations for more
/// information)
/// </summary>
public virtual IDscConfigurationOperations Configurations
{
get { return this._configurations; }
}
private IDscNodeConfigurationOperations _nodeConfigurations;
/// <summary>
/// Service operation for automation dsc node configurations. (see
/// http://aka.ms/azureautomationsdk/dscnodeconfigurations for more
/// information)
/// </summary>
public virtual IDscNodeConfigurationOperations NodeConfigurations
{
get { return this._nodeConfigurations; }
}
private IDscNodeOperations _nodes;
/// <summary>
/// Service operation for dsc nodes. (see
/// http://aka.ms/azureautomationsdk/dscnodeoperations for more
/// information)
/// </summary>
public virtual IDscNodeOperations Nodes
{
get { return this._nodes; }
}
private IDscNodeReportsOperations _nodeReports;
/// <summary>
/// Service operation for node reports. (see
/// http://aka.ms/azureautomationsdk/dscnodereportoperations for more
/// information)
/// </summary>
public virtual IDscNodeReportsOperations NodeReports
{
get { return this._nodeReports; }
}
private IHybridRunbookWorkerGroupOperations _hybridRunbookWorkerGroups;
/// <summary>
/// Service operation for automation hybrid runbook worker group. (see
/// http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations
/// for more information)
/// </summary>
public virtual IHybridRunbookWorkerGroupOperations HybridRunbookWorkerGroups
{
get { return this._hybridRunbookWorkerGroups; }
}
private IJobOperations _jobs;
/// <summary>
/// Service operation for automation jobs. (see
/// http://aka.ms/azureautomationsdk/joboperations for more
/// information)
/// </summary>
public virtual IJobOperations Jobs
{
get { return this._jobs; }
}
private IJobScheduleOperations _jobSchedules;
/// <summary>
/// Service operation for automation job schedules. (see
/// http://aka.ms/azureautomationsdk/jobscheduleoperations for more
/// information)
/// </summary>
public virtual IJobScheduleOperations JobSchedules
{
get { return this._jobSchedules; }
}
private IJobStreamOperations _jobStreams;
/// <summary>
/// Service operation for automation job streams. (see
/// http://aka.ms/azureautomationsdk/jobstreamoperations for more
/// information)
/// </summary>
public virtual IJobStreamOperations JobStreams
{
get { return this._jobStreams; }
}
private ILinkedWorkspaceOperations _linkedWorkspace;
/// <summary>
/// Service operation for automation linked workspace. (see
/// http://aka.ms/azureautomationsdk/linkedworkspaceoperations for
/// more information)
/// </summary>
public virtual ILinkedWorkspaceOperations LinkedWorkspace
{
get { return this._linkedWorkspace; }
}
private IModuleOperations _modules;
/// <summary>
/// Service operation for automation modules. (see
/// http://aka.ms/azureautomationsdk/moduleoperations for more
/// information)
/// </summary>
public virtual IModuleOperations Modules
{
get { return this._modules; }
}
private IObjectDataTypeOperations _objectDataTypes;
/// <summary>
/// Service operation for automation object data types. (see
/// http://aka.ms/azureautomationsdk/objectdatatypeoperations for more
/// information)
/// </summary>
public virtual IObjectDataTypeOperations ObjectDataTypes
{
get { return this._objectDataTypes; }
}
private IRunbookDraftOperations _runbookDraft;
/// <summary>
/// Service operation for automation runbook draft. (see
/// http://aka.ms/azureautomationsdk/runbookdraftoperations for more
/// information)
/// </summary>
public virtual IRunbookDraftOperations RunbookDraft
{
get { return this._runbookDraft; }
}
private IRunbookOperations _runbooks;
/// <summary>
/// Service operation for automation runbooks. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
public virtual IRunbookOperations Runbooks
{
get { return this._runbooks; }
}
private IScheduleOperations _schedules;
/// <summary>
/// Service operation for automation schedules. (see
/// http://aka.ms/azureautomationsdk/scheduleoperations for more
/// information)
/// </summary>
public virtual IScheduleOperations Schedules
{
get { return this._schedules; }
}
private ISoftwareUpdateConfigurationOperations _softwareUpdateConfigurations;
/// <summary>
/// Service operation for automation variables. (see
/// http://aka.ms/azureautomationsdk/variableoperations for more
/// information)
/// </summary>
public virtual ISoftwareUpdateConfigurationOperations SoftwareUpdateConfigurations
{
get { return this._softwareUpdateConfigurations; }
}
private IStatisticsOperations _statistics;
/// <summary>
/// Service operation for automation statistics. (see
/// http://aka.ms/azureautomationsdk/statisticsoperations for more
/// information)
/// </summary>
public virtual IStatisticsOperations Statistics
{
get { return this._statistics; }
}
private ITestJobOperations _testJobs;
/// <summary>
/// Service operation for automation test jobs. (see
/// http://aka.ms/azureautomationsdk/testjoboperations for more
/// information)
/// </summary>
public virtual ITestJobOperations TestJobs
{
get { return this._testJobs; }
}
private ITypeFieldOperations _typeFields;
/// <summary>
/// Service operation for automation type fields. (see
/// http://aka.ms/azureautomationsdk/typefieldoperations for more
/// information)
/// </summary>
public virtual ITypeFieldOperations TypeFields
{
get { return this._typeFields; }
}
private IUsageOperations _usages;
/// <summary>
/// Service operation for automation usages. (see
/// http://aka.ms/azureautomationsdk/usageoperations for more
/// information)
/// </summary>
public virtual IUsageOperations Usages
{
get { return this._usages; }
}
private IVariableOperations _variables;
/// <summary>
/// Service operation for automation variables. (see
/// http://aka.ms/azureautomationsdk/variableoperations for more
/// information)
/// </summary>
public virtual IVariableOperations Variables
{
get { return this._variables; }
}
private IWatcherActionOperations _watcherActions;
/// <summary>
/// Service operation for automation watcher actions. (see
/// http://aka.ms/azureautomationsdk/watcheractionoperations for more
/// information)
/// </summary>
public virtual IWatcherActionOperations WatcherActions
{
get { return this._watcherActions; }
}
private IWatcherOperations _watchers;
/// <summary>
/// Service operation for automation watchers. (see
/// http://aka.ms/azureautomationsdk/watcheroperations for more
/// information)
/// </summary>
public virtual IWatcherOperations Watchers
{
get { return this._watchers; }
}
private IWatcherStreamOperations _watcherStreams;
/// <summary>
/// Service operation for automation watcher streams. (see
/// http://aka.ms/azureautomationsdk/watcherstreamoperations for more
/// information)
/// </summary>
public virtual IWatcherStreamOperations WatcherStreams
{
get { return this._watcherStreams; }
}
private IWebhookOperations _webhooks;
/// <summary>
/// Service operation for automation webhook. (see
/// http://aka.ms/azureautomationsdk/webhookoperations for more
/// information)
/// </summary>
public virtual IWebhookOperations Webhooks
{
get { return this._webhooks; }
}
/// <summary>
/// Initializes a new instance of the AutomationManagementClient class.
/// </summary>
public AutomationManagementClient()
: base()
{
this._activities = new ActivityOperations(this);
this._agentRegistrationInformation = new AgentRegistrationOperation(this);
this._automationAccounts = new AutomationAccountOperations(this);
this._certificates = new CertificateOperations(this);
this._connections = new ConnectionOperations(this);
this._connectionTypes = new ConnectionTypeOperations(this);
this._psCredentials = new CredentialOperations(this);
this._compilationJobs = new DscCompilationJobOperations(this);
this._configurations = new DscConfigurationOperations(this);
this._nodeConfigurations = new DscNodeConfigurationOperations(this);
this._nodes = new DscNodeOperations(this);
this._nodeReports = new DscNodeReportsOperations(this);
this._hybridRunbookWorkerGroups = new HybridRunbookWorkerGroupOperations(this);
this._jobs = new JobOperations(this);
this._jobSchedules = new JobScheduleOperations(this);
this._jobStreams = new JobStreamOperations(this);
this._linkedWorkspace = new LinkedWorkspaceOperations(this);
this._modules = new ModuleOperations(this);
this._objectDataTypes = new ObjectDataTypeOperations(this);
this._runbookDraft = new RunbookDraftOperations(this);
this._runbooks = new RunbookOperations(this);
this._schedules = new ScheduleOperations(this);
this._softwareUpdateConfigurations = new SoftwareUpdateConfigurationOperations(this);
this._statistics = new StatisticsOperations(this);
this._testJobs = new TestJobOperations(this);
this._typeFields = new TypeFieldOperations(this);
this._usages = new UsageOperations(this);
this._variables = new VariableOperations(this);
this._watcherActions = new WatcherActionOperations(this);
this._watchers = new WatcherOperations(this);
this._watcherStreams = new WatcherStreamOperations(this);
this._webhooks = new WebhookOperations(this);
this._resourceNamespace = "Microsoft.Automation";
this._apiVersion = "2014-06-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the AutomationManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public AutomationManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the AutomationManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
public AutomationManagementClient(SubscriptionCloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the AutomationManagementClient class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
public AutomationManagementClient(HttpClient httpClient)
: base(httpClient)
{
this._activities = new ActivityOperations(this);
this._agentRegistrationInformation = new AgentRegistrationOperation(this);
this._automationAccounts = new AutomationAccountOperations(this);
this._certificates = new CertificateOperations(this);
this._connections = new ConnectionOperations(this);
this._connectionTypes = new ConnectionTypeOperations(this);
this._psCredentials = new CredentialOperations(this);
this._compilationJobs = new DscCompilationJobOperations(this);
this._configurations = new DscConfigurationOperations(this);
this._nodeConfigurations = new DscNodeConfigurationOperations(this);
this._nodes = new DscNodeOperations(this);
this._nodeReports = new DscNodeReportsOperations(this);
this._hybridRunbookWorkerGroups = new HybridRunbookWorkerGroupOperations(this);
this._jobs = new JobOperations(this);
this._jobSchedules = new JobScheduleOperations(this);
this._jobStreams = new JobStreamOperations(this);
this._linkedWorkspace = new LinkedWorkspaceOperations(this);
this._modules = new ModuleOperations(this);
this._objectDataTypes = new ObjectDataTypeOperations(this);
this._runbookDraft = new RunbookDraftOperations(this);
this._runbooks = new RunbookOperations(this);
this._schedules = new ScheduleOperations(this);
this._softwareUpdateConfigurations = new SoftwareUpdateConfigurationOperations(this);
this._statistics = new StatisticsOperations(this);
this._testJobs = new TestJobOperations(this);
this._typeFields = new TypeFieldOperations(this);
this._usages = new UsageOperations(this);
this._variables = new VariableOperations(this);
this._watcherActions = new WatcherActionOperations(this);
this._watchers = new WatcherOperations(this);
this._watcherStreams = new WatcherStreamOperations(this);
this._webhooks = new WebhookOperations(this);
this._resourceNamespace = "Microsoft.Automation";
this._apiVersion = "2014-06-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the AutomationManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public AutomationManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the AutomationManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public AutomationManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another
/// AutomationManagementClient instance
/// </summary>
/// <param name='client'>
/// Instance of AutomationManagementClient to clone to
/// </param>
protected override void Clone(ServiceClient<AutomationManagementClient> client)
{
base.Clone(client);
if (client is AutomationManagementClient)
{
AutomationManagementClient clonedClient = ((AutomationManagementClient)client);
clonedClient._resourceNamespace = this._resourceNamespace;
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public async Task<LongRunningOperationResultResponse> GetOperationResultStatusAsync(string operationStatusLink, CancellationToken cancellationToken)
{
// Validate
if (operationStatusLink == null)
{
throw new ArgumentNullException("operationStatusLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("operationStatusLink", operationStatusLink);
TracingAdapter.Enter(invocationId, this, "GetOperationResultStatusAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + operationStatusLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
LongRunningOperationResultResponse result = null;
// Deserialize Response
result = new LongRunningOperationResultResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (statusCode == HttpStatusCode.NotFound)
{
result.Status = OperationStatus.Failed;
}
if (statusCode == HttpStatusCode.BadRequest)
{
result.Status = OperationStatus.Failed;
}
if (statusCode == HttpStatusCode.OK)
{
result.Status = OperationStatus.Succeeded;
}
if (statusCode == HttpStatusCode.Created)
{
result.Status = OperationStatus.Succeeded;
}
if (statusCode == HttpStatusCode.NoContent)
{
result.Status = OperationStatus.Succeeded;
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Get Operation Status operation returns the status of
/// thespecified operation. After calling an asynchronous operation,
/// you can call Get Operation Status to determine whether the
/// operation has succeeded, failed, or is still in progress. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx
/// for more information)
/// </summary>
/// <param name='requestId'>
/// Required. The request ID for the request you wish to track. The
/// request ID is returned in the x-ms-request-id response header for
/// every request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<LongRunningOperationStatusResponse> GetOperationStatusAsync(string requestId, CancellationToken cancellationToken)
{
// Validate
if (requestId == null)
{
throw new ArgumentNullException("requestId");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("requestId", requestId);
TracingAdapter.Enter(invocationId, this, "GetOperationStatusAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Credentials.SubscriptionId);
}
url = url + "/operations/";
url = url + Uri.EscapeDataString(requestId);
string baseUrl = this.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
LongRunningOperationStatusResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new LongRunningOperationStatusResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement operationElement = responseDoc.Element(XName.Get("Operation", "http://schemas.microsoft.com/windowsazure"));
if (operationElement != null)
{
XElement idElement = operationElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
result.Id = idInstance;
}
XElement statusElement = operationElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure"));
if (statusElement != null)
{
OperationStatus statusInstance = ((OperationStatus)Enum.Parse(typeof(OperationStatus), statusElement.Value, true));
result.Status = statusInstance;
}
XElement httpStatusCodeElement = operationElement.Element(XName.Get("HttpStatusCode", "http://schemas.microsoft.com/windowsazure"));
if (httpStatusCodeElement != null)
{
HttpStatusCode httpStatusCodeInstance = ((HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), httpStatusCodeElement.Value, true));
result.HttpStatusCode = httpStatusCodeInstance;
}
XElement errorElement = operationElement.Element(XName.Get("Error", "http://schemas.microsoft.com/windowsazure"));
if (errorElement != null)
{
LongRunningOperationStatusResponse.ErrorDetails errorInstance = new LongRunningOperationStatusResponse.ErrorDetails();
result.Error = errorInstance;
XElement codeElement = errorElement.Element(XName.Get("Code", "http://schemas.microsoft.com/windowsazure"));
if (codeElement != null)
{
string codeInstance = codeElement.Value;
errorInstance.Code = codeInstance;
}
XElement messageElement = errorElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure"));
if (messageElement != null)
{
string messageInstance = messageElement.Value;
errorInstance.Message = messageInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Physics.Manager;
namespace OpenSim.Region.Physics.BasicPhysicsPlugin
{
public class BasicActor : PhysicsActor
{
private Vector3 _position;
private Vector3 _velocity;
private Vector3 _acceleration;
private Vector3 _size;
private Vector3 m_rotationalVelocity;
private bool flying;
private bool iscolliding;
public BasicActor()
{
}
public override int PhysicsActorType
{
get { return (int) ActorTypes.Agent; }
set { return; }
}
public override Vector3 RotationalVelocity
{
get { return m_rotationalVelocity; }
set { m_rotationalVelocity = value; }
}
public override bool SetAlwaysRun
{
get { return false; }
set { return; }
}
public override uint LocalID
{
set { return; }
}
public override bool Grabbed
{
set { return; }
}
public override bool Selected
{
set { return; }
}
public override float Buoyancy
{
get { return 0f; }
set { return; }
}
public override bool FloatOnWater
{
set { return; }
}
public override bool IsPhysical
{
get { return false; }
set { return; }
}
public override bool ThrottleUpdates
{
get { return false; }
set { return; }
}
public override bool Flying
{
get { return flying; }
set { flying = value; }
}
public override bool IsColliding
{
get { return iscolliding; }
set { iscolliding = value; }
}
public override bool CollidingGround
{
get { return false; }
set { return; }
}
public override bool CollidingObj
{
get { return false; }
set { return; }
}
public override bool Stopped
{
get { return false; }
}
public override Vector3 Position
{
get { return _position; }
set { _position = value; }
}
public override Vector3 Size
{
get { return _size; }
set {
_size = value;
_size.Z = _size.Z / 2.0f;
}
}
public override PrimitiveBaseShape Shape
{
set { return; }
}
public override float Mass
{
get { return 0f; }
}
public override Vector3 Force
{
get { return Vector3.Zero; }
set { return; }
}
public override int VehicleType
{
get { return 0; }
set { return; }
}
public override void VehicleFloatParam(int param, float value)
{
}
public override void VehicleVectorParam(int param, Vector3 value)
{
}
public override void VehicleRotationParam(int param, Quaternion rotation)
{
}
public override void VehicleFlags(int param, bool remove)
{
}
public override void SetVolumeDetect(int param)
{
}
public override Vector3 CenterOfMass
{
get { return Vector3.Zero; }
}
public override Vector3 GeometricCenter
{
get { return Vector3.Zero; }
}
public override Vector3 Velocity
{
get { return _velocity; }
set { _velocity = value; }
}
public override Vector3 Torque
{
get { return Vector3.Zero; }
set { return; }
}
public override float CollisionScore
{
get { return 0f; }
set { }
}
public override Quaternion Orientation
{
get { return Quaternion.Identity; }
set { }
}
public override Vector3 Acceleration
{
get { return _acceleration; }
}
public override bool Kinematic
{
get { return true; }
set { }
}
public override void link(PhysicsActor obj)
{
}
public override void delink()
{
}
public override void LockAngularMotion(Vector3 axis)
{
}
public void SetAcceleration(Vector3 accel)
{
_acceleration = accel;
}
public override void AddForce(Vector3 force, bool pushforce)
{
}
public override void AddAngularForce(Vector3 force, bool pushforce)
{
}
public override void SetMomentum(Vector3 momentum)
{
}
public override void CrossingFailure()
{
}
public override Vector3 PIDTarget
{
set { return; }
}
public override bool PIDActive
{
set { return; }
}
public override float PIDTau
{
set { return; }
}
public override float PIDHoverHeight
{
set { return; }
}
public override bool PIDHoverActive
{
set { return; }
}
public override PIDHoverType PIDHoverType
{
set { return; }
}
public override float PIDHoverTau
{
set { return; }
}
public override Quaternion APIDTarget
{
set { return; }
}
public override bool APIDActive
{
set { return; }
}
public override float APIDStrength
{
set { return; }
}
public override float APIDDamping
{
set { return; }
}
public override void SubscribeEvents(int ms)
{
}
public override void UnSubscribeEvents()
{
}
public override bool SubscribedEvents()
{
return false;
}
}
}
| |
using System;
using System.Net;
using System.Threading;
using Orleans.Runtime.Configuration;
using Orleans.Messaging;
namespace Orleans.Runtime.Messaging
{
internal class MessageCenter : ISiloMessageCenter, IDisposable
{
private Gateway Gateway { get; set; }
private IncomingMessageAcceptor ima;
private static readonly TraceLogger log = TraceLogger.GetLogger("Orleans.Messaging.MessageCenter");
private Action<Message> rerouteHandler;
// ReSharper disable NotAccessedField.Local
private IntValueStatistic sendQueueLengthCounter;
private IntValueStatistic receiveQueueLengthCounter;
// ReSharper restore NotAccessedField.Local
internal IOutboundMessageQueue OutboundQueue { get; set; }
internal IInboundMessageQueue InboundQueue { get; set; }
internal SocketManager SocketManager;
internal bool IsBlockingApplicationMessages { get; private set; }
internal ISiloPerformanceMetrics Metrics { get; private set; }
public bool IsProxying { get { return Gateway != null; } }
public bool TryDeliverToProxy(Message msg)
{
return msg.TargetGrain.IsClient && Gateway != null && Gateway.TryDeliverToProxy(msg);
}
// This is determined by the IMA but needed by the OMS, and so is kept here in the message center itself.
public SiloAddress MyAddress { get; private set; }
public IMessagingConfiguration MessagingConfiguration { get; private set; }
public MessageCenter(IPEndPoint here, int generation, IMessagingConfiguration config, ISiloPerformanceMetrics metrics = null)
{
Initialize(here, generation, config, metrics);
}
private void Initialize(IPEndPoint here, int generation, IMessagingConfiguration config, ISiloPerformanceMetrics metrics = null)
{
if(log.IsVerbose3) log.Verbose3("Starting initialization.");
SocketManager = new SocketManager(config);
ima = new IncomingMessageAcceptor(this, here, SocketDirection.SiloToSilo);
MyAddress = SiloAddress.New((IPEndPoint)ima.AcceptingSocket.LocalEndPoint, generation);
MessagingConfiguration = config;
InboundQueue = new InboundMessageQueue();
OutboundQueue = new OutboundMessageQueue(this, config);
Gateway = null;
Metrics = metrics;
sendQueueLengthCounter = IntValueStatistic.FindOrCreate(StatisticNames.MESSAGE_CENTER_SEND_QUEUE_LENGTH, () => SendQueueLength);
receiveQueueLengthCounter = IntValueStatistic.FindOrCreate(StatisticNames.MESSAGE_CENTER_RECEIVE_QUEUE_LENGTH, () => ReceiveQueueLength);
if (log.IsVerbose3) log.Verbose3("Completed initialization.");
}
public void InstallGateway(IPEndPoint gatewayAddress)
{
Gateway = new Gateway(this, gatewayAddress);
}
public void Start()
{
IsBlockingApplicationMessages = false;
ima.Start();
OutboundQueue.Start();
}
public void StartGateway(ClientObserverRegistrar clientRegistrar)
{
if (Gateway != null)
Gateway.Start(clientRegistrar);
}
public void PrepareToStop()
{
}
public void Stop()
{
IsBlockingApplicationMessages = true;
try
{
ima.Stop();
}
catch (Exception exc)
{
log.Error(ErrorCode.Runtime_Error_100108, "Stop failed.", exc);
}
StopAcceptingClientMessages();
try
{
OutboundQueue.Stop();
}
catch (Exception exc)
{
log.Error(ErrorCode.Runtime_Error_100110, "Stop failed.", exc);
}
try
{
SocketManager.Stop();
}
catch (Exception exc)
{
log.Error(ErrorCode.Runtime_Error_100111, "Stop failed.", exc);
}
}
public void StopAcceptingClientMessages()
{
if (log.IsVerbose) log.Verbose("StopClientMessages");
if (Gateway == null) return;
try
{
Gateway.Stop();
}
catch (Exception exc) { log.Error(ErrorCode.Runtime_Error_100109, "Stop failed.", exc); }
Gateway = null;
}
public Action<Message> RerouteHandler
{
set
{
if (rerouteHandler != null)
throw new InvalidOperationException("MessageCenter RerouteHandler already set");
rerouteHandler = value;
}
}
public void RerouteMessage(Message message)
{
if (rerouteHandler != null)
rerouteHandler(message);
else
SendMessage(message);
}
public Action<Message> SniffIncomingMessage
{
set
{
ima.SniffIncomingMessage = value;
}
}
public Func<SiloAddress, bool> SiloDeadOracle { get; set; }
public void SendMessage(Message msg)
{
// Note that if we identify or add other grains that are required for proper stopping, we will need to treat them as we do the membership table grain here.
if (IsBlockingApplicationMessages && (msg.Category == Message.Categories.Application) && (msg.Result != Message.ResponseTypes.Rejection)
&& !Constants.SystemMembershipTableId.Equals(msg.TargetGrain))
{
// Drop the message on the floor if it's an application message that isn't a rejection
}
else
{
if (msg.SendingSilo == null)
msg.SendingSilo = MyAddress;
OutboundQueue.SendMessage(msg);
}
}
internal void SendRejection(Message msg, Message.RejectionTypes rejectionType, string reason)
{
MessagingStatisticsGroup.OnRejectedMessage(msg);
if (string.IsNullOrEmpty(reason)) reason = String.Format("Rejection from silo {0} - Unknown reason.", MyAddress);
Message error = msg.CreateRejectionResponse(rejectionType, reason);
// rejection msgs are always originated in the local silo, they are never remote.
InboundQueue.PostMessage(error);
}
public Message WaitMessage(Message.Categories type, CancellationToken ct)
{
return InboundQueue.WaitMessage(type);
}
public void Dispose()
{
if (ima != null)
{
ima.Dispose();
ima = null;
}
OutboundQueue.Dispose();
GC.SuppressFinalize(this);
}
public int SendQueueLength { get { return OutboundQueue.Count; } }
public int ReceiveQueueLength { get { return InboundQueue.Count; } }
/// <summary>
/// Indicates that application messages should be blocked from being sent or received.
/// This method is used by the "fast stop" process.
/// <para>
/// Specifically, all outbound application messages are dropped, except for rejections and messages to the membership table grain.
/// Inbound application requests are rejected, and other inbound application messages are dropped.
/// </para>
/// </summary>
public void BlockApplicationMessages()
{
if(log.IsVerbose) log.Verbose("BlockApplicationMessages");
IsBlockingApplicationMessages = true;
}
}
}
| |
namespace System.Data.Entity.Core.Objects.ELinq
{
using System.Collections.Generic;
using System.Data.Entity.Core.Common.CommandTrees;
using System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Resources;
using System.Data.Entity.Utilities;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using CqtExpression = System.Data.Entity.Core.Common.CommandTrees.DbExpression;
using LinqExpression = System.Linq.Expressions.Expression;
internal sealed partial class ExpressionConverter
{
internal static class StringTranslatorUtil
{
[SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily",
Justification = "the same linqExpression value is never cast to ConstantExpression twice")]
internal static DbExpression ConvertToString(ExpressionConverter parent, LinqExpression linqExpression)
{
if (linqExpression.Type == typeof(object))
{
var constantExpression = linqExpression as ConstantExpression;
linqExpression =
constantExpression != null ?
Expression.Constant(constantExpression.Value) :
linqExpression.RemoveConvert();
}
var expression = parent.TranslateExpression(linqExpression);
var clrType = TypeSystem.GetNonNullableType(linqExpression.Type);
if (clrType.IsEnum)
{
//Flag enums are not supported.
if (Attribute.IsDefined(clrType, typeof(FlagsAttribute)))
{
throw new NotSupportedException(Strings.Elinq_ToStringNotSupportedForEnumsWithFlags);
}
if (linqExpression.IsNullConstant())
{
return DbExpressionBuilder.Constant(string.Empty);
}
//Constant expression, optimize to constant name
if (linqExpression.NodeType == ExpressionType.Constant)
{
var value = ((ConstantExpression)linqExpression).Value;
var name = Enum.GetName(clrType, value) ?? value.ToString();
return DbExpressionBuilder.Constant(name);
}
var integralType = clrType.GetEnumUnderlyingType();
var type = parent.GetValueLayerType(integralType);
var values = clrType.GetEnumValues()
.Cast<object>()
.Select(v => System.Convert.ChangeType(v, integralType, CultureInfo.InvariantCulture)) //cast to integral type so that unmapped enum types works too
.Select(v => DbExpressionBuilder.Constant(v))
.Select(c => (DbExpression)expression.CastTo(type).Equal(c)) //cast expression to integral type before comparing to constant
.Concat(new[] { expression.CastTo(type).IsNull() }); // default case
var names = clrType.GetEnumNames()
.Select(s => DbExpressionBuilder.Constant(s))
.Concat(new[] { DbExpressionBuilder.Constant(string.Empty) }); // default case
//translate unnamed enum values for the else clause, raw linq -> as integral value -> translate to cqt -> to string
//e.g. ((DayOfWeek)99) -> "99"
var asIntegralLinq = LinqExpression.Convert(linqExpression, integralType);
var asStringCqt = parent
.TranslateExpression(asIntegralLinq)
.CastTo(parent.GetValueLayerType(typeof(string)));
return DbExpressionBuilder.Case(values, names, asStringCqt);
}
else if (TypeSemantics.IsPrimitiveType(expression.ResultType, PrimitiveTypeKind.String))
{
return StripNull(linqExpression, expression, expression);
}
else if (TypeSemantics.IsPrimitiveType(expression.ResultType, PrimitiveTypeKind.Guid))
{
return StripNull(linqExpression, expression, expression.CastTo(parent.GetValueLayerType(typeof(string))).ToLower());
}
else if (TypeSemantics.IsPrimitiveType(expression.ResultType, PrimitiveTypeKind.Boolean))
{
if (linqExpression.IsNullConstant())
{
return DbExpressionBuilder.Constant(string.Empty);
}
if (linqExpression.NodeType == ExpressionType.Constant)
{
var name = ((ConstantExpression)linqExpression).Value.ToString();
return DbExpressionBuilder.Constant(name);
}
var whenTrue = expression.Equal(DbExpressionBuilder.True);
var whenFalse = expression.Equal(DbExpressionBuilder.False);
var thenTrue = DbExpressionBuilder.Constant(true.ToString());
var thenFalse = DbExpressionBuilder.Constant(false.ToString());
return DbExpressionBuilder.Case(
new[] { whenTrue, whenFalse },
new[] { thenTrue, thenFalse },
DbExpressionBuilder.Constant(string.Empty));
}
else
{
if (!SupportsCastToString(expression.ResultType))
{
throw new NotSupportedException(
Strings.Elinq_ToStringNotSupportedForType(expression.ResultType.EdmType.Name));
}
//treat all other types as a simple cast
return StripNull(linqExpression, expression, expression.CastTo(parent.GetValueLayerType(typeof(string))));
}
}
internal static IEnumerable<Expression> GetConcatArgs(Expression linq)
{
if (linq.IsStringAddExpression())
{
foreach (var arg in GetConcatArgs((BinaryExpression)linq))
{
yield return arg;
}
}
else
{
yield return linq; //leaf node
}
}
internal static IEnumerable<Expression> GetConcatArgs(BinaryExpression linq)
{
// one could also flatten calls to String.Concat here, to avoid multi concat
// in "a + b + String.Concat(d, e)", just flatten it to a, b, c, d, e
//rec traverse left node
foreach (var arg in GetConcatArgs(linq.Left))
{
yield return arg;
}
//rec traverse right node
foreach (var arg in GetConcatArgs(linq.Right))
{
yield return arg;
}
}
internal static CqtExpression ConcatArgs(ExpressionConverter parent, BinaryExpression linq)
{
return ConcatArgs(parent, linq, GetConcatArgs(linq).ToArray());
}
internal static CqtExpression ConcatArgs(ExpressionConverter parent, Expression linq, Expression[] linqArgs)
{
var args = linqArgs
.Where(arg => !arg.IsNullConstant()) // remove null constants
.Select(arg => ConvertToString(parent, arg)) // Apply ToString semantics
.ToArray();
//if all args was null constants, optimize the entire expression to constant ""
// e.g null + null + null == ""
if (args.Length == 0)
{
return DbExpressionBuilder.Constant(string.Empty);
}
var current = args.First();
foreach (var next in args.Skip(1)) //concat all args
{
current = parent.CreateCanonicalFunction(Concat, linq, current, next);
}
return current;
}
internal static CqtExpression StripNull(LinqExpression sourceExpression,
DbExpression inputExpression, DbExpression outputExpression)
{
if (sourceExpression.IsNullConstant())
{
return DbExpressionBuilder.Constant(string.Empty);
}
if (sourceExpression.NodeType == ExpressionType.Constant)
{
return outputExpression;
}
// converts evaluated null values to empty string, nullable primitive properties etc.
var castNullToEmptyString = DbExpressionBuilder.Case(
new[] { inputExpression.IsNull() },
new[] { DbExpressionBuilder.Constant(string.Empty) },
outputExpression);
return castNullToEmptyString;
}
internal static bool SupportsCastToString(TypeUsage typeUsage)
{
return (TypeSemantics.IsPrimitiveType(typeUsage, PrimitiveTypeKind.String)
|| TypeSemantics.IsNumericType(typeUsage)
|| TypeSemantics.IsBooleanType(typeUsage)
|| TypeSemantics.IsPrimitiveType(typeUsage, PrimitiveTypeKind.DateTime)
|| TypeSemantics.IsPrimitiveType(typeUsage, PrimitiveTypeKind.DateTimeOffset)
|| TypeSemantics.IsPrimitiveType(typeUsage, PrimitiveTypeKind.Time)
|| TypeSemantics.IsPrimitiveType(typeUsage, PrimitiveTypeKind.Guid));
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using System.Reactive;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Threading;
namespace Burden
{
/// <summary>
/// A job queue of a given input and output type, where the jobs are executed by manually calling StartNext, or StartAsManyAs.
/// </summary>
/// <remarks> 7/15/2011. </remarks>
/// <typeparam name="TJobInput"> Type of the job input. </typeparam>
/// <typeparam name="TJobOutput"> Type of the job output. </typeparam>
public class ManualJobExecutionQueue<TJobInput, TJobOutput>
: IJobExecutionQueue<TJobInput, TJobOutput>
{
//this class uniquely identifies an internal cancellation so we can properly modify the running job count
[SuppressMessage("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors", Justification = "This is only used within this class, and doesn't need a complete implementation")]
[SuppressMessage("Microsoft.Usage", "CA2237:MarkISerializableTypesWithSerializable", Justification = "This is only used within this class, and doesn't need a complete implementation")]
private sealed class JobQueueCancellationException : OperationCanceledException
{ }
/// <summary> Defines the members necessary to encapsulate a job. </summary>
/// <remarks> 8/3/2011. </remarks>
protected struct Job
{
/// <summary> Gets or sets the jobs input. </summary>
/// <value> The input. </value>
public TJobInput Input { get; set; }
/// <summary> Gets or sets the asynchronous Func used to start the job. </summary>
/// <value> The asynchronous start. </value>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Nested generics, while advanced, are perfectly acceptable within Funcs and IObservables, especially given this use case")]
public Func<TJobInput, IObservable<TJobOutput>> AsyncStart { get; set; }
/// <summary> Gets or sets the completion handler. </summary>
/// <value> The completion handler. </value>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Nested generics, while advanced, are perfectly acceptable within Funcs and IObservables, especially given this use case")]
public AsyncSubject<JobResult<TJobInput, TJobOutput>> CompletionHandler { get; set; }
/// <summary> Keeps track of the job cancellation. </summary>
/// <value> The cancel. </value>
public BooleanDisposable Cancel { get; set; }
/// <summary> Gets or sets the job subscription. </summary>
/// <value> The job subscription. </value>
public MultipleAssignmentDisposable JobSubscription { get; set; }
}
private bool _disposed, _completionDisposed;
private readonly IScheduler _scheduler;
private ConcurrentQueue<Job> _queue = new ConcurrentQueue<Job>();
private int _runningCount;
private static int _maxAllowedConcurrentJobs = 50;
private static int _defaultConcurrent = 20;
private int _maxConcurrent;
private Subject<JobResult<TJobInput, TJobOutput>> _whenJobCompletes
= new Subject<JobResult<TJobInput, TJobOutput>>();
private Subject<Unit> _whenQueueEmpty = new Subject<Unit>();
/// <summary> Default constructor, that uses the TaskPool scheduler in standard .NET or the ThreadPool scheduler in Silverlight. </summary>
/// <remarks> 7/15/2011. </remarks>
public ManualJobExecutionQueue()
: this(DefaultConcurrent)
{ }
/// <summary> Default constructor, that uses the TaskPool scheduler in standard .NET or the ThreadPool scheduler in Silverlight. </summary>
/// <remarks> 7/15/2011. </remarks>
public ManualJobExecutionQueue(int maxConcurrent)
: this(LocalScheduler.Default, maxConcurrent)
{
if (maxConcurrent < 1 || maxConcurrent > _maxAllowedConcurrentJobs)
{
throw new ArgumentOutOfRangeException("maxConcurrent", maxConcurrent, "must be at least 1 and less than or equal to MaxAllowedConcurrentJobs");
}
}
//allowing maxConcurrent here lets us use 0 in tests
[SuppressMessage("Gendarme.Rules.Performance", "AvoidUncalledPrivateCodeRule", Justification = "Used by test classes to change scheduler")]
internal ManualJobExecutionQueue(IScheduler scheduler, int maxConcurrent)
{
this._scheduler = scheduler;
this._maxConcurrent = maxConcurrent;
// whenQueueEmpty subscription
_whenJobCompletes.Subscribe(n =>
{
int queueCount = _queue.Count;
int running = _runningCount;
//only decrement the running count if we're not dealing with a cancellation
if (null == n.Exception as JobQueueCancellationException)
{
running = Interlocked.Decrement(ref _runningCount);
}
if (running == 0 && queueCount == 0)
_whenQueueEmpty.OnNext(new Unit());
});
}
/// <summary> Throws an ObjectDisposedException if this object has been disposed of. </summary>
/// <remarks> 8/3/2011. </remarks>
/// <exception cref="ObjectDisposedException"> Thrown when a supplied object has been disposed. </exception>
protected void ThrowIfDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException("this");
}
}
/// <summary> Gets a value indicating whether the instance has been disposed. </summary>
/// <value> true if disposed, false if not. </value>
protected bool Disposed
{
get { return _disposed; }
}
/// <summary> Dispose of this object, cleaning up any resources it uses. </summary>
/// <remarks> 7/24/2011. </remarks>
public void Dispose()
{
if (!this._disposed)
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
/// <summary>
/// Dispose of this object, cleaning up any resources it uses. Will cancel any outstanding un-executed jobs, and will wait on jobs
/// currently executing to complete.
/// </summary>
/// <remarks> 7/24/2011. </remarks>
/// <param name="disposing"> true if resources should be disposed, false if not. </param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
this._disposed = true;
//attempt to wait for jobs currently executing to complete before disposing
CancelOutstandingJobs();
using (var wait = new ManualResetEventSlim(false))
using (var subscription = _whenQueueEmpty.Subscribe(n => wait.Set()))
{
if (RunningCount != 0)
{
wait.Wait(TimeSpan.FromSeconds(20));
}
}
_whenJobCompletes.Dispose();
this._completionDisposed = true;
_whenQueueEmpty.Dispose();
}
}
/// <summary> Gets the default number of concurrent jobs to run on this ManualJobExecutionQueue. </summary>
/// <value> The default number of concurrent jobs. </value>
public static int DefaultConcurrent
{
get { return _defaultConcurrent; }
}
/// <summary> Gets the maximum allowed concurrent jobs for a ManualJobExecutionQueue. </summary>
/// <value> The maximum allowed concurrent jobs. </value>
public static int MaxAllowedConcurrentJobs
{
get { return _maxAllowedConcurrentJobs; }
}
/// <summary>
/// Gets or sets the maximum number of allowed concurrent jobs. If a value is set above MaxAllowedConcurrentJobs, then
/// MaxAllowedConcurrentJobs is set as the value. If set below 1, the value is set to 1. Does not affect the status of currently
/// executing jobs.
/// </summary>
/// <value> The maximum allowed concurrent jobs, which defaults to the maximum allowed 50. </value>
public int MaxConcurrent
{
get { return _maxConcurrent; }
set
{
_maxConcurrent = Math.Max(1, Math.Min(value, MaxAllowedConcurrentJobs));
}
}
/// <summary>
/// The Observable that monitors job completion, where completion can be either run to completion, exception or cancellation.
/// </summary>
/// <value> A sequence of observable job completion notifications. </value>
/// <exception cref="ObjectDisposedException"> Thrown when the object has been disposed of, and is therefore no longer accepting new
/// jobs or publishing notifications. </exception>
public IObservable<JobResult<TJobInput, TJobOutput>> WhenJobCompletes
{
get
{
ThrowIfDisposed();
return _whenJobCompletes
.Select(result =>
{
//have to convert our custom exception back to something standard
if (result.Exception is JobQueueCancellationException)
{
return JobResult.CreateOnError(result.Input, new OperationCanceledException());
}
return result;
})
.AsObservable();
}
}
/// <summary> The observable that monitors job queue empty status. </summary>
/// <value> A simple notification indicating the queue has reached empty status. </value>
/// <exception cref="ObjectDisposedException"> Thrown when the object has been disposed of, and is therefore no longer accepting new
/// jobs or publishing notifications. </exception>
public IObservable<Unit> WhenQueueEmpty
{
get
{
ThrowIfDisposed();
return _whenQueueEmpty.AsObservable();
}
}
/// <summary> Gets the number of running jobs. </summary>
/// <value> The number of running jobs. </value>
public int RunningCount
{
get { return _runningCount; }
}
/// <summary> Gets the number of queued jobs. </summary>
/// <value> The number of queued jobs. </value>
public int QueuedCount
{
get { return _queue.Count; }
}
/// <summary> Adds a job matching a given input / output typing and an input value. </summary>
/// <remarks> 8/3/2011. </remarks>
/// <exception cref="ArgumentNullException"> Thrown when one the input or action are null. </exception>
/// <exception cref="ObjectDisposedException"> Thrown when the object has been disposed of, and is therefore no longer accepting new
/// jobs or publishing notifications. </exception>
/// <param name="input"> The input. </param>
/// <param name="action"> The action to perform. </param>
/// <returns> A sequence of Observable JobResult instances. </returns>
public IObservable<JobResult<TJobInput, TJobOutput>> Add(TJobInput input, Func<TJobInput, TJobOutput> action)
{
ThrowIfDisposed();
if (null == input) { throw new ArgumentNullException("input"); }
if (null == action) { throw new ArgumentNullException("action"); }
return Add(input, Observable.ToAsync(action));
}
/// <summary> Adds a job matching a given input / output typing and an input value. </summary>
/// <remarks> 8/3/2011. </remarks>
/// <exception cref="ArgumentNullException"> Thrown when the input or asyncStart are null. </exception>
/// <exception cref="ObjectDisposedException"> Thrown when the object has been disposed of, and is therefore no longer accepting new
/// jobs or publishing notifications. </exception>
/// <param name="input"> The input. </param>
/// <param name="asyncStart"> The asynchronous observable action to perform. </param>
/// <returns> A sequence of Observable JobResult instances. </returns>
[SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "Job disposables are tracked and later disposed as necessary")]
public virtual IObservable<JobResult<TJobInput, TJobOutput>> Add(TJobInput input, Func<TJobInput, IObservable<TJobOutput>> asyncStart)
{
ThrowIfDisposed();
if (null == input) { throw new ArgumentNullException("input"); }
if (null == asyncStart) { throw new ArgumentNullException("asyncStart"); }
Job job = new Job()
{
AsyncStart = asyncStart,
CompletionHandler = new AsyncSubject<JobResult<TJobInput, TJobOutput>>(),
Cancel = new BooleanDisposable(),
JobSubscription = new MultipleAssignmentDisposable(),
Input = input
};
var cancelable = Observable.Create<JobResult<TJobInput, TJobOutput>>(o => new CompositeDisposable(
job.CompletionHandler.Subscribe(o),
job.JobSubscription,
job.Cancel))
.ObserveOn(_scheduler);
job.CompletionHandler
.ObserveOn(_scheduler)
.Materialize()
.Where(n => n.Kind == NotificationKind.OnNext)
.Select(n => n.Value)
.Subscribe(_whenJobCompletes.OnNext);
// pass on errors and completions
_queue.Enqueue(job);
return cancelable;
}
/// <summary>
/// Starts the next job in the queue, as long as the current number of running jobs does not exceed the maximum upper limit allowed by
/// the job queue, presently 50.
/// </summary>
/// <exception cref="ObjectDisposedException"> Thrown when the object has been disposed of, and is therefore no longer accepting new
/// jobs or publishing notifications. </exception>
/// <remarks> 7/30/2011. </remarks>
/// <returns> true if it succeeds, false if it fails. </returns>
public bool StartNext()
{
ThrowIfDisposed();
if (_runningCount >= _maxConcurrent)
{
return false;
}
Job job;
if (TryDequeNextJob(out job))
{
Interlocked.Increment(ref _runningCount);
StartJob(job);
return true;
}
return false;
}
/// <summary> Starts up to the given number of jobs in the queue concurrently. </summary>
/// <remarks> 7/30/2011. </remarks>
/// <exception cref="ObjectDisposedException"> Thrown when the object has been disposed of, and is therefore no longer accepting new
/// jobs or publishing notifications. </exception>
/// <param name="maxConcurrentlyRunning"> The maximum concurrently running jobs to allow, which will be set to an upper limit of
/// MaxAllowedConcurrentJobs (presently 50). </param>
/// <returns> The number of jobs started. </returns>
public int StartAsManyAs(int maxConcurrentlyRunning)
{
ThrowIfDisposed();
maxConcurrentlyRunning = Math.Min(maxConcurrentlyRunning, _maxConcurrent);
int started = 0;
while (true)
{
int running = 0;
do // test and increment with compare and swap
{
running = _runningCount;
if (running >= maxConcurrentlyRunning)
return started;
}
while (Interlocked.CompareExchange(ref _runningCount, running + 1, running) != running);
Job job;
if (TryDequeNextJob(out job))
{
StartJob(job);
++started;
}
else
{
// dequeing job failed but we already incremented running count
Interlocked.Decrement(ref _runningCount);
// ensure that no other thread queued an item and did not start it
// because the running count was too high
if (_queue.Count == 0)
{
// if there is nothing in the queue after the decrement
// we can safely return
return started;
}
}
}
}
/// <summary> Cancel outstanding jobs, which will result in Notifications being pushed through the WhenJobCompletes observable. </summary>
public void CancelOutstandingJobs()
{
Job job;
while (TryDequeNextJob(out job))
{
job.Cancel.Dispose();
job.CompletionHandler.OnNext(JobResult.CreateOnError(job.Input, new JobQueueCancellationException()));
job.CompletionHandler.OnCompleted();
}
}
private bool TryDequeNextJob(out Job job)
{
do
{
if (!_queue.TryDequeue(out job))
return false;
}
while (job.Cancel.IsDisposed);
return true;
}
[SuppressMessage("Gendarme.Rules.Correctness", "EnsureLocalDisposalRule", Justification = "Proper job disposal is spread out amongst several methods")]
private void StartJob(Job job)
{
try
{
job.JobSubscription.Disposable = job.AsyncStart(job.Input).ObserveOn(_scheduler).Subscribe(
result => OnJobCompleted(job, result, null),
e => OnJobCompleted(job, default(TJobOutput), e));
if (job.Cancel.IsDisposed)
job.JobSubscription.Dispose();
}
catch (Exception ex)
{
OnJobCompleted(job, default(TJobOutput), ex);
throw;
}
}
/// <summary> Fires OnNext for our CompletionHandler, passing along the appropriate JobResult based on whether or not there was an error. </summary>
/// <remarks> 8/3/2011. </remarks>
/// <param name="job"> The job. </param>
/// <param name="jobResult"> The job result. </param>
/// <param name="exception"> The error, if one exists. </param>
protected virtual void OnJobCompleted(Job job, TJobOutput jobResult, Exception exception)
{
if (_completionDisposed)
{
return;
}
job.CompletionHandler.OnNext(exception == null ? JobResult.CreateOnCompletion(job.Input, jobResult)
: JobResult.CreateOnError(job.Input, exception));
job.CompletionHandler.OnCompleted();
}
}
}
| |
// 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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Diagnostics
{
public partial class StackFrame
{
public StackFrame() { }
public StackFrame(bool fNeedFileInfo) { }
public StackFrame(int skipFrames) { }
public StackFrame(int skipFrames, bool fNeedFileInfo) { }
public StackFrame(string fileName, int lineNumber) { }
public StackFrame(string fileName, int lineNumber, int colNumber) { }
public const int OFFSET_UNKNOWN = -1;
public virtual int GetFileColumnNumber() { throw null; }
public virtual int GetFileLineNumber() { throw null; }
public virtual string GetFileName() { throw null; }
public virtual int GetILOffset() { throw null; }
public virtual System.Reflection.MethodBase GetMethod() { throw null; }
public override string ToString() { throw null; }
public virtual int GetNativeOffset() { throw null; }
}
public static partial class StackFrameExtensions
{
public static System.IntPtr GetNativeImageBase(this System.Diagnostics.StackFrame stackFrame) { throw null; }
public static System.IntPtr GetNativeIP(this System.Diagnostics.StackFrame stackFrame) { throw null; }
public static bool HasILOffset(this System.Diagnostics.StackFrame stackFrame) { throw null; }
public static bool HasMethod(this System.Diagnostics.StackFrame stackFrame) { throw null; }
public static bool HasNativeImage(this System.Diagnostics.StackFrame stackFrame) { throw null; }
public static bool HasSource(this System.Diagnostics.StackFrame stackFrame) { throw null; }
}
public partial class StackTrace
{
public const int METHODS_TO_SKIP = 0;
public StackTrace() { }
public StackTrace(bool fNeedFileInfo) { }
public StackTrace(StackFrame frame) { }
public StackTrace(System.Exception e) { }
public StackTrace(System.Exception e, bool fNeedFileInfo) { }
public StackTrace(System.Exception e, int skipFrames) { }
public StackTrace(System.Exception e, int skipFrames, bool fNeedFileInfo) { }
public StackTrace(int skipFrames) { }
public StackTrace(int skipFrames, bool fNeedFileInfo) { }
public virtual int FrameCount { get { throw null; } }
public virtual System.Diagnostics.StackFrame[] GetFrames() { throw null; }
public virtual System.Diagnostics.StackFrame GetFrame(int index) { throw null; }
public override string ToString() { throw null; }
}
}
namespace System.Diagnostics.SymbolStore
{
public partial interface ISymbolBinder
{
[System.ObsoleteAttribute("The recommended alternative is ISymbolBinder1.GetReader. ISymbolBinder1.GetReader takes the importer interface pointer as an IntPtr instead of an Int32, and thus works on both 32-bit and 64-bit architectures. http://go.microsoft.com/fwlink/?linkid=14202=14202")]
System.Diagnostics.SymbolStore.ISymbolReader GetReader(int importer, string filename, string searchPath);
}
public partial interface ISymbolBinder1
{
System.Diagnostics.SymbolStore.ISymbolReader GetReader(System.IntPtr importer, string filename, string searchPath);
}
public partial interface ISymbolDocument
{
System.Guid CheckSumAlgorithmId { get; }
System.Guid DocumentType { get; }
bool HasEmbeddedSource { get; }
System.Guid Language { get; }
System.Guid LanguageVendor { get; }
int SourceLength { get; }
string URL { get; }
int FindClosestLine(int line);
byte[] GetCheckSum();
byte[] GetSourceRange(int startLine, int startColumn, int endLine, int endColumn);
}
public partial interface ISymbolDocumentWriter
{
void SetCheckSum(System.Guid algorithmId, byte[] checkSum);
void SetSource(byte[] source);
}
public partial interface ISymbolMethod
{
System.Diagnostics.SymbolStore.ISymbolScope RootScope { get; }
int SequencePointCount { get; }
System.Diagnostics.SymbolStore.SymbolToken Token { get; }
System.Diagnostics.SymbolStore.ISymbolNamespace GetNamespace();
int GetOffset(System.Diagnostics.SymbolStore.ISymbolDocument document, int line, int column);
System.Diagnostics.SymbolStore.ISymbolVariable[] GetParameters();
int[] GetRanges(System.Diagnostics.SymbolStore.ISymbolDocument document, int line, int column);
System.Diagnostics.SymbolStore.ISymbolScope GetScope(int offset);
void GetSequencePoints(int[] offsets, System.Diagnostics.SymbolStore.ISymbolDocument[] documents, int[] lines, int[] columns, int[] endLines, int[] endColumns);
bool GetSourceStartEnd(System.Diagnostics.SymbolStore.ISymbolDocument[] docs, int[] lines, int[] columns);
}
public partial interface ISymbolNamespace
{
string Name { get; }
System.Diagnostics.SymbolStore.ISymbolNamespace[] GetNamespaces();
System.Diagnostics.SymbolStore.ISymbolVariable[] GetVariables();
}
public partial interface ISymbolReader
{
System.Diagnostics.SymbolStore.SymbolToken UserEntryPoint { get; }
System.Diagnostics.SymbolStore.ISymbolDocument GetDocument(string url, System.Guid language, System.Guid languageVendor, System.Guid documentType);
System.Diagnostics.SymbolStore.ISymbolDocument[] GetDocuments();
System.Diagnostics.SymbolStore.ISymbolVariable[] GetGlobalVariables();
System.Diagnostics.SymbolStore.ISymbolMethod GetMethod(System.Diagnostics.SymbolStore.SymbolToken method);
System.Diagnostics.SymbolStore.ISymbolMethod GetMethod(System.Diagnostics.SymbolStore.SymbolToken method, int version);
System.Diagnostics.SymbolStore.ISymbolMethod GetMethodFromDocumentPosition(System.Diagnostics.SymbolStore.ISymbolDocument document, int line, int column);
System.Diagnostics.SymbolStore.ISymbolNamespace[] GetNamespaces();
byte[] GetSymAttribute(System.Diagnostics.SymbolStore.SymbolToken parent, string name);
System.Diagnostics.SymbolStore.ISymbolVariable[] GetVariables(System.Diagnostics.SymbolStore.SymbolToken parent);
}
public partial interface ISymbolScope
{
int EndOffset { get; }
System.Diagnostics.SymbolStore.ISymbolMethod Method { get; }
System.Diagnostics.SymbolStore.ISymbolScope Parent { get; }
int StartOffset { get; }
System.Diagnostics.SymbolStore.ISymbolScope[] GetChildren();
System.Diagnostics.SymbolStore.ISymbolVariable[] GetLocals();
System.Diagnostics.SymbolStore.ISymbolNamespace[] GetNamespaces();
}
public partial interface ISymbolVariable
{
int AddressField1 { get; }
int AddressField2 { get; }
int AddressField3 { get; }
System.Diagnostics.SymbolStore.SymAddressKind AddressKind { get; }
object Attributes { get; }
int EndOffset { get; }
string Name { get; }
int StartOffset { get; }
byte[] GetSignature();
}
public partial interface ISymbolWriter
{
void Close();
void CloseMethod();
void CloseNamespace();
void CloseScope(int endOffset);
System.Diagnostics.SymbolStore.ISymbolDocumentWriter DefineDocument(string url, System.Guid language, System.Guid languageVendor, System.Guid documentType);
void DefineField(System.Diagnostics.SymbolStore.SymbolToken parent, string name, System.Reflection.FieldAttributes attributes, byte[] signature, System.Diagnostics.SymbolStore.SymAddressKind addrKind, int addr1, int addr2, int addr3);
void DefineGlobalVariable(string name, System.Reflection.FieldAttributes attributes, byte[] signature, System.Diagnostics.SymbolStore.SymAddressKind addrKind, int addr1, int addr2, int addr3);
void DefineLocalVariable(string name, System.Reflection.FieldAttributes attributes, byte[] signature, System.Diagnostics.SymbolStore.SymAddressKind addrKind, int addr1, int addr2, int addr3, int startOffset, int endOffset);
void DefineParameter(string name, System.Reflection.ParameterAttributes attributes, int sequence, System.Diagnostics.SymbolStore.SymAddressKind addrKind, int addr1, int addr2, int addr3);
void DefineSequencePoints(System.Diagnostics.SymbolStore.ISymbolDocumentWriter document, int[] offsets, int[] lines, int[] columns, int[] endLines, int[] endColumns);
void Initialize(System.IntPtr emitter, string filename, bool fFullBuild);
void OpenMethod(System.Diagnostics.SymbolStore.SymbolToken method);
void OpenNamespace(string name);
int OpenScope(int startOffset);
void SetMethodSourceRange(System.Diagnostics.SymbolStore.ISymbolDocumentWriter startDoc, int startLine, int startColumn, System.Diagnostics.SymbolStore.ISymbolDocumentWriter endDoc, int endLine, int endColumn);
void SetScopeRange(int scopeID, int startOffset, int endOffset);
void SetSymAttribute(System.Diagnostics.SymbolStore.SymbolToken parent, string name, byte[] data);
void SetUnderlyingWriter(System.IntPtr underlyingWriter);
void SetUserEntryPoint(System.Diagnostics.SymbolStore.SymbolToken entryMethod);
void UsingNamespace(string fullName);
}
public enum SymAddressKind
{
BitField = 9,
ILOffset = 1,
NativeOffset = 5,
NativeRegister = 3,
NativeRegisterRegister = 6,
NativeRegisterRelative = 4,
NativeRegisterStack = 7,
NativeRVA = 2,
NativeSectionOffset = 10,
NativeStackRegister = 8,
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct SymbolToken
{
public SymbolToken(int val) { throw null; }
public bool Equals(System.Diagnostics.SymbolStore.SymbolToken obj) { throw null; }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public int GetToken() { throw null; }
public static bool operator ==(System.Diagnostics.SymbolStore.SymbolToken a, System.Diagnostics.SymbolStore.SymbolToken b) { throw null; }
public static bool operator !=(System.Diagnostics.SymbolStore.SymbolToken a, System.Diagnostics.SymbolStore.SymbolToken b) { throw null; }
}
public partial class SymDocumentType
{
public static readonly System.Guid Text;
public SymDocumentType() { }
}
public partial class SymLanguageType
{
public static readonly System.Guid Basic;
public static readonly System.Guid C;
public static readonly System.Guid Cobol;
public static readonly System.Guid CPlusPlus;
public static readonly System.Guid CSharp;
public static readonly System.Guid ILAssembly;
public static readonly System.Guid Java;
public static readonly System.Guid JScript;
public static readonly System.Guid MCPlusPlus;
public static readonly System.Guid Pascal;
public static readonly System.Guid SMC;
public SymLanguageType() { }
}
public partial class SymLanguageVendor
{
public static readonly System.Guid Microsoft;
public SymLanguageVendor() { }
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Javax.Microedition.Khronos.Egl.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 Javax.Microedition.Khronos.Egl
{
/// <java-name>
/// javax/microedition/khronos/egl/EGL10
/// </java-name>
[Dot42.DexImport("javax/microedition/khronos/egl/EGL10", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IEGL10Constants
/* scope: __dot42__ */
{
/// <java-name>
/// EGL_SUCCESS
/// </java-name>
[Dot42.DexImport("EGL_SUCCESS", "I", AccessFlags = 25)]
public const int EGL_SUCCESS = 12288;
/// <java-name>
/// EGL_NOT_INITIALIZED
/// </java-name>
[Dot42.DexImport("EGL_NOT_INITIALIZED", "I", AccessFlags = 25)]
public const int EGL_NOT_INITIALIZED = 12289;
/// <java-name>
/// EGL_BAD_ACCESS
/// </java-name>
[Dot42.DexImport("EGL_BAD_ACCESS", "I", AccessFlags = 25)]
public const int EGL_BAD_ACCESS = 12290;
/// <java-name>
/// EGL_BAD_ALLOC
/// </java-name>
[Dot42.DexImport("EGL_BAD_ALLOC", "I", AccessFlags = 25)]
public const int EGL_BAD_ALLOC = 12291;
/// <java-name>
/// EGL_BAD_ATTRIBUTE
/// </java-name>
[Dot42.DexImport("EGL_BAD_ATTRIBUTE", "I", AccessFlags = 25)]
public const int EGL_BAD_ATTRIBUTE = 12292;
/// <java-name>
/// EGL_BAD_CONFIG
/// </java-name>
[Dot42.DexImport("EGL_BAD_CONFIG", "I", AccessFlags = 25)]
public const int EGL_BAD_CONFIG = 12293;
/// <java-name>
/// EGL_BAD_CONTEXT
/// </java-name>
[Dot42.DexImport("EGL_BAD_CONTEXT", "I", AccessFlags = 25)]
public const int EGL_BAD_CONTEXT = 12294;
/// <java-name>
/// EGL_BAD_CURRENT_SURFACE
/// </java-name>
[Dot42.DexImport("EGL_BAD_CURRENT_SURFACE", "I", AccessFlags = 25)]
public const int EGL_BAD_CURRENT_SURFACE = 12295;
/// <java-name>
/// EGL_BAD_DISPLAY
/// </java-name>
[Dot42.DexImport("EGL_BAD_DISPLAY", "I", AccessFlags = 25)]
public const int EGL_BAD_DISPLAY = 12296;
/// <java-name>
/// EGL_BAD_MATCH
/// </java-name>
[Dot42.DexImport("EGL_BAD_MATCH", "I", AccessFlags = 25)]
public const int EGL_BAD_MATCH = 12297;
/// <java-name>
/// EGL_BAD_NATIVE_PIXMAP
/// </java-name>
[Dot42.DexImport("EGL_BAD_NATIVE_PIXMAP", "I", AccessFlags = 25)]
public const int EGL_BAD_NATIVE_PIXMAP = 12298;
/// <java-name>
/// EGL_BAD_NATIVE_WINDOW
/// </java-name>
[Dot42.DexImport("EGL_BAD_NATIVE_WINDOW", "I", AccessFlags = 25)]
public const int EGL_BAD_NATIVE_WINDOW = 12299;
/// <java-name>
/// EGL_BAD_PARAMETER
/// </java-name>
[Dot42.DexImport("EGL_BAD_PARAMETER", "I", AccessFlags = 25)]
public const int EGL_BAD_PARAMETER = 12300;
/// <java-name>
/// EGL_BAD_SURFACE
/// </java-name>
[Dot42.DexImport("EGL_BAD_SURFACE", "I", AccessFlags = 25)]
public const int EGL_BAD_SURFACE = 12301;
/// <java-name>
/// EGL_BUFFER_SIZE
/// </java-name>
[Dot42.DexImport("EGL_BUFFER_SIZE", "I", AccessFlags = 25)]
public const int EGL_BUFFER_SIZE = 12320;
/// <java-name>
/// EGL_ALPHA_SIZE
/// </java-name>
[Dot42.DexImport("EGL_ALPHA_SIZE", "I", AccessFlags = 25)]
public const int EGL_ALPHA_SIZE = 12321;
/// <java-name>
/// EGL_BLUE_SIZE
/// </java-name>
[Dot42.DexImport("EGL_BLUE_SIZE", "I", AccessFlags = 25)]
public const int EGL_BLUE_SIZE = 12322;
/// <java-name>
/// EGL_GREEN_SIZE
/// </java-name>
[Dot42.DexImport("EGL_GREEN_SIZE", "I", AccessFlags = 25)]
public const int EGL_GREEN_SIZE = 12323;
/// <java-name>
/// EGL_RED_SIZE
/// </java-name>
[Dot42.DexImport("EGL_RED_SIZE", "I", AccessFlags = 25)]
public const int EGL_RED_SIZE = 12324;
/// <java-name>
/// EGL_DEPTH_SIZE
/// </java-name>
[Dot42.DexImport("EGL_DEPTH_SIZE", "I", AccessFlags = 25)]
public const int EGL_DEPTH_SIZE = 12325;
/// <java-name>
/// EGL_STENCIL_SIZE
/// </java-name>
[Dot42.DexImport("EGL_STENCIL_SIZE", "I", AccessFlags = 25)]
public const int EGL_STENCIL_SIZE = 12326;
/// <java-name>
/// EGL_CONFIG_CAVEAT
/// </java-name>
[Dot42.DexImport("EGL_CONFIG_CAVEAT", "I", AccessFlags = 25)]
public const int EGL_CONFIG_CAVEAT = 12327;
/// <java-name>
/// EGL_CONFIG_ID
/// </java-name>
[Dot42.DexImport("EGL_CONFIG_ID", "I", AccessFlags = 25)]
public const int EGL_CONFIG_ID = 12328;
/// <java-name>
/// EGL_LEVEL
/// </java-name>
[Dot42.DexImport("EGL_LEVEL", "I", AccessFlags = 25)]
public const int EGL_LEVEL = 12329;
/// <java-name>
/// EGL_MAX_PBUFFER_HEIGHT
/// </java-name>
[Dot42.DexImport("EGL_MAX_PBUFFER_HEIGHT", "I", AccessFlags = 25)]
public const int EGL_MAX_PBUFFER_HEIGHT = 12330;
/// <java-name>
/// EGL_MAX_PBUFFER_PIXELS
/// </java-name>
[Dot42.DexImport("EGL_MAX_PBUFFER_PIXELS", "I", AccessFlags = 25)]
public const int EGL_MAX_PBUFFER_PIXELS = 12331;
/// <java-name>
/// EGL_MAX_PBUFFER_WIDTH
/// </java-name>
[Dot42.DexImport("EGL_MAX_PBUFFER_WIDTH", "I", AccessFlags = 25)]
public const int EGL_MAX_PBUFFER_WIDTH = 12332;
/// <java-name>
/// EGL_NATIVE_RENDERABLE
/// </java-name>
[Dot42.DexImport("EGL_NATIVE_RENDERABLE", "I", AccessFlags = 25)]
public const int EGL_NATIVE_RENDERABLE = 12333;
/// <java-name>
/// EGL_NATIVE_VISUAL_ID
/// </java-name>
[Dot42.DexImport("EGL_NATIVE_VISUAL_ID", "I", AccessFlags = 25)]
public const int EGL_NATIVE_VISUAL_ID = 12334;
/// <java-name>
/// EGL_NATIVE_VISUAL_TYPE
/// </java-name>
[Dot42.DexImport("EGL_NATIVE_VISUAL_TYPE", "I", AccessFlags = 25)]
public const int EGL_NATIVE_VISUAL_TYPE = 12335;
/// <java-name>
/// EGL_SAMPLES
/// </java-name>
[Dot42.DexImport("EGL_SAMPLES", "I", AccessFlags = 25)]
public const int EGL_SAMPLES = 12337;
/// <java-name>
/// EGL_SAMPLE_BUFFERS
/// </java-name>
[Dot42.DexImport("EGL_SAMPLE_BUFFERS", "I", AccessFlags = 25)]
public const int EGL_SAMPLE_BUFFERS = 12338;
/// <java-name>
/// EGL_SURFACE_TYPE
/// </java-name>
[Dot42.DexImport("EGL_SURFACE_TYPE", "I", AccessFlags = 25)]
public const int EGL_SURFACE_TYPE = 12339;
/// <java-name>
/// EGL_TRANSPARENT_TYPE
/// </java-name>
[Dot42.DexImport("EGL_TRANSPARENT_TYPE", "I", AccessFlags = 25)]
public const int EGL_TRANSPARENT_TYPE = 12340;
/// <java-name>
/// EGL_TRANSPARENT_BLUE_VALUE
/// </java-name>
[Dot42.DexImport("EGL_TRANSPARENT_BLUE_VALUE", "I", AccessFlags = 25)]
public const int EGL_TRANSPARENT_BLUE_VALUE = 12341;
/// <java-name>
/// EGL_TRANSPARENT_GREEN_VALUE
/// </java-name>
[Dot42.DexImport("EGL_TRANSPARENT_GREEN_VALUE", "I", AccessFlags = 25)]
public const int EGL_TRANSPARENT_GREEN_VALUE = 12342;
/// <java-name>
/// EGL_TRANSPARENT_RED_VALUE
/// </java-name>
[Dot42.DexImport("EGL_TRANSPARENT_RED_VALUE", "I", AccessFlags = 25)]
public const int EGL_TRANSPARENT_RED_VALUE = 12343;
/// <java-name>
/// EGL_NONE
/// </java-name>
[Dot42.DexImport("EGL_NONE", "I", AccessFlags = 25)]
public const int EGL_NONE = 12344;
/// <java-name>
/// EGL_LUMINANCE_SIZE
/// </java-name>
[Dot42.DexImport("EGL_LUMINANCE_SIZE", "I", AccessFlags = 25)]
public const int EGL_LUMINANCE_SIZE = 12349;
/// <java-name>
/// EGL_ALPHA_MASK_SIZE
/// </java-name>
[Dot42.DexImport("EGL_ALPHA_MASK_SIZE", "I", AccessFlags = 25)]
public const int EGL_ALPHA_MASK_SIZE = 12350;
/// <java-name>
/// EGL_COLOR_BUFFER_TYPE
/// </java-name>
[Dot42.DexImport("EGL_COLOR_BUFFER_TYPE", "I", AccessFlags = 25)]
public const int EGL_COLOR_BUFFER_TYPE = 12351;
/// <java-name>
/// EGL_RENDERABLE_TYPE
/// </java-name>
[Dot42.DexImport("EGL_RENDERABLE_TYPE", "I", AccessFlags = 25)]
public const int EGL_RENDERABLE_TYPE = 12352;
/// <java-name>
/// EGL_SLOW_CONFIG
/// </java-name>
[Dot42.DexImport("EGL_SLOW_CONFIG", "I", AccessFlags = 25)]
public const int EGL_SLOW_CONFIG = 12368;
/// <java-name>
/// EGL_NON_CONFORMANT_CONFIG
/// </java-name>
[Dot42.DexImport("EGL_NON_CONFORMANT_CONFIG", "I", AccessFlags = 25)]
public const int EGL_NON_CONFORMANT_CONFIG = 12369;
/// <java-name>
/// EGL_TRANSPARENT_RGB
/// </java-name>
[Dot42.DexImport("EGL_TRANSPARENT_RGB", "I", AccessFlags = 25)]
public const int EGL_TRANSPARENT_RGB = 12370;
/// <java-name>
/// EGL_RGB_BUFFER
/// </java-name>
[Dot42.DexImport("EGL_RGB_BUFFER", "I", AccessFlags = 25)]
public const int EGL_RGB_BUFFER = 12430;
/// <java-name>
/// EGL_LUMINANCE_BUFFER
/// </java-name>
[Dot42.DexImport("EGL_LUMINANCE_BUFFER", "I", AccessFlags = 25)]
public const int EGL_LUMINANCE_BUFFER = 12431;
/// <java-name>
/// EGL_VENDOR
/// </java-name>
[Dot42.DexImport("EGL_VENDOR", "I", AccessFlags = 25)]
public const int EGL_VENDOR = 12371;
/// <java-name>
/// EGL_VERSION
/// </java-name>
[Dot42.DexImport("EGL_VERSION", "I", AccessFlags = 25)]
public const int EGL_VERSION = 12372;
/// <java-name>
/// EGL_EXTENSIONS
/// </java-name>
[Dot42.DexImport("EGL_EXTENSIONS", "I", AccessFlags = 25)]
public const int EGL_EXTENSIONS = 12373;
/// <java-name>
/// EGL_HEIGHT
/// </java-name>
[Dot42.DexImport("EGL_HEIGHT", "I", AccessFlags = 25)]
public const int EGL_HEIGHT = 12374;
/// <java-name>
/// EGL_WIDTH
/// </java-name>
[Dot42.DexImport("EGL_WIDTH", "I", AccessFlags = 25)]
public const int EGL_WIDTH = 12375;
/// <java-name>
/// EGL_LARGEST_PBUFFER
/// </java-name>
[Dot42.DexImport("EGL_LARGEST_PBUFFER", "I", AccessFlags = 25)]
public const int EGL_LARGEST_PBUFFER = 12376;
/// <java-name>
/// EGL_RENDER_BUFFER
/// </java-name>
[Dot42.DexImport("EGL_RENDER_BUFFER", "I", AccessFlags = 25)]
public const int EGL_RENDER_BUFFER = 12422;
/// <java-name>
/// EGL_COLORSPACE
/// </java-name>
[Dot42.DexImport("EGL_COLORSPACE", "I", AccessFlags = 25)]
public const int EGL_COLORSPACE = 12423;
/// <java-name>
/// EGL_ALPHA_FORMAT
/// </java-name>
[Dot42.DexImport("EGL_ALPHA_FORMAT", "I", AccessFlags = 25)]
public const int EGL_ALPHA_FORMAT = 12424;
/// <java-name>
/// EGL_HORIZONTAL_RESOLUTION
/// </java-name>
[Dot42.DexImport("EGL_HORIZONTAL_RESOLUTION", "I", AccessFlags = 25)]
public const int EGL_HORIZONTAL_RESOLUTION = 12432;
/// <java-name>
/// EGL_VERTICAL_RESOLUTION
/// </java-name>
[Dot42.DexImport("EGL_VERTICAL_RESOLUTION", "I", AccessFlags = 25)]
public const int EGL_VERTICAL_RESOLUTION = 12433;
/// <java-name>
/// EGL_PIXEL_ASPECT_RATIO
/// </java-name>
[Dot42.DexImport("EGL_PIXEL_ASPECT_RATIO", "I", AccessFlags = 25)]
public const int EGL_PIXEL_ASPECT_RATIO = 12434;
/// <java-name>
/// EGL_SINGLE_BUFFER
/// </java-name>
[Dot42.DexImport("EGL_SINGLE_BUFFER", "I", AccessFlags = 25)]
public const int EGL_SINGLE_BUFFER = 12421;
/// <java-name>
/// EGL_CORE_NATIVE_ENGINE
/// </java-name>
[Dot42.DexImport("EGL_CORE_NATIVE_ENGINE", "I", AccessFlags = 25)]
public const int EGL_CORE_NATIVE_ENGINE = 12379;
/// <java-name>
/// EGL_DRAW
/// </java-name>
[Dot42.DexImport("EGL_DRAW", "I", AccessFlags = 25)]
public const int EGL_DRAW = 12377;
/// <java-name>
/// EGL_READ
/// </java-name>
[Dot42.DexImport("EGL_READ", "I", AccessFlags = 25)]
public const int EGL_READ = 12378;
/// <java-name>
/// EGL_DONT_CARE
/// </java-name>
[Dot42.DexImport("EGL_DONT_CARE", "I", AccessFlags = 25)]
public const int EGL_DONT_CARE = -1;
/// <java-name>
/// EGL_PBUFFER_BIT
/// </java-name>
[Dot42.DexImport("EGL_PBUFFER_BIT", "I", AccessFlags = 25)]
public const int EGL_PBUFFER_BIT = 1;
/// <java-name>
/// EGL_PIXMAP_BIT
/// </java-name>
[Dot42.DexImport("EGL_PIXMAP_BIT", "I", AccessFlags = 25)]
public const int EGL_PIXMAP_BIT = 2;
/// <java-name>
/// EGL_WINDOW_BIT
/// </java-name>
[Dot42.DexImport("EGL_WINDOW_BIT", "I", AccessFlags = 25)]
public const int EGL_WINDOW_BIT = 4;
/// <java-name>
/// EGL_DEFAULT_DISPLAY
/// </java-name>
[Dot42.DexImport("EGL_DEFAULT_DISPLAY", "Ljava/lang/Object;", AccessFlags = 25)]
public static readonly object EGL_DEFAULT_DISPLAY;
/// <java-name>
/// EGL_NO_DISPLAY
/// </java-name>
[Dot42.DexImport("EGL_NO_DISPLAY", "Ljavax/microedition/khronos/egl/EGLDisplay;", AccessFlags = 25)]
public static readonly global::Javax.Microedition.Khronos.Egl.EGLDisplay EGL_NO_DISPLAY;
/// <java-name>
/// EGL_NO_CONTEXT
/// </java-name>
[Dot42.DexImport("EGL_NO_CONTEXT", "Ljavax/microedition/khronos/egl/EGLContext;", AccessFlags = 25)]
public static readonly global::Javax.Microedition.Khronos.Egl.EGLContext EGL_NO_CONTEXT;
/// <java-name>
/// EGL_NO_SURFACE
/// </java-name>
[Dot42.DexImport("EGL_NO_SURFACE", "Ljavax/microedition/khronos/egl/EGLSurface;", AccessFlags = 25)]
public static readonly global::Javax.Microedition.Khronos.Egl.EGLSurface EGL_NO_SURFACE;
}
/// <java-name>
/// javax/microedition/khronos/egl/EGL10
/// </java-name>
[Dot42.DexImport("javax/microedition/khronos/egl/EGL10", AccessFlags = 1537)]
public partial interface IEGL10 : global::Javax.Microedition.Khronos.Egl.IEGL
/* scope: __dot42__ */
{
/// <java-name>
/// eglChooseConfig
/// </java-name>
[Dot42.DexImport("eglChooseConfig", "(Ljavax/microedition/khronos/egl/EGLDisplay;[I[Ljavax/microedition/khronos/egl/EG" +
"LConfig;I[I)Z", AccessFlags = 1025)]
bool EglChooseConfig(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, int[] attrib_list, global::Javax.Microedition.Khronos.Egl.EGLConfig[] configs, int config_size, int[] num_config) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglCopyBuffers
/// </java-name>
[Dot42.DexImport("eglCopyBuffers", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLSu" +
"rface;Ljava/lang/Object;)Z", AccessFlags = 1025)]
bool EglCopyBuffers(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLSurface surface, object native_pixmap) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglCreateContext
/// </java-name>
[Dot42.DexImport("eglCreateContext", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" +
"nfig;Ljavax/microedition/khronos/egl/EGLContext;[I)Ljavax/microedition/khronos/e" +
"gl/EGLContext;", AccessFlags = 1025)]
global::Javax.Microedition.Khronos.Egl.EGLContext EglCreateContext(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig config, global::Javax.Microedition.Khronos.Egl.EGLContext share_context, int[] attrib_list) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglCreatePbufferSurface
/// </java-name>
[Dot42.DexImport("eglCreatePbufferSurface", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" +
"nfig;[I)Ljavax/microedition/khronos/egl/EGLSurface;", AccessFlags = 1025)]
global::Javax.Microedition.Khronos.Egl.EGLSurface EglCreatePbufferSurface(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig config, int[] attrib_list) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglCreatePixmapSurface
/// </java-name>
[Dot42.DexImport("eglCreatePixmapSurface", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" +
"nfig;Ljava/lang/Object;[I)Ljavax/microedition/khronos/egl/EGLSurface;", AccessFlags = 1025)]
global::Javax.Microedition.Khronos.Egl.EGLSurface EglCreatePixmapSurface(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig config, object native_pixmap, int[] attrib_list) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglCreateWindowSurface
/// </java-name>
[Dot42.DexImport("eglCreateWindowSurface", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" +
"nfig;Ljava/lang/Object;[I)Ljavax/microedition/khronos/egl/EGLSurface;", AccessFlags = 1025)]
global::Javax.Microedition.Khronos.Egl.EGLSurface EglCreateWindowSurface(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig config, object native_window, int[] attrib_list) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglDestroyContext
/// </java-name>
[Dot42.DexImport("eglDestroyContext", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" +
"ntext;)Z", AccessFlags = 1025)]
bool EglDestroyContext(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLContext context) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglDestroySurface
/// </java-name>
[Dot42.DexImport("eglDestroySurface", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLSu" +
"rface;)Z", AccessFlags = 1025)]
bool EglDestroySurface(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLSurface surface) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglGetConfigAttrib
/// </java-name>
[Dot42.DexImport("eglGetConfigAttrib", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" +
"nfig;I[I)Z", AccessFlags = 1025)]
bool EglGetConfigAttrib(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig config, int attribute, int[] value) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglGetConfigs
/// </java-name>
[Dot42.DexImport("eglGetConfigs", "(Ljavax/microedition/khronos/egl/EGLDisplay;[Ljavax/microedition/khronos/egl/EGLC" +
"onfig;I[I)Z", AccessFlags = 1025)]
bool EglGetConfigs(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig[] configs, int config_size, int[] num_config) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglGetCurrentContext
/// </java-name>
[Dot42.DexImport("eglGetCurrentContext", "()Ljavax/microedition/khronos/egl/EGLContext;", AccessFlags = 1025)]
global::Javax.Microedition.Khronos.Egl.EGLContext EglGetCurrentContext() /* MethodBuilder.Create */ ;
/// <java-name>
/// eglGetCurrentDisplay
/// </java-name>
[Dot42.DexImport("eglGetCurrentDisplay", "()Ljavax/microedition/khronos/egl/EGLDisplay;", AccessFlags = 1025)]
global::Javax.Microedition.Khronos.Egl.EGLDisplay EglGetCurrentDisplay() /* MethodBuilder.Create */ ;
/// <java-name>
/// eglGetCurrentSurface
/// </java-name>
[Dot42.DexImport("eglGetCurrentSurface", "(I)Ljavax/microedition/khronos/egl/EGLSurface;", AccessFlags = 1025)]
global::Javax.Microedition.Khronos.Egl.EGLSurface EglGetCurrentSurface(int readdraw) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglGetDisplay
/// </java-name>
[Dot42.DexImport("eglGetDisplay", "(Ljava/lang/Object;)Ljavax/microedition/khronos/egl/EGLDisplay;", AccessFlags = 1025)]
global::Javax.Microedition.Khronos.Egl.EGLDisplay EglGetDisplay(object native_display) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglGetError
/// </java-name>
[Dot42.DexImport("eglGetError", "()I", AccessFlags = 1025)]
int EglGetError() /* MethodBuilder.Create */ ;
/// <java-name>
/// eglInitialize
/// </java-name>
[Dot42.DexImport("eglInitialize", "(Ljavax/microedition/khronos/egl/EGLDisplay;[I)Z", AccessFlags = 1025)]
bool EglInitialize(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, int[] major_minor) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglMakeCurrent
/// </java-name>
[Dot42.DexImport("eglMakeCurrent", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLSu" +
"rface;Ljavax/microedition/khronos/egl/EGLSurface;Ljavax/microedition/khronos/egl" +
"/EGLContext;)Z", AccessFlags = 1025)]
bool EglMakeCurrent(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLSurface draw, global::Javax.Microedition.Khronos.Egl.EGLSurface read, global::Javax.Microedition.Khronos.Egl.EGLContext context) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglQueryContext
/// </java-name>
[Dot42.DexImport("eglQueryContext", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" +
"ntext;I[I)Z", AccessFlags = 1025)]
bool EglQueryContext(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLContext context, int attribute, int[] value) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglQueryString
/// </java-name>
[Dot42.DexImport("eglQueryString", "(Ljavax/microedition/khronos/egl/EGLDisplay;I)Ljava/lang/String;", AccessFlags = 1025)]
string EglQueryString(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, int name) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglQuerySurface
/// </java-name>
[Dot42.DexImport("eglQuerySurface", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLSu" +
"rface;I[I)Z", AccessFlags = 1025)]
bool EglQuerySurface(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLSurface surface, int attribute, int[] value) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglSwapBuffers
/// </java-name>
[Dot42.DexImport("eglSwapBuffers", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLSu" +
"rface;)Z", AccessFlags = 1025)]
bool EglSwapBuffers(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLSurface surface) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglTerminate
/// </java-name>
[Dot42.DexImport("eglTerminate", "(Ljavax/microedition/khronos/egl/EGLDisplay;)Z", AccessFlags = 1025)]
bool EglTerminate(global::Javax.Microedition.Khronos.Egl.EGLDisplay display) /* MethodBuilder.Create */ ;
/// <java-name>
/// eglWaitGL
/// </java-name>
[Dot42.DexImport("eglWaitGL", "()Z", AccessFlags = 1025)]
bool EglWaitGL() /* MethodBuilder.Create */ ;
/// <java-name>
/// eglWaitNative
/// </java-name>
[Dot42.DexImport("eglWaitNative", "(ILjava/lang/Object;)Z", AccessFlags = 1025)]
bool EglWaitNative(int engine, object bindTarget) /* MethodBuilder.Create */ ;
}
/// <java-name>
/// javax/microedition/khronos/egl/EGLConfig
/// </java-name>
[Dot42.DexImport("javax/microedition/khronos/egl/EGLConfig", AccessFlags = 1057)]
public abstract partial class EGLConfig
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public EGLConfig() /* MethodBuilder.Create */
{
}
}
/// <java-name>
/// javax/microedition/khronos/egl/EGL
/// </java-name>
[Dot42.DexImport("javax/microedition/khronos/egl/EGL", AccessFlags = 1537)]
public partial interface IEGL
/* scope: __dot42__ */
{
}
/// <java-name>
/// javax/microedition/khronos/egl/EGLContext
/// </java-name>
[Dot42.DexImport("javax/microedition/khronos/egl/EGLContext", AccessFlags = 1057)]
public abstract partial class EGLContext
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public EGLContext() /* MethodBuilder.Create */
{
}
/// <java-name>
/// getEGL
/// </java-name>
[Dot42.DexImport("getEGL", "()Ljavax/microedition/khronos/egl/EGL;", AccessFlags = 9)]
public static global::Javax.Microedition.Khronos.Egl.IEGL GetEGL() /* MethodBuilder.Create */
{
return default(global::Javax.Microedition.Khronos.Egl.IEGL);
}
/// <java-name>
/// getGL
/// </java-name>
[Dot42.DexImport("getGL", "()Ljavax/microedition/khronos/opengles/GL;", AccessFlags = 1025)]
public abstract global::Javax.Microedition.Khronos.Opengles.IGL GetGL() /* MethodBuilder.Create */ ;
/// <java-name>
/// getEGL
/// </java-name>
public static global::Javax.Microedition.Khronos.Egl.IEGL EGL
{
[Dot42.DexImport("getEGL", "()Ljavax/microedition/khronos/egl/EGL;", AccessFlags = 9)]
get{ return GetEGL(); }
}
/// <java-name>
/// getGL
/// </java-name>
public global::Javax.Microedition.Khronos.Opengles.IGL GL
{
[Dot42.DexImport("getGL", "()Ljavax/microedition/khronos/opengles/GL;", AccessFlags = 1025)]
get{ return GetGL(); }
}
}
/// <java-name>
/// javax/microedition/khronos/egl/EGL11
/// </java-name>
[Dot42.DexImport("javax/microedition/khronos/egl/EGL11", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IEGL11Constants
/* scope: __dot42__ */
{
/// <java-name>
/// EGL_CONTEXT_LOST
/// </java-name>
[Dot42.DexImport("EGL_CONTEXT_LOST", "I", AccessFlags = 25)]
public const int EGL_CONTEXT_LOST = 12302;
}
/// <java-name>
/// javax/microedition/khronos/egl/EGL11
/// </java-name>
[Dot42.DexImport("javax/microedition/khronos/egl/EGL11", AccessFlags = 1537)]
public partial interface IEGL11 : global::Javax.Microedition.Khronos.Egl.IEGL10
/* scope: __dot42__ */
{
}
/// <java-name>
/// javax/microedition/khronos/egl/EGLDisplay
/// </java-name>
[Dot42.DexImport("javax/microedition/khronos/egl/EGLDisplay", AccessFlags = 1057)]
public abstract partial class EGLDisplay
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public EGLDisplay() /* MethodBuilder.Create */
{
}
}
/// <java-name>
/// javax/microedition/khronos/egl/EGLSurface
/// </java-name>
[Dot42.DexImport("javax/microedition/khronos/egl/EGLSurface", AccessFlags = 1057)]
public abstract partial class EGLSurface
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public EGLSurface() /* MethodBuilder.Create */
{
}
}
}
| |
// ReSharper disable InconsistentNaming
using System;
using System.Text;
using EasyNetQ.Consumer;
using EasyNetQ.Tests.Mocking;
using NUnit.Framework;
using RabbitMQ.Client;
using Rhino.Mocks;
namespace EasyNetQ.Tests
{
[TestFixture]
public class When_using_default_conventions
{
private Conventions conventions;
private ITypeNameSerializer typeNameSerializer;
[SetUp]
public void SetUp()
{
typeNameSerializer = new TypeNameSerializer();
conventions = new Conventions(typeNameSerializer);
}
[Test]
public void The_default_exchange_naming_convention_should_use_the_TypeNameSerializers_Serialize_method()
{
var result = conventions.ExchangeNamingConvention(typeof (TestMessage));
result.ShouldEqual(typeNameSerializer.Serialize(typeof(TestMessage)));
}
[Test]
public void The_default_topic_naming_convention_should_return_an_empty_string()
{
var result = conventions.TopicNamingConvention(typeof (TestMessage));
result.ShouldEqual("");
}
[Test]
public void The_default_queue_naming_convention_should_use_the_TypeNameSerializers_Serialize_method_then_an_underscore_then_the_subscription_id()
{
const string subscriptionId = "test";
var result = conventions.QueueNamingConvention(typeof (TestMessage), subscriptionId);
result.ShouldEqual(typeNameSerializer.Serialize(typeof(TestMessage)) + "_" + subscriptionId);
}
[Test]
public void The_default_error_queue_name_should_be()
{
var result = conventions.ErrorQueueNamingConvention(new MessageReceivedInfo());
result.ShouldEqual("EasyNetQ_Default_Error_Queue");
}
[Test]
public void The_default_error_exchange_name_should_be()
{
var info = new MessageReceivedInfo("consumer_tag", 0, false, "exchange", "routingKey", "queue");
var result = conventions.ErrorExchangeNamingConvention(info);
result.ShouldEqual("ErrorExchange_routingKey");
}
[Test]
public void The_default_rpc_exchange_name_should_be()
{
var result = conventions.RpcExchangeNamingConvention();
result.ShouldEqual("easy_net_q_rpc");
}
[Test]
public void The_default_rpc_routingkey_naming_convention_should_use_the_TypeNameSerializers_Serialize_method()
{
var result = conventions.RpcRoutingKeyNamingConvention(typeof(TestMessage));
result.ShouldEqual(typeNameSerializer.Serialize(typeof(TestMessage)));
}
}
[TestFixture]
public class When_using_QueueAttribute
{
private Conventions conventions;
private ITypeNameSerializer typeNameSerializer;
[SetUp]
public void SetUp()
{
typeNameSerializer = new TypeNameSerializer();
conventions = new Conventions(typeNameSerializer);
}
[Test]
[TestCase(typeof(AnnotatedTestMessage))]
[TestCase(typeof(IAnnotatedTestMessage))]
public void The_queue_naming_convention_should_use_attribute_queueName_then_an_underscore_then_the_subscription_id(Type messageType)
{
const string subscriptionId = "test";
var result = conventions.QueueNamingConvention(messageType, subscriptionId);
result.ShouldEqual("MyQueue" + "_" + subscriptionId);
}
[Test]
[TestCase(typeof(AnnotatedTestMessage))]
[TestCase(typeof(IAnnotatedTestMessage))]
public void And_subscription_id_is_empty_the_queue_naming_convention_should_use_attribute_queueName(Type messageType)
{
const string subscriptionId = "";
var result = conventions.QueueNamingConvention(messageType, subscriptionId);
result.ShouldEqual("MyQueue");
}
[Test]
[TestCase(typeof(EmptyQueueNameAnnotatedTestMessage))]
[TestCase(typeof(IEmptyQueueNameAnnotatedTestMessage))]
public void And_queueName_is_empty_should_use_the_TypeNameSerializers_Serialize_method_then_an_underscore_then_the_subscription_id(Type messageType)
{
const string subscriptionId = "test";
var result = conventions.QueueNamingConvention(messageType, subscriptionId);
result.ShouldEqual(typeNameSerializer.Serialize(messageType) + "_" + subscriptionId);
}
[Test]
[TestCase(typeof(AnnotatedTestMessage))]
[TestCase(typeof(IAnnotatedTestMessage))]
public void The_exchange_name_convention_should_use_attribute_exchangeName(Type messageType)
{
var result = conventions.ExchangeNamingConvention(messageType);
result.ShouldEqual("MyExchange");
}
[Test]
[TestCase(typeof(QueueNameOnlyAnnotatedTestMessage))]
[TestCase(typeof(IQueueNameOnlyAnnotatedTestMessage))]
public void And_exchangeName_not_specified_the_exchange_name_convention_should_use_the_TypeNameSerializers_Serialize_method(Type messageType)
{
var result = conventions.ExchangeNamingConvention(messageType);
result.ShouldEqual(typeNameSerializer.Serialize(messageType));
}
}
[TestFixture]
public class When_publishing_a_message
{
private MockBuilder mockBuilder;
private ITypeNameSerializer typeNameSerializer;
[SetUp]
public void SetUp()
{
typeNameSerializer = new TypeNameSerializer();
var customConventions = new Conventions(typeNameSerializer)
{
ExchangeNamingConvention = x => "CustomExchangeNamingConvention",
QueueNamingConvention = (x, y) => "CustomQueueNamingConvention",
TopicNamingConvention = x => "CustomTopicNamingConvention"
};
mockBuilder = new MockBuilder(x => x.Register<IConventions>(_ => customConventions));
mockBuilder.Bus.Publish(new TestMessage());
}
[Test]
public void Should_use_exchange_name_from_conventions_to_create_the_exchange()
{
mockBuilder.Channels[0].AssertWasCalled(x =>
x.ExchangeDeclare("CustomExchangeNamingConvention", "topic", true, false, null));
}
[Test]
public void Should_use_exchange_name_from_conventions_as_the_exchange_to_publish_to()
{
mockBuilder.Channels[0].AssertWasCalled(x =>
x.BasicPublish(
Arg<string>.Is.Equal("CustomExchangeNamingConvention"),
Arg<string>.Is.Anything,
Arg<bool>.Is.Equal(false),
Arg<bool>.Is.Equal(false),
Arg<IBasicProperties>.Is.Anything,
Arg<byte[]>.Is.Anything));
}
[Test]
public void Should_use_topic_name_from_conventions_as_the_topic_to_publish_to()
{
mockBuilder.Channels[0].AssertWasCalled(x =>
x.BasicPublish(
Arg<string>.Is.Anything,
Arg<string>.Is.Equal("CustomTopicNamingConvention"),
Arg<bool>.Is.Equal(false),
Arg<bool>.Is.Equal(false),
Arg<IBasicProperties>.Is.Anything,
Arg<byte[]>.Is.Anything));
}
}
[TestFixture]
public class When_registering_response_handler
{
private MockBuilder mockBuilder;
[SetUp]
public void SetUp()
{
var customConventions = new Conventions(new TypeNameSerializer())
{
RpcExchangeNamingConvention = () => "CustomRpcExchangeName",
RpcRoutingKeyNamingConvention = messageType => "CustomRpcRoutingKeyName"
};
mockBuilder = new MockBuilder(x => x.Register<IConventions>(_ => customConventions));
mockBuilder.Bus.Respond<TestMessage, TestMessage>(t => new TestMessage());
}
[Test]
public void Should_correctly_bind_using_new_conventions()
{
mockBuilder.Channels[0].AssertWasCalled(x =>
x.QueueBind(
"CustomRpcRoutingKeyName",
"CustomRpcExchangeName",
"CustomRpcRoutingKeyName"));
}
[Test]
public void Should_declare_correct_exchange()
{
mockBuilder.Channels[0].AssertWasCalled(x =>
x.ExchangeDeclare("CustomRpcExchangeName", "direct", true, false, null));
}
}
[TestFixture]
public class When_using_default_consumer_error_strategy
{
private DefaultConsumerErrorStrategy errorStrategy;
private MockBuilder mockBuilder;
private AckStrategy errorAckStrategy;
private AckStrategy cancelAckStrategy;
[SetUp]
public void SetUp()
{
var customConventions = new Conventions(new TypeNameSerializer())
{
ErrorQueueNamingConvention = info => "CustomEasyNetQErrorQueueName." + info.Queue,
ErrorExchangeNamingConvention = info => "CustomErrorExchangePrefixName." + info.RoutingKey
};
mockBuilder = new MockBuilder();
errorStrategy = new DefaultConsumerErrorStrategy(
mockBuilder.ConnectionFactory,
new JsonSerializer(new TypeNameSerializer()),
MockRepository.GenerateStub<IEasyNetQLogger>(),
customConventions,
new TypeNameSerializer());
const string originalMessage = "";
var originalMessageBody = Encoding.UTF8.GetBytes(originalMessage);
var context = new ConsumerExecutionContext(
(bytes, properties, arg3) => null,
new MessageReceivedInfo("consumerTag", 0, false, "orginalExchange", "originalRoutingKey", "originalQueue"),
new MessageProperties
{
CorrelationId = string.Empty,
AppId = string.Empty
},
originalMessageBody,
MockRepository.GenerateStub<IBasicConsumer>()
);
try
{
errorAckStrategy = errorStrategy.HandleConsumerError(context, new Exception());
cancelAckStrategy = errorStrategy.HandleConsumerCancelled(context);
}
catch (Exception)
{
// swallow
}
}
[Test]
public void Should_use_exchange_name_from_custom_names_provider()
{
mockBuilder.Channels[0].AssertWasCalled(x =>
x.ExchangeDeclare("CustomErrorExchangePrefixName.originalRoutingKey", "direct", true));
}
[Test]
public void Should_use_queue_name_from_custom_names_provider()
{
mockBuilder.Channels[0].AssertWasCalled(x =>
x.QueueDeclare("CustomEasyNetQErrorQueueName.originalQueue", true, false, false, null));
}
[Test]
public void Should_Ack_failed_message()
{
Assert.AreSame(AckStrategies.Ack, errorAckStrategy);
}
[Test]
public void Should_Ack_canceled_message()
{
Assert.AreSame(AckStrategies.Ack, cancelAckStrategy);
}
}
}
// ReSharper restore InconsistentNaming
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.IO;
using System.Xml.Schema;
using Xunit;
using Xunit.Abstractions;
namespace System.Xml.Tests
{
// ===================== ValidateAttribute =====================
public class TCValidateAttribute : CXmlSchemaValidatorTestCase
{
private ITestOutputHelper _output;
private ExceptionVerifier _exVerifier;
public TCValidateAttribute(ITestOutputHelper output) : base(output)
{
_output = output;
_exVerifier = new ExceptionVerifier("System.Xml", _output);
}
[Theory]
[InlineData(null, "")]
[InlineData("attr", null)]
public void PassNull_LocalName_NameSpace__Invalid(String localName, String nameSpace)
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("OneAttributeElement", "", null);
try
{
val.ValidateAttribute(localName, nameSpace, StringGetter("foo"), info);
}
catch (ArgumentNullException)
{
return;
}
Assert.True(false);
}
[Fact]
public void PassNullValueGetter__Invalid()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("OneAttributeElement", "", null);
try
{
val.ValidateAttribute("attr", "", (XmlValueGetter)null, info);
}
catch (ArgumentNullException)
{
return;
}
Assert.True(false);
}
[Fact]
public void PassNullXmlSchemaInfo__Valid()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("OneAttributeElement", "", null);
val.ValidateAttribute("attr", "", StringGetter("foo"), null);
return;
}
[Theory]
[InlineData("RequiredAttribute")]
[InlineData("OptionalAttribute")]
[InlineData("DefaultAttribute")]
[InlineData("FixedAttribute")]
[InlineData("FixedRequiredAttribute")]
public void Validate_Required_Optional_Default_Fixed_FixedRequired_Attribute(String attrType)
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement(attrType + "Element", "", null);
val.ValidateAttribute(attrType, "", StringGetter("foo"), info);
Assert.Equal(info.SchemaAttribute.QualifiedName, new XmlQualifiedName(attrType));
Assert.Equal(info.Validity, XmlSchemaValidity.Valid);
Assert.Equal(info.SchemaType.TypeCode, XmlTypeCode.String);
return;
}
[Fact]
public void ValidateAttributeWithNamespace()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("NamespaceAttributeElement", "", null);
val.ValidateAttribute("attr1", "uri:tempuri", StringGetter("123"), info);
Assert.Equal(info.SchemaAttribute.QualifiedName, new XmlQualifiedName("attr1", "uri:tempuri"));
Assert.Equal(info.Validity, XmlSchemaValidity.Valid);
Assert.Equal(info.SchemaType.TypeCode, XmlTypeCode.Int);
return;
}
[Fact]
public void ValidateAnyAttribute()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("AnyAttributeElement", "", null);
val.ValidateAttribute("SomeAttribute", "", StringGetter("foo"), info);
Assert.Equal(info.Validity, XmlSchemaValidity.NotKnown);
return;
}
[Fact]
public void AskForDefaultAttributesAndValidateThem()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_200_DEF_ATTRIBUTES);
XmlSchemaInfo info = new XmlSchemaInfo();
ArrayList atts = new ArrayList();
val.Initialize();
val.ValidateElement("StressElement", "", null);
val.GetUnspecifiedDefaultAttributes(atts);
foreach (XmlSchemaAttribute a in atts)
{
val.ValidateAttribute(a.QualifiedName.Name, a.QualifiedName.Namespace, StringGetter(a.DefaultValue), info);
Assert.Equal(info.SchemaAttribute, a);
}
atts.Clear();
val.GetUnspecifiedDefaultAttributes(atts);
Assert.Equal(atts.Count, 0);
return;
}
[Fact]
public void ValidateTopLevelAttribute()
{
XmlSchemaValidator val;
XmlSchemaSet schemas = new XmlSchemaSet();
XmlSchemaInfo info = new XmlSchemaInfo();
schemas.Add("", Path.Combine(TestData, XSDFILE_200_DEF_ATTRIBUTES));
schemas.Compile();
val = CreateValidator(schemas);
val.Initialize();
val.ValidateAttribute("BasicAttribute", "", StringGetter("foo"), info);
Assert.Equal(info.SchemaAttribute, schemas.GlobalAttributes[new XmlQualifiedName("BasicAttribute")]);
return;
}
[Fact]
public void ValidateSameAttributeTwice()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("RequiredAttributeElement", "", null);
val.ValidateAttribute("RequiredAttribute", "", StringGetter("foo"), info);
try
{
val.ValidateAttribute("RequiredAttribute", "", StringGetter("foo"), info);
}
catch (XmlSchemaValidationException e)
{
_exVerifier.IsExceptionOk(e, "Sch_DuplicateAttribute", new string[] { "RequiredAttribute" });
return;
}
Assert.True(false);
}
}
// ===================== GetUnspecifiedDefaultAttributes =====================
public class TCGetUnspecifiedDefaultAttributes : CXmlSchemaValidatorTestCase
{
private ITestOutputHelper _output;
public TCGetUnspecifiedDefaultAttributes(ITestOutputHelper output) : base(output)
{
_output = output;
}
[Fact]
public void PassNull__Invalid()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("OneAttributeElement", "", null);
try
{
val.GetUnspecifiedDefaultAttributes(null);
}
catch (ArgumentNullException)
{
return;
}
Assert.True(false);
}
[Fact]
public void CallTwice()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE);
ArrayList atts = new ArrayList();
val.Initialize();
val.ValidateElement("MixedAttributesElement", "", null);
val.GetUnspecifiedDefaultAttributes(atts);
CheckDefaultAttributes(atts, new string[] { "def1", "def2" });
atts.Clear();
val.GetUnspecifiedDefaultAttributes(atts);
CheckDefaultAttributes(atts, new string[] { "def1", "def2" });
return;
}
[Fact]
public void NestBetweenValidateAttributeCalls()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE);
ArrayList atts = new ArrayList();
val.Initialize();
val.ValidateElement("MixedAttributesElement", "", null);
val.GetUnspecifiedDefaultAttributes(atts);
CheckDefaultAttributes(atts, new string[] { "def1", "def2" });
val.ValidateAttribute("req1", "", StringGetter("foo"), null);
atts.Clear();
val.GetUnspecifiedDefaultAttributes(atts);
CheckDefaultAttributes(atts, new string[] { "def1", "def2" });
val.ValidateAttribute("req2", "", StringGetter("foo"), null);
atts.Clear();
val.GetUnspecifiedDefaultAttributes(atts);
CheckDefaultAttributes(atts, new string[] { "def1", "def2" });
return;
}
[Fact]
public void CallAfterGetExpectedAttributes()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE);
ArrayList atts = new ArrayList();
val.Initialize();
val.ValidateElement("MixedAttributesElement", "", null);
val.ValidateAttribute("req1", "", StringGetter("foo"), null);
val.GetExpectedAttributes();
val.GetUnspecifiedDefaultAttributes(atts);
CheckDefaultAttributes(atts, new string[] { "def1", "def2" });
return;
}
[Fact]
public void CallAfterValidatingSomeDefaultAttributes()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE);
ArrayList atts = new ArrayList();
val.Initialize();
val.ValidateElement("MixedAttributesElement", "", null);
val.ValidateAttribute("def1", "", StringGetter("foo"), null);
val.GetUnspecifiedDefaultAttributes(atts);
CheckDefaultAttributes(atts, new string[] { "def2" });
val.ValidateAttribute("def2", "", StringGetter("foo"), null);
atts.Clear();
val.GetUnspecifiedDefaultAttributes(atts);
CheckDefaultAttributes(atts, new string[] { });
return;
}
[Fact]
public void CallOnElementWithFixedAttribute()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE);
ArrayList atts = new ArrayList();
val.Initialize();
val.ValidateElement("FixedAttributeElement", "", null);
val.GetUnspecifiedDefaultAttributes(atts);
CheckDefaultAttributes(atts, new string[] { "FixedAttribute" });
return;
}
[Fact]
public void v6a()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE);
ArrayList atts = new ArrayList();
val.Initialize();
val.ValidateElement("FixedRequiredAttributeElement", "", null);
val.GetUnspecifiedDefaultAttributes(atts);
CheckDefaultAttributes(atts, new string[] { });
return;
}
private void CheckDefaultAttributes(ArrayList actual, string[] expected)
{
int nFound;
Assert.Equal(actual.Count, expected.Length);
foreach (string str in expected)
{
nFound = 0;
foreach (XmlSchemaAttribute attr in actual)
{
if (attr.QualifiedName.Name == str)
nFound++;
}
Assert.Equal(nFound, 1);
}
}
}
// ===================== ValidateEndOfAttributes =====================
public class TCValidateEndOfAttributes : CXmlSchemaValidatorTestCase
{
private ITestOutputHelper _output;
private ExceptionVerifier _exVerifier;
public TCValidateEndOfAttributes(ITestOutputHelper output) : base(output)
{
_output = output;
_exVerifier = new ExceptionVerifier("System.Xml", _output);
}
[Fact]
public void CallOnELementWithNoAttributes()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE);
val.Initialize();
val.ValidateElement("NoAttributesElement", "", null);
val.ValidateEndOfAttributes(null);
return;
}
[Fact]
public void CallAfterValidationOfAllAttributes()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE);
val.Initialize();
val.ValidateElement("MixedAttributesElement", "", null);
foreach (string attr in new string[] { "req1", "req2", "def1", "def2" })
val.ValidateAttribute(attr, "", StringGetter("foo"), null);
val.ValidateEndOfAttributes(null);
return;
}
[Theory]
[InlineData("OptionalAttribute")]
[InlineData("FixedAttribute")]
public void CallWithoutValidationOf_Optional_Fixed_Attributes(String attrType)
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE);
val.Initialize();
val.ValidateElement(attrType + "Element", "", null);
val.ValidateEndOfAttributes(null);
return;
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void CallWithoutValidationOfDefaultAttributesGetUnspecifiedDefault_Called_NotCalled(bool call)
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE);
ArrayList atts = new ArrayList();
val.Initialize();
val.ValidateElement("DefaultAttributeElement", "", null);
if (call)
val.GetUnspecifiedDefaultAttributes(atts);
val.ValidateEndOfAttributes(null);
return;
}
[Fact]
public void CallWithoutValidationOfRequiredAttribute()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE);
ArrayList atts = new ArrayList();
val.Initialize();
val.ValidateElement("RequiredAttributeElement", "", null);
try
{
val.ValidateEndOfAttributes(null);
}
catch (XmlSchemaValidationException e)
{
_exVerifier.IsExceptionOk(e, "Sch_MissRequiredAttribute", new string[] { "RequiredAttribute" });
return;
}
Assert.True(false);
}
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010-2015 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT
#define UNITY
#endif
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using MsgPack.Serialization.Polymorphic;
namespace MsgPack.Serialization
{
internal static partial class PreGeneratedSerializerActivator
{
private static readonly IList<Type> _knownTypes = InitializeKnownTypes();
private static readonly Dictionary<Type, MessagePackSerializerProvider> _serializers = InitializeSerializers( _knownTypes );
public static IEnumerable<Type> KnownTypes
{
get { return _knownTypes; }
}
private static Dictionary<Type, MessagePackSerializerProvider> InitializeSerializers( IList<Type> knownTypes )
{
var result = new Dictionary<Type, MessagePackSerializerProvider>( knownTypes.Count );
foreach ( var knownType in knownTypes )
{
if ( knownType.GetIsInterface() || knownType.GetIsAbstract() )
{
// skip
continue;
}
var serializerTypeName =
"MsgPack.Serialization.GeneratedSerializers." + IdentifierUtility.EscapeTypeName( knownType ) + "Serializer";
var serializerType = typeof( PreGeneratedSerializerActivator ).GetAssembly().GetType( serializerTypeName );
Type type = knownType;
var serializer =
new LazyMessagePackSerializerProvider(
knownType,
serializerType != null
? new Func<SerializationContext, PolymorphismSchema, MessagePackSerializer>( SerializerActivator.Create( knownType, serializerType, knownType ).Activate )
: ( ( c, s ) =>
{
throw new Exception(
String.Format(
CultureInfo.CurrentCulture,
"Pre-generated serializer '{0}' for type '{1}' does not exist in this project.",
serializerTypeName,
type
)
);
}
)
);
try
{
result.Add( knownType, serializer );
}
catch ( ArgumentException )
{
// ReSharper disable once NotResolvedInText
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, "Key '{0}' is already added.", knownType ), "key" );
}
}
return result;
}
/// <summary>
/// Creates new <see cref="SerializationContext"/> for generation based testing.
/// </summary>
/// <param name="method"><see cref="SerializationMethod"/>.</param>
/// <param name="compatibilityOptions"><see cref="PackerCompatibilityOptions"/> for built-in serializers.</param>
/// <returns>A new <see cref="SerializationContext"/> for generation based testing.</returns>
public static SerializationContext CreateContext( SerializationMethod method, PackerCompatibilityOptions compatibilityOptions )
{
var context = new SerializationContext( compatibilityOptions ) { SerializationMethod = method };
foreach ( var entry in _serializers )
{
context.Serializers.Register( entry.Key, entry.Value, null, null, SerializerRegistrationOptions.None );
}
#if !AOT
context.SerializerOptions.DisableRuntimeCodeGeneration = true;
#endif // !AOT
return context;
}
/// <summary>
/// Creates new <see cref="SerializationContext"/> for generation based testing.
/// </summary>
/// <param name="method"><see cref="SerializationMethod"/>.</param>
/// <param name="compatibilityLevel"><see cref="SerializationCompatibilityLevel"/> for built-in serializers.</param>
/// <returns>A new <see cref="SerializationContext"/> for generation based testing.</returns>
public static SerializationContext CreateContext( SerializationMethod method, SerializationCompatibilityLevel compatibilityLevel )
{
var context = SerializationContext.CreateClassicContext( compatibilityLevel );
context.SerializationMethod = method;
foreach ( var entry in _serializers )
{
context.Serializers.Register( entry.Key, entry.Value, null, null, SerializerRegistrationOptions.None );
}
#if !AOT
context.SerializerOptions.DisableRuntimeCodeGeneration = true;
#endif // !AOT
return context;
}
private sealed class LazyMessagePackSerializerProvider : MessagePackSerializerProvider
{
private readonly Func<SerializationContext, PolymorphismSchema, MessagePackSerializer> _activator;
private readonly Type _targetType;
public LazyMessagePackSerializerProvider( Type targetType, Func<SerializationContext, PolymorphismSchema, MessagePackSerializer> activator )
{
this._targetType = targetType;
this._activator = activator;
}
public override object Get( SerializationContext context, object providerParameter )
{
return
this._targetType.GetIsEnum()
? new EnumMessagePackSerializerProvider(
this._targetType,
( ICustomizableEnumSerializer )this._activator( context, providerParameter as PolymorphismSchema )
).Get( context, providerParameter )
: this._activator( context, providerParameter as PolymorphismSchema );
}
}
private interface ISerializerActivator
{
MessagePackSerializer Activate( SerializationContext context, PolymorphismSchema schema );
}
private class SerializerActivator
{
protected static readonly Type[] SerializerConstructorParameterTypes1 = { typeof( SerializationContext ) };
protected static readonly Type[] SerializerConstructorParameterTypes3 = { typeof( SerializationContext ), typeof( Type ), typeof( PolymorphismSchema ) };
public static ISerializerActivator Create( Type targetType, Type serializerType, Type serializationTargetType )
{
return
#if !UNITY
( ISerializerActivator )Activator.CreateInstance(
typeof( SerializerActivator<> ).MakeGenericType( targetType ),
serializerType,
serializationTargetType
);
#else
new SerializerActivatorImpl( targetType, serializerType, serializationTargetType );
#endif // !UNITY
}
}
#if !UNITY
private sealed class SerializerActivator<T> : SerializerActivator, ISerializerActivator
#else
private sealed class SerializerActivatorImpl : SerializerActivator, ISerializerActivator
#endif // !UNITY
{
#if UNITY
private readonly Type _targetType;
#endif // UNITY
private readonly Type _serializerType;
private readonly Type _serializationTargetType;
private readonly ConstructorInfo _constructor1;
private readonly ConstructorInfo _constructor3;
#if !UNITY
public SerializerActivator( Type serializerType, Type serializationTargetType )
#else
public SerializerActivatorImpl( Type targetType, Type serializerType, Type serializationTargetType )
#endif // !UNITY
{
#if UNITY
this._targetType = targetType;
#endif // UNITY
this._serializerType = serializerType;
this._serializationTargetType = serializationTargetType;
this._constructor1 = serializerType.GetConstructor( SerializerConstructorParameterTypes1 );
this._constructor3 = serializerType.GetConstructor( SerializerConstructorParameterTypes3 );
}
public MessagePackSerializer Activate( SerializationContext context, PolymorphismSchema schema )
{
if ( this._constructor1 == null && this._constructor3 == null )
{
throw new Exception( "A cosntructor of type '" + this._serializerType.FullName + "' is not found." );
}
#if !UNITY
MessagePackSerializer<T> serializer;
if ( this._constructor1 != null )
{
serializer = ( MessagePackSerializer<T> )this._constructor1.InvokePreservingExceptionType( context );
}
else
{
serializer = ( MessagePackSerializer<T> )this._constructor3.InvokePreservingExceptionType( context, this._serializationTargetType, null );
}
return new PolymorphicSerializerProvider<T>( serializer ).Get( context, schema ?? PolymorphismSchema.Default ) as MessagePackSerializer;
#else
MessagePackSerializer serializer;
if ( this._constructor1 != null )
{
serializer = this._constructor1.InvokePreservingExceptionType( context ) as MessagePackSerializer;
}
else
{
serializer = this._constructor3.InvokePreservingExceptionType( context, this._serializationTargetType, null ) as MessagePackSerializer;
}
return
ReflectionExtensions.CreateInstancePreservingExceptionType<MessagePackSerializerProvider>(
typeof( PolymorphicSerializerProvider<> ).MakeGenericType( this._targetType ),
context,
serializer
).Get( context, schema ?? PolymorphismSchema.Default ) as MessagePackSerializer;
#endif // !UNITY
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Orleans.Utilities;
namespace Orleans.Runtime
{
/// <summary>
/// Formats and parses <see cref="Type"/> instances using configured rules.
/// </summary>
public class TypeConverter
{
private readonly ITypeConverter[] _converters;
private readonly ClrTypeConverter _defaultFormatter;
private readonly Func<QualifiedType, QualifiedType> _convertToDisplayName;
private readonly Func<QualifiedType, QualifiedType> _convertFromDisplayName;
public TypeConverter(IEnumerable<ITypeConverter> formatters)
{
_converters = formatters.ToArray();
_defaultFormatter = new ClrTypeConverter();
_convertToDisplayName = ConvertToDisplayName;
_convertFromDisplayName = ConvertFromDisplayName;
}
/// <summary>
/// Formats the provided type.
/// </summary>
public string Format(Type type) => FormatInternal(type);
/// <summary>
/// Formats the provided type, rewriting elements using the provided delegate.
/// </summary>
internal string Format(Type type, Func<TypeSpec, TypeSpec> rewriter) => FormatInternal(type, rewriter);
/// <summary>
/// Parses the provided type string.
/// </summary>
public Type Parse(string formatted) => ParseInternal(formatted);
private string FormatInternal(Type type, Func<TypeSpec, TypeSpec> rewriter = null)
{
string runtimeType = null;
foreach (var converter in _converters)
{
if (converter.TryFormat(type, out var value))
{
runtimeType = value;
break;
}
}
if (string.IsNullOrWhiteSpace(runtimeType))
{
runtimeType = _defaultFormatter.Format(type);
}
var runtimeTypeSpec = RuntimeTypeNameParser.Parse(runtimeType);
var displayTypeSpec = RuntimeTypeNameRewriter.Rewrite(runtimeTypeSpec, _convertToDisplayName);
if (rewriter is object)
{
displayTypeSpec = rewriter(displayTypeSpec);
}
var formatted = displayTypeSpec.Format();
return formatted;
}
private Type ParseInternal(string formatted)
{
var parsed = RuntimeTypeNameParser.Parse(formatted);
var runtimeTypeSpec = RuntimeTypeNameRewriter.Rewrite(parsed, _convertFromDisplayName);
var runtimeType = runtimeTypeSpec.Format();
foreach (var converter in _converters)
{
if (converter.TryParse(runtimeType, out var result))
{
return result;
}
}
return _defaultFormatter.Parse(runtimeType);
}
private QualifiedType ConvertToDisplayName(QualifiedType input)
{
return input switch
{
(_, "System.Object") => new QualifiedType(null, "object"),
(_, "System.String") => new QualifiedType(null, "string"),
(_, "System.Char") => new QualifiedType(null, "char"),
(_, "System.SByte") => new QualifiedType(null, "sbyte"),
(_, "System.Byte") => new QualifiedType(null, "byte"),
(_, "System.Boolean") => new QualifiedType(null, "bool"),
(_, "System.Int16") => new QualifiedType(null, "short"),
(_, "System.UInt16") => new QualifiedType(null, "ushort"),
(_, "System.Int32") => new QualifiedType(null, "int"),
(_, "System.UInt32") => new QualifiedType(null, "uint"),
(_, "System.Int64") => new QualifiedType(null, "long"),
(_, "System.UInt64") => new QualifiedType(null, "ulong"),
(_, "System.Single") => new QualifiedType(null, "float"),
(_, "System.Double") => new QualifiedType(null, "double"),
(_, "System.Decimal") => new QualifiedType(null, "decimal"),
_ => input,
};
}
private QualifiedType ConvertFromDisplayName(QualifiedType input)
{
return input switch
{
(_, "object") => new QualifiedType(null, "System.Object"),
(_, "string") => new QualifiedType(null, "System.String"),
(_, "char") => new QualifiedType(null, "System.Char"),
(_, "sbyte") => new QualifiedType(null, "System.SByte"),
(_, "byte") => new QualifiedType(null, "System.Byte"),
(_, "bool") => new QualifiedType(null, "System.Boolean"),
(_, "short") => new QualifiedType(null, "System.Int16"),
(_, "ushort") => new QualifiedType(null, "System.UInt16"),
(_, "int") => new QualifiedType(null, "System.Int32"),
(_, "uint") => new QualifiedType(null, "System.UInt32"),
(_, "long") => new QualifiedType(null, "System.Int64"),
(_, "ulong") => new QualifiedType(null, "System.UInt64"),
(_, "float") => new QualifiedType(null, "System.Single"),
(_, "double") => new QualifiedType(null, "System.Double"),
(_, "decimal") => new QualifiedType(null, "System.Decimal"),
_ => input,
};
}
}
/// <summary>
/// Extensions for working with <see cref="TypeConverter"/>.
/// </summary>
public static class TypeConverterExtensions
{
private const char GenericTypeIndicator = '`';
private const char StartArgument = '[';
/// <summary>
/// Returns true if the provided type string is a generic type.
/// </summary>
public static bool IsGenericType(string type)
{
if (string.IsNullOrWhiteSpace(type)) return false;
return type.IndexOf(GenericTypeIndicator) >= 0;
}
/// <summary>
/// Returns true if the provided type string is a constructed generic type.
/// </summary>
public static bool IsConstructed(string type)
{
if (string.IsNullOrWhiteSpace(type)) return false;
var index = type.IndexOf(StartArgument);
return index > 0;
}
/// <summary>
/// Returns the deconstructed form of the provided generic type.
/// </summary>
public static string GetDeconstructed(string type)
{
if (string.IsNullOrWhiteSpace(type)) return null;
var index = type.IndexOf(StartArgument);
if (index <= 0)
{
return type;
}
return type.Substring(0, index);
}
/// <summary>
/// Returns the constructed form of the provided generic type.
/// </summary>
public static string GetConstructed(this TypeConverter formatter, string unconstructed, params Type[] typeArguments)
{
var typeString = unconstructed;
var indicatorIndex = typeString.IndexOf(GenericTypeIndicator);
var argumentsIndex = typeString.IndexOf(StartArgument, indicatorIndex);
if (argumentsIndex >= 0)
{
throw new InvalidOperationException("Cannot construct an already-constructed type");
}
var arityString = typeString.Substring(indicatorIndex + 1);
var arity = int.Parse(arityString);
if (typeArguments.Length != arity)
{
throw new InvalidOperationException($"Insufficient number of type arguments, {typeArguments.Length}, provided while constructing type \"{unconstructed}\" of arity {arity}");
}
var typeSpecs = new TypeSpec[typeArguments.Length];
for (var i = 0; i < typeArguments.Length; i++)
{
typeSpecs[i] = RuntimeTypeNameParser.Parse(formatter.Format(typeArguments[i]));
}
var constructed = new ConstructedGenericTypeSpec(new NamedTypeSpec(null, typeString, typeArguments.Length), typeSpecs).Format();
return constructed;
}
/// <summary>
/// Returns the type arguments for the provided constructed generic type string.
/// </summary>
public static string GetArgumentsString(string type)
{
if (string.IsNullOrWhiteSpace(type)) return null;
var index = type.IndexOf(StartArgument);
if (index <= 0)
{
return null;
}
return type.Substring(index);
}
/// <summary>
/// Returns the type arguments for the provided constructed generic type string.
/// </summary>
public static Type[] GetArguments(this TypeConverter formatter, string constructed)
{
var str = constructed;
var index = str.IndexOf(StartArgument);
if (index <= 0)
{
return Array.Empty<Type>();
}
var safeString = "safer" + str.Substring(str.IndexOf(GenericTypeIndicator));
var parsed = RuntimeTypeNameParser.Parse(safeString);
if (!(parsed is ConstructedGenericTypeSpec spec))
{
throw new InvalidOperationException($"Unable to correctly parse grain type {str}");
}
var result = new Type[spec.Arguments.Length];
for (var i = 0; i < result.Length; i++)
{
var arg = spec.Arguments[i];
var formattedArg = arg.Format();
result[i] = formatter.Parse(formattedArg);
if (result[i] is null)
{
throw new InvalidOperationException($"Unable to parse argument \"{formattedArg}\" as a type for grain type \"{str}\"");
}
}
return result;
}
}
internal class ClrTypeConverter
{
private readonly CachedTypeResolver _resolver = new CachedTypeResolver();
public string Format(Type type) => RuntimeTypeNameFormatter.Format(type);
public Type Parse(string formatted) => _resolver.ResolveType(formatted);
}
/// <summary>
/// Converts between <see cref="Type"/> and <see cref="string"/> representations.
/// </summary>
public interface ITypeConverter
{
/// <summary>
/// Formats the provided type as a string.
/// </summary>
bool TryFormat(Type type, out string formatted);
/// <summary>
/// Parses the provided type.
/// </summary>
bool TryParse(string formatted, out Type type);
}
}
| |
#pragma warning disable 0168
using nHydrate.DataImport;
using nHydrate.Dsl;
using nHydrate.DslPackage.Objects;
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
namespace nHydrate.DslPackage.Forms
{
public partial class RefreshItemFromDatabase : Form
{
#region Class Members
private nHydrateModel _model = null;
private Microsoft.VisualStudio.Modeling.Store _store = null;
private Microsoft.VisualStudio.Modeling.Shell.ModelingDocData _docData = null;
private nHydrate.Dsl.IDatabaseEntity _modelElement = null;
private List<SpecialField> _auditFields = new List<SpecialField>();
private IImportDomain _importDomain = null;
#endregion
public RefreshItemFromDatabase()
{
InitializeComponent();
wizard1.BeforeSwitchPages += new Wizard.Wizard.BeforeSwitchPagesEventHandler(wizard1_BeforeSwitchPages);
wizard1.AfterSwitchPages += new Wizard.Wizard.AfterSwitchPagesEventHandler(wizard1_AfterSwitchPages);
wizard1.Finish += new EventHandler(wizard1_Finish);
cboItem.SelectedIndexChanged += new EventHandler(cboItem_SelectedIndexChanged);
}
public RefreshItemFromDatabase(
nHydrateModel model,
nHydrate.Dsl.IDatabaseEntity modelElement,
Microsoft.VisualStudio.Modeling.Store store,
Microsoft.VisualStudio.Modeling.Shell.ModelingDocData docData)
: this()
{
if (modelElement == null)
throw new Exception("Model element canot be null.");
_model = model;
_store = store;
_modelElement = modelElement;
_importDomain = new nHydrate.DataImport.SqlClient.ImportDomain();
this.DatabaseConnectionControl1.FileName = Path.Combine((new FileInfo(docData.FileName)).DirectoryName, "importconnection.cache");
DatabaseConnectionControl1.LoadSettings();
//Setup new model
_auditFields.Add(new SpecialField { Name = _model.CreatedByColumnName, Type = SpecialFieldTypeConstants.CreatedBy });
_auditFields.Add(new SpecialField { Name = _model.CreatedDateColumnName, Type = SpecialFieldTypeConstants.CreatedDate });
_auditFields.Add(new SpecialField { Name = _model.ModifiedByColumnName, Type = SpecialFieldTypeConstants.ModifiedBy });
_auditFields.Add(new SpecialField { Name = _model.ModifiedDateColumnName, Type = SpecialFieldTypeConstants.ModifiedDate });
_auditFields.Add(new SpecialField { Name = _model.ConcurrencyCheckColumnName, Type = SpecialFieldTypeConstants.Timestamp });
_auditFields.Add(new SpecialField { Name = _model.TenantColumnName, Type = SpecialFieldTypeConstants.Tenant });
wizard1.FinishEnabled = false;
}
private void LoadDatabaseObjects()
{
//var _importDomain = new nHydrate.DataImport.SqlClient.ImportDomain();
//Load database objects for user selection
try
{
var objectName = string.Empty;
if (_modelElement is nHydrate.Dsl.Entity)
{
objectName = (_modelElement as nHydrate.Dsl.Entity).Name;
var list = _importDomain.GetEntityList(DatabaseConnectionControl1.ImportOptions.GetConnectionString());
cboItem.Items.Clear();
cboItem.Items.Add("(Choose One)");
foreach (var item in list)
cboItem.Items.Add(item);
}
else if (_modelElement is nHydrate.Dsl.View)
{
objectName = (_modelElement as nHydrate.Dsl.View).Name;
var list = _importDomain.GetViewList(DatabaseConnectionControl1.ImportOptions.GetConnectionString());
cboItem.Items.Clear();
cboItem.Items.Add("(Choose One)");
foreach (var item in list)
cboItem.Items.Add(item);
}
cboItem.SelectedItem = objectName;
if (cboItem.Items.Count > 0 && cboItem.SelectedIndex == -1)
cboItem.SelectedIndex = 0;
}
catch (Exception ex)
{
throw;
}
}
private void wizard1_AfterSwitchPages(object sender, Wizard.Wizard.AfterSwitchPagesEventArgs e)
{
lblError.Text = string.Empty;
if (wizard1.WizardPages[e.NewIndex] == pageLast)
{
}
}
private void wizard1_BeforeSwitchPages(object sender, Wizard.Wizard.BeforeSwitchPagesEventArgs e)
{
if (wizard1.WizardPages[e.OldIndex] == pageDatabase && wizard1.WizardPages[e.NewIndex] == pageChoose)
{
try
{
LoadDatabaseObjects();
}
catch (Exception ex)
{
MessageBox.Show("There was an error while trying to connect to the database.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
e.Cancel = true;
return;
}
if (cboItem.Items.Count == 0)
{
e.Cancel = true;
MessageBox.Show("No objects could be found in the database.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
}
if (e.NewIndex == 0)
{
//On database page there should be no Finish button
wizard1.FinishEnabled = false;
}
else if (e.NewIndex == 1)
{
//Do Nothing
wizard1.FinishEnabled = false;
}
else if (e.NewIndex == 2)
{
wizard1.FinishEnabled = (cboItem.SelectedIndex != -1);
}
}
private void wizard1_Finish(object sender, EventArgs e)
{
ApplyChanges();
this.DialogResult = System.Windows.Forms.DialogResult.OK;
this.Close();
}
private void ApplyChanges()
{
//Save the actual item
using (var transaction = _store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString()))
{
#region Entity
if (_modelElement is nHydrate.Dsl.Entity)
{
var targetItem = _modelElement as nHydrate.Dsl.Entity;
var importItem = _importDomain.GetEntity(DatabaseConnectionControl1.ImportOptions.GetConnectionString(), (string)cboItem.SelectedItem, _auditFields);
targetItem.AllowCreateAudit = importItem.AllowCreateAudit;
targetItem.AllowModifyAudit = importItem.AllowModifyAudit;
targetItem.AllowTimestamp = importItem.AllowTimestamp;
targetItem.IsTenant = importItem.IsTenant;
DatabaseImportDomain.PopulateFields(_model, importItem, targetItem);
this.Text += " [Entity: " + targetItem.Name + "]";
}
#endregion
#region View
else if (_modelElement is nHydrate.Dsl.View)
{
var targetItem = _modelElement as nHydrate.Dsl.View;
var importItem = _importDomain.GetView(DatabaseConnectionControl1.ImportOptions.GetConnectionString(), (string)cboItem.SelectedItem, _auditFields);
targetItem.SQL = importItem.SQL;
DatabaseImportDomain.PopulateFields(_model, importItem, targetItem);
this.Text += " [View: " + targetItem.Name + "]";
}
#endregion
transaction.Commit();
}
DatabaseConnectionControl1.PersistSettings();
}
private void cboItem_SelectedIndexChanged(object sender, EventArgs e)
{
wizard1.FinishEnabled = (cboItem.SelectedIndex != -1);
}
private void cmdViewDiff_Click(object sender, EventArgs e)
{
SQLObject oldItem = null;
SQLObject newItem = null;
#region Entity
if (_modelElement is nHydrate.Dsl.Entity)
{
oldItem = (_modelElement as nHydrate.Dsl.Entity).ToDatabaseObject();
newItem = _importDomain.GetEntity(DatabaseConnectionControl1.ImportOptions.GetConnectionString(), (string)cboItem.SelectedItem, _auditFields);
}
#endregion
#region View
else if (_modelElement is nHydrate.Dsl.View)
{
oldItem = (_modelElement as nHydrate.Dsl.View).ToDatabaseObject();
newItem = _importDomain.GetView(DatabaseConnectionControl1.ImportOptions.GetConnectionString(), (string)cboItem.SelectedItem, _auditFields);
}
#endregion
var F = new DBObjectDifferenceForm(oldItem, newItem);
if (F.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="ActorPublisher.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Concurrent;
using System.Threading;
using Akka.Actor;
using Akka.Event;
using Akka.Pattern;
using Akka.Streams.Dsl;
using Akka.Streams.Implementation;
using Reactive.Streams;
namespace Akka.Streams.Actors
{
#region Internal messages
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="T">TBD</typeparam>
public sealed class Subscribe<T> : INoSerializationVerificationNeeded, IDeadLetterSuppression
{
/// <summary>
/// TBD
/// </summary>
public readonly ISubscriber<T> Subscriber;
/// <summary>
/// TBD
/// </summary>
/// <param name="subscriber">TBD</param>
public Subscribe(ISubscriber<T> subscriber)
{
Subscriber = subscriber;
}
}
/// <summary>
/// TBD
/// </summary>
[Serializable]
public enum LifecycleState
{
/// <summary>
/// TBD
/// </summary>
PreSubscriber,
/// <summary>
/// TBD
/// </summary>
Active,
/// <summary>
/// TBD
/// </summary>
Canceled,
/// <summary>
/// TBD
/// </summary>
Completed,
/// <summary>
/// TBD
/// </summary>
CompleteThenStop,
/// <summary>
/// TBD
/// </summary>
ErrorEmitted
}
#endregion
/// <summary>
/// TBD
/// </summary>
public interface IActorPublisherMessage: IDeadLetterSuppression { }
/// <summary>
/// This message is delivered to the <see cref="ActorPublisher{T}"/> actor when the stream
/// subscriber requests more elements.
/// </summary>
[Serializable]
public sealed class Request : IActorPublisherMessage
{
/// <summary>
/// TBD
/// </summary>
public readonly long Count;
/// <summary>
/// TBD
/// </summary>
/// <param name="count">TBD</param>
public Request(long count)
{
Count = count;
}
/// <summary>
/// INTERNAL API: needed for stash support
/// </summary>
internal void MarkProcessed() => IsProcessed = true;
/// <summary>
/// INTERNAL API: needed for stash support
/// </summary>
internal bool IsProcessed { get; private set; }
}
/// <summary>
/// This message is delivered to the <see cref="ActorPublisher{T}"/> actor when the stream
/// subscriber cancels the subscription.
/// </summary>
[Serializable]
public sealed class Cancel : IActorPublisherMessage
{
/// <summary>
/// TBD
/// </summary>
public static readonly Cancel Instance = new Cancel();
private Cancel() { }
}
/// <summary>
/// This message is delivered to the <see cref="ActorPublisher{T}"/> actor in order to signal
/// the exceeding of an subscription timeout. Once the actor receives this message, this
/// publisher will already be in cancelled state, thus the actor should clean-up and stop itself.
/// </summary>
[Serializable]
public sealed class SubscriptionTimeoutExceeded : IActorPublisherMessage
{
/// <summary>
/// TBD
/// </summary>
public static readonly SubscriptionTimeoutExceeded Instance = new SubscriptionTimeoutExceeded();
private SubscriptionTimeoutExceeded() { }
}
/// <summary>
/// <para>
/// Extend this actor to make it a stream publisher that keeps track of the subscription life cycle and
/// requested elements.
/// </para>
/// <para>
/// Create a <see cref="IPublisher{T}"/> backed by this actor with <see cref="ActorPublisher.Create{T}"/>.
/// </para>
/// <para>
/// It can be attached to a <see cref="ISubscriber{T}"/> or be used as an input source for a
/// <see cref="IFlow{T,TMat}"/>. You can only attach one subscriber to this publisher.
/// </para>
/// <para>
/// The life cycle state of the subscription is tracked with the following boolean members:
/// <see cref="IsActive"/>, <see cref="IsCompleted"/>, <see cref="IsErrorEmitted"/>,
/// and <see cref="IsCanceled"/>.
/// </para>
/// <para>
/// You send elements to the stream by calling <see cref="OnNext"/>. You are allowed to send as many
/// elements as have been requested by the stream subscriber. This amount can be inquired with
/// <see cref="TotalDemand"/>. It is only allowed to use <see cref="OnNext"/> when <see cref="IsActive"/>
/// <see cref="TotalDemand"/> > 0, otherwise <see cref="OnNext"/> will throw
/// <see cref="IllegalStateException"/>.
/// </para>
/// <para>
/// When the stream subscriber requests more elements the <see cref="Request"/> message
/// is delivered to this actor, and you can act on that event. The <see cref="TotalDemand"/>
/// is updated automatically.
/// </para>
/// <para>
/// When the stream subscriber cancels the subscription the <see cref="Cancel"/> message
/// is delivered to this actor. After that subsequent calls to <see cref="OnNext"/> will be ignored.
/// </para>
/// <para>
/// You can complete the stream by calling <see cref="OnComplete"/>. After that you are not allowed to
/// call <see cref="OnNext"/>, <see cref="OnError"/> and <see cref="OnComplete"/>.
/// </para>
/// <para>
/// You can terminate the stream with failure by calling <see cref="OnError"/>. After that you are not allowed to
/// call <see cref="OnNext"/>, <see cref="OnError"/> and <see cref="OnComplete"/>.
/// </para>
/// <para>
/// If you suspect that this <see cref="ActorPublisher{T}"/> may never get subscribed to,
/// you can override the <see cref="SubscriptionTimeout"/> method to provide a timeout after which
/// this Publisher should be considered canceled. The actor will be notified when
/// the timeout triggers via an <see cref="SubscriptionTimeoutExceeded"/> message and MUST then
/// perform cleanup and stop itself.
/// </para>
/// <para>
/// If the actor is stopped the stream will be completed, unless it was not already terminated with
/// failure, completed or canceled.
/// </para>
/// </summary>
/// <typeparam name="T">TBD</typeparam>
public abstract class ActorPublisher<T> : ActorBase
{
private readonly ActorPublisherState _state = ActorPublisherState.Instance.Apply(Context.System);
private long _demand;
private LifecycleState _lifecycleState = LifecycleState.PreSubscriber;
private ISubscriber<T> _subscriber;
private ICancelable _scheduledSubscriptionTimeout = NoopSubscriptionTimeout.Instance;
// case and stop fields are used only when combined with LifecycleState.ErrorEmitted
private OnErrorBlock _onError;
/// <summary>
/// TBD
/// </summary>
protected ActorPublisher()
{
SubscriptionTimeout = Timeout.InfiniteTimeSpan;
}
/// <summary>
/// Subscription timeout after which this actor will become Canceled and reject any incoming "late" subscriber.
///
/// The actor will receive an <see cref="SubscriptionTimeoutExceeded"/> message upon which it
/// MUST react by performing all necessary cleanup and stopping itself.
///
/// Use this feature in order to avoid leaking actors when you suspect that this Publisher may never get subscribed to by some Subscriber.
/// </summary>
/// <summary>
/// <para>
/// Subscription timeout after which this actor will become Canceled and reject any incoming "late" subscriber.
/// </para>
/// <para>
/// The actor will receive an <see cref="SubscriptionTimeoutExceeded"/> message upon which it
/// MUST react by performing all necessary cleanup and stopping itself.
/// </para>
/// <para>
/// Use this feature in order to avoid leaking actors when you suspect that this Publisher
/// may never get subscribed to by some Subscriber.
/// </para>
/// </summary>
public TimeSpan SubscriptionTimeout { get; protected set; }
/// <summary>
/// The state when the publisher is active, i.e. before the subscriber is attached
/// and when an subscriber is attached. It is allowed to
/// call <see cref="OnComplete"/> and <see cref="OnError"/> in this state. It is
/// allowed to call <see cref="OnNext"/> in this state when <see cref="TotalDemand"/>
/// is greater than zero.
/// </summary>
public bool IsActive
=> _lifecycleState == LifecycleState.Active || _lifecycleState == LifecycleState.PreSubscriber;
/// <summary>
/// Total number of requested elements from the stream subscriber.
/// This actor automatically keeps tracks of this amount based on
/// incoming request messages and outgoing <see cref="OnNext"/>.
/// </summary>
public long TotalDemand => _demand;
/// <summary>
/// The terminal state after calling <see cref="OnComplete"/>. It is not allowed to
/// <see cref="OnNext"/>, <see cref="OnError"/>, and <see cref="OnComplete"/> in this state.
/// </summary>
public bool IsCompleted => _lifecycleState == LifecycleState.Completed;
/// <summary>
/// The terminal state after calling <see cref="OnError"/>. It is not allowed to
/// call <see cref="OnNext"/>, <see cref="OnError"/>, and <see cref="OnComplete"/> in this state.
/// </summary>
public bool IsErrorEmitted => _lifecycleState == LifecycleState.ErrorEmitted;
/// <summary>
/// The state after the stream subscriber has canceled the subscription.
/// It is allowed to call <see cref="OnNext"/>, <see cref="OnError"/>, and <see cref="OnComplete"/> in
/// this state, but the calls will not perform anything.
/// </summary>
public bool IsCanceled => _lifecycleState == LifecycleState.Canceled;
/// <summary>
/// Send an element to the stream subscriber. You are allowed to send as many elements
/// as have been requested by the stream subscriber. This amount can be inquired with
/// <see cref="TotalDemand"/>. It is only allowed to use <see cref="OnNext"/> when
/// <see cref="IsActive"/> and <see cref="TotalDemand"/> > 0,
/// otherwise <see cref="OnNext"/> will throw <see cref="IllegalStateException"/>.
/// </summary>
/// <param name="element">TBD</param>
/// <exception cref="IllegalStateException">TBD</exception>
public void OnNext(T element)
{
switch (_lifecycleState)
{
case LifecycleState.Active:
case LifecycleState.PreSubscriber:
if (_demand > 0)
{
_demand--;
ReactiveStreamsCompliance.TryOnNext(_subscriber, element);
}
else
{
throw new IllegalStateException(
"OnNext is not allowed when the stream has not requested elements, total demand was 0");
}
break;
case LifecycleState.ErrorEmitted:
throw new IllegalStateException("OnNext must not be called after OnError");
case LifecycleState.Completed:
case LifecycleState.CompleteThenStop:
throw new IllegalStateException("OnNext must not be called after OnComplete");
case LifecycleState.Canceled: break;
}
}
/// <summary>
/// Complete the stream. After that you are not allowed to
/// call <see cref="OnNext"/>, <see cref="OnError"/> and <see cref="OnComplete"/>.
/// </summary>
/// <exception cref="IllegalStateException">TBD</exception>
public void OnComplete()
{
switch (_lifecycleState)
{
case LifecycleState.Active:
case LifecycleState.PreSubscriber:
_lifecycleState = LifecycleState.Completed;
_onError = null;
if (_subscriber != null)
{
// otherwise onComplete will be called when the subscription arrives
try
{
ReactiveStreamsCompliance.TryOnComplete(_subscriber);
}
finally
{
_subscriber = null;
}
}
break;
case LifecycleState.ErrorEmitted: throw new IllegalStateException("OnComplete must not be called after OnError");
case LifecycleState.Completed:
case LifecycleState.CompleteThenStop: throw new IllegalStateException("OnComplete must only be called once");
case LifecycleState.Canceled: break;
}
}
/// <summary>
/// <para>
/// Complete the stream. After that you are not allowed to
/// call <see cref="OnNext"/>, <see cref="OnError"/> and <see cref="OnComplete"/>.
/// </para>
/// <para>
/// After signalling completion the Actor will then stop itself as it has completed the protocol.
/// When <see cref="OnComplete"/> is called before any <see cref="ISubscriber{T}"/> has had the chance to subscribe
/// to this <see cref="ActorPublisher{T}"/> the completion signal (and therefore stopping of the Actor as well)
/// will be delayed until such <see cref="ISubscriber{T}"/> arrives.
/// </para>
/// </summary>
public void OnCompleteThenStop()
{
switch (_lifecycleState)
{
case LifecycleState.Active:
case LifecycleState.PreSubscriber:
_lifecycleState = LifecycleState.CompleteThenStop;
_onError = null;
if (_subscriber != null)
{
// otherwise onComplete will be called when the subscription arrives
try
{
ReactiveStreamsCompliance.TryOnComplete(_subscriber);
}
finally
{
Context.Stop(Self);
}
}
break;
default: OnComplete(); break;
}
}
/// <summary>
/// Terminate the stream with failure. After that you are not allowed to
/// call <see cref="OnNext"/>, <see cref="OnError"/> and <see cref="OnComplete"/>.
/// </summary>
/// <param name="cause">TBD</param>
/// <exception cref="IllegalStateException">TBD</exception>
public void OnError(Exception cause)
{
switch (_lifecycleState)
{
case LifecycleState.Active:
case LifecycleState.PreSubscriber:
_lifecycleState = LifecycleState.ErrorEmitted;
_onError = new OnErrorBlock(cause, false);
if (_subscriber != null)
{
// otherwise onError will be called when the subscription arrives
try
{
ReactiveStreamsCompliance.TryOnError(_subscriber, cause);
}
finally
{
_subscriber = null;
}
}
break;
case LifecycleState.ErrorEmitted: throw new IllegalStateException("OnError must only be called once");
case LifecycleState.Completed:
case LifecycleState.CompleteThenStop: throw new IllegalStateException("OnError must not be called after OnComplete");
case LifecycleState.Canceled: break;
}
}
/// <summary>
/// <para>
/// Terminate the stream with failure. After that you are not allowed to
/// call <see cref="OnNext"/>, <see cref="OnError"/> and <see cref="OnComplete"/>.
/// </para>
/// <para>
/// After signalling the Error the Actor will then stop itself as it has completed the protocol.
/// When <see cref="OnError"/> is called before any <see cref="ISubscriber{T}"/> has had the chance to subscribe
/// to this <see cref="ActorPublisher{T}"/> the error signal (and therefore stopping of the Actor as well)
/// will be delayed until such <see cref="ISubscriber{T}"/> arrives.
/// </para>
/// </summary>
/// <param name="cause">TBD</param>
public void OnErrorThenStop(Exception cause)
{
switch (_lifecycleState)
{
case LifecycleState.Active:
case LifecycleState.PreSubscriber:
_lifecycleState = LifecycleState.ErrorEmitted;
_onError = new OnErrorBlock(cause, stop: true);
if (_subscriber != null)
{
// otherwise onError will be called when the subscription arrives
try
{
ReactiveStreamsCompliance.TryOnError(_subscriber, cause);
}
finally
{
Context.Stop(Self);
}
}
break;
default: OnError(cause); break;
}
}
#region Internal API
/// <summary>
/// TBD
/// </summary>
/// <param name="receive">TBD</param>
/// <param name="message">TBD</param>
/// <returns>TBD</returns>
protected override bool AroundReceive(Receive receive, object message)
{
if (message is Request)
{
var req = (Request) message;
if (req.IsProcessed)
{
// it's an unstashed Request, demand is already handled
base.AroundReceive(receive, req);
}
else
{
if (req.Count < 1)
{
if (_lifecycleState == LifecycleState.Active)
OnError(new ArgumentException("Number of requested elements must be positive. Rule 3.9"));
}
else
{
_demand += req.Count;
if (_demand < 0)
_demand = long.MaxValue; // long overflow: effectively unbounded
req.MarkProcessed();
base.AroundReceive(receive, message);
}
}
}
else if (message is Subscribe<T>)
{
var sub = (Subscribe<T>) message;
var subscriber = sub.Subscriber;
switch (_lifecycleState)
{
case LifecycleState.PreSubscriber:
_scheduledSubscriptionTimeout.Cancel();
_subscriber = subscriber;
_lifecycleState = LifecycleState.Active;
ReactiveStreamsCompliance.TryOnSubscribe(subscriber, new ActorPublisherSubscription(Self));
break;
case LifecycleState.ErrorEmitted:
if (_onError.Stop) Context.Stop(Self);
ReactiveStreamsCompliance.TryOnSubscribe(subscriber, CancelledSubscription.Instance);
ReactiveStreamsCompliance.TryOnError(subscriber, _onError.Cause);
break;
case LifecycleState.Completed:
ReactiveStreamsCompliance.TryOnSubscribe(subscriber, CancelledSubscription.Instance);
ReactiveStreamsCompliance.TryOnComplete(subscriber);
break;
case LifecycleState.CompleteThenStop:
Context.Stop(Self);
ReactiveStreamsCompliance.TryOnSubscribe(subscriber, CancelledSubscription.Instance);
ReactiveStreamsCompliance.TryOnComplete(subscriber);
break;
case LifecycleState.Active:
case LifecycleState.Canceled:
if(_subscriber == subscriber)
ReactiveStreamsCompliance.RejectDuplicateSubscriber(subscriber);
else
ReactiveStreamsCompliance.RejectAdditionalSubscriber(subscriber, "ActorPublisher");
break;
}
}
else if (message is Cancel)
{
if (_lifecycleState != LifecycleState.Canceled)
{
// possible to receive again in case of stash
CancelSelf();
base.AroundReceive(receive, message);
}
}
else if (message is SubscriptionTimeoutExceeded)
{
if (!_scheduledSubscriptionTimeout.IsCancellationRequested)
{
CancelSelf();
base.AroundReceive(receive, message);
}
}
else return base.AroundReceive(receive, message);
return true;
}
private void CancelSelf()
{
_lifecycleState = LifecycleState.Canceled;
_subscriber = null;
_onError = null;
_demand = 0L;
}
/// <summary>
/// TBD
/// </summary>
public override void AroundPreStart()
{
base.AroundPreStart();
if (SubscriptionTimeout != Timeout.InfiniteTimeSpan)
{
_scheduledSubscriptionTimeout = new Cancelable(Context.System.Scheduler);
Context.System.Scheduler.ScheduleTellOnce(SubscriptionTimeout, Self, SubscriptionTimeoutExceeded.Instance, Self, _scheduledSubscriptionTimeout);
}
}
/// <summary>
/// TBD
/// </summary>
/// <param name="cause">TBD</param>
/// <param name="message">TBD</param>
public override void AroundPreRestart(Exception cause, object message)
{
// some state must survive restart
_state.Set(Self, new ActorPublisherState.State(UntypedSubscriber.FromTyped(_subscriber), _demand, _lifecycleState));
base.AroundPreRestart(cause, message);
}
/// <summary>
/// TBD
/// </summary>
/// <param name="cause">TBD</param>
/// <param name="message">TBD</param>
public override void AroundPostRestart(Exception cause, object message)
{
var s = _state.Remove(Self);
if (s != null)
{
_subscriber = UntypedSubscriber.ToTyped<T>(s.Subscriber);
_demand = s.Demand;
_lifecycleState = s.LifecycleState;
}
base.AroundPostRestart(cause, message);
}
/// <summary>
/// TBD
/// </summary>
public override void AroundPostStop()
{
_state.Remove(Self);
try
{
if (_lifecycleState == LifecycleState.Active)
ReactiveStreamsCompliance.TryOnComplete(_subscriber);
}
finally
{
base.AroundPostStop();
}
}
#endregion
}
/// <summary>
/// TBD
/// </summary>
public static class ActorPublisher
{
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="T">TBD</typeparam>
/// <param name="ref">TBD</param>
/// <returns>TBD</returns>
public static IPublisher<T> Create<T>(IActorRef @ref) => new ActorPublisherImpl<T>(@ref);
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="T">TBD</typeparam>
public sealed class ActorPublisherImpl<T> : IPublisher<T>
{
private readonly IActorRef _ref;
/// <summary>
/// TBD
/// </summary>
/// <param name="ref">TBD</param>
/// <exception cref="ArgumentNullException">TBD</exception>
public ActorPublisherImpl(IActorRef @ref)
{
if(@ref == null) throw new ArgumentNullException(nameof(@ref), "ActorPublisherImpl requires IActorRef to be defined");
_ref = @ref;
}
/// <summary>
/// TBD
/// </summary>
/// <param name="subscriber">TBD</param>
/// <exception cref="ArgumentNullException">TBD</exception>
public void Subscribe(ISubscriber<T> subscriber)
{
if (subscriber == null) throw new ArgumentNullException(nameof(subscriber), "Subscriber must not be null");
_ref.Tell(new Subscribe<T>(subscriber));
}
}
/// <summary>
/// TBD
/// </summary>
public sealed class ActorPublisherSubscription : ISubscription
{
private readonly IActorRef _ref;
/// <summary>
/// TBD
/// </summary>
/// <param name="ref">TBD</param>
/// <exception cref="ArgumentNullException">TBD</exception>
public ActorPublisherSubscription(IActorRef @ref)
{
if (@ref == null) throw new ArgumentNullException(nameof(@ref), "ActorPublisherSubscription requires IActorRef to be defined");
_ref = @ref;
}
/// <summary>
/// TBD
/// </summary>
/// <param name="n">TBD</param>
public void Request(long n) => _ref.Tell(new Request(n));
/// <summary>
/// TBD
/// </summary>
public void Cancel() => _ref.Tell(Actors.Cancel.Instance);
}
/// <summary>
/// TBD
/// </summary>
public sealed class OnErrorBlock
{
/// <summary>
/// TBD
/// </summary>
public readonly Exception Cause;
/// <summary>
/// TBD
/// </summary>
public readonly bool Stop;
/// <summary>
/// TBD
/// </summary>
/// <param name="cause">TBD</param>
/// <param name="stop">TBD</param>
public OnErrorBlock(Exception cause, bool stop)
{
Cause = cause;
Stop = stop;
}
}
/// <summary>
/// TBD
/// </summary>
internal class ActorPublisherState : ExtensionIdProvider<ActorPublisherState>, IExtension
{
/// <summary>
/// TBD
/// </summary>
public sealed class State
{
/// <summary>
/// TBD
/// </summary>
public readonly IUntypedSubscriber Subscriber;
/// <summary>
/// TBD
/// </summary>
public readonly long Demand;
/// <summary>
/// TBD
/// </summary>
public readonly LifecycleState LifecycleState;
/// <summary>
/// TBD
/// </summary>
/// <param name="subscriber">TBD</param>
/// <param name="demand">TBD</param>
/// <param name="lifecycleState">TBD</param>
public State(IUntypedSubscriber subscriber, long demand, LifecycleState lifecycleState)
{
Subscriber = subscriber;
Demand = demand;
LifecycleState = lifecycleState;
}
}
private readonly ConcurrentDictionary<IActorRef, State> _state = new ConcurrentDictionary<IActorRef, State>();
/// <summary>
/// TBD
/// </summary>
public static readonly ActorPublisherState Instance = new ActorPublisherState();
private ActorPublisherState() { }
/// <summary>
/// TBD
/// </summary>
/// <param name="actorRef">TBD</param>
/// <returns>TBD</returns>
public State Get(IActorRef actorRef)
{
State state;
return _state.TryGetValue(actorRef, out state) ? state : null;
}
/// <summary>
/// TBD
/// </summary>
/// <param name="actorRef">TBD</param>
/// <param name="s">TBD</param>
public void Set(IActorRef actorRef, State s) => _state.AddOrUpdate(actorRef, s, (@ref, oldState) => s);
/// <summary>
/// TBD
/// </summary>
/// <param name="actorRef">TBD</param>
/// <returns>TBD</returns>
public State Remove(IActorRef actorRef)
{
State s;
return _state.TryRemove(actorRef, out s) ? s : null;
}
/// <summary>
/// TBD
/// </summary>
/// <param name="system">TBD</param>
/// <returns>TBD</returns>
public override ActorPublisherState CreateExtension(ExtendedActorSystem system) => new ActorPublisherState();
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="GraphOpsIntegrationSpec.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Akka.Streams.Dsl;
using Akka.Streams.TestKit;
using Akka.TestKit;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
// ReSharper disable InvokeAsExtensionMethod
namespace Akka.Streams.Tests.Dsl
{
public class GraphOpsIntegrationSpec : AkkaSpec
{
private static class Shuffle
{
internal class ShufflePorts: Shape
{
private readonly Inlet _in1;
private readonly Inlet _in2;
private readonly Outlet _out1;
private readonly Outlet _out2;
public ShufflePorts(Inlet in1, Inlet in2, Outlet out1, Outlet out2)
{
_in1 = in1;
_in2 = in2;
_out1 = out1;
_out2 = out2;
Inlets = ImmutableArray.Create(in1, in2);
Outlets = ImmutableArray.Create(out1, out2);
}
public override ImmutableArray<Inlet> Inlets { get; }
public override ImmutableArray<Outlet> Outlets { get; }
public Inlet<int> In1 => (Inlet<int>) _in1;
public Inlet<int> In2 => (Inlet<int>) _in2;
public Outlet<int> Out1 => (Outlet<int>) _out1;
public Outlet<int> Out2 => (Outlet<int>) _out2;
public override Shape DeepCopy()
=> new ShufflePorts(_in1.CarbonCopy(), _in2.CarbonCopy(), _out1.CarbonCopy(), _out2.CarbonCopy());
public override Shape CopyFromPorts(ImmutableArray<Inlet> inlets, ImmutableArray<Outlet> outlets)
{
if (Inlets.Length != inlets.Length)
throw new ArgumentException("Inlets must have the same size", nameof(inlets));
if (Outlets.Length != outlets.Length)
throw new ArgumentException("Outlets must have the same size", nameof(outlets));
return new ShufflePorts(inlets[0], inlets[1], outlets[0], outlets[1]);
}
}
internal static IGraph<ShufflePorts, NotUsed> Create<TIn, TOut>(Flow<TIn, TOut, NotUsed> pipeline)
{
return GraphDsl.Create(b =>
{
var merge = b.Add(new Merge<TIn>(2));
var balance = b.Add(new Balance<TOut>(2));
b.From(merge.Out).Via(pipeline).To(balance.In);
return new ShufflePorts(merge.In(0), merge.In(1), balance.Out(0), balance.Out(1));
});
}
}
private ActorMaterializer Materializer { get; }
public GraphOpsIntegrationSpec(ITestOutputHelper helper) : base(helper)
{
var settings = ActorMaterializerSettings.Create(Sys).WithInputBuffer(2, 16);
Materializer = ActorMaterializer.Create(Sys, settings);
}
[Fact]
public void GraphDSLs_must_support_broadcast_merge_layouts()
{
var task = RunnableGraph.FromGraph(GraphDsl.Create(Sink.First<IEnumerable<int>>(), (b, sink) =>
{
var broadcast = b.Add(new Broadcast<int>(2));
var merge = b.Add(new Merge<int>(2));
var source = Source.From(Enumerable.Range(1, 3)).MapMaterializedValue<Task<IEnumerable<int>>>(_ => null);
b.From(source).To(broadcast.In);
b.From(broadcast.Out(0)).To(merge.In(0));
b.From(broadcast.Out(1)).Via(Flow.Create<int>().Select(x => x + 3)).To(merge.In(1));
b.From(merge.Out).Via(Flow.Create<int>().Grouped(10)).To(sink.Inlet);
return ClosedShape.Instance;
})).Run(Materializer);
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
task.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 6));
}
[Fact]
public void GraphDSLs_must_support_balance_merge_parallelization_layouts()
{
var elements = Enumerable.Range(0, 11).ToList();
var task = RunnableGraph.FromGraph(GraphDsl.Create(Sink.First<IEnumerable<int>>(), (b, sink) =>
{
var balance = b.Add(new Balance<int>(5));
var merge = b.Add(new Merge<int>(5));
var source = Source.From(elements).MapMaterializedValue<Task<IEnumerable<int>>>(_ => null);
b.From(source).To(balance.In);
for (var i = 0; i < 5; i++)
b.From(balance.Out(i)).To(merge.In(i));
b.From(merge.Out).Via(Flow.Create<int>().Grouped(elements.Count*2)).To(sink.Inlet);
return ClosedShape.Instance;
})).Run(Materializer);
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
task.Result.ShouldAllBeEquivalentTo(elements);
}
[Fact]
public void GraphDSLs_must_support_wikipedia_Topological_sorting_2()
{
Func<int, Source<int, Tuple<Task<IEnumerable<int>>, Task<IEnumerable<int>>, Task<IEnumerable<int>>>>> source =
i =>
Source.From(new[] {i})
.MapMaterializedValue<Tuple<Task<IEnumerable<int>>, Task<IEnumerable<int>>, Task<IEnumerable<int>>>>(
_ => null);
// see https://en.wikipedia.org/wiki/Topological_sorting#mediaviewer/File:Directed_acyclic_graph.png
var seqSink = Sink.First<IEnumerable<int>>();
var t = RunnableGraph.FromGraph(GraphDsl.Create(seqSink, seqSink, seqSink, Tuple.Create, (b, sink2,sink9,sink10) =>
{
var b3 = b.Add(new Broadcast<int>(2));
var b7 = b.Add(new Broadcast<int>(2));
var b11 = b.Add(new Broadcast<int>(3));
var m8 = b.Add(new Merge<int>(2));
var m9 = b.Add(new Merge<int>(2));
var m10 = b.Add(new Merge<int>(2));
var m11 = b.Add(new Merge<int>(2));
var in3 = source(3);
var in5 = source(5);
var in7 = source(7);
// First layer
b.From(in7).To(b7.In);
b.From(b7.Out(0)).To(m11.In(0));
b.From(b7.Out(1)).To(m8.In(0));
b.From(in5).To(m11.In(1));
b.From(in3).To(b3.In);
b.From(b3.Out(0)).To(m8.In(1));
b.From(b3.Out(1)).To(m10.In(0));
// Second layer
b.From(m11.Out).To(b11.In);
b.From(b11.Out(0)).Via(Flow.Create<int>().Grouped(1000)).To(sink2.Inlet);
b.From(b11.Out(1)).To(m9.In(0));
b.From(b11.Out(2)).To(m10.In(1));
b.From(m8.Out).To(m9.In(1));
// Third layer
b.From(m9.Out).Via(Flow.Create<int>().Grouped(1000)).To(sink9.Inlet);
b.From(m10.Out).Via(Flow.Create<int>().Grouped(1000)).To(sink10.Inlet);
return ClosedShape.Instance;
})).Run(Materializer);
var task = Task.WhenAll(t.Item1, t.Item2, t.Item3);
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
task.Result[0].ShouldAllBeEquivalentTo(new[] {5, 7});
task.Result[1].ShouldAllBeEquivalentTo(new[] { 3, 5, 7, 7 });
task.Result[2].ShouldAllBeEquivalentTo(new[] { 3, 5, 7 });
}
[Fact]
public void GraphDSLs_must_allow_adding_of_flows_to_sources_and_sinks_to_flows()
{
var task = RunnableGraph.FromGraph(GraphDsl.Create(Sink.First<IEnumerable<int>>(), (b, sink) =>
{
var broadcast = b.Add(new Broadcast<int>(2));
var merge = b.Add(new Merge<int>(2));
var source = Source.From(Enumerable.Range(1,3)).MapMaterializedValue<Task<IEnumerable<int>>>(_ => null);
b.From(source.Select(x => x*2)).To(broadcast.In);
b.From(broadcast.Out(0)).To(merge.In(0));
b.From(broadcast.Out(1)).Via(Flow.Create<int>().Select(x => x + 3)).To(merge.In(1));
b.From(merge.Out).Via(Flow.Create<int>().Grouped(10)).To(sink.Inlet);
return ClosedShape.Instance;
})).Run(Materializer);
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
task.Result.ShouldAllBeEquivalentTo(new[] {2, 4, 6, 5, 7, 9});
}
[Fact]
public void GraphDSLs_must_be_able_to_run_plain_flow()
{
var p = Source.From(Enumerable.Range(1, 3)).RunWith(Sink.AsPublisher<int>(false), Materializer);
var s = this.CreateManualSubscriberProbe<int>();
var flow = Flow.Create<int>().Select(x => x*2);
RunnableGraph.FromGraph(GraphDsl.Create(b =>
{
b.From(Source.FromPublisher(p)).Via(flow).To(Sink.FromSubscriber(s));
return ClosedShape.Instance;
})).Run(Materializer);
var sub = s.ExpectSubscription();
sub.Request(10);
s.ExpectNext(1*2, 2*2, 3*2).ExpectComplete();
}
[Fact]
public void GraphDSLs_must_be_possible_to_use_as_lego_bricks()
{
Func<int, Source<int, Tuple<NotUsed, NotUsed, NotUsed, Task<IEnumerable<int>>>>> source =
i =>
Source.From(Enumerable.Range(i, 3))
.MapMaterializedValue<Tuple<NotUsed, NotUsed, NotUsed, Task<IEnumerable<int>>>>(_ => null);
var shuffler = Shuffle.Create(Flow.Create<int>().Select(x => x + 1));
var task =
RunnableGraph.FromGraph(GraphDsl.Create(shuffler, shuffler, shuffler, Sink.First<IEnumerable<int>>(),
Tuple.Create,
(b, s1, s2, s3, sink) =>
{
var merge = b.Add(new Merge<int>(2));
b.From(source(1)).To(s1.In1);
b.From(source(10)).To(s1.In2);
b.From(s1.Out1).To(s2.In1);
b.From(s1.Out2).To(s2.In2);
b.From(s2.Out1).To(s3.In1);
b.From(s2.Out2).To(s3.In2);
b.From(s3.Out1).To(merge.In(0));
b.From(s3.Out2).To(merge.In(1));
b.From(merge.Out).Via(Flow.Create<int>().Grouped(1000)).To(sink);
return ClosedShape.Instance;
})).Run(Materializer).Item4;
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
task.Result.ShouldAllBeEquivalentTo(new[] {4, 5, 6, 13, 14, 15});
}
}
}
| |
// Contains code from bplusdotnet project (BSD License) by Aaron Watters, Copyright 2004: http://bplusdotnet.sourceforge.net/
using System;
using System.Collections.Generic;
using System.Linq;
namespace McBits.LanguageLib.BPTree
{
/// <summary>
/// Bucket for elements sharing a prefix.
/// Intended for small buckets.
/// </summary>
public class XBucket
{
private readonly List<string> _keys;
private readonly XBPTreeBytes _owner;
private readonly List<byte[]> _values;
public XBucket(XBPTreeBytes owner)
{
_keys = new List<string>();
_values = new List<byte[]>();
_owner = owner;
}
public int Count
{
get { return _keys.Count; }
}
public void Load(byte[] serialization)
{
int index = 0;
int byteCount = serialization.Length;
if (_values.Count != 0 || _keys.Count != 0)
throw new BPTreeException("Cannot load. Bucket must be empty");
while (index < byteCount)
{
// get key prefix and key
int keyLength = Bytes.ToInt32(serialization, index);
index += sizeof(int);
string keyString = BPTree.BytesToString(serialization, index, keyLength);
index += keyLength;
// get value prefix and value
int valueLength = Bytes.ToInt32(serialization, index);
index += sizeof(int);
var valueBytes = new byte[valueLength];
Array.Copy(serialization, index, valueBytes, 0, valueLength);
// record new key and value
_keys.Add(keyString);
_values.Add(valueBytes);
index += valueLength;
}
if (index != byteCount)
throw new BPTreeException("Cannot load. Bad byte count in serialization: " + byteCount);
}
public byte[] Dump()
{
var allbytes = new List<byte[]>();
for (int index = 0; index < _keys.Count; index++)
{
string thisKey = _keys[index];
var thisValue = _values[index];
var keyprefix = new byte[Bytes.Int];
var keybytes = BPTree.StringToBytes(thisKey);
Bytes.ToBuffer(keybytes.Length, keyprefix, 0);
allbytes.Add(keyprefix);
allbytes.Add(keybytes);
var valueprefix = new byte[Bytes.Int];
Bytes.ToBuffer(thisValue.Length, valueprefix, 0);
allbytes.Add(valueprefix);
allbytes.Add(thisValue);
}
int byteCount = allbytes.Sum(bytes => bytes.Length);
int outindex = 0;
var result = new byte[byteCount];
foreach (var bytes in allbytes)
{
int length = bytes.Length;
Array.Copy(bytes, 0, result, outindex, length);
outindex += length;
}
if (outindex != byteCount)
throw new BPTreeException("Cannot dump. Error counting bytes in dump: " + outindex + "!=" + byteCount);
return result;
}
public void Add(string key, byte[] map)
{
int index = 0;
int limit = _owner.BucketSizeLimit;
while (index < _keys.Count)
{
string thiskey = _keys[index];
int comparison = _owner.Compare(thiskey, key);
if (comparison == 0)
{
_values[index] = map;
_keys[index] = key;
return;
}
if (comparison > 0)
{
_values.Insert(index, map);
_keys.Insert(index, key);
if (limit > 0 && _keys.Count > limit)
throw new BPTreeBadKeyValue("Cannot add. Bucket size limit exceeded");
return;
}
index++;
}
_keys.Add(key);
_values.Add(map);
if (limit > 0 && _keys.Count > limit)
throw new BPTreeBadKeyValue("Cannot add. Bucket size limit exceeded");
}
public void Remove(string key)
{
int index = _keys.Count;
while (--index >= 0)
{
if (_owner.Compare(_keys[index], key) != 0)
continue;
_values.RemoveAt(index);
_keys.RemoveAt(index);
return;
}
throw new BPTreeBadKeyValue("Cannot remove. Key not found: " + key);
}
public bool TryGetValue(string key, out byte[] map)
{
map = null;
int index = 0;
while (index < _keys.Count)
{
string thiskey = _keys[index];
if (_owner.Compare(thiskey, key) == 0)
{
map = _values[index];
return true;
}
index++;
}
return false;
}
public string FirstKey()
{
return _keys.Count < 1 ? null : _keys[0];
}
public string NextKey(string afterThisKey)
{
int index = 0;
while (index < _keys.Count)
{
string thiskey = _keys[index];
if (_owner.Compare(thiskey, afterThisKey) > 0)
return thiskey;
index++;
}
return null;
}
}
}
| |
/******************************************************************************
* The MIT License
* Copyright (c) 2003 Novell Inc. www.novell.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the Software), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
//
// Novell.Directory.Ldap.LdapCompareAttrNames.cs
//
// Author:
// Sunil Kumar (Sunilk@novell.com)
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//
using Novell.Directory.LDAP.VQ.Utilclass;
namespace Novell.Directory.LDAP.VQ
{
/// <summary> Compares Ldap entries based on attribute name.
///
/// An object of this class defines ordering when sorting LdapEntries,
/// usually from search results. When using this Comparator, LdapEntry objects
/// are sorted by the attribute names(s) passed in on the
/// constructor, in ascending or descending order. The object is typically
/// supplied to an implementation of the collection interfaces such as
/// java.util.TreeSet which performs sorting.
///
/// Comparison is performed via locale-sensitive Java string comparison,
/// which may not correspond to the Ldap ordering rules by which an Ldap server
/// would sort them.
///
/// </summary>
public class LdapCompareAttrNames : System.Collections.IComparer
{
private void InitBlock()
{
// location = Locale.getDefault();
location = System.Globalization.CultureInfo.CurrentCulture;
collator = System.Globalization.CultureInfo.CurrentCulture.CompareInfo;
}
/// <summary> Returns the locale to be used for sorting, if a locale has been
/// specified.
///
/// If locale is null, a basic string.compareTo method is used for
/// collation. If non-null, a locale-specific collation is used.
///
/// </summary>
/// <returns> The locale if one has been specified
/// </returns>
/// <summary> Sets the locale to be used for sorting.
///
/// </summary>
/// <param name="locale"> The locale to be used for sorting.
/// </param>
virtual public System.Globalization.CultureInfo Locale
{
get
{
//currently supports only English local.
return location;
}
set
{
collator = value.CompareInfo;
location = value;
}
}
private string[] sortByNames; //names to to sort by.
private bool[] sortAscending; //true if sorting ascending
private System.Globalization.CultureInfo location;
private System.Globalization.CompareInfo collator;
/// <summary> Constructs an object that sorts results by a single attribute, in
/// ascending order.
///
/// </summary>
/// <param name="attrName"> Name of an attribute by which to sort.
///
/// </param>
public LdapCompareAttrNames(string attrName)
{
InitBlock();
sortByNames = new string[1];
sortByNames[0] = attrName;
sortAscending = new bool[1];
sortAscending[0] = true;
}
/// <summary> Constructs an object that sorts results by a single attribute, in
/// either ascending or descending order.
///
/// </summary>
/// <param name="attrName"> Name of an attribute to sort by.
///
/// </param>
/// <param name="ascendingFlag"> True specifies ascending order; false specifies
/// descending order.
/// </param>
public LdapCompareAttrNames(string attrName, bool ascendingFlag)
{
InitBlock();
sortByNames = new string[1];
sortByNames[0] = attrName;
sortAscending = new bool[1];
sortAscending[0] = ascendingFlag;
}
/// <summary> Constructs an object that sorts by one or more attributes, in the
/// order provided, in ascending order.
///
/// Note: Novell eDirectory allows sorting by one attribute only. The
/// direcctory server must also be configured to index the specified
/// attribute.
///
/// </summary>
/// <param name="attrNames"> Array of names of attributes to sort by.
///
/// </param>
public LdapCompareAttrNames(string[] attrNames)
{
InitBlock();
sortByNames = new string[attrNames.Length];
sortAscending = new bool[attrNames.Length];
for (int i = 0; i < attrNames.Length; i++)
{
sortByNames[i] = attrNames[i];
sortAscending[i] = true;
}
}
/// <summary> Constructs an object that sorts by one or more attributes, in the
/// order provided, in either ascending or descending order for each
/// attribute.
///
/// Note: Novell eDirectory supports only ascending sort order (A,B,C ...)
/// and allows sorting only by one attribute. The directory server must be
/// configured to index this attribute.
///
/// </summary>
/// <param name="attrNames"> Array of names of attributes to sort by.
///
/// </param>
/// <param name="ascendingFlags"> Array of flags, one for each attrName, where
/// true specifies ascending order and false specifies
/// descending order. An LdapException is thrown if
/// the length of ascendingFlags is not greater than
/// or equal to the length of attrNames.
///
/// </param>
/// <exception> LdapException A general exception which includes an error
/// message and an Ldap error code.
///
/// </exception>
public LdapCompareAttrNames(string[] attrNames, bool[] ascendingFlags)
{
InitBlock();
if (attrNames.Length != ascendingFlags.Length)
{
throw new LdapException(ExceptionMessages.UNEQUAL_LENGTHS, LdapException.INAPPROPRIATE_MATCHING, null);
//"Length of attribute Name array does not equal length of Flags array"
}
sortByNames = new string[attrNames.Length];
sortAscending = new bool[ascendingFlags.Length];
for (int i = 0; i < attrNames.Length; i++)
{
sortByNames[i] = attrNames[i];
sortAscending[i] = ascendingFlags[i];
}
}
/// <summary> Compares the the attributes of the first LdapEntry to the second.
/// Only the values of the attributes named at the construction of this
/// object will be compared. Multi-valued attributes compare on the first
/// value only.
///
/// </summary>
/// <param name="object1"> Target entry for comparison.
///
/// </param>
/// <param name="object2"> Entry to be compared to.
///
/// </param>
/// <returns> Negative value if the first entry is less than the second and
/// positive if the first is greater than the second. Zero is returned if all
/// attributes to be compared are the same.
/// </returns>
public virtual int Compare(object object1, object object2)
{
LdapEntry entry1 = (LdapEntry)object1;
LdapEntry entry2 = (LdapEntry)object2;
LdapAttribute one, two;
string[] first; //multivalued attributes are ignored.
string[] second; //we just use the first element
int compare, i = 0;
if (collator == null)
{
//using default locale
collator = System.Globalization.CultureInfo.CurrentCulture.CompareInfo;
}
do
{
//while first and second are equal
one = entry1.getAttribute(sortByNames[i]);
two = entry2.getAttribute(sortByNames[i]);
if ((one != null) && (two != null))
{
first = one.StringValueArray;
second = two.StringValueArray;
compare = collator.Compare(first[0], second[0]);
}
//We could also use the other multivalued attributes to break ties.
//one of the entries was null
else
{
if (one != null)
compare = -1;
//one is greater than two
else if (two != null)
compare = 1;
//one is lesser than two
else
compare = 0; //tie - break it with the next attribute name
}
i++;
}
while ((compare == 0) && (i < sortByNames.Length));
if (sortAscending[i - 1])
{
// return the normal ascending comparison.
return compare;
}
// negate the comparison for a descending comparison.
return -compare;
}
/// <summary> Determines if this comparator is equal to the comparator passed in.
///
/// This will return true if the comparator is an instance of
/// LdapCompareAttrNames and compares the same attributes names in the same
/// order.
///
/// </summary>
/// <returns> true the comparators are equal
/// </returns>
public override bool Equals(object comparator)
{
if (!(comparator is LdapCompareAttrNames))
{
return false;
}
LdapCompareAttrNames comp = (LdapCompareAttrNames)comparator;
// Test to see if the attribute to compare are the same length
if ((comp.sortByNames.Length != sortByNames.Length) || (comp.sortAscending.Length != sortAscending.Length))
{
return false;
}
// Test to see if the attribute names and sorting orders are the same.
for (int i = 0; i < sortByNames.Length; i++)
{
if (comp.sortAscending[i] != sortAscending[i])
return false;
if (!comp.sortByNames[i].ToUpper().Equals(sortByNames[i].ToUpper()))
return false;
}
return true;
}
}
}
| |
#region License
/*---------------------------------------------------------------------------------*\
Distributed under the terms of an MIT-style license:
The MIT License
Copyright (c) 2006-2010 Stephen M. McKamey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
\*---------------------------------------------------------------------------------*/
#endregion License
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace JsonFx.Linq
{
internal abstract class ExpressionVisitor<T>
{
#region Constants
private const string ErrorUnexpectedExpression = "Unexpected expression ({0})";
private const string ErrorUnexpectedMemberBinding = "Unexpected member binding ({0})";
#endregion Constants
#region Init
/// <summary>
/// Ctor
/// </summary>
protected ExpressionVisitor()
{
}
#endregion Init
#region Visit Methods
protected virtual Expression Visit(Expression expression, T context)
{
if (expression == null)
{
return null;
}
switch (expression.NodeType)
{
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
case ExpressionType.Not:
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
case ExpressionType.ArrayLength:
case ExpressionType.Quote:
case ExpressionType.TypeAs:
case ExpressionType.UnaryPlus:
#if NET40
case ExpressionType.Decrement:
case ExpressionType.Increment:
case ExpressionType.Throw:
case ExpressionType.Unbox:
case ExpressionType.PreIncrementAssign:
case ExpressionType.PreDecrementAssign:
case ExpressionType.PostIncrementAssign:
case ExpressionType.PostDecrementAssign:
case ExpressionType.OnesComplement:
case ExpressionType.IsTrue:
case ExpressionType.IsFalse:
#endif
{
return this.VisitUnary((UnaryExpression)expression, context);
}
case ExpressionType.Add:
case ExpressionType.AddChecked:
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
case ExpressionType.Divide:
case ExpressionType.Modulo:
case ExpressionType.And:
case ExpressionType.AndAlso:
case ExpressionType.Or:
case ExpressionType.OrElse:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.Equal:
case ExpressionType.NotEqual:
case ExpressionType.Coalesce:
case ExpressionType.ArrayIndex:
case ExpressionType.RightShift:
case ExpressionType.LeftShift:
case ExpressionType.ExclusiveOr:
case ExpressionType.Power:
#if NET40
case ExpressionType.Assign:
case ExpressionType.AddAssign:
case ExpressionType.AndAssign:
case ExpressionType.DivideAssign:
case ExpressionType.ExclusiveOrAssign:
case ExpressionType.LeftShiftAssign:
case ExpressionType.ModuloAssign:
case ExpressionType.MultiplyAssign:
case ExpressionType.OrAssign:
case ExpressionType.PowerAssign:
case ExpressionType.RightShiftAssign:
case ExpressionType.SubtractAssign:
case ExpressionType.AddAssignChecked:
case ExpressionType.MultiplyAssignChecked:
case ExpressionType.SubtractAssignChecked:
#endif
{
return this.VisitBinary((BinaryExpression)expression, context);
}
case ExpressionType.TypeIs:
{
return this.VisitTypeIs((TypeBinaryExpression)expression, context);
}
case ExpressionType.Conditional:
{
return this.VisitConditional((ConditionalExpression)expression, context);
}
case ExpressionType.Constant:
{
return this.VisitConstant((ConstantExpression)expression, context);
}
case ExpressionType.Parameter:
{
return this.VisitParameter((ParameterExpression)expression, context);
}
case ExpressionType.MemberAccess:
{
return this.VisitMemberAccess((MemberExpression)expression, context);
}
case ExpressionType.Call:
{
return this.VisitMethodCall((MethodCallExpression)expression, context);
}
case ExpressionType.Lambda:
{
return this.VisitLambda((LambdaExpression)expression, context);
}
case ExpressionType.New:
{
return this.VisitNew((NewExpression)expression, context);
}
case ExpressionType.NewArrayInit:
case ExpressionType.NewArrayBounds:
{
return this.VisitNewArray((NewArrayExpression)expression, context);
}
case ExpressionType.Invoke:
{
return this.VisitInvocation((InvocationExpression)expression, context);
}
case ExpressionType.MemberInit:
{
return this.VisitMemberInit((MemberInitExpression)expression, context);
}
case ExpressionType.ListInit:
{
return this.VisitListInit((ListInitExpression)expression, context);
}
#if NET40
case ExpressionType.Block:
{
return this.VisitBlock((BlockExpression)expression, context);
}
case ExpressionType.Dynamic:
{
return this.VisitDynamic((DynamicExpression)expression, context);
}
case ExpressionType.Default:
{
return this.VisitDefault((DefaultExpression)expression, context);
}
case ExpressionType.Goto:
case ExpressionType.Label:
case ExpressionType.RuntimeVariables:
case ExpressionType.Loop:
case ExpressionType.Switch:
case ExpressionType.Try:
case ExpressionType.TypeEqual:
case ExpressionType.DebugInfo:
case ExpressionType.Index:
case ExpressionType.Extension:
{
// TODO: implement visitor method
return expression;
}
#endif
default:
{
return this.VisitUnknown(expression, context);
}
}
}
protected virtual Expression VisitUnknown(Expression exp, T context)
{
throw new NotSupportedException(String.Format(
ExpressionVisitor<T>.ErrorUnexpectedExpression,
exp.NodeType));
}
protected virtual MemberBinding VisitBinding(MemberBinding binding, T context)
{
switch (binding.BindingType)
{
case MemberBindingType.Assignment:
{
return this.VisitMemberAssignment((MemberAssignment)binding, context);
}
case MemberBindingType.MemberBinding:
{
return this.VisitMemberMemberBinding((MemberMemberBinding)binding, context);
}
case MemberBindingType.ListBinding:
{
return this.VisitMemberListBinding((MemberListBinding)binding, context);
}
default:
{
throw new NotSupportedException(String.Format(
ExpressionVisitor<T>.ErrorUnexpectedMemberBinding,
binding.BindingType));
}
}
}
protected virtual ElementInit VisitElementInitializer(ElementInit initializer, T context)
{
IEnumerable<Expression> arguments = this.VisitExpressionList(initializer.Arguments, context);
if (arguments == initializer.Arguments)
{
// no change
return initializer;
}
return Expression.ElementInit(initializer.AddMethod, arguments);
}
protected virtual Expression VisitUnary(UnaryExpression unary, T context)
{
Expression operand = this.Visit(unary.Operand, context);
if (operand == unary.Operand)
{
// no change
return unary;
}
return Expression.MakeUnary(unary.NodeType, operand, operand.Type, unary.Method);
}
protected virtual Expression VisitBinary(BinaryExpression binary, T context)
{
Expression left = this.Visit(binary.Left, context);
Expression right = this.Visit(binary.Right, context);
Expression conversion = this.Visit(binary.Conversion, context);
if (left == binary.Left &&
right == binary.Right &&
conversion == binary.Conversion)
{
// no change
return binary;
}
if (binary.NodeType == ExpressionType.Coalesce && binary.Conversion != null)
{
return Expression.Coalesce(left, right, conversion as LambdaExpression);
}
return Expression.MakeBinary(binary.NodeType, left, right, binary.IsLiftedToNull, binary.Method);
}
protected virtual Expression VisitTypeIs(TypeBinaryExpression binary, T context)
{
Expression expr = this.Visit(binary.Expression, context);
if (expr == binary.Expression)
{
// no change
return binary;
}
return Expression.TypeIs(expr, binary.TypeOperand);
}
protected virtual Expression VisitConstant(ConstantExpression constant, T context)
{
// no change
return constant;
}
protected virtual Expression VisitConditional(ConditionalExpression conditional, T context)
{
Expression test = this.Visit(conditional.Test, context);
Expression ifTrue = this.Visit(conditional.IfTrue, context);
Expression ifFalse = this.Visit(conditional.IfFalse, context);
if (test == conditional.Test &&
ifTrue == conditional.IfTrue &&
ifFalse == conditional.IfFalse)
{
// no change
return conditional;
}
return Expression.Condition(test, ifTrue, ifFalse);
}
protected virtual ParameterExpression VisitParameter(ParameterExpression p, T context)
{
// no change
return p;
}
protected virtual IEnumerable<ParameterExpression> VisitParameterList(IList<ParameterExpression> original, T context)
{
List<ParameterExpression> list = null;
for (int i=0, length=original.Count; i<length; i++)
{
ParameterExpression exp = this.VisitParameter(original[i], context);
if (list != null)
{
list.Add(exp);
}
else if (exp != original[i])
{
list = new List<ParameterExpression>(length);
for (int j=0; j<i; j++)
{
// copy preceding values
list.Add(original[j]);
}
list.Add(exp);
}
}
if (list == null)
{
// no change
return original;
}
return list.AsReadOnly();
}
protected virtual Expression VisitMemberAccess(MemberExpression m, T context)
{
Expression exp = this.Visit(m.Expression, context);
if (exp == m.Expression)
{
// no change
return m;
}
return Expression.MakeMemberAccess(exp, m.Member);
}
protected virtual Expression VisitMethodCall(MethodCallExpression m, T context)
{
Expression obj = this.Visit(m.Object, context);
IEnumerable<Expression> args = this.VisitExpressionList(m.Arguments, context);
if (obj == m.Object && args == m.Arguments)
{
// no change
return m;
}
return Expression.Call(obj, m.Method, args);
}
protected virtual IEnumerable<Expression> VisitExpressionList(IList<Expression> original, T context)
{
List<Expression> list = null;
for (int i=0, length=original.Count; i<length; i++)
{
Expression exp = this.Visit(original[i], context);
if (list != null)
{
list.Add(exp);
}
else if (exp != original[i])
{
list = new List<Expression>(length);
for (int j=0; j<i; j++)
{
// copy preceding values
list.Add(original[j]);
}
list.Add(exp);
}
}
if (list == null)
{
// no change
return original;
}
return list.AsReadOnly();
}
protected virtual MemberAssignment VisitMemberAssignment(MemberAssignment assignment, T context)
{
Expression exp = this.Visit(assignment.Expression, context);
if (exp == assignment.Expression)
{
// no change
return assignment;
}
return Expression.Bind(assignment.Member, exp);
}
protected virtual MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding binding, T context)
{
IEnumerable<MemberBinding> bindings = this.VisitBindingList(binding.Bindings, context);
if (bindings == binding.Bindings)
{
// no change
return binding;
}
return Expression.MemberBind(binding.Member, bindings);
}
protected virtual MemberListBinding VisitMemberListBinding(MemberListBinding binding, T context)
{
IEnumerable<ElementInit> initializers = this.VisitElementInitializerList(binding.Initializers, context);
if (initializers == binding.Initializers)
{
// no change
return binding;
}
return Expression.ListBind(binding.Member, initializers);
}
protected virtual IEnumerable<MemberBinding> VisitBindingList(IList<MemberBinding> original, T context)
{
List<MemberBinding> list = null;
for (int i=0, length=original.Count; i<length; i++)
{
MemberBinding b = this.VisitBinding(original[i], context);
if (list != null)
{
list.Add(b);
}
else if (b != original[i])
{
list = new List<MemberBinding>(length);
for (int j = 0; j < i; j++)
{
// copy preceding values
list.Add(original[j]);
}
list.Add(b);
}
}
if (list == null)
{
// no change
return original;
}
return list;
}
protected virtual IEnumerable<ElementInit> VisitElementInitializerList(IList<ElementInit> original, T context)
{
List<ElementInit> list = null;
for (int i=0, length=original.Count; i<length; i++)
{
ElementInit init = this.VisitElementInitializer(original[i], context);
if (list != null)
{
list.Add(init);
}
else if (init != original[i])
{
list = new List<ElementInit>(length);
for (int j = 0; j < i; j++)
{
// copy preceding values
list.Add(original[j]);
}
list.Add(init);
}
}
if (list == null)
{
// no change
return original;
}
return list;
}
protected virtual Expression VisitLambda(LambdaExpression lambda, T context)
{
Expression body = this.Visit(lambda.Body, context);
if (body == lambda.Body)
{
// no change
return lambda;
}
return Expression.Lambda(lambda.Type, body, lambda.Parameters);
}
protected virtual NewExpression VisitNew(NewExpression ctor, T context)
{
IEnumerable<Expression> args = this.VisitExpressionList(ctor.Arguments, context);
if (args == ctor.Arguments)
{
// no change
return ctor;
}
if (ctor.Members == null)
{
return Expression.New(ctor.Constructor, args);
}
return Expression.New(ctor.Constructor, args, ctor.Members);
}
protected virtual Expression VisitMemberInit(MemberInitExpression init, T context)
{
NewExpression ctor = this.VisitNew(init.NewExpression, context);
IEnumerable<MemberBinding> bindings = this.VisitBindingList(init.Bindings, context);
if (ctor == init.NewExpression && bindings == init.Bindings)
{
// no change
return init;
}
return Expression.MemberInit(ctor, bindings);
}
protected virtual Expression VisitListInit(ListInitExpression init, T context)
{
NewExpression ctor = this.VisitNew(init.NewExpression, context);
IEnumerable<ElementInit> initializers = this.VisitElementInitializerList(init.Initializers, context);
if (ctor == init.NewExpression && initializers == init.Initializers)
{
// no change
return init;
}
return Expression.ListInit(ctor, initializers);
}
protected virtual Expression VisitNewArray(NewArrayExpression ctor, T context)
{
IEnumerable<Expression> exprs = this.VisitExpressionList(ctor.Expressions, context);
if (exprs == ctor.Expressions)
{
// no change
return ctor;
}
if (ctor.NodeType == ExpressionType.NewArrayInit)
{
return Expression.NewArrayInit(ctor.Type.GetElementType(), exprs);
}
return Expression.NewArrayBounds(ctor.Type.GetElementType(), exprs);
}
protected virtual Expression VisitInvocation(InvocationExpression invoke, T context)
{
IEnumerable<Expression> args = this.VisitExpressionList(invoke.Arguments, context);
Expression expr = this.Visit(invoke.Expression, context);
if (args == invoke.Arguments && expr == invoke.Expression)
{
// no change
return invoke;
}
return Expression.Invoke(expr, args);
}
#if NET40
protected virtual Expression VisitBlock(BlockExpression block, T context)
{
// TODO: implement visitor method
return block;
}
protected virtual Expression VisitDynamic(DynamicExpression dyn, T context)
{
// TODO: implement visitor method
return dyn;
}
protected virtual Expression VisitDefault(DefaultExpression exp, T context)
{
// TODO: implement visitor method
return exp;
}
#endif
#endregion Visit Methods
#region Utility Methods
protected static LambdaExpression GetLambda(Expression expression)
{
while (expression.NodeType == ExpressionType.Quote)
{
expression = ((UnaryExpression)expression).Operand;
}
if (expression.NodeType == ExpressionType.Constant)
{
return ((ConstantExpression)expression).Value as LambdaExpression;
}
return expression as LambdaExpression;
}
#endregion Utility Methods
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.PythonTools.Analysis.Values;
using Microsoft.PythonTools.Interpreter;
namespace Microsoft.PythonTools.Analysis {
/// <summary>
/// Maintains the list of modules loaded into the PythonAnalyzer.
///
/// This keeps track of the builtin modules as well as the user defined modules. It's wraps
/// up various elements we need to keep track of such as thread safety and lazy loading of built-in
/// modules.
/// </summary>
class ModuleTable : IEnumerable<KeyValuePair<string, ModuleLoadState>> {
private readonly IPythonInterpreter _interpreter;
private readonly PythonAnalyzer _analyzer;
private readonly ConcurrentDictionary<IPythonModule, BuiltinModule> _builtinModuleTable = new ConcurrentDictionary<IPythonModule, BuiltinModule>();
private readonly ConcurrentDictionary<string, ModuleReference> _modules = new ConcurrentDictionary<string, ModuleReference>(StringComparer.Ordinal);
public ModuleTable(PythonAnalyzer analyzer, IPythonInterpreter interpreter) {
_analyzer = analyzer;
_interpreter = interpreter;
}
public bool Contains(string name) {
return _modules.ContainsKey(name);
}
/// <summary>
/// Gets a reference to a module that has already been imported. You
/// probably want to use <see cref="TryImport"/>.
/// </summary>
/// <returns>
/// True if an attempt to import the module was made during the analysis
/// that used this module table. The reference may be null, or the
/// module within the reference may be null, even if this function
/// returns true.
/// </returns>
/// <remarks>
/// This exists for inspecting the results of an analysis (for example,
/// <see cref="SaveAnalysis"/>). To get access to a module while
/// analyzing code, even (especially!) if the module may not exist,
/// you should call <see cref="TryImport"/>.
/// </remarks>
internal bool TryGetImportedModule(string name, out ModuleReference res) {
return _modules.TryGetValue(name, out res);
}
/// <summary>
/// Gets a reference to a module.
/// </summary>
/// <param name="name">The full import name of the module.</param>
/// <param name="res">The module reference object.</param>
/// <returns>
/// True if the module is available. This means that <c>res.Module</c>
/// is not null. If this function returns false, <paramref name="res"/>
/// may be valid and should not be replaced, but it is an unresolved
/// reference.
/// </returns>
public async Task<ModuleReference> TryImportAsync(string name) {
ModuleReference res;
bool firstImport = false;
if (!_modules.TryGetValue(name, out res) || res == null) {
var mod = await Task.Run(() => _interpreter.ImportModule(name)).ConfigureAwait(false);
_modules[name] = res = new ModuleReference(GetBuiltinModule(mod));
firstImport = true;
}
if (res != null && res.Module == null) {
var mod = await Task.Run(() => _interpreter.ImportModule(name)).ConfigureAwait(false);
res.Module = GetBuiltinModule(mod);
}
if (firstImport && res != null && res.Module != null && _analyzer != null) {
await Task.Run(() => _analyzer.DoDelayedSpecialization(name)).ConfigureAwait(false);
}
if (res != null && res.Module == null) {
return null;
}
return res;
}
/// <summary>
/// Gets a reference to a module.
/// </summary>
/// <param name="name">The full import name of the module.</param>
/// <param name="res">The module reference object.</param>
/// <returns>
/// True if the module is available. This means that <c>res.Module</c>
/// is not null. If this function returns false, <paramref name="res"/>
/// may be valid and should not be replaced, but it is an unresolved
/// reference.
/// </returns>
public bool TryImport(string name, out ModuleReference res) {
bool firstImport = false;
if (!_modules.TryGetValue(name, out res) || res == null) {
_modules[name] = res = new ModuleReference(GetBuiltinModule(_interpreter.ImportModule(name)));
firstImport = true;
}
if (res != null && res.Module == null) {
res.Module = GetBuiltinModule(_interpreter.ImportModule(name));
}
if (firstImport && res != null && res.Module != null && _analyzer != null) {
_analyzer.DoDelayedSpecialization(name);
}
return res != null && res.Module != null;
}
public bool TryRemove(string name, out ModuleReference res) {
return _modules.TryRemove(name, out res);
}
public ModuleReference this[string name] {
get {
ModuleReference res;
if (!TryImport(name, out res)) {
throw new KeyNotFoundException(name);
}
return res;
}
set {
_modules[name] = value;
}
}
public ModuleReference GetOrAdd(string name) {
return _modules.GetOrAdd(name, _ => new ModuleReference());
}
/// <summary>
/// Reloads the modules when the interpreter says they've changed.
/// Modules that are already in the table as builtins are replaced or
/// removed, but no new modules are added.
/// </summary>
public void ReInit() {
var newNames = new HashSet<string>(_interpreter.GetModuleNames(), StringComparer.Ordinal);
foreach (var keyValue in _modules) {
var name = keyValue.Key;
var moduleRef = keyValue.Value;
var builtinModule = moduleRef.Module as BuiltinModule;
if (builtinModule != null) {
IPythonModule newModule = null;
if (newNames.Contains(name)) {
newModule = _interpreter.ImportModule(name);
}
if (newModule == null) {
// this module was unloaded
ModuleReference dummy;
_modules.TryRemove(name, out dummy);
BuiltinModule removedModule;
_builtinModuleTable.TryRemove(builtinModule.InterpreterModule, out removedModule);
foreach (var child in builtinModule.InterpreterModule.GetChildrenModules()) {
_modules.TryRemove(builtinModule.Name + "." + child, out dummy);
}
} else if (builtinModule.InterpreterModule != newModule) {
// this module was replaced with a new module
BuiltinModule removedModule;
_builtinModuleTable.TryRemove(builtinModule.InterpreterModule, out removedModule);
moduleRef.Module = GetBuiltinModule(newModule);
ImportChildren(newModule);
}
}
}
}
internal BuiltinModule GetBuiltinModule(IPythonModule attr) {
if (attr == null) {
return null;
}
BuiltinModule res;
if (!_builtinModuleTable.TryGetValue(attr, out res)) {
_builtinModuleTable[attr] = res = new BuiltinModule(attr, _analyzer);
}
return res;
}
internal void ImportChildren(IPythonModule interpreterModule) {
BuiltinModule module = null;
foreach (var child in interpreterModule.GetChildrenModules()) {
module = module ?? GetBuiltinModule(interpreterModule);
ModuleReference modRef;
var fullname = module.Name + "." + child;
if (!_modules.TryGetValue(fullname, out modRef) || modRef == null || modRef.Module == null) {
IAnalysisSet value;
if (module.TryGetMember(child, out value)) {
var mod = value as IModule;
if (mod != null) {
_modules[fullname] = new ModuleReference(mod);
_analyzer?.DoDelayedSpecialization(fullname);
}
}
}
}
}
#region IEnumerable<KeyValuePair<string,ModuleReference>> Members
public IEnumerator<KeyValuePair<string, ModuleLoadState>> GetEnumerator() {
var unloadedNames = new HashSet<string>(_interpreter.GetModuleNames(), StringComparer.Ordinal);
var unresolvedNames = _analyzer?.GetAllUnresolvedModuleNames();
foreach (var keyValue in _modules) {
unloadedNames.Remove(keyValue.Key);
unresolvedNames?.Remove(keyValue.Key);
yield return new KeyValuePair<string, ModuleLoadState>(keyValue.Key, new InitializedModuleLoadState(keyValue.Value));
}
foreach (var name in unloadedNames) {
yield return new KeyValuePair<string, ModuleLoadState>(name, new UninitializedModuleLoadState(this, name));
}
if (unresolvedNames != null) {
foreach (var name in unresolvedNames) {
yield return new KeyValuePair<string, ModuleLoadState>(name, new UnresolvedModuleLoadState());
}
}
}
class UnresolvedModuleLoadState : ModuleLoadState {
public override AnalysisValue Module {
get { return null; }
}
public override bool HasModule {
get { return false; }
}
public override bool HasReferences {
get { return false; }
}
public override bool IsValid {
get { return true; }
}
public override PythonMemberType MemberType {
get { return PythonMemberType.Unknown; }
}
internal override bool ModuleContainsMember(IModuleContext context, string name) {
return false;
}
}
class UninitializedModuleLoadState : ModuleLoadState {
private readonly ModuleTable _moduleTable;
private readonly string _name;
private PythonMemberType? _type;
public UninitializedModuleLoadState(ModuleTable moduleTable, string name) {
this._moduleTable = moduleTable;
this._name = name;
}
public override AnalysisValue Module {
get {
ModuleReference res;
if (_moduleTable.TryImport(_name, out res)) {
return res.AnalysisModule;
}
return null;
}
}
public override bool IsValid {
get {
return true;
}
}
public override bool HasReferences {
get {
return false;
}
}
public override bool HasModule {
get {
return true;
}
}
public override PythonMemberType MemberType {
get {
if (_type == null) {
var mod = _moduleTable._interpreter.ImportModule(_name);
if (mod != null) {
_type = mod.MemberType;
} else {
_type = PythonMemberType.Module;
}
}
return _type.Value;
}
}
internal override bool ModuleContainsMember(IModuleContext context, string name) {
var mod = _moduleTable._interpreter.ImportModule(_name);
if (mod != null) {
return BuiltinModuleContainsMember(context, name, mod);
}
return false;
}
}
class InitializedModuleLoadState : ModuleLoadState {
private readonly ModuleReference _reference;
public InitializedModuleLoadState(ModuleReference reference) {
_reference = reference;
}
public override AnalysisValue Module {
get {
return _reference.AnalysisModule;
}
}
public override bool HasReferences {
get {
return _reference.HasReferences;
}
}
public override bool IsValid {
get {
return Module != null || HasReferences;
}
}
public override bool HasModule {
get {
return Module != null;
}
}
public override PythonMemberType MemberType {
get {
if (Module != null) {
return Module.MemberType;
}
return PythonMemberType.Module;
}
}
internal override bool ModuleContainsMember(IModuleContext context, string name) {
BuiltinModule builtin = Module as BuiltinModule;
if (builtin != null) {
return BuiltinModuleContainsMember(context, name, builtin.InterpreterModule);
}
ModuleInfo modInfo = Module as ModuleInfo;
if (modInfo != null) {
VariableDef varDef;
if (modInfo.Scope.TryGetVariable(name, out varDef) &&
varDef.VariableStillExists) {
var types = varDef.TypesNoCopy;
if (types.Count > 0) {
foreach (var type in types) {
if (type is ModuleInfo || type is BuiltinModule) {
// we find modules via our modules list, dont duplicate these
return false;
}
foreach (var location in type.Locations) {
if (location.FilePath != modInfo.ProjectEntry.FilePath) {
// declared in another module
return false;
}
}
}
}
return true;
}
}
return false;
}
}
private static bool BuiltinModuleContainsMember(IModuleContext context, string name, IPythonModule interpModule) {
var mem = interpModule.GetMember(context, name);
if (mem != null) {
if (IsExcludedBuiltin(interpModule, mem)) {
// if a module imports a builtin and exposes it don't report it for purposes of adding imports
return false;
}
IPythonMultipleMembers multiMem = mem as IPythonMultipleMembers;
if (multiMem != null) {
foreach (var innerMem in multiMem.Members) {
if (IsExcludedBuiltin(interpModule, innerMem)) {
// if something non-excludable aliased w/ something excluable we probably
// only care about the excluable (for example a module and None - timeit.py
// does this in the std lib)
return false;
}
}
}
return true;
}
return false;
}
private static bool IsExcludedBuiltin(IPythonModule builtin, IMember mem) {
IPythonFunction func;
IPythonType type;
IPythonConstant constant;
if (mem is IPythonModule || // modules are handled specially
((func = mem as IPythonFunction) != null && func.DeclaringModule != builtin) || // function imported into another module
((type = mem as IPythonType) != null && type.DeclaringModule != builtin) || // type imported into another module
((constant = mem as IPythonConstant) != null && constant.Type.TypeId == BuiltinTypeId.Object)) { // constant which we have no real type info for.
return true;
}
if (constant != null) {
if (constant.Type.DeclaringModule.Name == "__future__" &&
constant.Type.Name == "_Feature" &&
builtin.Name != "__future__") {
// someone has done a from __future__ import blah, don't include import in another
// module in the list of places where you can import this from.
return true;
}
}
return false;
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
return GetEnumerator();
}
#endregion
}
abstract class ModuleLoadState {
public abstract AnalysisValue Module {
get;
}
public abstract bool HasModule {
get;
}
public abstract bool HasReferences {
get;
}
public abstract bool IsValid {
get;
}
public abstract PythonMemberType MemberType {
get;
}
internal abstract bool ModuleContainsMember(IModuleContext context, string name);
}
}
| |
/*
Copyright 2008 The 'A Concurrent Hashtable' development team
(http://www.codeplex.com/CH/People/ProjectPeople.aspx)
This library is licensed under the GNU Library General Public License (LGPL). You should
have received a copy of the license along with the source code. If not, an online copy
of the license can be found at http://www.codeplex.com/CH/license.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Orvid.Concurrent.Threading;
namespace Orvid.Concurrent.Collections
{
/// <summary>
/// A 'single writer - multi reader' threaded segment in a hashtable.
/// </summary>
/// <typeparam name="TStored"></typeparam>
/// <typeparam name="TSearch"></typeparam>
/// <remarks>
/// Though each segment can be accessed by 1 writer thread simultaneously, the hashtable becomes concurrent
/// for writing by containing many segments so that collisions are rare. The table will be fully concurrent
/// for read operations as far as they are not colliding with write operations.
/// Each segment is itself a small hashtable that can grow and shrink individualy. This prevents blocking of
/// the entire hashtable when growing or shrinking is needed. Because each segment is relatively small (depending on
/// the quality of the hash) resizing of the individual segments should not take much time.
/// </remarks>
internal class Segment<TStored,TSearch>
{
#region Construction
protected Segment( )
{}
public static Segment<TStored, TSearch> Create(Int32 initialSize)
{
var instance = new Segment<TStored, TSearch>();
instance.Initialize(initialSize);
return instance;
}
/// <summary>
/// Initialize the segment.
/// </summary>
/// <param name="initialSize"></param>
protected virtual void Initialize(Int32 initialSize)
{ _List = new TStored[Math.Max(4, initialSize)]; }
/// <summary>
/// When segment gets introduced into hashtable then its allocated space should be added to the
/// total allocated space.
/// Single threaded access or locking is needed
/// </summary>
/// <param name="traits"></param>
public void Welcome(ConcurrentHashtable<TStored, TSearch> traits)
{ traits.EffectTotalAllocatedSpace(_List.Length); }
/// <summary>
/// When segment gets removed from hashtable then its allocated space should be subtracted to the
/// total allocated space.
/// Single threaded access or locking is needed
/// </summary>
/// <param name="traits"></param>
public void Bye(ConcurrentHashtable<TStored, TSearch> traits)
{
traits.EffectTotalAllocatedSpace(-_List.Length);
_List = null;
}
#endregion
#region Locking
TinyReaderWriterLock _Lock;
internal void LockForWriting()
{ _Lock.LockForWriting(); }
internal void LockForReading()
{ _Lock.LockForReading(); }
internal bool Lock(bool forReading)
{
return forReading ? _Lock.LockForReading(false) : _Lock.LockForWriting(false);
}
internal void ReleaseForWriting()
{ _Lock.ReleaseForWriting(); }
internal void ReleaseForReading()
{ _Lock.ReleaseForReading(); }
internal void Release(bool forReading)
{
if (forReading)
_Lock.ReleaseForReading();
else
_Lock.ReleaseForWriting();
}
#endregion
/// <summary>
/// Array with 'slots'. Each slot can be filled or empty.
/// </summary>
internal TStored[] _List;
/// <summary>
/// Boolean value indicating if this segment has not been trashed yet.
/// </summary>
internal bool IsAlive { get { return _List != null; } }
#region Item Manipulation methods
/// <summary>
/// Inserts an item into a *not empty* spot given by position i. It moves items forward until an empty spot is found.
/// </summary>
/// <param name="mask"></param>
/// <param name="i"></param>
/// <param name="itemCopy"></param>
/// <param name="traits"></param>
private void InsertItemAtIndex(UInt32 mask, UInt32 i, TStored itemCopy, ConcurrentHashtable<TStored, TSearch> traits)
{
do
{
//swap
TStored temp = _List[i];
_List[i] = itemCopy;
itemCopy = temp;
i = (i + 1) & mask;
}
while(!traits.IsEmpty(ref _List[i]));
_List[i] = itemCopy;
}
/// <summary>
/// Find item in segment.
/// </summary>
/// <param name="key">Reference to the search key to use.</param>
/// <param name="item">Out reference to store the found item in.</param>
/// <param name="traits">Object that tells this segment how to treat items and keys.</param>
/// <returns>True if an item could be found, otherwise false.</returns>
public bool FindItem(ref TSearch key, out TStored item, ConcurrentHashtable<TStored, TSearch> traits)
{
var searchHash = traits.GetKeyHashCode(ref key);
var mask = (UInt32)(_List.Length - 1);
var i = searchHash & mask;
if (!traits.IsEmpty(ref _List[i]))
{
var firstHash = traits.GetItemHashCode(ref _List[i]);
var storedItemHash = firstHash;
var searchHashDiff = (searchHash - firstHash) & mask;
do
{
if (storedItemHash == searchHash && traits.ItemEqualsKey(ref _List[i], ref key))
{
item = _List[i];
return true;
}
i = (i + 1) & mask;
if(traits.IsEmpty(ref _List[i]))
break;
storedItemHash = traits.GetItemHashCode(ref _List[i]);
}
while (((storedItemHash - firstHash) & mask) <= searchHashDiff);
}
item = default(TStored);
return false;
}
/// <summary>
/// Find an existing item or, if it can't be found, insert a new item.
/// </summary>
/// <param name="key">Reference to the item that will be inserted if an existing item can't be found. It will also be used to search with.</param>
/// <param name="item">Out reference to store the found item or, if it can not be found, the new inserted item.</param>
/// <param name="traits">Object that tells this segment how to treat items and keys.</param>
/// <returns>True if an existing item could be found, otherwise false.</returns>
public bool GetOldestItem(ref TStored key, out TStored item, ConcurrentHashtable<TStored, TSearch> traits)
{
var searchHash = traits.GetItemHashCode(ref key);
var mask = (UInt32)(_List.Length - 1);
var i = searchHash & mask;
if (!traits.IsEmpty(ref _List[i]))
{
var firstHash = traits.GetItemHashCode(ref _List[i]);
var storedItemHash = firstHash;
var searchHashDiff = (searchHash - firstHash) & mask;
while (true)
{
if (storedItemHash == searchHash && traits.ItemEqualsItem(ref _List[i], ref key))
{
item = _List[i];
return true;
}
i = (i + 1) & mask;
if (traits.IsEmpty(ref _List[i]))
break;
storedItemHash = traits.GetItemHashCode(ref _List[i]);
if (((storedItemHash - firstHash) & mask) > searchHashDiff)
{
//insert
InsertItemAtIndex(mask, i, key, traits);
IncrementCount(traits);
item = key;
return false;
}
}
}
item = _List[i] = key;
IncrementCount(traits);
return false;
}
/// <summary>
/// Inserts an item in the segment, possibly replacing an equal existing item.
/// </summary>
/// <param name="key">A reference to the item to insert.</param>
/// <param name="item">An out reference where any replaced item will be written to, if no item was replaced the new item will be written to this reference.</param>
/// <param name="traits">Object that tells this segment how to treat items and keys.</param>
/// <returns>True if an existing item could be found and is replaced, otherwise false.</returns>
public bool InsertItem(ref TStored key, out TStored item, ConcurrentHashtable<TStored, TSearch> traits)
{
var searchHash = traits.GetItemHashCode(ref key);
var mask = (UInt32)(_List.Length - 1);
var i = searchHash & mask;
if (!traits.IsEmpty(ref _List[i]))
{
var firstHash = traits.GetItemHashCode(ref _List[i]);
var storedItemHash = firstHash;
var searchHashDiff = (searchHash - firstHash) & mask;
while (true)
{
if (storedItemHash == searchHash && traits.ItemEqualsItem(ref _List[i], ref key))
{
item = _List[i];
_List[i] = key;
return true;
}
i = (i + 1) & mask;
if (traits.IsEmpty(ref _List[i]))
break;
storedItemHash = traits.GetItemHashCode(ref _List[i]);
if (((storedItemHash - firstHash) & mask) > searchHashDiff)
{
//insert
InsertItemAtIndex(mask, i, key, traits);
IncrementCount(traits);
item = key;
return false;
}
}
}
item = _List[i] = key;
IncrementCount(traits);
return false;
}
/// <summary>
/// Removes an item from the segment.
/// </summary>
/// <param name="key">A reference to the key to search with.</param>
/// <param name="item">An out reference where the removed item will be stored or default(<typeparamref name="TStored"/>) if no item to remove can be found.</param>
/// <param name="traits">Object that tells this segment how to treat items and keys.</param>
/// <returns>True if an item could be found and is removed, false otherwise.</returns>
public bool RemoveItem(ref TSearch key, out TStored item, ConcurrentHashtable<TStored, TSearch> traits)
{
var searchHash = traits.GetKeyHashCode(ref key);
var mask = (UInt32)(_List.Length - 1);
var i = searchHash & mask;
if (!traits.IsEmpty(ref _List[i]))
{
var firstHash = traits.GetItemHashCode(ref _List[i]);
var storedItemHash = firstHash;
var searchHashDiff = (searchHash - firstHash) & mask;
do
{
if (storedItemHash == searchHash && traits.ItemEqualsKey(ref _List[i], ref key))
{
item = _List[i];
RemoveAtIndex(i, traits);
DecrementCount(traits);
return true;
}
i = (i + 1) & mask;
if (traits.IsEmpty(ref _List[i]))
break;
storedItemHash = traits.GetItemHashCode(ref _List[i]);
}
while (((storedItemHash - firstHash) & mask) <= searchHashDiff);
}
item = default(TStored);
return false;
}
protected void RemoveAtIndex(UInt32 index, ConcurrentHashtable<TStored, TSearch> traits)
{
var mask = (UInt32)(_List.Length - 1);
var i = index;
var j = (index + 1) & mask;
while(!traits.IsEmpty(ref _List[j]) && (traits.GetItemHashCode(ref _List[j]) & mask) != j)
{
_List[i] = _List[j];
i = j;
j = (j + 1) & mask;
}
_List[i] = default(TStored);
}
public void Clear(ConcurrentHashtable<TStored, TSearch> traits)
{
var oldList = _List;
_List = new TStored[4];
var effect = _List.Length - oldList.Length;
if (effect != 0)
traits.EffectTotalAllocatedSpace(effect);
_Count = 0;
}
/// <summary>
/// Iterate over items in the segment.
/// </summary>
/// <param name="beyond">Position beyond which the next filled slot will be found and the item in that slot returned. (Starting with -1)</param>
/// <param name="item">Out reference where the next item will be stored or default if the end of the segment is reached.</param>
/// <param name="traits">Object that tells this segment how to treat items and keys.</param>
/// <returns>The index position the next item has been found or -1 otherwise.</returns>
public int GetNextItem(int beyond, out TStored item, ConcurrentHashtable<TStored, TSearch> traits)
{
for (int end = _List.Length; ++beyond < end; )
{
if (!traits.IsEmpty(ref _List[beyond]))
{
item = _List[beyond];
return beyond;
}
}
item = default(TStored);
return -1;
}
#endregion
#region Resizing
protected virtual void ResizeList(ConcurrentHashtable<TStored, TSearch> traits)
{
var oldList = _List;
var oldListLength = oldList.Length;
var newListLength = 2;
while (newListLength < _Count)
newListLength <<= 1;
newListLength <<= 1;
if (newListLength != oldListLength)
{
_List = new TStored[newListLength];
var mask = (UInt32)(newListLength - 1);
for (int i = 0; i != oldListLength; ++i)
if (!traits.IsEmpty(ref oldList[i]))
{
var searchHash = traits.GetItemHashCode(ref oldList[i]);
//j is prefered insertion pos in new list.
var j = searchHash & mask;
if (traits.IsEmpty(ref _List[j]))
_List[j] = oldList[i];
else
{
var firstHash = traits.GetItemHashCode(ref _List[j]);
var storedItemHash = firstHash;
var searchHashDiff = (searchHash - firstHash) & mask;
while (true)
{
j = (j + 1) & mask;
if (traits.IsEmpty(ref _List[j]))
{
_List[j] = oldList[i];
break;
}
storedItemHash = traits.GetItemHashCode(ref _List[j]);
if (((storedItemHash - firstHash) & mask) > searchHashDiff)
{
InsertItemAtIndex(mask, j, oldList[i], traits);
break;
}
}
}
}
traits.EffectTotalAllocatedSpace(newListLength - oldListLength);
}
}
/// <summary>
/// Total numer of filled slots in _List.
/// </summary>
internal Int32 _Count;
protected void DecrementCount(ConcurrentHashtable<TStored, TSearch> traits, int amount)
{
var oldListLength = _List.Length;
_Count -= amount;
if (oldListLength > 4 && _Count < (oldListLength >> 2))
//Shrink
ResizeList(traits);
}
protected void DecrementCount(ConcurrentHashtable<TStored, TSearch> traits)
{ DecrementCount(traits, 1); }
private void IncrementCount(ConcurrentHashtable<TStored, TSearch> traits)
{
var oldListLength = _List.Length;
if (++_Count >= (oldListLength - (oldListLength >> 2)))
//Grow
ResizeList(traits);
}
/// <summary>
/// Remove any excess allocated space
/// </summary>
/// <param name="traits"></param>
internal void Trim(ConcurrentHashtable<TStored, TSearch> traits)
{ DecrementCount(traits, 0); }
#endregion
}
}
| |
//
// Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Conditions
{
using NLog.Internal;
using NLog.Conditions;
using NLog.Config;
using NLog.LayoutRenderers;
using NLog.Layouts;
using Xunit;
public class ConditionParserTests : NLogTestBase
{
[Fact]
public void ParseNullText()
{
Assert.Null(ConditionParser.ParseExpression(null));
}
[Fact]
public void ParseEmptyText()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression(""));
}
[Fact]
public void ImplicitOperatorTest()
{
ConditionExpression cond = "true and true";
Assert.IsType<ConditionAndExpression>(cond);
}
[Fact]
public void NullLiteralTest()
{
Assert.Equal("null", ConditionParser.ParseExpression("null").ToString());
}
[Fact]
public void BooleanLiteralTest()
{
Assert.Equal("True", ConditionParser.ParseExpression("true").ToString());
Assert.Equal("True", ConditionParser.ParseExpression("tRuE").ToString());
Assert.Equal("False", ConditionParser.ParseExpression("false").ToString());
Assert.Equal("False", ConditionParser.ParseExpression("fAlSe").ToString());
}
[Fact]
public void AndTest()
{
Assert.Equal("(True and True)", ConditionParser.ParseExpression("true and true").ToString());
Assert.Equal("(True and True)", ConditionParser.ParseExpression("tRuE AND true").ToString());
Assert.Equal("(True and True)", ConditionParser.ParseExpression("tRuE && true").ToString());
Assert.Equal("((True and True) and True)", ConditionParser.ParseExpression("true and true && true").ToString());
Assert.Equal("((True and True) and True)", ConditionParser.ParseExpression("tRuE AND true and true").ToString());
Assert.Equal("((True and True) and True)", ConditionParser.ParseExpression("tRuE && true AND true").ToString());
}
[Fact]
public void OrTest()
{
Assert.Equal("(True or True)", ConditionParser.ParseExpression("true or true").ToString());
Assert.Equal("(True or True)", ConditionParser.ParseExpression("tRuE OR true").ToString());
Assert.Equal("(True or True)", ConditionParser.ParseExpression("tRuE || true").ToString());
Assert.Equal("((True or True) or True)", ConditionParser.ParseExpression("true or true || true").ToString());
Assert.Equal("((True or True) or True)", ConditionParser.ParseExpression("tRuE OR true or true").ToString());
Assert.Equal("((True or True) or True)", ConditionParser.ParseExpression("tRuE || true OR true").ToString());
}
[Fact]
public void NotTest()
{
Assert.Equal("(not True)", ConditionParser.ParseExpression("not true").ToString());
Assert.Equal("(not (not True))", ConditionParser.ParseExpression("not not true").ToString());
Assert.Equal("(not (not (not True)))", ConditionParser.ParseExpression("not not not true").ToString());
}
[Fact]
public void StringTest()
{
Assert.Equal("''", ConditionParser.ParseExpression("''").ToString());
Assert.Equal("'Foo'", ConditionParser.ParseExpression("'Foo'").ToString());
Assert.Equal("'Bar'", ConditionParser.ParseExpression("'Bar'").ToString());
Assert.Equal("'d'Artagnan'", ConditionParser.ParseExpression("'d''Artagnan'").ToString());
var cle = ConditionParser.ParseExpression("'${message} ${level}'") as ConditionLayoutExpression;
Assert.NotNull(cle);
SimpleLayout sl = cle.Layout as SimpleLayout;
Assert.NotNull(sl);
Assert.Equal(3, sl.Renderers.Count);
Assert.IsType<MessageLayoutRenderer>(sl.Renderers[0]);
Assert.IsType<LiteralLayoutRenderer>(sl.Renderers[1]);
Assert.IsType<LevelLayoutRenderer>(sl.Renderers[2]);
}
[Fact]
public void LogLevelTest()
{
var result = ConditionParser.ParseExpression("LogLevel.Info") as ConditionLiteralExpression;
Assert.NotNull(result);
Assert.Same(LogLevel.Info, result.LiteralValue);
result = ConditionParser.ParseExpression("LogLevel.Trace") as ConditionLiteralExpression;
Assert.NotNull(result);
Assert.Same(LogLevel.Trace, result.LiteralValue);
}
[Fact]
public void RelationalOperatorTest()
{
RelationalOperatorTestInner("=", "==");
RelationalOperatorTestInner("==", "==");
RelationalOperatorTestInner("!=", "!=");
RelationalOperatorTestInner("<>", "!=");
RelationalOperatorTestInner("<", "<");
RelationalOperatorTestInner(">", ">");
RelationalOperatorTestInner("<=", "<=");
RelationalOperatorTestInner(">=", ">=");
}
[Fact]
public void NumberTest()
{
Assert.Equal("3.141592", ConditionParser.ParseExpression("3.141592").ToString());
Assert.Equal("42", ConditionParser.ParseExpression("42").ToString());
Assert.Equal("-42", ConditionParser.ParseExpression("-42").ToString());
Assert.Equal("-3.141592", ConditionParser.ParseExpression("-3.141592").ToString());
}
[Fact]
public void ExtraParenthesisTest()
{
Assert.Equal("3.141592", ConditionParser.ParseExpression("(((3.141592)))").ToString());
}
[Fact]
public void MessageTest()
{
var result = ConditionParser.ParseExpression("message");
Assert.IsType<ConditionMessageExpression>(result);
Assert.Equal("message", result.ToString());
}
[Fact]
public void LevelTest()
{
var result = ConditionParser.ParseExpression("level");
Assert.IsType<ConditionLevelExpression>(result);
Assert.Equal("level", result.ToString());
}
[Fact]
public void LoggerTest()
{
var result = ConditionParser.ParseExpression("logger");
Assert.IsType<ConditionLoggerNameExpression>(result);
Assert.Equal("logger", result.ToString());
}
[Fact]
public void ConditionFunctionTests()
{
var result = ConditionParser.ParseExpression("starts-with(logger, 'x${message}')") as ConditionMethodExpression;
Assert.NotNull(result);
Assert.Equal("starts-with(logger, 'x${message}')", result.ToString());
Assert.Equal("StartsWith", result.MethodInfo.Name);
Assert.Equal(typeof(ConditionMethods), result.MethodInfo.DeclaringType);
}
[Fact]
public void CustomNLogFactoriesTest()
{
var configurationItemFactory = new ConfigurationItemFactory();
configurationItemFactory.LayoutRenderers.RegisterDefinition("foo", typeof(FooLayoutRenderer));
configurationItemFactory.ConditionMethods.RegisterDefinition("check", typeof(MyConditionMethods).GetMethod("CheckIt"));
ConditionParser.ParseExpression("check('${foo}')", configurationItemFactory);
}
[Fact]
public void MethodNameWithUnderscores()
{
var configurationItemFactory = new ConfigurationItemFactory();
configurationItemFactory.LayoutRenderers.RegisterDefinition("foo", typeof(FooLayoutRenderer));
configurationItemFactory.ConditionMethods.RegisterDefinition("__check__", typeof(MyConditionMethods).GetMethod("CheckIt"));
ConditionParser.ParseExpression("__check__('${foo}')", configurationItemFactory);
}
[Fact]
public void UnbalancedParenthesis1Test()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("check("));
}
[Fact]
public void UnbalancedParenthesis2Test()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("((1)"));
}
[Fact]
public void UnbalancedParenthesis3Test()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("(1))"));
}
[Fact]
public void LogLevelWithoutAName()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("LogLevel.'somestring'"));
}
[Fact]
public void InvalidNumberWithUnaryMinusTest()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("-a31"));
}
[Fact]
public void InvalidNumberTest()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("-123.4a"));
}
[Fact]
public void UnclosedString()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("'Hello world"));
}
[Fact]
public void UnrecognizedToken()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("somecompletelyunrecognizedtoken"));
}
[Fact]
public void UnrecognizedPunctuation()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("#"));
}
[Fact]
public void UnrecognizedUnicodeChar()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("\u0090"));
}
[Fact]
public void UnrecognizedUnicodeChar2()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("\u0015"));
}
[Fact]
public void UnrecognizedMethod()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("unrecognized-method()"));
}
[Fact]
public void TokenizerEOFTest()
{
var tokenizer = new ConditionTokenizer(new SimpleStringReader(string.Empty));
Assert.Throws<ConditionParseException>(() => tokenizer.GetNextToken());
}
private void RelationalOperatorTestInner(string op, string result)
{
string operand1 = "3";
string operand2 = "7";
string input = operand1 + " " + op + " " + operand2;
string expectedOutput = "(" + operand1 + " " + result + " " + operand2 + ")";
var condition = ConditionParser.ParseExpression(input);
Assert.Equal(expectedOutput, condition.ToString());
}
public class FooLayoutRenderer : LayoutRenderer
{
protected override void Append(System.Text.StringBuilder builder, LogEventInfo logEvent)
{
throw new System.NotImplementedException();
}
}
public class MyConditionMethods
{
public static bool CheckIt(string s)
{
return s == "X";
}
}
}
}
| |
using System;
using System.Diagnostics;
using SharpFlame.Core.Domain;
using SharpFlame.Core.Extensions;
using SharpFlame.Mapping.Tools;
using SharpFlame.Maths;
namespace SharpFlame
{
public class clsBrush
{
public sBrushTiles Tiles;
private bool alignment;
private double radius;
private ShapeType shape = ShapeType.Circle;
public clsBrush(double initialRadius, ShapeType initialShape)
{
radius = initialRadius;
shape = initialShape;
CreateTiles();
}
public bool Alignment
{
get { return alignment; }
}
public double Radius
{
get { return radius; }
set
{
if ( radius == value )
{
return;
}
radius = value;
CreateTiles();
}
}
public ShapeType Shape
{
get { return shape; }
set
{
if ( shape == value )
{
return;
}
shape = value;
CreateTiles();
}
}
private void CreateTiles()
{
var alignmentOffset = radius - Math.Floor(radius);
double radiusB = Math.Floor(radius + 0.25D);
alignment = alignmentOffset >= 0.25D & alignmentOffset < 0.75D;
switch ( shape )
{
case ShapeType.Circle:
Tiles.CreateCircle(radiusB, 1.0D, alignment);
break;
case ShapeType.Square:
Tiles.CreateSquare(radiusB, 1.0D, alignment);
break;
}
}
public void PerformActionMapTiles(clsAction tool, sPosNum centre)
{
PerformAction(tool, centre, new XYInt(tool.Map.Terrain.TileSize.X - 1, tool.Map.Terrain.TileSize.Y - 1));
}
public void PerformActionMapVertices(clsAction tool, sPosNum centre)
{
PerformAction(tool, centre, tool.Map.Terrain.TileSize);
}
public void PerformActionMapSectors(clsAction tool, sPosNum centre)
{
PerformAction(tool, centre, new XYInt(tool.Map.SectorCount.X - 1, tool.Map.SectorCount.Y - 1));
}
public XYInt GetPosNum(sPosNum posNum)
{
if ( alignment )
{
return posNum.Alignment;
}
return posNum.Normal;
}
private void PerformAction(clsAction action, sPosNum posNum, XYInt lastValidNum)
{
var y = 0;
if ( action.Map == null )
{
Debugger.Break();
return;
}
var centre = GetPosNum(posNum);
action.Effect = 1.0D;
for ( y = MathUtil.ClampInt(Tiles.YMin + centre.Y, 0, lastValidNum.Y) - centre.Y;
y <= MathUtil.ClampInt(Tiles.YMax + centre.Y, 0, lastValidNum.Y) - centre.Y;
y++ )
{
action.PosNum.Y = centre.Y + y;
var xNum = y - Tiles.YMin;
var x = 0;
for ( x = MathUtil.ClampInt(Tiles.XMin[xNum] + centre.X, 0, lastValidNum.X) - centre.X;
x <= MathUtil.ClampInt(Convert.ToInt32(Tiles.XMax[xNum] + centre.X), 0, lastValidNum.X) - centre.X;
x++ )
{
action.PosNum.X = centre.X + x;
if ( action.UseEffect )
{
if ( Tiles.ResultRadius > 0.0D )
{
switch ( shape )
{
case ShapeType.Circle:
if ( alignment )
{
action.Effect =
Convert.ToDouble(1.0D -
(new XYDouble(action.PosNum.X, action.PosNum.Y) -
new XYDouble(centre.X - 0.5D, centre.Y - 0.5D)).GetMagnitude() /
(Tiles.ResultRadius + 0.5D));
}
else
{
action.Effect = Convert.ToDouble(1.0D - (centre - action.PosNum).ToDoubles().GetMagnitude() / (Tiles.ResultRadius + 0.5D));
}
break;
case ShapeType.Square:
if ( alignment )
{
action.Effect = 1.0D -
Math.Max(Math.Abs(action.PosNum.X - (centre.X - 0.5D)), Math.Abs(action.PosNum.Y - (centre.Y - 0.5D))) /
(Tiles.ResultRadius + 0.5D);
}
else
{
action.Effect = 1.0D -
Math.Max(Math.Abs(action.PosNum.X - centre.X), Math.Abs(action.PosNum.Y - centre.Y)) /
(Tiles.ResultRadius + 0.5D);
}
break;
}
}
}
action.ActionPerform();
}
}
}
public struct sPosNum
{
public XYInt Alignment;
public XYInt Normal;
}
}
public enum ShapeType
{
Circle,
Square
}
public struct sBrushTiles
{
public double ResultRadius;
public int[] XMax;
public int[] XMin;
public int YMax;
public int YMin;
public void CreateCircle(double Radius, double TileSize, bool Alignment)
{
var X = 0;
var Y = 0;
double dblX = 0;
double dblY = 0;
double radiusB = 0;
double radiusC = 0;
var A = 0;
var B = 0;
radiusB = Radius / TileSize;
if ( Alignment )
{
radiusB += 1.0D;
Y = (radiusB).Floor().ToInt();
YMin = Convert.ToInt32(- Y);
YMax = Y - 1;
B = YMax - YMin;
XMin = new int[B + 1];
XMax = new int[B + 1];
radiusC = radiusB * radiusB;
for ( Y = YMin; Y <= YMax; Y++ )
{
dblY = Y + 0.5D;
dblX = Math.Sqrt(radiusC - dblY * dblY) + 0.5D;
A = Y - YMin;
X = (dblX).Floor().ToInt();
XMin[A] = Convert.ToInt32(- X);
XMax[A] = X - 1;
}
}
else
{
radiusB += 0.125D;
Y = Math.Floor(radiusB).ToInt();
YMin = Convert.ToInt32(- Y);
YMax = Y;
B = YMax - YMin;
XMin = new int[B + 1];
XMax = new int[B + 1];
radiusC = radiusB * radiusB;
for ( Y = YMin; Y <= YMax; Y++ )
{
dblY = Y;
dblX = Math.Sqrt(radiusC - dblY * dblY);
A = Y - YMin;
X = dblX.Floor().ToInt();
XMin[A] = -X;
XMax[A] = X;
}
}
ResultRadius = B / 2.0D;
}
public void CreateSquare(double Radius, double TileSize, bool Alignment)
{
var Y = 0;
var A = 0;
var B = 0;
double RadiusB = 0;
RadiusB = Radius / TileSize + 0.5D;
if ( Alignment )
{
RadiusB += 0.5D;
A = RadiusB.Floor().ToInt();
YMin = -A;
YMax = A - 1;
}
else
{
A = RadiusB.Floor().ToInt();
YMin = -A;
YMax = A;
}
B = YMax - YMin;
XMin = new int[B + 1];
XMax = new int[B + 1];
for ( Y = 0; Y <= B; Y++ )
{
XMin[Y] = YMin;
XMax[Y] = YMax;
}
ResultRadius = B / 2.0D;
}
}
}
| |
// 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.Globalization;
using Xunit;
namespace System.Tests
{
public static class Int32Tests
{
[Fact]
public static void Ctor_Empty()
{
var i = new int();
Assert.Equal(0, i);
}
[Fact]
public static void Ctor_Value()
{
int i = 41;
Assert.Equal(41, i);
}
[Fact]
public static void MaxValue()
{
Assert.Equal(0x7FFFFFFF, int.MaxValue);
}
[Fact]
public static void MinValue()
{
Assert.Equal(unchecked((int)0x80000000), int.MinValue);
}
[Theory]
[InlineData(234, 234, 0)]
[InlineData(234, int.MinValue, 1)]
[InlineData(234, -123, 1)]
[InlineData(234, 0, 1)]
[InlineData(234, 123, 1)]
[InlineData(234, 456, -1)]
[InlineData(234, int.MaxValue, -1)]
[InlineData(-234, -234, 0)]
[InlineData(-234, 234, -1)]
[InlineData(-234, -432, 1)]
[InlineData(234, null, 1)]
public static void CompareTo(int i, object value, int expected)
{
if (value is int)
{
Assert.Equal(expected, Math.Sign(i.CompareTo((int)value)));
}
IComparable comparable = i;
Assert.Equal(expected, Math.Sign(comparable.CompareTo(value)));
}
[Fact]
public static void CompareTo_ObjectNotInt_ThrowsArgumentException()
{
IComparable comparable = 234;
Assert.Throws<ArgumentException>(null, () => comparable.CompareTo("a")); // Obj is not an int
Assert.Throws<ArgumentException>(null, () => comparable.CompareTo((long)234)); // Obj is not an int
}
[Theory]
[InlineData(789, 789, true)]
[InlineData(789, -789, false)]
[InlineData(789, 0, false)]
[InlineData(0, 0, true)]
[InlineData(-789, -789, true)]
[InlineData(-789, 789, false)]
[InlineData(789, null, false)]
[InlineData(789, "789", false)]
[InlineData(789, (long)789, false)]
public static void Equals(int i1, object obj, bool expected)
{
if (obj is int)
{
int i2 = (int)obj;
Assert.Equal(expected, i1.Equals(i2));
Assert.Equal(expected, i1.GetHashCode().Equals(i2.GetHashCode()));
}
Assert.Equal(expected, i1.Equals(obj));
}
public static IEnumerable<object[]> ToString_TestData()
{
NumberFormatInfo emptyFormat = NumberFormatInfo.CurrentInfo;
yield return new object[] { int.MinValue, "G", emptyFormat, "-2147483648" };
yield return new object[] { -4567, "G", emptyFormat, "-4567" };
yield return new object[] { 0, "G", emptyFormat, "0" };
yield return new object[] { 4567, "G", emptyFormat, "4567" };
yield return new object[] { int.MaxValue, "G", emptyFormat, "2147483647" };
yield return new object[] { 0x2468, "x", emptyFormat, "2468" };
yield return new object[] { 2468, "N", emptyFormat, string.Format("{0:N}", 2468.00) };
NumberFormatInfo customFormat = new NumberFormatInfo();
customFormat.NegativeSign = "#";
customFormat.NumberDecimalSeparator = "~";
customFormat.NumberGroupSeparator = "*";
yield return new object[] { -2468, "N", customFormat, "#2*468~00" };
yield return new object[] { 2468, "N", customFormat, "2*468~00" };
}
[Theory]
[MemberData(nameof(ToString_TestData))]
public static void ToString(int i, string format, IFormatProvider provider, string expected)
{
// Format is case insensitive
string upperFormat = format.ToUpperInvariant();
string lowerFormat = format.ToLowerInvariant();
string upperExpected = expected.ToUpperInvariant();
string lowerExpected = expected.ToLowerInvariant();
bool isDefaultProvider = (provider == null || provider == NumberFormatInfo.CurrentInfo);
if (string.IsNullOrEmpty(format) || format.ToUpperInvariant() == "G")
{
if (isDefaultProvider)
{
Assert.Equal(upperExpected, i.ToString());
Assert.Equal(upperExpected, i.ToString((IFormatProvider)null));
}
Assert.Equal(upperExpected, i.ToString(provider));
}
if (isDefaultProvider)
{
Assert.Equal(upperExpected, i.ToString(upperFormat));
Assert.Equal(lowerExpected, i.ToString(lowerFormat));
Assert.Equal(upperExpected, i.ToString(upperFormat, null));
Assert.Equal(lowerExpected, i.ToString(lowerFormat, null));
}
Assert.Equal(upperExpected, i.ToString(upperFormat, provider));
Assert.Equal(lowerExpected, i.ToString(lowerFormat, provider));
}
[Fact]
public static void ToString_InvalidFormat_ThrowsFormatException()
{
int i = 123;
Assert.Throws<FormatException>(() => i.ToString("Y")); // Invalid format
Assert.Throws<FormatException>(() => i.ToString("Y", null)); // Invalid format
}
public static IEnumerable<object[]> Parse_Valid_TestData()
{
NumberFormatInfo samePositiveNegativeFormat = new NumberFormatInfo()
{
PositiveSign = "|",
NegativeSign = "|"
};
NumberFormatInfo emptyPositiveFormat = new NumberFormatInfo() { PositiveSign = "" };
NumberFormatInfo emptyNegativeFormat = new NumberFormatInfo() { NegativeSign = "" };
// None
yield return new object[] { "0", NumberStyles.None, null, 0 };
yield return new object[] { "123", NumberStyles.None, null, 123 };
yield return new object[] { "2147483647", NumberStyles.None, null, 2147483647 };
yield return new object[] { "123\0\0", NumberStyles.None, null, 123 };
// HexNumber
yield return new object[] { "123", NumberStyles.HexNumber, null, 0x123 };
yield return new object[] { "abc", NumberStyles.HexNumber, null, 0xabc };
yield return new object[] { "ABC", NumberStyles.HexNumber, null, 0xabc };
yield return new object[] { "12", NumberStyles.HexNumber, null, 0x12 };
yield return new object[] { "80000000", NumberStyles.HexNumber, null, -2147483648 };
yield return new object[] { "FFFFFFFF", NumberStyles.HexNumber, null, -1 };
// Currency
NumberFormatInfo currencyFormat = new NumberFormatInfo()
{
CurrencySymbol = "$",
CurrencyGroupSeparator = "|",
NumberGroupSeparator = "/"
};
yield return new object[] { "$1|000", NumberStyles.Currency, currencyFormat, 1000 };
yield return new object[] { "$1000", NumberStyles.Currency, currencyFormat, 1000 };
yield return new object[] { "$ 1000", NumberStyles.Currency, currencyFormat, 1000 };
yield return new object[] { "1000", NumberStyles.Currency, currencyFormat, 1000 };
yield return new object[] { "$(1000)", NumberStyles.Currency, currencyFormat, -1000};
yield return new object[] { "($1000)", NumberStyles.Currency, currencyFormat, -1000 };
yield return new object[] { "$-1000", NumberStyles.Currency, currencyFormat, -1000 };
yield return new object[] { "-$1000", NumberStyles.Currency, currencyFormat, -1000 };
NumberFormatInfo emptyCurrencyFormat = new NumberFormatInfo() { CurrencySymbol = "" };
yield return new object[] { "100", NumberStyles.Currency, emptyCurrencyFormat, 100 };
// If CurrencySymbol and Negative are the same, NegativeSign is preferred
NumberFormatInfo sameCurrencyNegativeSignFormat = new NumberFormatInfo()
{
NegativeSign = "|",
CurrencySymbol = "|"
};
yield return new object[] { "|1000", NumberStyles.AllowCurrencySymbol | NumberStyles.AllowLeadingSign, sameCurrencyNegativeSignFormat, -1000 };
// Any
yield return new object[] { "123", NumberStyles.Any, null, 123 };
// AllowLeadingSign
yield return new object[] { "-2147483648", NumberStyles.AllowLeadingSign, null, -2147483648 };
yield return new object[] { "-123", NumberStyles.AllowLeadingSign, null, -123 };
yield return new object[] { "+0", NumberStyles.AllowLeadingSign, null, 0 };
yield return new object[] { "-0", NumberStyles.AllowLeadingSign, null, 0 };
yield return new object[] { "+123", NumberStyles.AllowLeadingSign, null, 123 };
// If PositiveSign and NegativeSign are the same, PositiveSign is preferred
yield return new object[] { "|123", NumberStyles.AllowLeadingSign, samePositiveNegativeFormat, 123 };
// Empty PositiveSign or NegativeSign
yield return new object[] { "100", NumberStyles.AllowLeadingSign, emptyPositiveFormat, 100 };
yield return new object[] { "100", NumberStyles.AllowLeadingSign, emptyNegativeFormat, 100 };
// AllowTrailingSign
yield return new object[] { "123", NumberStyles.AllowTrailingSign, null, 123 };
yield return new object[] { "123+", NumberStyles.AllowTrailingSign, null, 123 };
yield return new object[] { "123-", NumberStyles.AllowTrailingSign, null, -123 };
// If PositiveSign and NegativeSign are the same, PositiveSign is preferred
yield return new object[] { "123|", NumberStyles.AllowTrailingSign, samePositiveNegativeFormat, 123 };
// Empty PositiveSign or NegativeSign
yield return new object[] { "100", NumberStyles.AllowTrailingSign, emptyPositiveFormat, 100 };
yield return new object[] { "100", NumberStyles.AllowTrailingSign, emptyNegativeFormat, 100 };
// AllowLeadingWhite and AllowTrailingWhite
yield return new object[] { "123 ", NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, null, 123 };
yield return new object[] { " 123", NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, null, 123 };
yield return new object[] { " 123 ", NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, null, 123 };
// AllowThousands
NumberFormatInfo thousandsFormat = new NumberFormatInfo() { NumberGroupSeparator = "|" };
yield return new object[] { "1000", NumberStyles.AllowThousands, thousandsFormat, 1000 };
yield return new object[] { "1|0|0|0", NumberStyles.AllowThousands, thousandsFormat, 1000 };
yield return new object[] { "1|||", NumberStyles.AllowThousands, thousandsFormat, 1 };
NumberFormatInfo integerNumberSeparatorFormat = new NumberFormatInfo() { NumberGroupSeparator = "1" };
yield return new object[] { "1111", NumberStyles.AllowThousands, integerNumberSeparatorFormat, 1111 };
// AllowExponent
yield return new object[] { "1E2", NumberStyles.AllowExponent, null, 100 };
yield return new object[] { "1E+2", NumberStyles.AllowExponent, null, 100 };
yield return new object[] { "1e2", NumberStyles.AllowExponent, null, 100 };
yield return new object[] { "1E0", NumberStyles.AllowExponent, null, 1 };
yield return new object[] { "(1E2)", NumberStyles.AllowExponent | NumberStyles.AllowParentheses, null, -100 };
yield return new object[] { "-1E2", NumberStyles.AllowExponent | NumberStyles.AllowLeadingSign, null, -100 };
NumberFormatInfo negativeFormat = new NumberFormatInfo() { PositiveSign = "|" };
yield return new object[] { "1E|2", NumberStyles.AllowExponent, negativeFormat, 100 };
// AllowParentheses
yield return new object[] { "123", NumberStyles.AllowParentheses, null, 123 };
yield return new object[] { "(123)", NumberStyles.AllowParentheses, null, -123 };
// AllowDecimalPoint
NumberFormatInfo decimalFormat = new NumberFormatInfo() { NumberDecimalSeparator = "|" };
yield return new object[] { "67|", NumberStyles.AllowDecimalPoint, decimalFormat, 67 };
// NumberFormatInfo has a custom property with length > 1
NumberFormatInfo integerCurrencyFormat = new NumberFormatInfo() { CurrencySymbol = "123" };
yield return new object[] { "123123", NumberStyles.AllowCurrencySymbol, integerCurrencyFormat, 123 };
NumberFormatInfo integerPositiveSignFormat = new NumberFormatInfo() { PositiveSign = "123" };
yield return new object[] { "123123", NumberStyles.AllowLeadingSign, integerPositiveSignFormat, 123 };
}
[Theory]
[MemberData(nameof(Parse_Valid_TestData))]
public static void Parse(string value, NumberStyles style, IFormatProvider provider, int expected)
{
bool isDefaultProvider = provider == null || provider == NumberFormatInfo.CurrentInfo;
int result;
if ((style & ~NumberStyles.Integer) == 0 && style != NumberStyles.None)
{
// Use Parse(string) or Parse(string, IFormatProvider)
if (isDefaultProvider)
{
Assert.True(int.TryParse(value, out result));
Assert.Equal(expected, result);
Assert.Equal(expected, int.Parse(value));
}
Assert.Equal(expected, int.Parse(value, provider));
}
// Use Parse(string, NumberStyles, IFormatProvider)
Assert.True(int.TryParse(value, style, provider, out result));
Assert.Equal(expected, result);
Assert.Equal(expected, int.Parse(value, style, provider));
if (isDefaultProvider)
{
// Use Parse(string, NumberStyles) or Parse(string, NumberStyles, IFormatProvider)
Assert.True(int.TryParse(value, style, NumberFormatInfo.CurrentInfo, out result));
Assert.Equal(expected, result);
Assert.Equal(expected, int.Parse(value, style));
Assert.Equal(expected, int.Parse(value, style, NumberFormatInfo.CurrentInfo));
}
}
public static IEnumerable<object[]> Parse_Invalid_TestData()
{
// String is null, empty or entirely whitespace
yield return new object[] { null, NumberStyles.Integer, null, typeof(ArgumentNullException) };
yield return new object[] { null, NumberStyles.Any, null, typeof(ArgumentNullException) };
yield return new object[] { "", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { "", NumberStyles.Any, null, typeof(FormatException) };
yield return new object[] { " \t \n \r ", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { " \t \n \r ", NumberStyles.Any, null, typeof(FormatException) };
// String is garbage
yield return new object[] { "Garbage", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { "Garbage", NumberStyles.Any, null, typeof(FormatException) };
// String has leading zeros
yield return new object[] { "\0\0123", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { "\0\0123", NumberStyles.Any, null, typeof(FormatException) };
// String has internal zeros
yield return new object[] { "1\023", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { "1\023", NumberStyles.Any, null, typeof(FormatException) };
// Integer doesn't allow hex, exponents, paretheses, currency, thousands, decimal
yield return new object[] { "abc", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { "1E23", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { "(123)", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { 1000.ToString("C0"), NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { 1000.ToString("N0"), NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { 678.90.ToString("F2"), NumberStyles.Integer, null, typeof(FormatException) };
// HexNumber
yield return new object[] { "0xabc", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "&habc", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "G1", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "g1", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "+abc", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "-abc", NumberStyles.HexNumber, null, typeof(FormatException) };
// None doesn't allow hex or leading or trailing whitespace
yield return new object[] { "abc", NumberStyles.None, null, typeof(FormatException) };
yield return new object[] { "123 ", NumberStyles.None, null, typeof(FormatException) };
yield return new object[] { " 123", NumberStyles.None, null, typeof(FormatException) };
yield return new object[] { " 123 ", NumberStyles.None, null, typeof(FormatException) };
// AllowLeadingSign
yield return new object[] { "+", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
yield return new object[] { "-", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
yield return new object[] { "+-123", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
yield return new object[] { "-+123", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
yield return new object[] { "- 123", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
yield return new object[] { "+ 123", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
// AllowTrailingSign
yield return new object[] { "123-+", NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
yield return new object[] { "123+-", NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
yield return new object[] { "123 -", NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
yield return new object[] { "123 +", NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
// Parentheses has priority over CurrencySymbol and PositiveSign
NumberFormatInfo currencyNegativeParenthesesFormat = new NumberFormatInfo()
{
CurrencySymbol = "(",
PositiveSign = "))"
};
yield return new object[] { "(100))", NumberStyles.AllowParentheses | NumberStyles.AllowCurrencySymbol | NumberStyles.AllowTrailingSign, currencyNegativeParenthesesFormat, typeof(FormatException) };
// AllowTrailingSign and AllowLeadingSign
yield return new object[] { "+123+", NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
yield return new object[] { "+123-", NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
yield return new object[] { "-123+", NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
yield return new object[] { "-123-", NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
// AllowLeadingSign and AllowParentheses
yield return new object[] { "-(1000)", NumberStyles.AllowLeadingSign | NumberStyles.AllowParentheses, null, typeof(FormatException) };
yield return new object[] { "(-1000)", NumberStyles.AllowLeadingSign | NumberStyles.AllowParentheses, null, typeof(FormatException) };
// AllowLeadingWhite
yield return new object[] { "1 ", NumberStyles.AllowLeadingWhite, null, typeof(FormatException) };
yield return new object[] { " 1 ", NumberStyles.AllowLeadingWhite, null, typeof(FormatException) };
// AllowTrailingWhite
yield return new object[] { " 1 ", NumberStyles.AllowTrailingWhite, null, typeof(FormatException) };
yield return new object[] { " 1", NumberStyles.AllowTrailingWhite, null, typeof(FormatException) };
// AllowThousands
NumberFormatInfo thousandsFormat = new NumberFormatInfo() { NumberGroupSeparator = "|" };
yield return new object[] { "|||1", NumberStyles.AllowThousands, null, typeof(FormatException) };
// AllowExponent
yield return new object[] { "65E", NumberStyles.AllowExponent, null, typeof(FormatException) };
yield return new object[] { "65E10", NumberStyles.AllowExponent, null, typeof(OverflowException) };
yield return new object[] { "65E+10", NumberStyles.AllowExponent, null, typeof(OverflowException) };
yield return new object[] { "65E-1", NumberStyles.AllowExponent, null, typeof(OverflowException) };
// AllowDecimalPoint
NumberFormatInfo decimalFormat = new NumberFormatInfo() { NumberDecimalSeparator = "." };
yield return new object[] { (67.9).ToString(), NumberStyles.AllowDecimalPoint, null, typeof(OverflowException) };
// Parsing integers doesn't allow NaN, PositiveInfinity or NegativeInfinity
NumberFormatInfo doubleFormat = new NumberFormatInfo()
{
NaNSymbol = "NaN",
PositiveInfinitySymbol = "Infinity",
NegativeInfinitySymbol = "-Infinity"
};
yield return new object[] { "NaN", NumberStyles.Any, doubleFormat, typeof(FormatException) };
yield return new object[] { "Infinity", NumberStyles.Any, doubleFormat, typeof(FormatException) };
yield return new object[] { "-Infinity", NumberStyles.Any, doubleFormat, typeof(FormatException) };
// NumberFormatInfo has a custom property with length > 1
NumberFormatInfo integerCurrencyFormat = new NumberFormatInfo() { CurrencySymbol = "123" };
yield return new object[] { "123", NumberStyles.AllowCurrencySymbol, integerCurrencyFormat, typeof(FormatException) };
NumberFormatInfo integerPositiveSignFormat = new NumberFormatInfo() { PositiveSign = "123" };
yield return new object[] { "123", NumberStyles.AllowLeadingSign, integerPositiveSignFormat, typeof(FormatException) };
// Not in range of Int32
yield return new object[] { "2147483648", NumberStyles.Any, null, typeof(OverflowException) };
yield return new object[] { "2147483648", NumberStyles.Integer, null, typeof(OverflowException) };
yield return new object[] { "-2147483649", NumberStyles.Any, null, typeof(OverflowException) };
yield return new object[] { "-2147483649", NumberStyles.Integer, null, typeof(OverflowException) };
yield return new object[] { "2147483649-", NumberStyles.AllowTrailingSign, null, typeof(OverflowException) };
yield return new object[] { "(2147483649)", NumberStyles.AllowParentheses, null, typeof(OverflowException) };
yield return new object[] { "2E10", NumberStyles.AllowExponent, null, typeof(OverflowException) };
yield return new object[] { "800000000", NumberStyles.AllowHexSpecifier, null, typeof(OverflowException) };
yield return new object[] { "9223372036854775808", NumberStyles.Integer, null, typeof(OverflowException) };
yield return new object[] { "-9223372036854775809", NumberStyles.Integer, null, typeof(OverflowException) };
yield return new object[] { "8000000000000000", NumberStyles.AllowHexSpecifier, null, typeof(OverflowException) };
}
[Theory]
[MemberData(nameof(Parse_Invalid_TestData))]
public static void Parse_Invalid(string value, NumberStyles style, IFormatProvider provider, Type exceptionType)
{
bool isDefaultProvider = provider == null || provider == NumberFormatInfo.CurrentInfo;
int result;
if ((style & ~NumberStyles.Integer) == 0 && style != NumberStyles.None && (style & NumberStyles.AllowLeadingWhite) == (style & NumberStyles.AllowTrailingWhite))
{
// Use Parse(string) or Parse(string, IFormatProvider)
if (isDefaultProvider)
{
Assert.False(int.TryParse(value, out result));
Assert.Equal(default(int), result);
Assert.Throws(exceptionType, () => int.Parse(value));
}
Assert.Throws(exceptionType, () => int.Parse(value, provider));
}
// Use Parse(string, NumberStyles, IFormatProvider)
Assert.False(int.TryParse(value, style, provider, out result));
Assert.Equal(default(int), result);
Assert.Throws(exceptionType, () => int.Parse(value, style, provider));
if (isDefaultProvider)
{
// Use Parse(string, NumberStyles) or Parse(string, NumberStyles, IFormatProvider)
Assert.False(int.TryParse(value, style, NumberFormatInfo.CurrentInfo, out result));
Assert.Equal(default(int), result);
Assert.Throws(exceptionType, () => int.Parse(value, style));
Assert.Throws(exceptionType, () => int.Parse(value, style, NumberFormatInfo.CurrentInfo));
}
}
[Theory]
[InlineData(NumberStyles.HexNumber | NumberStyles.AllowParentheses)]
[InlineData(unchecked((NumberStyles)0xFFFFFC00))]
public static void TryParse_InvalidNumberStyle_ThrowsArgumentException(NumberStyles style)
{
int result = 0;
Assert.Throws<ArgumentException>(() => int.TryParse("1", style, null, out result));
Assert.Equal(default(int), result);
Assert.Throws<ArgumentException>(() => int.Parse("1", style));
Assert.Throws<ArgumentException>(() => int.Parse("1", style, null));
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_OXCFXICS
{
using System;
using System.IO;
/// <summary>
/// The ProgressInformation.
/// </summary>
[SerializableObjectAttribute(false, true)]
public class ProgressInformation : SerializableBase
{
/// <summary>
/// An unsigned 16-bit value that contains a number that identifies
/// the binary structure of the data that follows.
/// </summary>
[SerializableFieldAttribute(1)]
private ushort version;
/// <summary>
/// The padding.
/// </summary>
[SerializableFieldAttribute(2)]
private ushort padding1;
/// <summary>
/// An unsigned 32-bit integer value that contains
/// the total number of changes to FAI messages that
/// are scheduled for download during the current
/// synchronization operation.
/// </summary>
[SerializableFieldAttribute(3)]
private uint faiMessageCount;
/// <summary>
/// An unsigned 64-bit integer value that contains
/// the size in bytes of all changes to FAI messages
/// that are scheduled for download during the current
/// synchronization operation.
/// </summary>
[SerializableFieldAttribute(4)]
private ulong faiMessageTotalSize;
/// <summary>
/// An unsigned 32-bit integer value that contains
/// the total number of changes to normal messages
/// that are scheduled for download during the current
/// synchronization operation.
/// </summary>
[SerializableFieldAttribute(5)]
private uint normalMessageCount;
/// <summary>
/// SHOULD be set to zeros and MUST be ignored by clients.
/// </summary>
[SerializableFieldAttribute(6)]
private uint padding2;
/// <summary>
/// An unsigned 64-bit integer value that contains the size
/// in bytes of all changes to normal messages that are scheduled
/// for download during the current synchronization operation.
/// </summary>
[SerializableFieldAttribute(7)]
private ulong normalMessageTotalSize;
#region Properties
/// <summary>
/// Gets or sets the version.
/// </summary>
public ushort Version
{
get
{
return this.version;
}
set
{
this.version = value;
}
}
/// <summary>
/// Gets or sets the padding1.
/// </summary>
public ushort Padding1
{
get
{
return this.padding1;
}
set
{
this.padding1 = value;
}
}
/// <summary>
/// Gets or sets the faiMessageCount.
/// </summary>
public uint FAIMessageCount
{
get
{
return this.faiMessageCount;
}
set
{
this.faiMessageCount = value;
}
}
/// <summary>
/// Gets or sets the faiMessageTotalSize.
/// </summary>
public ulong FAIMessageTotalSize
{
get
{
return this.faiMessageTotalSize;
}
set
{
this.faiMessageTotalSize = value;
}
}
/// <summary>
/// Gets or sets the normalMessageCount.
/// </summary>
public uint NormalMessageCount
{
get
{
return this.normalMessageCount;
}
set
{
this.normalMessageCount = value;
}
}
/// <summary>
/// Gets or sets the padding2.
/// </summary>
public uint Padding2
{
get
{
return this.padding2;
}
set
{
this.padding2 = value;
}
}
/// <summary>
/// Gets or sets the normalMessageTotalSize.
/// </summary>
public ulong NormalMessageTotalSize
{
get
{
return this.normalMessageTotalSize;
}
set
{
this.normalMessageTotalSize = value;
}
}
#endregion
/// <summary>
/// Deserialize fields in this class from a stream.
/// </summary>
/// <param name="stream">Stream contains a serialized instance of this class.</param>
/// <param name="size">The number of bytes can read if -1, no limitation.</param>
/// <returns>Bytes have been read from the stream.</returns>
public override int Deserialize(Stream stream, int size)
{
int bytesRead = 0;
this.version = StreamHelper.ReadUInt16(stream);
bytesRead += 2;
if (size >= 0 && bytesRead > size)
{
AdapterHelper.Site.Assert.Fail("The bytes length to read is larger than stream size, the stream size is {0} and the bytes to read is {1}.", size, bytesRead);
}
this.padding1 = StreamHelper.ReadUInt16(stream);
bytesRead += 2;
if (size >= 0 && bytesRead > size)
{
AdapterHelper.Site.Assert.Fail("The bytes length to read is larger than stream size, the stream size is {0} and the bytes to read is {1}.", size, bytesRead);
}
this.faiMessageCount = StreamHelper.ReadUInt32(stream);
bytesRead += 4;
if (size >= 0 && bytesRead > size)
{
AdapterHelper.Site.Assert.Fail("The bytes length to read is larger than stream size, the stream size is {0} and the bytes to read is {1}.", size, bytesRead);
}
this.faiMessageTotalSize = StreamHelper.ReadUInt64(stream);
bytesRead += 8;
if (size >= 0 && bytesRead > size)
{
AdapterHelper.Site.Assert.Fail("The bytes length to read is larger than stream size, the stream size is {0} and the bytes to read is {1}.", size, bytesRead);
}
this.normalMessageCount = StreamHelper.ReadUInt32(stream);
bytesRead += 4;
if (size >= 0 && bytesRead > size)
{
AdapterHelper.Site.Assert.Fail("The bytes length to read is larger than stream size, the stream size is {0} and the bytes to read is {1}.", size, bytesRead);
}
this.padding2 = StreamHelper.ReadUInt32(stream);
bytesRead += 4;
if (size >= 0 && bytesRead > size)
{
AdapterHelper.Site.Assert.Fail("The bytes length to read is larger than stream size, the stream size is {0} and the bytes to read is {1}.", size, bytesRead);
}
this.normalMessageTotalSize = StreamHelper.ReadUInt64(stream);
bytesRead += 8;
if (size >= 0 && bytesRead > size)
{
AdapterHelper.Site.Assert.Fail("The bytes length to read is larger than stream size, the stream size is {0} and the bytes to read is {1}.", size, bytesRead);
}
return bytesRead;
}
}
}
| |
using System;
using System.Net;
using PacketParser;
using PacketParser.Packets;
using ProtocolIdentification;
namespace Spid
{
/// <summary>
/// The definition of a session is:
/// * SYN and SYN+ACK is received
/// * FIN+ACK not received
/// * RST not received
/// </summary>
internal class TcpSession : ISession
{
public delegate void ProtocolModelCompletedEventHandler(TcpSession session, ProtocolModel protocolModel);
public delegate void SessionClosedEventHandler(TcpSession session, ProtocolModel protocolModel);
public delegate void SessionEstablishedEventHandler(TcpSession session);
public enum TCPState
{
NONE,
SYN,
SYN_ACK,
ESTABLISHED,
FIN,
CLOSED
}
//each protocol model consumes 30*256*4 = 30720 bytes (30kB)
//private System.Net.NetworkInformation.PhysicalAddress serverMac, clientMac;
private Configuration config;
public TcpSession(Configuration config, ProtocolModel applicationProtocolModel) : this(config) { this.ApplicationProtocolModel = applicationProtocolModel; }
public TcpSession(Configuration config, IPAddress clientIp, UInt16 clientPort, IPAddress serverIp, UInt16 serverPort) : this(config)
{
this.ClientIP = clientIp;
this.ClientPort = clientPort;
this.ServerIP = serverIp;
this.ServerPort = serverPort;
}
public TcpSession(Configuration config)
{
this.config = config;
this.ApplicationProtocolModel = null; //protocol model is not initialized until the session is established
this.State = TCPState.NONE;
this.FirstPacketTimestamp = DateTime.MinValue;
this.ServerIP = null;
this.ClientIP = null;
this.UsePlaceholderProtocolModel = false;
}
public Int32 FrameCount { get; private set; }
public TCPState State { get; set; }
/// <summary>
/// The session's application protocol model can be replaced with a
/// "place holder" protocol model when the session or model is complete
/// in order to save memory.
/// Default value is: false
/// </summary>
public Boolean UsePlaceholderProtocolModel { get; set; }
public AttributeFingerprintHandler.PacketDirection AddFrame(Frame frame)
{
//ProtocolIdentification.AttributeFingerprintHandler.PacketDirection packetDirection=ProtocolIdentification.AttributeFingerprintHandler.PacketDirection.Unknown;
//let's get the IP and TCP packets from the frame
AbstractPacket ipPacket;
TcpPacket tcpPacket;
if(SessionHandler.TryGetIpAndTcpPackets(frame, out ipPacket, out tcpPacket))
{
//we now have the IP and TCP packets
var sourceIp = IPAddress.None;
var destinationIp = IPAddress.None;
var applicationLayerProtocolLength = 0;
if(ipPacket.GetType() == typeof(IPv4Packet))
{
var ipv4Packet = (IPv4Packet) ipPacket;
sourceIp = ipv4Packet.SourceIPAddress;
destinationIp = ipv4Packet.DestinationIPAddress;
applicationLayerProtocolLength = ipv4Packet.TotalLength - ipv4Packet.HeaderLength - tcpPacket.DataOffsetByteCount;
}
else if(ipPacket.GetType() == typeof(IPv6Packet))
{
var ipv6Packet = (IPv6Packet) ipPacket;
sourceIp = ipv6Packet.SourceIP;
destinationIp = ipv6Packet.DestinationIP;
applicationLayerProtocolLength = ipv6Packet.PayloadLength - tcpPacket.DataOffsetByteCount;
}
//Check if the client and server have been defined
if(this.ServerIP == null || this.ClientIP == null)
{
//find out which host is server and which is client
if(tcpPacket.FlagBits.Synchronize && !tcpPacket.FlagBits.Acknowledgement)
{
//source is client
this.ClientIP = sourceIp;
this.ClientPort = tcpPacket.SourcePort;
this.ServerIP = destinationIp;
this.ServerPort = tcpPacket.DestinationPort;
}
else if(tcpPacket.FlagBits.Synchronize && tcpPacket.FlagBits.Acknowledgement)
{
//source is server
this.ServerIP = sourceIp;
this.ServerPort = tcpPacket.SourcePort;
this.ClientIP = destinationIp;
this.ClientPort = tcpPacket.DestinationPort;
}
else
{
throw new Exception("Session does not start with a SYN or SYN+ACK packet");
}
}
//identify the direction
if(sourceIp.Equals(this.ClientIP) && destinationIp.Equals(this.ServerIP) && tcpPacket.SourcePort == this.ClientPort && tcpPacket.DestinationPort == this.ServerPort)
{
//AddFrame(ipPacket, tcpPacket, ProtocolIdentification.AttributeFingerprintHandler.PacketDirection.ClientToServer);
this.AddFrame(tcpPacket, AttributeFingerprintHandler.PacketDirection.ClientToServer, applicationLayerProtocolLength);
return AttributeFingerprintHandler.PacketDirection.ClientToServer;
}
if(sourceIp.Equals(this.ServerIP) && destinationIp.Equals(this.ClientIP) && tcpPacket.SourcePort == this.ServerPort && tcpPacket.DestinationPort == this.ClientPort)
{
this.AddFrame(tcpPacket, AttributeFingerprintHandler.PacketDirection.ServerToClient, applicationLayerProtocolLength);
return AttributeFingerprintHandler.PacketDirection.ServerToClient;
}
throw new Exception("IP's and ports do not match those belonging to this session\nSession server: " + this.ServerIP + ":" + this.ServerPort + "\nSession client: "
+ this.ClientIP + ":" + this.ClientPort + "\nPacket source: " + sourceIp + ":" + tcpPacket.SourcePort + "\nPacket destination: " + destinationIp
+ ":" + tcpPacket.DestinationPort);
}
return AttributeFingerprintHandler.PacketDirection.Unknown;
}
public ProtocolModel ApplicationProtocolModel { get; private set; }
public IPAddress ClientIP { get; set; }
public UInt16 ClientPort { get; set; }
public DateTime FirstPacketTimestamp { get; private set; }
public String Identifier => SessionHandler.GetSessionIdentifier(this.ClientIP, this.ClientPort, this.ServerIP, this.ServerPort, this.TransportProtocol);
public DateTime LastPacketTimestamp { get; private set; }
public IPAddress ServerIP { get; set; }
public UInt16 ServerPort { get; set; }
//public const int PROTOCOL_MODEL_MAX_FRAMES=100;
public SessionHandler.TransportProtocol TransportProtocol => SessionHandler.TransportProtocol.TCP;
public void AddFrame(TcpPacket tcpPacket, AttributeFingerprintHandler.PacketDirection direction, Int32 protocolPacketLength)
{
this.FrameCount++;
this.LastPacketTimestamp = tcpPacket.ParentFrame.Timestamp;
if(this.FirstPacketTimestamp == DateTime.MinValue) { this.FirstPacketTimestamp = tcpPacket.ParentFrame.Timestamp; }
if(direction == AttributeFingerprintHandler.PacketDirection.Unknown) { throw new Exception("A valid direction must be supplied"); }
if(this.FrameCount == this.config.MaxFramesToInspectPerSession + 1 && this.ApplicationProtocolModel != SessionHandler.PlaceholderProtocolModel)
{
if(this.ProtocolModelCompleted != null) { this.ProtocolModelCompleted(this, this.ApplicationProtocolModel); }
if(this.UsePlaceholderProtocolModel) { this.ApplicationProtocolModel = SessionHandler.PlaceholderProtocolModel; }
}
if(this.State == TCPState.CLOSED)
{
//do nothing
//throw new Exception("Cannot add a frame to a closed session");
}
else if(this.State == TCPState.NONE)
{
//Expected: client->server SYN
//or unidirectional server->client SYN+ACK
if(direction == AttributeFingerprintHandler.PacketDirection.ClientToServer && tcpPacket.FlagBits.Synchronize) {
this.State = TCPState.SYN;
}
else if(direction == AttributeFingerprintHandler.PacketDirection.ServerToClient && tcpPacket.FlagBits.Synchronize && tcpPacket.FlagBits.Acknowledgement) {
this.State = TCPState.SYN_ACK;
}
}
else if(this.State == TCPState.SYN)
{
//Expected: server->client SYN+ACK
//or unidirectional client->server ACK
if(direction == AttributeFingerprintHandler.PacketDirection.ServerToClient && tcpPacket.FlagBits.Synchronize && tcpPacket.FlagBits.Acknowledgement) {
this.State = TCPState.SYN_ACK;
}
else if(direction == AttributeFingerprintHandler.PacketDirection.ClientToServer && !tcpPacket.FlagBits.Synchronize && tcpPacket.FlagBits.Acknowledgement) {
this.State = TCPState.ESTABLISHED;
}
}
else if(this.State == TCPState.SYN_ACK)
{
//Expected: client->server ACK
//or unidirectional first data packet server->client
if(direction == AttributeFingerprintHandler.PacketDirection.ClientToServer && tcpPacket.FlagBits.Acknowledgement && !tcpPacket.FlagBits.Synchronize)
{
this.State = TCPState.ESTABLISHED;
//generate a SessionEstablishedEvent
if(this.SessionEstablished != null) { this.SessionEstablished(this); }
}
//else if(direction==ProtocolIdentification.AttributeFingerprintHandler.PacketDirection.ServerToClient && (ipPacket.TotalLength-(tcpPacket.PacketStartIndex-ipPacket.PacketStartIndex)-tcpPacket.DataOffsetByteCount)>0) {
else if(direction == AttributeFingerprintHandler.PacketDirection.ServerToClient && protocolPacketLength > 0)
{
this.State = TCPState.ESTABLISHED;
if(this.SessionEstablished != null) { this.SessionEstablished(this); }
//AddFrameToOpenSession(ipPacket, tcpPacket, direction);
this.AddFrameToOpenSession(tcpPacket, direction, protocolPacketLength);
}
}
else if(this.State == TCPState.ESTABLISHED || this.State == TCPState.FIN)
{
//AddFrameToOpenSession(ipPacket, tcpPacket, direction);
this.AddFrameToOpenSession(tcpPacket, direction, protocolPacketLength);
}
}
public event ProtocolModelCompletedEventHandler ProtocolModelCompleted;
public event SessionClosedEventHandler SessionClosed;
public event SessionEstablishedEventHandler SessionEstablished;
private void AddFrameToOpenSession(TcpPacket tcpPacket, AttributeFingerprintHandler.PacketDirection direction, Int32 protocolPacketLength)
{
if(this.State != TCPState.ESTABLISHED && this.State != TCPState.FIN) { throw new Exception("Session is not open!"); }
if(this.State == TCPState.ESTABLISHED && tcpPacket.FlagBits.Fin && !tcpPacket.FlagBits.Acknowledgement) {
this.State = TCPState.FIN;
}
else if(tcpPacket.FlagBits.Fin && tcpPacket.FlagBits.Acknowledgement)
{
this.State = TCPState.CLOSED;
if(this.SessionClosed != null) { this.SessionClosed(this, this.ApplicationProtocolModel); }
if(this.UsePlaceholderProtocolModel) {
this.ApplicationProtocolModel = SessionHandler.PlaceholderProtocolModel; //to save memory
}
}
else if(tcpPacket.FlagBits.Reset)
{
this.State = TCPState.CLOSED;
if(this.SessionClosed != null) { this.SessionClosed(this, this.ApplicationProtocolModel); }
if(this.UsePlaceholderProtocolModel) {
this.ApplicationProtocolModel = SessionHandler.PlaceholderProtocolModel; //to save memory
}
}
else
{
if(this.ApplicationProtocolModel == null) { this.ApplicationProtocolModel = new ProtocolModel(this.Identifier, this.config.ActiveAttributeMeters); }
if(this.FrameCount <= this.config.MaxFramesToInspectPerSession)
{
//at last we can add the observation to the model
//int protocolPacketStartIndex=tcpPacket.PacketStartIndex+tcpPacket.DataOffsetByteCount;
//int protocolPacketLength=ipPacket.TotalLength-(tcpPacket.PacketStartIndex-ipPacket.PacketStartIndex)-tcpPacket.DataOffsetByteCount;
if(protocolPacketLength > 0)
{
var protocolPacketStartIndex = tcpPacket.PacketStartIndex + tcpPacket.DataOffsetByteCount;
this.ApplicationProtocolModel.AddObservation(tcpPacket.ParentFrame.Data, protocolPacketStartIndex, protocolPacketLength, tcpPacket.ParentFrame.Timestamp,
direction);
}
}
}
}
}
}
| |
#region Header
// ---------------------------------------------------------------------------
// Copyright Sepura Plc
// All Rights reserved. Reproduction in whole or part is prohibited without
// written consent of the copyright owner.
//
// ByteStore.cs
// Implementation of the Class ByteStore
//
// Original author: robinsond
//
// $Id:$
// ---------------------------------------------------------------------------
#endregion
namespace Sepura.DataDictionary
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
/// <summary>
/// Class containing a sequence of bytes and an index into the current position
/// within the sequence.
/// </summary>
public class ByteStore
{
/// <summary>
/// Gets the index of the current read position.
/// </summary>
public int ReadPosition { get; private set; }
/// <summary>
/// Gets the index of the current write position.
/// </summary>
public int WritePosition
{
get
{
return m_Bytes.Count;
}
}
/// <summary>
/// Gets the payload as an enumerable set of bytes
/// </summary>
public IEnumerable<byte> Payload
{
get
{
return m_Bytes;
}
}
/// <summary>
/// Gets the length of the payload.
/// </summary>
/// <value>
/// The length of the payload.
/// </value>
public int PayloadLength
{
get { return m_Bytes.Count; }
}
/// <summary>
/// Initializes a new instance of the <see cref="ByteStore"/> class.
/// </summary>
public ByteStore()
{
m_Bytes = new List<byte>();
}
/// <summary>
/// Initializes a new instance of the <see cref="ByteStore"/> class populated with a collection
/// of bytes
/// </summary>
/// <param name="theBytes">The bytes to store in the internal store</param>
public ByteStore(IEnumerable<byte> theBytes)
{
m_Bytes = new List<byte>(theBytes);
}
/// <summary>
/// Reads a single byte from the sequence at the current read location and
/// increments the current read location
/// </summary>
/// <returns>The extracted value</returns>
public byte GetByte()
{
if (ReadPosition >= m_Bytes.Count)
{
throw new DataDictionaryException("Read beyond end of data");
}
return m_Bytes[ReadPosition++];
}
/// <summary>
/// Reads a 16-bit value from the buffer
/// </summary>
/// <returns>Value read from the buffer</returns>
public ushort GetUint16()
{
ushort result = 0;
if (DictionaryManager.Endianism == Endianism.BigEndian)
{
result = GetByte();
result = (ushort)((result << 8) + GetByte());
}
else
{
result = (ushort) GetByte();
result += (ushort)(GetByte() << 8);
}
return result;
}
/// <summary>
/// Reads a 32-bit value from the buffer
/// </summary>
/// <returns>Value read from the buffer</returns>
public uint GetUint32()
{
uint result = 0;
if (DictionaryManager.Endianism == Endianism.BigEndian)
{
result = GetByte();
result = (uint)((result << 8) + GetByte());
result = (uint)((result << 8) + GetByte());
result = (uint)((result << 8) + GetByte());
}
else
{
result = (uint)GetByte();
result += (uint)(GetByte() << 8);
result += (uint)(GetByte() << 16);
result += (uint)(GetByte() << 24);
}
return result;
}
/// <summary>
/// Reads a 64-bit value from the buffer
/// </summary>
/// <returns>Value read from the buffer</returns>
public ulong GetUint64()
{
ulong result = 0;
if (DictionaryManager.Endianism == Endianism.BigEndian)
{
for (int i = 0; i < 8; i++)
{
result = (result << 8) + GetByte();
}
}
else
{
int shiftBits = 0;
for (int i = 0; i < 8; i++)
{
result += (ulong)GetByte() << shiftBits;
shiftBits += 8;
}
}
return result;
}
/// <summary>
/// Adds a single byte to the sequence at the end of the sequence
/// </summary>
/// <param name="theByte">The byte.</param>
public void PutByte(byte theByte)
{
m_Bytes.Add(theByte);
}
/// <summary>
/// Puts the 16-bit value into the store
/// </summary>
/// <param name="theValue">The value.</param>
public void PutUint16 (ushort theValue)
{
if (DictionaryManager.Endianism == Endianism.BigEndian)
{
// Big endian - write the MSByte first
ushort shiftBits = 8;
ushort mask = (ushort)(0xff << shiftBits);
while (shiftBits > 0)
{
m_Bytes.Add((byte)((theValue & mask) >> shiftBits));
mask >>= 8;
shiftBits -= 8;
}
m_Bytes.Add((byte)(theValue & mask));
}
else
{
// Little endian - write the LSByte first
ushort mask = 0xff;
ushort shiftBits = 0;
do
{
m_Bytes.Add((byte)(theValue & mask));
theValue >>= 8;
shiftBits += 8;
}
while (shiftBits <= 8);
}
}
/// <summary>
/// Puts the 32-bit value into the store
/// </summary>
/// <param name="theValue">The value.</param>
public void PutUint32(uint theValue)
{
if (DictionaryManager.Endianism == Endianism.BigEndian)
{
// Big endian - write the MSByte first
int shiftBits = 24;
uint mask = (uint)((uint)0xff << shiftBits);
while (shiftBits > 0)
{
m_Bytes.Add((byte)((theValue & mask) >> shiftBits));
mask >>= 8;
shiftBits -= 8;
}
m_Bytes.Add((byte)(theValue & mask));
}
else
{
// Little endian - write the LSByte first
uint mask = 0xff;
uint shiftBits = 0;
do
{
m_Bytes.Add((byte)(theValue & mask));
theValue >>= 8;
shiftBits += 8;
}
while (shiftBits <= 24);
}
}
/// <summary>
/// Puts the 64-bit value into the store
/// </summary>
/// <param name="theValue">The value.</param>
public void PutUint64(ulong theValue)
{
if (DictionaryManager.Endianism == Endianism.BigEndian)
{
// Big endian - write the MSByte first
int shiftBits = 56;
ulong mask = (ulong)(0xff << shiftBits);
while (shiftBits > 0)
{
m_Bytes.Add((byte)((theValue & mask) >> shiftBits));
mask >>= 8;
shiftBits -= 8;
}
m_Bytes.Add((byte)(theValue & mask));
}
else
{
// Little endian - write the LSByte first
ulong mask = 0xff;
uint shiftBits = 0;
do
{
m_Bytes.Add((byte)(theValue & mask));
theValue >>= 8;
shiftBits += 8;
}
while (shiftBits <= 56);
}
}
/// <summary>
/// Removes the contents of the payload and resets the read/write locations
/// </summary>
public void Clear()
{
m_Bytes.Clear();
ReadPosition = 0;
}
/// <summary>
/// Sequence of bytes managed by this object
/// </summary>
private readonly List<byte> m_Bytes;
}
}
| |
#region Licence...
/*
The MIT License (MIT)
Copyright (c) 2014 Oleg Shilo
Permission is hereby granted,
free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion Licence...
namespace WixSharp
{
/// <summary>
/// Defines WiX CustomAction for executing embedded VBScript.
/// </summary>
///
/// <example>The following is an example of using <c>ScriptAction</c> to run
/// VBScript code:
/// <code>
/// var project =
/// new Project("My Product",
///
/// new Dir(@"%ProgramFiles%\My Company\My Product",
/// new File(binaries, @"AppFiles\MyApp.exe",
/// new WixSharp.Shortcut("MyApp", @"%ProgramMenu%\My Company\My Product"),
/// new WixSharp.Shortcut("MyApp", @"%Desktop%")),
///
/// new ScriptAction(@"MsgBox ""Executing VBScript code...""",
/// Return.ignore,
/// When.After,
/// Step.InstallFinalize,
/// Condition.NOT_Installed),
/// ...
///
/// Compiler.BuildMsi(project);
/// </code>
/// </example>
public partial class ScriptAction : Action
{
/// <summary>
/// Initializes a new instance of the <see cref="ScriptAction"/> class with properties/fields initialized with specified parameters.
/// </summary>
/// <param name="code">VBScript code to be executed.</param>
public ScriptAction(string code)
: base()
{
Code = code;
Name = "VBScript";
}
/// <summary>
/// Initializes a new instance of the <see cref="ScriptAction"/> class with properties/fields initialized with specified parameters.
/// </summary>
/// <param name="code">VBScript code to be executed.</param>
/// <param name="rollbackArg">VBScript code to be executed on rollback.</param>
public ScriptAction(string code, string rollbackArg)
: base()
{
Code = code;
Name = "VBScript";
Rollback = "VBScript";
RollbackArg = rollbackArg;
}
/// <summary>
/// Initializes a new instance of the <see cref="ScriptAction"/> class with properties/fields initialized with specified parameters.
/// </summary>
/// <param name="id">The explicit <see cref="Id"></see> to be associated with <see cref="ScriptAction"/> instance.</param>
/// <param name="code">VBScript code to be executed.</param>
public ScriptAction(Id id, string code)
: base(id)
{
Code = code; ;
Name = "VBScript";
}
/// <summary>
/// Initializes a new instance of the <see cref="ScriptAction"/> class with properties/fields initialized with specified parameters.
/// </summary>
/// <param name="id">The explicit <see cref="Id"></see> to be associated with <see cref="ScriptAction"/> instance.</param>
/// <param name="code">VBScript code to be executed.</param>
/// <param name="rollbackArg">VBScript code to be executed on rollback.</param>
public ScriptAction(Id id, string code, string rollbackArg)
: base(id)
{
Code = code; ;
Name = "VBScript";
Rollback = "VBScript";
RollbackArg = rollbackArg;
}
/// <summary>
/// Initializes a new instance of the <see cref="ScriptAction"/> class with properties/fields initialized with specified parameters.
/// </summary>
/// <param name="code">VBScript code to be executed.</param>
/// <param name="returnType">The return type of the action.</param>
/// <param name="when"><see cref="T:WixSharp.When"/> the action should be executed with respect to the <paramref name="step"/> parameter.</param>
/// <param name="step"><see cref="T:WixSharp.Step"/> the action should be executed before/after during the installation.</param>
/// <param name="condition">The launch condition for the <see cref="ScriptAction"/>.</param>
public ScriptAction(string code, Return returnType, When when, Step step, Condition condition)
: base(returnType, when, step, condition)
{
Code = code;
Name = "VBScript";
}
/// <summary>
/// Initializes a new instance of the <see cref="ScriptAction"/> class with properties/fields initialized with specified parameters.
/// </summary>
/// <param name="code">VBScript code to be executed.</param>
/// <param name="returnType">The return type of the action.</param>
/// <param name="when"><see cref="T:WixSharp.When"/> the action should be executed with respect to the <paramref name="step"/> parameter.</param>
/// <param name="step"><see cref="T:WixSharp.Step"/> the action should be executed before/after during the installation.</param>
/// <param name="condition">The launch condition for the <see cref="ScriptAction"/>.</param>
/// <param name="rollbackArg">VBScript code to be executed on rollback.</param>
public ScriptAction(string code, Return returnType, When when, Step step, Condition condition, string rollbackArg)
: base(returnType, when, step, condition)
{
Code = code;
Name = "VBScript";
Rollback = "VBScript";
RollbackArg = rollbackArg;
}
/// <summary>
/// Initializes a new instance of the <see cref="ScriptAction"/> class with properties/fields initialized with specified parameters.
/// </summary>
/// <param name="id">The explicit <see cref="Id"></see> to be associated with <see cref="ScriptAction"/> instance.</param>
/// <param name="code">VBScript code to be executed.</param>
/// <param name="returnType">The return type of the action.</param>
/// <param name="when"><see cref="T:WixSharp.When"/> the action should be executed with respect to the <paramref name="step"/> parameter.</param>
/// <param name="step"><see cref="T:WixSharp.Step"/> the action should be executed before/after during the installation.</param>
/// <param name="condition">The launch condition for the <see cref="ScriptAction"/>.</param>
public ScriptAction(Id id, string code, Return returnType, When when, Step step, Condition condition)
: base(id, returnType, when, step, condition)
{
Code = code;
Name = "VBScript";
}
/// <summary>
/// Initializes a new instance of the <see cref="ScriptAction"/> class with properties/fields initialized with specified parameters.
/// </summary>
/// <param name="id">The explicit <see cref="Id"></see> to be associated with <see cref="ScriptAction"/> instance.</param>
/// <param name="code">VBScript code to be executed.</param>
/// <param name="returnType">The return type of the action.</param>
/// <param name="when"><see cref="T:WixSharp.When"/> the action should be executed with respect to the <paramref name="step"/> parameter.</param>
/// <param name="step"><see cref="T:WixSharp.Step"/> the action should be executed before/after during the installation.</param>
/// <param name="condition">The launch condition for the <see cref="ScriptAction"/>.</param>
/// <param name="rollbackArg">VBScript code to be executed on rollback.</param>
public ScriptAction(Id id, string code, Return returnType, When when, Step step, Condition condition, string rollbackArg)
: base(id, returnType, when, step, condition)
{
Code = code;
Name = "VBScript";
Rollback = "VBScript";
RollbackArg = rollbackArg;
}
/// <summary>
/// Initializes a new instance of the <see cref="ScriptAction"/> class with properties/fields initialized with specified parameters.
/// </summary>
/// <param name="code">VBScript code to be executed.</param>
/// <param name="returnType">The return type of the action.</param>
/// <param name="when"><see cref="T:WixSharp.When"/> the action should be executed with respect to the <paramref name="step"/> parameter.</param>
/// <param name="step"><see cref="T:WixSharp.Step"/> the action should be executed before/after during the installation.</param>
/// <param name="condition">The launch condition for the <see cref="ScriptAction"/>.</param>
/// <param name="sequence">The MSI sequence the action belongs to.</param>
public ScriptAction(string code, Return returnType, When when, Step step, Condition condition, Sequence sequence)
: base(returnType, when, step, condition, sequence)
{
Code = code;
Name = "VBScript";
}
/// <summary>
/// Initializes a new instance of the <see cref="ScriptAction"/> class with properties/fields initialized with specified parameters.
/// </summary>
/// <param name="code">VBScript code to be executed.</param>
/// <param name="returnType">The return type of the action.</param>
/// <param name="when"><see cref="T:WixSharp.When"/> the action should be executed with respect to the <paramref name="step"/> parameter.</param>
/// <param name="step"><see cref="T:WixSharp.Step"/> the action should be executed before/after during the installation.</param>
/// <param name="condition">The launch condition for the <see cref="ScriptAction"/>.</param>
/// <param name="sequence">The MSI sequence the action belongs to.</param>
/// <param name="rollbackArg">VBScript code to be executed on rollback.</param>
public ScriptAction(string code, Return returnType, When when, Step step, Condition condition, Sequence sequence, string rollbackArg)
: base(returnType, when, step, condition, sequence)
{
Code = code;
Name = "VBScript";
Rollback = "VBScript";
RollbackArg = rollbackArg;
}
/// <summary>
/// Initializes a new instance of the <see cref="ScriptAction"/> class with properties/fields initialized with specified parameters.
/// </summary>
/// <param name="id">The explicit <see cref="Id"></see> to be associated with <see cref="ScriptAction"/> instance.</param>
/// <param name="code">VBScript code to be executed.</param>
/// <param name="returnType">The return type of the action.</param>
/// <param name="when"><see cref="T:WixSharp.When"/> the action should be executed with respect to the <paramref name="step"/> parameter.</param>
/// <param name="step"><see cref="T:WixSharp.Step"/> the action should be executed before/after during the installation.</param>
/// <param name="condition">The launch condition for the <see cref="ScriptAction"/>.</param>
/// <param name="sequence">The MSI sequence the action belongs to.</param>
public ScriptAction(Id id, string code, Return returnType, When when, Step step, Condition condition, Sequence sequence)
: base(id, returnType, when, step, condition, sequence)
{
Code = code;
Name = "VBScript";
}
/// <summary>
/// Initializes a new instance of the <see cref="ScriptAction"/> class with properties/fields initialized with specified parameters.
/// </summary>
/// <param name="id">The explicit <see cref="Id"></see> to be associated with <see cref="ScriptAction"/> instance.</param>
/// <param name="code">VBScript code to be executed.</param>
/// <param name="returnType">The return type of the action.</param>
/// <param name="when"><see cref="T:WixSharp.When"/> the action should be executed with respect to the <paramref name="step"/> parameter.</param>
/// <param name="step"><see cref="T:WixSharp.Step"/> the action should be executed before/after during the installation.</param>
/// <param name="condition">The launch condition for the <see cref="ScriptAction"/>.</param>
/// <param name="sequence">The MSI sequence the action belongs to.</param>
/// <param name="rollbackArg">VBScript code to be executed on rollback.</param>
public ScriptAction(Id id, string code, Return returnType, When when, Step step, Condition condition, Sequence sequence, string rollbackArg)
: base(id, returnType, when, step, condition, sequence)
{
Code = code;
Name = "VBScript";
Rollback = "VBScript";
RollbackArg = rollbackArg;
}
/// <summary>
/// VBScript code to be executed.
/// </summary>
public string Code = "";
}
}
| |
using System.Diagnostics;
using Urho;
namespace Urho.Actions
{
public class Sequence : FiniteTimeAction
{
public FiniteTimeAction[] Actions { get; } = new FiniteTimeAction[2];
#region Constructors
public Sequence (FiniteTimeAction action1, FiniteTimeAction action2) : base (action1.Duration + action2.Duration)
{
InitSequence (action1, action2);
}
public Sequence(FiniteTimeAction[] actions, FiniteTimeAction other)
{
InitFromArray(actions, other);
}
public Sequence (FiniteTimeAction[] actions) : base ()
{
InitFromArray(actions, null);
}
void InitFromArray(FiniteTimeAction[] actions, FiniteTimeAction other)
{
var prev = actions[0];
// Can't call base(duration) because we need to calculate duration here
float combinedDuration = 0.0f;
foreach (FiniteTimeAction action in actions)
{
combinedDuration += action.Duration;
}
Duration = combinedDuration;
if (actions.Length == 1)
{
InitSequence(prev, other ?? new ExtraAction());
}
else
{
// Basically what we are doing here is creating a whole bunch of
// nested Sequences from the actions.
int count = other != null ? actions.Length : actions.Length - 1;
for (int i = 1; i < count; i++)
{
prev = new Sequence(prev, actions[i]);
}
if (other != null)
{
InitSequence(prev, other);
}
else
{
InitSequence(prev, actions[actions.Length - 1]);
}
}
}
void InitSequence (FiniteTimeAction actionOne, FiniteTimeAction actionTwo)
{
Debug.Assert (actionOne != null);
Debug.Assert (actionTwo != null);
Actions [0] = actionOne;
Actions [1] = actionTwo;
}
#endregion Constructors
protected internal override ActionState StartAction(Node target)
{
return new SequenceState (this, target);
}
public override FiniteTimeAction Reverse ()
{
return new Sequence (Actions [1].Reverse (), Actions [0].Reverse ());
}
}
public class SequenceState : FiniteTimeActionState
{
protected int last;
protected FiniteTimeAction[] actionSequences = new FiniteTimeAction[2];
protected FiniteTimeActionState[] actionStates = new FiniteTimeActionState[2];
protected float split;
private bool hasInfiniteAction = false;
public SequenceState (Sequence action, Node target)
: base (action, target)
{
actionSequences = action.Actions;
hasInfiniteAction = (actionSequences [0] is RepeatForever) || (actionSequences [1] is RepeatForever);
split = actionSequences [0].Duration / Duration;
last = -1;
}
public override bool IsDone {
get {
if (hasInfiniteAction && actionSequences [last] is RepeatForever)
{
return false;
}
return base.IsDone;
}
}
protected internal override void Stop ()
{
// Issue #1305
if (last != -1)
{
actionStates [last].Stop ();
}
}
protected internal override void Step (float dt)
{
if (last > -1 && (actionSequences [last] is RepeatForever))
{
actionStates [last].Step (dt);
}
else
{
base.Step (dt);
}
}
public override void Update (float time)
{
int found;
float new_t;
if (time < split)
{
// action[0]
found = 0;
if (split != 0)
new_t = time / split;
else
new_t = 1;
}
else
{
// action[1]
found = 1;
if (split == 1)
new_t = 1;
else
new_t = (time - split) / (1 - split);
}
if (found == 1)
{
if (last == -1)
{
// action[0] was skipped, execute it.
actionStates [0] = (FiniteTimeActionState)actionSequences [0].StartAction (Target);
actionStates [0].Update (1.0f);
actionStates [0].Stop ();
}
else if (last == 0)
{
actionStates [0].Update (1.0f);
actionStates [0].Stop ();
}
}
else if (found == 0 && last == 1)
{
// Reverse mode ?
// XXX: Bug. this case doesn't contemplate when _last==-1, found=0 and in "reverse mode"
// since it will require a hack to know if an action is on reverse mode or not.
// "step" should be overriden, and the "reverseMode" value propagated to inner Sequences.
actionStates [1].Update (0);
actionStates [1].Stop ();
}
// Last action found and it is done.
if (found == last && actionStates [found].IsDone)
{
return;
}
// Last action found and it is done
if (found != last)
{
actionStates [found] = (FiniteTimeActionState)actionSequences [found].StartAction (Target);
}
actionStates [found].Update (new_t);
last = found;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using LibGit2Sharp.Core;
using Xunit;
namespace LibGit2Sharp.Tests.TestHelpers
{
public class BaseFixture : IPostTestDirectoryRemover, IDisposable
{
private readonly List<string> directories = new List<string>();
public BaseFixture()
{
BuildFakeConfigs(this);
#if LEAKS_IDENTIFYING
LeaksContainer.Clear();
#endif
}
static BaseFixture()
{
// Do the set up in the static ctor so it only happens once
SetUpTestEnvironment();
}
public static string BareTestRepoPath { get; private set; }
public static string StandardTestRepoWorkingDirPath { get; private set; }
public static string StandardTestRepoPath { get; private set; }
public static string ShallowTestRepoPath { get; private set; }
public static string MergedTestRepoWorkingDirPath { get; private set; }
public static string MergeTestRepoWorkingDirPath { get; private set; }
public static string MergeRenamesTestRepoWorkingDirPath { get; private set; }
public static string RevertTestRepoWorkingDirPath { get; private set; }
public static string SubmoduleTestRepoWorkingDirPath { get; private set; }
private static string SubmoduleTargetTestRepoWorkingDirPath { get; set; }
private static string AssumeUnchangedRepoWorkingDirPath { get; set; }
public static string SubmoduleSmallTestRepoWorkingDirPath { get; set; }
public static string PackBuilderTestRepoPath { get; private set; }
public static DirectoryInfo ResourcesDirectory { get; private set; }
public static bool IsFileSystemCaseSensitive { get; private set; }
protected static DateTimeOffset TruncateSubSeconds(DateTimeOffset dto)
{
int seconds = dto.ToSecondsSinceEpoch();
return Epoch.ToDateTimeOffset(seconds, (int)dto.Offset.TotalMinutes);
}
private static void SetUpTestEnvironment()
{
IsFileSystemCaseSensitive = IsFileSystemCaseSensitiveInternal();
string initialAssemblyParentFolder = Directory.GetParent(new Uri(typeof(BaseFixture).Assembly.EscapedCodeBase).LocalPath).FullName;
const string sourceRelativePath = @"../../Resources";
ResourcesDirectory = new DirectoryInfo(Path.Combine(initialAssemblyParentFolder, sourceRelativePath));
// Setup standard paths to our test repositories
BareTestRepoPath = Path.Combine(sourceRelativePath, "testrepo.git");
StandardTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "testrepo_wd");
StandardTestRepoPath = Path.Combine(StandardTestRepoWorkingDirPath, "dot_git");
ShallowTestRepoPath = Path.Combine(sourceRelativePath, "shallow.git");
MergedTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "mergedrepo_wd");
MergeRenamesTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "mergerenames_wd");
MergeTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "merge_testrepo_wd");
RevertTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "revert_testrepo_wd");
SubmoduleTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "submodule_wd");
SubmoduleTargetTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "submodule_target_wd");
AssumeUnchangedRepoWorkingDirPath = Path.Combine(sourceRelativePath, "assume_unchanged_wd");
SubmoduleSmallTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "submodule_small_wd");
PackBuilderTestRepoPath = Path.Combine(sourceRelativePath, "packbuilder_testrepo_wd");
CleanupTestReposOlderThan(TimeSpan.FromMinutes(15));
}
public static void BuildFakeConfigs(IPostTestDirectoryRemover dirRemover)
{
var scd = new SelfCleaningDirectory(dirRemover);
string global = null, xdg = null, system = null, programData = null;
BuildFakeRepositoryOptions(scd, out global, out xdg, out system, out programData);
StringBuilder sb = new StringBuilder()
.AppendFormat("[Woot]{0}", Environment.NewLine)
.AppendFormat("this-rocks = global{0}", Environment.NewLine)
.AppendFormat("[Wow]{0}", Environment.NewLine)
.AppendFormat("Man-I-am-totally-global = 42{0}", Environment.NewLine);
File.WriteAllText(Path.Combine(global, ".gitconfig"), sb.ToString());
sb = new StringBuilder()
.AppendFormat("[Woot]{0}", Environment.NewLine)
.AppendFormat("this-rocks = system{0}", Environment.NewLine);
File.WriteAllText(Path.Combine(system, "gitconfig"), sb.ToString());
sb = new StringBuilder()
.AppendFormat("[Woot]{0}", Environment.NewLine)
.AppendFormat("this-rocks = xdg{0}", Environment.NewLine);
File.WriteAllText(Path.Combine(xdg, "config"), sb.ToString());
sb = new StringBuilder()
.AppendFormat("[Woot]{0}", Environment.NewLine)
.AppendFormat("this-rocks = programdata{0}", Environment.NewLine);
File.WriteAllText(Path.Combine(programData, "config"), sb.ToString());
GlobalSettings.SetConfigSearchPaths(ConfigurationLevel.Global, global);
GlobalSettings.SetConfigSearchPaths(ConfigurationLevel.Xdg, xdg);
GlobalSettings.SetConfigSearchPaths(ConfigurationLevel.System, system);
GlobalSettings.SetConfigSearchPaths(ConfigurationLevel.ProgramData, programData);
}
private static void CleanupTestReposOlderThan(TimeSpan olderThan)
{
var oldTestRepos = new DirectoryInfo(Constants.TemporaryReposPath)
.EnumerateDirectories()
.Where(di => di.CreationTimeUtc < DateTimeOffset.Now.Subtract(olderThan))
.Select(di => di.FullName);
foreach (var dir in oldTestRepos)
{
DirectoryHelper.DeleteDirectory(dir);
}
}
private static bool IsFileSystemCaseSensitiveInternal()
{
var mixedPath = Path.Combine(Constants.TemporaryReposPath, "mIxEdCase-" + Path.GetRandomFileName());
if (Directory.Exists(mixedPath))
{
Directory.Delete(mixedPath);
}
Directory.CreateDirectory(mixedPath);
bool isInsensitive = Directory.Exists(mixedPath.ToLowerInvariant());
Directory.Delete(mixedPath);
return !isInsensitive;
}
protected void CreateCorruptedDeadBeefHead(string repoPath)
{
const string deadbeef = "deadbeef";
string headPath = string.Format("refs/heads/{0}", deadbeef);
Touch(repoPath, headPath, string.Format("{0}{0}{0}{0}{0}\n", deadbeef));
}
protected SelfCleaningDirectory BuildSelfCleaningDirectory()
{
return new SelfCleaningDirectory(this);
}
protected SelfCleaningDirectory BuildSelfCleaningDirectory(string path)
{
return new SelfCleaningDirectory(this, path);
}
protected string SandboxBareTestRepo()
{
return Sandbox(BareTestRepoPath);
}
protected string SandboxStandardTestRepo()
{
return Sandbox(StandardTestRepoWorkingDirPath);
}
protected string SandboxMergedTestRepo()
{
return Sandbox(MergedTestRepoWorkingDirPath);
}
protected string SandboxStandardTestRepoGitDir()
{
return Sandbox(Path.Combine(StandardTestRepoWorkingDirPath));
}
protected string SandboxMergeTestRepo()
{
return Sandbox(MergeTestRepoWorkingDirPath);
}
protected string SandboxRevertTestRepo()
{
return Sandbox(RevertTestRepoWorkingDirPath);
}
public string SandboxSubmoduleTestRepo()
{
return Sandbox(SubmoduleTestRepoWorkingDirPath, SubmoduleTargetTestRepoWorkingDirPath);
}
public string SandboxAssumeUnchangedTestRepo()
{
return Sandbox(AssumeUnchangedRepoWorkingDirPath);
}
public string SandboxSubmoduleSmallTestRepo()
{
var path = Sandbox(SubmoduleSmallTestRepoWorkingDirPath, SubmoduleTargetTestRepoWorkingDirPath);
Directory.CreateDirectory(Path.Combine(path, "submodule_target_wd"));
return path;
}
protected string SandboxPackBuilderTestRepo()
{
return Sandbox(PackBuilderTestRepoPath);
}
protected string Sandbox(string sourceDirectoryPath, params string[] additionalSourcePaths)
{
var scd = BuildSelfCleaningDirectory();
var source = new DirectoryInfo(sourceDirectoryPath);
var clonePath = Path.Combine(scd.DirectoryPath, source.Name);
DirectoryHelper.CopyFilesRecursively(source, new DirectoryInfo(clonePath));
foreach (var additionalPath in additionalSourcePaths)
{
var additional = new DirectoryInfo(additionalPath);
var targetForAdditional = Path.Combine(scd.DirectoryPath, additional.Name);
DirectoryHelper.CopyFilesRecursively(additional, new DirectoryInfo(targetForAdditional));
}
return clonePath;
}
protected string InitNewRepository(bool isBare = false)
{
SelfCleaningDirectory scd = BuildSelfCleaningDirectory();
return Repository.Init(scd.DirectoryPath, isBare);
}
public void Register(string directoryPath)
{
directories.Add(directoryPath);
}
public virtual void Dispose()
{
foreach (string directory in directories)
{
DirectoryHelper.DeleteDirectory(directory);
}
#if LEAKS_IDENTIFYING
GC.Collect();
GC.WaitForPendingFinalizers();
if (LeaksContainer.TypeNames.Any())
{
Assert.False(true, string.Format("Some handles of the following types haven't been properly released: {0}.{1}"
+ "In order to get some help fixing those leaks, uncomment the define LEAKS_TRACKING in Libgit2Object.cs{1}"
+ "and run the tests locally.", string.Join(", ", LeaksContainer.TypeNames), Environment.NewLine));
}
#endif
}
protected static void InconclusiveIf(Func<bool> predicate, string message)
{
if (!predicate())
{
return;
}
throw new SkipException(message);
}
protected void RequiresDotNetOrMonoGreaterThanOrEqualTo(System.Version minimumVersion)
{
Type type = Type.GetType("Mono.Runtime");
if (type == null)
{
// We're running on top of .Net
return;
}
MethodInfo displayName = type.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static);
if (displayName == null)
{
throw new InvalidOperationException("Cannot access Mono.RunTime.GetDisplayName() method.");
}
var version = (string)displayName.Invoke(null, null);
System.Version current;
try
{
current = new System.Version(version.Split(' ')[0]);
}
catch (Exception e)
{
throw new Exception(string.Format("Cannot parse Mono version '{0}'.", version), e);
}
InconclusiveIf(() => current < minimumVersion,
string.Format(
"Current Mono version is {0}. Minimum required version to run this test is {1}.",
current, minimumVersion));
}
protected static void AssertValueInConfigFile(string configFilePath, string regex)
{
var text = File.ReadAllText(configFilePath);
var r = new Regex(regex, RegexOptions.Multiline).Match(text);
Assert.True(r.Success, text);
}
private static void BuildFakeRepositoryOptions(SelfCleaningDirectory scd, out string global, out string xdg, out string system, out string programData)
{
string confs = Path.Combine(scd.DirectoryPath, "confs");
Directory.CreateDirectory(confs);
global = Path.Combine(confs, "my-global-config");
Directory.CreateDirectory(global);
xdg = Path.Combine(confs, "my-xdg-config");
Directory.CreateDirectory(xdg);
system = Path.Combine(confs, "my-system-config");
Directory.CreateDirectory(system);
programData = Path.Combine(confs, "my-programdata-config");
Directory.CreateDirectory(programData);
}
/// <summary>
/// Creates a configuration file with user.name and user.email set to signature
/// </summary>
/// <remarks>The configuration file will be removed automatically when the tests are finished</remarks>
/// <param name="identity">The identity to use for user.name and user.email</param>
/// <returns>The path to the configuration file</returns>
protected void CreateConfigurationWithDummyUser(Repository repo, Identity identity)
{
CreateConfigurationWithDummyUser(repo, identity.Name, identity.Email);
}
protected void CreateConfigurationWithDummyUser(Repository repo, string name, string email)
{
Configuration config = repo.Config;
{
if (name != null)
{
config.Set("user.name", name);
}
if (email != null)
{
config.Set("user.email", email);
}
}
}
/// <summary>
/// Asserts that the commit has been authored and committed by the specified signature
/// </summary>
/// <param name="commit">The commit</param>
/// <param name="identity">The identity to compare author and commiter to</param>
protected void AssertCommitIdentitiesAre(Commit commit, Identity identity)
{
Assert.Equal(identity.Name, commit.Author.Name);
Assert.Equal(identity.Email, commit.Author.Email);
Assert.Equal(identity.Name, commit.Committer.Name);
Assert.Equal(identity.Email, commit.Committer.Email);
}
protected static string Touch(string parent, string file, string content = null, Encoding encoding = null)
{
string filePath = Path.Combine(parent, file);
string dir = Path.GetDirectoryName(filePath);
Debug.Assert(dir != null);
Directory.CreateDirectory(dir);
File.WriteAllText(filePath, content ?? string.Empty, encoding ?? Encoding.ASCII);
return filePath;
}
protected static string Touch(string parent, string file, Stream stream)
{
Debug.Assert(stream != null);
string filePath = Path.Combine(parent, file);
string dir = Path.GetDirectoryName(filePath);
Debug.Assert(dir != null);
Directory.CreateDirectory(dir);
using (var fs = File.Open(filePath, FileMode.Create))
{
CopyStream(stream, fs);
fs.Flush();
}
return filePath;
}
protected string Expected(string filename)
{
return File.ReadAllText(Path.Combine(ResourcesDirectory.FullName, "expected/" + filename));
}
protected string Expected(string filenameFormat, params object[] args)
{
return Expected(string.Format(CultureInfo.InvariantCulture, filenameFormat, args));
}
protected static void AssertRefLogEntry(IRepository repo, string canonicalName,
string message, ObjectId @from, ObjectId to,
Identity committer, DateTimeOffset before)
{
var reflogEntry = repo.Refs.Log(canonicalName).First();
Assert.Equal(to, reflogEntry.To);
Assert.Equal(message, reflogEntry.Message);
Assert.Equal(@from ?? ObjectId.Zero, reflogEntry.From);
Assert.Equal(committer.Email, reflogEntry.Committer.Email);
Assert.InRange(reflogEntry.Committer.When, before, DateTimeOffset.Now);
}
protected static void EnableRefLog(IRepository repository, bool enable = true)
{
repository.Config.Set("core.logAllRefUpdates", enable);
}
public static void CopyStream(Stream input, Stream output)
{
// Reused from the following Stack Overflow post with permission
// of Jon Skeet (obtained on 25 Feb 2013)
// http://stackoverflow.com/questions/411592/how-do-i-save-a-stream-to-a-file/411605#411605
var buffer = new byte[8 * 1024];
int len;
while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, len);
}
}
public static bool StreamEquals(Stream one, Stream two)
{
int onebyte, twobyte;
while ((onebyte = one.ReadByte()) >= 0 && (twobyte = two.ReadByte()) >= 0)
{
if (onebyte != twobyte)
return false;
}
return true;
}
public void AssertBelongsToARepository<T>(IRepository repo, T instance)
where T : IBelongToARepository
{
Assert.Same(repo, ((IBelongToARepository)instance).Repository);
}
protected void CreateAttributesFile(IRepository repo, string attributeEntry)
{
Touch(repo.Info.WorkingDirectory, ".gitattributes", attributeEntry);
}
}
}
| |
// 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!
namespace Google.Cloud.Compute.V1.Snippets
{
using Google.Api.Gax;
using System;
using System.Linq;
using System.Threading.Tasks;
using lro = Google.LongRunning;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedSecurityPoliciesClientSnippets
{
/// <summary>Snippet for AddRule</summary>
public void AddRuleRequestObject()
{
// Snippet: AddRule(AddRuleSecurityPolicyRequest, CallSettings)
// Create client
SecurityPoliciesClient securityPoliciesClient = SecurityPoliciesClient.Create();
// Initialize request argument(s)
AddRuleSecurityPolicyRequest request = new AddRuleSecurityPolicyRequest
{
SecurityPolicy = "",
Project = "",
SecurityPolicyRuleResource = new SecurityPolicyRule(),
};
// Make the request
lro::Operation<Operation, Operation> response = securityPoliciesClient.AddRule(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = securityPoliciesClient.PollOnceAddRule(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for AddRuleAsync</summary>
public async Task AddRuleRequestObjectAsync()
{
// Snippet: AddRuleAsync(AddRuleSecurityPolicyRequest, CallSettings)
// Additional: AddRuleAsync(AddRuleSecurityPolicyRequest, CancellationToken)
// Create client
SecurityPoliciesClient securityPoliciesClient = await SecurityPoliciesClient.CreateAsync();
// Initialize request argument(s)
AddRuleSecurityPolicyRequest request = new AddRuleSecurityPolicyRequest
{
SecurityPolicy = "",
Project = "",
SecurityPolicyRuleResource = new SecurityPolicyRule(),
};
// Make the request
lro::Operation<Operation, Operation> response = await securityPoliciesClient.AddRuleAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await securityPoliciesClient.PollOnceAddRuleAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for AddRule</summary>
public void AddRule()
{
// Snippet: AddRule(string, string, SecurityPolicyRule, CallSettings)
// Create client
SecurityPoliciesClient securityPoliciesClient = SecurityPoliciesClient.Create();
// Initialize request argument(s)
string project = "";
string securityPolicy = "";
SecurityPolicyRule securityPolicyRuleResource = new SecurityPolicyRule();
// Make the request
lro::Operation<Operation, Operation> response = securityPoliciesClient.AddRule(project, securityPolicy, securityPolicyRuleResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = securityPoliciesClient.PollOnceAddRule(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for AddRuleAsync</summary>
public async Task AddRuleAsync()
{
// Snippet: AddRuleAsync(string, string, SecurityPolicyRule, CallSettings)
// Additional: AddRuleAsync(string, string, SecurityPolicyRule, CancellationToken)
// Create client
SecurityPoliciesClient securityPoliciesClient = await SecurityPoliciesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string securityPolicy = "";
SecurityPolicyRule securityPolicyRuleResource = new SecurityPolicyRule();
// Make the request
lro::Operation<Operation, Operation> response = await securityPoliciesClient.AddRuleAsync(project, securityPolicy, securityPolicyRuleResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await securityPoliciesClient.PollOnceAddRuleAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Delete</summary>
public void DeleteRequestObject()
{
// Snippet: Delete(DeleteSecurityPolicyRequest, CallSettings)
// Create client
SecurityPoliciesClient securityPoliciesClient = SecurityPoliciesClient.Create();
// Initialize request argument(s)
DeleteSecurityPolicyRequest request = new DeleteSecurityPolicyRequest
{
RequestId = "",
SecurityPolicy = "",
Project = "",
};
// Make the request
lro::Operation<Operation, Operation> response = securityPoliciesClient.Delete(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = securityPoliciesClient.PollOnceDelete(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteAsync</summary>
public async Task DeleteRequestObjectAsync()
{
// Snippet: DeleteAsync(DeleteSecurityPolicyRequest, CallSettings)
// Additional: DeleteAsync(DeleteSecurityPolicyRequest, CancellationToken)
// Create client
SecurityPoliciesClient securityPoliciesClient = await SecurityPoliciesClient.CreateAsync();
// Initialize request argument(s)
DeleteSecurityPolicyRequest request = new DeleteSecurityPolicyRequest
{
RequestId = "",
SecurityPolicy = "",
Project = "",
};
// Make the request
lro::Operation<Operation, Operation> response = await securityPoliciesClient.DeleteAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await securityPoliciesClient.PollOnceDeleteAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Delete</summary>
public void Delete()
{
// Snippet: Delete(string, string, CallSettings)
// Create client
SecurityPoliciesClient securityPoliciesClient = SecurityPoliciesClient.Create();
// Initialize request argument(s)
string project = "";
string securityPolicy = "";
// Make the request
lro::Operation<Operation, Operation> response = securityPoliciesClient.Delete(project, securityPolicy);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = securityPoliciesClient.PollOnceDelete(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteAsync</summary>
public async Task DeleteAsync()
{
// Snippet: DeleteAsync(string, string, CallSettings)
// Additional: DeleteAsync(string, string, CancellationToken)
// Create client
SecurityPoliciesClient securityPoliciesClient = await SecurityPoliciesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string securityPolicy = "";
// Make the request
lro::Operation<Operation, Operation> response = await securityPoliciesClient.DeleteAsync(project, securityPolicy);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await securityPoliciesClient.PollOnceDeleteAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Get</summary>
public void GetRequestObject()
{
// Snippet: Get(GetSecurityPolicyRequest, CallSettings)
// Create client
SecurityPoliciesClient securityPoliciesClient = SecurityPoliciesClient.Create();
// Initialize request argument(s)
GetSecurityPolicyRequest request = new GetSecurityPolicyRequest
{
SecurityPolicy = "",
Project = "",
};
// Make the request
SecurityPolicy response = securityPoliciesClient.Get(request);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetRequestObjectAsync()
{
// Snippet: GetAsync(GetSecurityPolicyRequest, CallSettings)
// Additional: GetAsync(GetSecurityPolicyRequest, CancellationToken)
// Create client
SecurityPoliciesClient securityPoliciesClient = await SecurityPoliciesClient.CreateAsync();
// Initialize request argument(s)
GetSecurityPolicyRequest request = new GetSecurityPolicyRequest
{
SecurityPolicy = "",
Project = "",
};
// Make the request
SecurityPolicy response = await securityPoliciesClient.GetAsync(request);
// End snippet
}
/// <summary>Snippet for Get</summary>
public void Get()
{
// Snippet: Get(string, string, CallSettings)
// Create client
SecurityPoliciesClient securityPoliciesClient = SecurityPoliciesClient.Create();
// Initialize request argument(s)
string project = "";
string securityPolicy = "";
// Make the request
SecurityPolicy response = securityPoliciesClient.Get(project, securityPolicy);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetAsync()
{
// Snippet: GetAsync(string, string, CallSettings)
// Additional: GetAsync(string, string, CancellationToken)
// Create client
SecurityPoliciesClient securityPoliciesClient = await SecurityPoliciesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string securityPolicy = "";
// Make the request
SecurityPolicy response = await securityPoliciesClient.GetAsync(project, securityPolicy);
// End snippet
}
/// <summary>Snippet for GetRule</summary>
public void GetRuleRequestObject()
{
// Snippet: GetRule(GetRuleSecurityPolicyRequest, CallSettings)
// Create client
SecurityPoliciesClient securityPoliciesClient = SecurityPoliciesClient.Create();
// Initialize request argument(s)
GetRuleSecurityPolicyRequest request = new GetRuleSecurityPolicyRequest
{
SecurityPolicy = "",
Project = "",
Priority = 0,
};
// Make the request
SecurityPolicyRule response = securityPoliciesClient.GetRule(request);
// End snippet
}
/// <summary>Snippet for GetRuleAsync</summary>
public async Task GetRuleRequestObjectAsync()
{
// Snippet: GetRuleAsync(GetRuleSecurityPolicyRequest, CallSettings)
// Additional: GetRuleAsync(GetRuleSecurityPolicyRequest, CancellationToken)
// Create client
SecurityPoliciesClient securityPoliciesClient = await SecurityPoliciesClient.CreateAsync();
// Initialize request argument(s)
GetRuleSecurityPolicyRequest request = new GetRuleSecurityPolicyRequest
{
SecurityPolicy = "",
Project = "",
Priority = 0,
};
// Make the request
SecurityPolicyRule response = await securityPoliciesClient.GetRuleAsync(request);
// End snippet
}
/// <summary>Snippet for GetRule</summary>
public void GetRule()
{
// Snippet: GetRule(string, string, CallSettings)
// Create client
SecurityPoliciesClient securityPoliciesClient = SecurityPoliciesClient.Create();
// Initialize request argument(s)
string project = "";
string securityPolicy = "";
// Make the request
SecurityPolicyRule response = securityPoliciesClient.GetRule(project, securityPolicy);
// End snippet
}
/// <summary>Snippet for GetRuleAsync</summary>
public async Task GetRuleAsync()
{
// Snippet: GetRuleAsync(string, string, CallSettings)
// Additional: GetRuleAsync(string, string, CancellationToken)
// Create client
SecurityPoliciesClient securityPoliciesClient = await SecurityPoliciesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string securityPolicy = "";
// Make the request
SecurityPolicyRule response = await securityPoliciesClient.GetRuleAsync(project, securityPolicy);
// End snippet
}
/// <summary>Snippet for Insert</summary>
public void InsertRequestObject()
{
// Snippet: Insert(InsertSecurityPolicyRequest, CallSettings)
// Create client
SecurityPoliciesClient securityPoliciesClient = SecurityPoliciesClient.Create();
// Initialize request argument(s)
InsertSecurityPolicyRequest request = new InsertSecurityPolicyRequest
{
RequestId = "",
SecurityPolicyResource = new SecurityPolicy(),
Project = "",
};
// Make the request
lro::Operation<Operation, Operation> response = securityPoliciesClient.Insert(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = securityPoliciesClient.PollOnceInsert(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for InsertAsync</summary>
public async Task InsertRequestObjectAsync()
{
// Snippet: InsertAsync(InsertSecurityPolicyRequest, CallSettings)
// Additional: InsertAsync(InsertSecurityPolicyRequest, CancellationToken)
// Create client
SecurityPoliciesClient securityPoliciesClient = await SecurityPoliciesClient.CreateAsync();
// Initialize request argument(s)
InsertSecurityPolicyRequest request = new InsertSecurityPolicyRequest
{
RequestId = "",
SecurityPolicyResource = new SecurityPolicy(),
Project = "",
};
// Make the request
lro::Operation<Operation, Operation> response = await securityPoliciesClient.InsertAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await securityPoliciesClient.PollOnceInsertAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Insert</summary>
public void Insert()
{
// Snippet: Insert(string, SecurityPolicy, CallSettings)
// Create client
SecurityPoliciesClient securityPoliciesClient = SecurityPoliciesClient.Create();
// Initialize request argument(s)
string project = "";
SecurityPolicy securityPolicyResource = new SecurityPolicy();
// Make the request
lro::Operation<Operation, Operation> response = securityPoliciesClient.Insert(project, securityPolicyResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = securityPoliciesClient.PollOnceInsert(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for InsertAsync</summary>
public async Task InsertAsync()
{
// Snippet: InsertAsync(string, SecurityPolicy, CallSettings)
// Additional: InsertAsync(string, SecurityPolicy, CancellationToken)
// Create client
SecurityPoliciesClient securityPoliciesClient = await SecurityPoliciesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
SecurityPolicy securityPolicyResource = new SecurityPolicy();
// Make the request
lro::Operation<Operation, Operation> response = await securityPoliciesClient.InsertAsync(project, securityPolicyResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await securityPoliciesClient.PollOnceInsertAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for List</summary>
public void ListRequestObject()
{
// Snippet: List(ListSecurityPoliciesRequest, CallSettings)
// Create client
SecurityPoliciesClient securityPoliciesClient = SecurityPoliciesClient.Create();
// Initialize request argument(s)
ListSecurityPoliciesRequest request = new ListSecurityPoliciesRequest
{
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedEnumerable<SecurityPolicyList, SecurityPolicy> response = securityPoliciesClient.List(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (SecurityPolicy 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 (SecurityPolicyList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (SecurityPolicy item in page)
{
// Do something with each item
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<SecurityPolicy> 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 (SecurityPolicy item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAsync</summary>
public async Task ListRequestObjectAsync()
{
// Snippet: ListAsync(ListSecurityPoliciesRequest, CallSettings)
// Create client
SecurityPoliciesClient securityPoliciesClient = await SecurityPoliciesClient.CreateAsync();
// Initialize request argument(s)
ListSecurityPoliciesRequest request = new ListSecurityPoliciesRequest
{
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedAsyncEnumerable<SecurityPolicyList, SecurityPolicy> response = securityPoliciesClient.ListAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((SecurityPolicy 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((SecurityPolicyList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (SecurityPolicy item in page)
{
// Do something with each item
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<SecurityPolicy> 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 (SecurityPolicy item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for List</summary>
public void List()
{
// Snippet: List(string, string, int?, CallSettings)
// Create client
SecurityPoliciesClient securityPoliciesClient = SecurityPoliciesClient.Create();
// Initialize request argument(s)
string project = "";
// Make the request
PagedEnumerable<SecurityPolicyList, SecurityPolicy> response = securityPoliciesClient.List(project);
// Iterate over all response items, lazily performing RPCs as required
foreach (SecurityPolicy 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 (SecurityPolicyList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (SecurityPolicy item in page)
{
// Do something with each item
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<SecurityPolicy> 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 (SecurityPolicy item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAsync</summary>
public async Task ListAsync()
{
// Snippet: ListAsync(string, string, int?, CallSettings)
// Create client
SecurityPoliciesClient securityPoliciesClient = await SecurityPoliciesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
// Make the request
PagedAsyncEnumerable<SecurityPolicyList, SecurityPolicy> response = securityPoliciesClient.ListAsync(project);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((SecurityPolicy 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((SecurityPolicyList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (SecurityPolicy item in page)
{
// Do something with each item
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<SecurityPolicy> 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 (SecurityPolicy item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListPreconfiguredExpressionSets</summary>
public void ListPreconfiguredExpressionSetsRequestObject()
{
// Snippet: ListPreconfiguredExpressionSets(ListPreconfiguredExpressionSetsSecurityPoliciesRequest, CallSettings)
// Create client
SecurityPoliciesClient securityPoliciesClient = SecurityPoliciesClient.Create();
// Initialize request argument(s)
ListPreconfiguredExpressionSetsSecurityPoliciesRequest request = new ListPreconfiguredExpressionSetsSecurityPoliciesRequest
{
PageToken = "",
MaxResults = 0U,
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
SecurityPoliciesListPreconfiguredExpressionSetsResponse response = securityPoliciesClient.ListPreconfiguredExpressionSets(request);
// End snippet
}
/// <summary>Snippet for ListPreconfiguredExpressionSetsAsync</summary>
public async Task ListPreconfiguredExpressionSetsRequestObjectAsync()
{
// Snippet: ListPreconfiguredExpressionSetsAsync(ListPreconfiguredExpressionSetsSecurityPoliciesRequest, CallSettings)
// Additional: ListPreconfiguredExpressionSetsAsync(ListPreconfiguredExpressionSetsSecurityPoliciesRequest, CancellationToken)
// Create client
SecurityPoliciesClient securityPoliciesClient = await SecurityPoliciesClient.CreateAsync();
// Initialize request argument(s)
ListPreconfiguredExpressionSetsSecurityPoliciesRequest request = new ListPreconfiguredExpressionSetsSecurityPoliciesRequest
{
PageToken = "",
MaxResults = 0U,
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
SecurityPoliciesListPreconfiguredExpressionSetsResponse response = await securityPoliciesClient.ListPreconfiguredExpressionSetsAsync(request);
// End snippet
}
/// <summary>Snippet for ListPreconfiguredExpressionSets</summary>
public void ListPreconfiguredExpressionSets()
{
// Snippet: ListPreconfiguredExpressionSets(string, CallSettings)
// Create client
SecurityPoliciesClient securityPoliciesClient = SecurityPoliciesClient.Create();
// Initialize request argument(s)
string project = "";
// Make the request
SecurityPoliciesListPreconfiguredExpressionSetsResponse response = securityPoliciesClient.ListPreconfiguredExpressionSets(project);
// End snippet
}
/// <summary>Snippet for ListPreconfiguredExpressionSetsAsync</summary>
public async Task ListPreconfiguredExpressionSetsAsync()
{
// Snippet: ListPreconfiguredExpressionSetsAsync(string, CallSettings)
// Additional: ListPreconfiguredExpressionSetsAsync(string, CancellationToken)
// Create client
SecurityPoliciesClient securityPoliciesClient = await SecurityPoliciesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
// Make the request
SecurityPoliciesListPreconfiguredExpressionSetsResponse response = await securityPoliciesClient.ListPreconfiguredExpressionSetsAsync(project);
// End snippet
}
/// <summary>Snippet for Patch</summary>
public void PatchRequestObject()
{
// Snippet: Patch(PatchSecurityPolicyRequest, CallSettings)
// Create client
SecurityPoliciesClient securityPoliciesClient = SecurityPoliciesClient.Create();
// Initialize request argument(s)
PatchSecurityPolicyRequest request = new PatchSecurityPolicyRequest
{
RequestId = "",
SecurityPolicy = "",
SecurityPolicyResource = new SecurityPolicy(),
Project = "",
};
// Make the request
lro::Operation<Operation, Operation> response = securityPoliciesClient.Patch(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = securityPoliciesClient.PollOncePatch(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for PatchAsync</summary>
public async Task PatchRequestObjectAsync()
{
// Snippet: PatchAsync(PatchSecurityPolicyRequest, CallSettings)
// Additional: PatchAsync(PatchSecurityPolicyRequest, CancellationToken)
// Create client
SecurityPoliciesClient securityPoliciesClient = await SecurityPoliciesClient.CreateAsync();
// Initialize request argument(s)
PatchSecurityPolicyRequest request = new PatchSecurityPolicyRequest
{
RequestId = "",
SecurityPolicy = "",
SecurityPolicyResource = new SecurityPolicy(),
Project = "",
};
// Make the request
lro::Operation<Operation, Operation> response = await securityPoliciesClient.PatchAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await securityPoliciesClient.PollOncePatchAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Patch</summary>
public void Patch()
{
// Snippet: Patch(string, string, SecurityPolicy, CallSettings)
// Create client
SecurityPoliciesClient securityPoliciesClient = SecurityPoliciesClient.Create();
// Initialize request argument(s)
string project = "";
string securityPolicy = "";
SecurityPolicy securityPolicyResource = new SecurityPolicy();
// Make the request
lro::Operation<Operation, Operation> response = securityPoliciesClient.Patch(project, securityPolicy, securityPolicyResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = securityPoliciesClient.PollOncePatch(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for PatchAsync</summary>
public async Task PatchAsync()
{
// Snippet: PatchAsync(string, string, SecurityPolicy, CallSettings)
// Additional: PatchAsync(string, string, SecurityPolicy, CancellationToken)
// Create client
SecurityPoliciesClient securityPoliciesClient = await SecurityPoliciesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string securityPolicy = "";
SecurityPolicy securityPolicyResource = new SecurityPolicy();
// Make the request
lro::Operation<Operation, Operation> response = await securityPoliciesClient.PatchAsync(project, securityPolicy, securityPolicyResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await securityPoliciesClient.PollOncePatchAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for PatchRule</summary>
public void PatchRuleRequestObject()
{
// Snippet: PatchRule(PatchRuleSecurityPolicyRequest, CallSettings)
// Create client
SecurityPoliciesClient securityPoliciesClient = SecurityPoliciesClient.Create();
// Initialize request argument(s)
PatchRuleSecurityPolicyRequest request = new PatchRuleSecurityPolicyRequest
{
SecurityPolicy = "",
Project = "",
SecurityPolicyRuleResource = new SecurityPolicyRule(),
Priority = 0,
};
// Make the request
lro::Operation<Operation, Operation> response = securityPoliciesClient.PatchRule(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = securityPoliciesClient.PollOncePatchRule(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for PatchRuleAsync</summary>
public async Task PatchRuleRequestObjectAsync()
{
// Snippet: PatchRuleAsync(PatchRuleSecurityPolicyRequest, CallSettings)
// Additional: PatchRuleAsync(PatchRuleSecurityPolicyRequest, CancellationToken)
// Create client
SecurityPoliciesClient securityPoliciesClient = await SecurityPoliciesClient.CreateAsync();
// Initialize request argument(s)
PatchRuleSecurityPolicyRequest request = new PatchRuleSecurityPolicyRequest
{
SecurityPolicy = "",
Project = "",
SecurityPolicyRuleResource = new SecurityPolicyRule(),
Priority = 0,
};
// Make the request
lro::Operation<Operation, Operation> response = await securityPoliciesClient.PatchRuleAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await securityPoliciesClient.PollOncePatchRuleAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for PatchRule</summary>
public void PatchRule()
{
// Snippet: PatchRule(string, string, SecurityPolicyRule, CallSettings)
// Create client
SecurityPoliciesClient securityPoliciesClient = SecurityPoliciesClient.Create();
// Initialize request argument(s)
string project = "";
string securityPolicy = "";
SecurityPolicyRule securityPolicyRuleResource = new SecurityPolicyRule();
// Make the request
lro::Operation<Operation, Operation> response = securityPoliciesClient.PatchRule(project, securityPolicy, securityPolicyRuleResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = securityPoliciesClient.PollOncePatchRule(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for PatchRuleAsync</summary>
public async Task PatchRuleAsync()
{
// Snippet: PatchRuleAsync(string, string, SecurityPolicyRule, CallSettings)
// Additional: PatchRuleAsync(string, string, SecurityPolicyRule, CancellationToken)
// Create client
SecurityPoliciesClient securityPoliciesClient = await SecurityPoliciesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string securityPolicy = "";
SecurityPolicyRule securityPolicyRuleResource = new SecurityPolicyRule();
// Make the request
lro::Operation<Operation, Operation> response = await securityPoliciesClient.PatchRuleAsync(project, securityPolicy, securityPolicyRuleResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await securityPoliciesClient.PollOncePatchRuleAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for RemoveRule</summary>
public void RemoveRuleRequestObject()
{
// Snippet: RemoveRule(RemoveRuleSecurityPolicyRequest, CallSettings)
// Create client
SecurityPoliciesClient securityPoliciesClient = SecurityPoliciesClient.Create();
// Initialize request argument(s)
RemoveRuleSecurityPolicyRequest request = new RemoveRuleSecurityPolicyRequest
{
SecurityPolicy = "",
Project = "",
Priority = 0,
};
// Make the request
lro::Operation<Operation, Operation> response = securityPoliciesClient.RemoveRule(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = securityPoliciesClient.PollOnceRemoveRule(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for RemoveRuleAsync</summary>
public async Task RemoveRuleRequestObjectAsync()
{
// Snippet: RemoveRuleAsync(RemoveRuleSecurityPolicyRequest, CallSettings)
// Additional: RemoveRuleAsync(RemoveRuleSecurityPolicyRequest, CancellationToken)
// Create client
SecurityPoliciesClient securityPoliciesClient = await SecurityPoliciesClient.CreateAsync();
// Initialize request argument(s)
RemoveRuleSecurityPolicyRequest request = new RemoveRuleSecurityPolicyRequest
{
SecurityPolicy = "",
Project = "",
Priority = 0,
};
// Make the request
lro::Operation<Operation, Operation> response = await securityPoliciesClient.RemoveRuleAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await securityPoliciesClient.PollOnceRemoveRuleAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for RemoveRule</summary>
public void RemoveRule()
{
// Snippet: RemoveRule(string, string, CallSettings)
// Create client
SecurityPoliciesClient securityPoliciesClient = SecurityPoliciesClient.Create();
// Initialize request argument(s)
string project = "";
string securityPolicy = "";
// Make the request
lro::Operation<Operation, Operation> response = securityPoliciesClient.RemoveRule(project, securityPolicy);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = securityPoliciesClient.PollOnceRemoveRule(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for RemoveRuleAsync</summary>
public async Task RemoveRuleAsync()
{
// Snippet: RemoveRuleAsync(string, string, CallSettings)
// Additional: RemoveRuleAsync(string, string, CancellationToken)
// Create client
SecurityPoliciesClient securityPoliciesClient = await SecurityPoliciesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string securityPolicy = "";
// Make the request
lro::Operation<Operation, Operation> response = await securityPoliciesClient.RemoveRuleAsync(project, securityPolicy);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await securityPoliciesClient.PollOnceRemoveRuleAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="Int32AnimationUsingKeyFrames.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.KnownBoxes;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Media.Animation;
using System.Windows.Media.Media3D;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
using MS.Internal.PresentationCore;
namespace System.Windows.Media.Animation
{
/// <summary>
/// This class is used to animate a Int32 property value along a set
/// of key frames.
/// </summary>
[ContentProperty("KeyFrames")]
public class Int32AnimationUsingKeyFrames : Int32AnimationBase, IKeyFrameAnimation, IAddChild
{
#region Data
private Int32KeyFrameCollection _keyFrames;
private ResolvedKeyFrameEntry[] _sortedResolvedKeyFrames;
private bool _areKeyTimesValid;
#endregion
#region Constructors
/// <Summary>
/// Creates a new KeyFrameInt32Animation.
/// </Summary>
public Int32AnimationUsingKeyFrames()
: base()
{
_areKeyTimesValid = true;
}
#endregion
#region Freezable
/// <summary>
/// Creates a copy of this KeyFrameInt32Animation.
/// </summary>
/// <returns>The copy</returns>
public new Int32AnimationUsingKeyFrames Clone()
{
return (Int32AnimationUsingKeyFrames)base.Clone();
}
/// <summary>
/// Returns a version of this class with all its base property values
/// set to the current animated values and removes the animations.
/// </summary>
/// <returns>
/// Since this class isn't animated, this method will always just return
/// this instance of the class.
/// </returns>
public new Int32AnimationUsingKeyFrames CloneCurrentValue()
{
return (Int32AnimationUsingKeyFrames)base.CloneCurrentValue();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.FreezeCore">Freezable.FreezeCore</see>.
/// </summary>
protected override bool FreezeCore(bool isChecking)
{
bool canFreeze = base.FreezeCore(isChecking);
canFreeze &= Freezable.Freeze(_keyFrames, isChecking);
if (canFreeze & !_areKeyTimesValid)
{
ResolveKeyTimes();
}
return canFreeze;
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.OnChanged">Freezable.OnChanged</see>.
/// </summary>
protected override void OnChanged()
{
_areKeyTimesValid = false;
base.OnChanged();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new Int32AnimationUsingKeyFrames();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CloneCore(System.Windows.Freezable)">Freezable.CloneCore</see>.
/// </summary>
protected override void CloneCore(Freezable sourceFreezable)
{
Int32AnimationUsingKeyFrames sourceAnimation = (Int32AnimationUsingKeyFrames) sourceFreezable;
base.CloneCore(sourceFreezable);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ false);
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CloneCurrentValueCore(Freezable)">Freezable.CloneCurrentValueCore</see>.
/// </summary>
protected override void CloneCurrentValueCore(Freezable sourceFreezable)
{
Int32AnimationUsingKeyFrames sourceAnimation = (Int32AnimationUsingKeyFrames) sourceFreezable;
base.CloneCurrentValueCore(sourceFreezable);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ true);
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.GetAsFrozenCore(Freezable)">Freezable.GetAsFrozenCore</see>.
/// </summary>
protected override void GetAsFrozenCore(Freezable source)
{
Int32AnimationUsingKeyFrames sourceAnimation = (Int32AnimationUsingKeyFrames) source;
base.GetAsFrozenCore(source);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ false);
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.GetCurrentValueAsFrozenCore(Freezable)">Freezable.GetCurrentValueAsFrozenCore</see>.
/// </summary>
protected override void GetCurrentValueAsFrozenCore(Freezable source)
{
Int32AnimationUsingKeyFrames sourceAnimation = (Int32AnimationUsingKeyFrames) source;
base.GetCurrentValueAsFrozenCore(source);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ true);
}
/// <summary>
/// Helper used by the four Freezable clone methods to copy the resolved key times and
/// key frames. The Get*AsFrozenCore methods are implemented the same as the Clone*Core
/// methods; Get*AsFrozen at the top level will recursively Freeze so it's not done here.
/// </summary>
/// <param name="sourceAnimation"></param>
/// <param name="isCurrentValueClone"></param>
private void CopyCommon(Int32AnimationUsingKeyFrames sourceAnimation, bool isCurrentValueClone)
{
_areKeyTimesValid = sourceAnimation._areKeyTimesValid;
if ( _areKeyTimesValid
&& sourceAnimation._sortedResolvedKeyFrames != null)
{
// _sortedResolvedKeyFrames is an array of ResolvedKeyFrameEntry so the notion of CurrentValueClone doesn't apply
_sortedResolvedKeyFrames = (ResolvedKeyFrameEntry[])sourceAnimation._sortedResolvedKeyFrames.Clone();
}
if (sourceAnimation._keyFrames != null)
{
if (isCurrentValueClone)
{
_keyFrames = (Int32KeyFrameCollection)sourceAnimation._keyFrames.CloneCurrentValue();
}
else
{
_keyFrames = (Int32KeyFrameCollection)sourceAnimation._keyFrames.Clone();
}
OnFreezablePropertyChanged(null, _keyFrames);
}
}
#endregion // Freezable
#region IAddChild interface
/// <summary>
/// Adds a child object to this KeyFrameAnimation.
/// </summary>
/// <param name="child">
/// The child object to add.
/// </param>
/// <remarks>
/// A KeyFrameAnimation only accepts a KeyFrame of the proper type as
/// a child.
/// </remarks>
void IAddChild.AddChild(object child)
{
WritePreamble();
if (child == null)
{
throw new ArgumentNullException("child");
}
AddChild(child);
WritePostscript();
}
/// <summary>
/// Implemented to allow KeyFrames to be direct children
/// of KeyFrameAnimations in markup.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void AddChild(object child)
{
Int32KeyFrame keyFrame = child as Int32KeyFrame;
if (keyFrame != null)
{
KeyFrames.Add(keyFrame);
}
else
{
throw new ArgumentException(SR.Get(SRID.Animation_ChildMustBeKeyFrame), "child");
}
}
/// <summary>
/// Adds a text string as a child of this KeyFrameAnimation.
/// </summary>
/// <param name="childText">
/// The text to add.
/// </param>
/// <remarks>
/// A KeyFrameAnimation does not accept text as a child, so this method will
/// raise an InvalididOperationException unless a derived class has
/// overridden the behavior to add text.
/// </remarks>
/// <exception cref="ArgumentNullException">The childText parameter is
/// null.</exception>
void IAddChild.AddText(string childText)
{
if (childText == null)
{
throw new ArgumentNullException("childText");
}
AddText(childText);
}
/// <summary>
/// This method performs the core functionality of the AddText()
/// method on the IAddChild interface. For a KeyFrameAnimation this means
/// throwing and InvalidOperationException because it doesn't
/// support adding text.
/// </summary>
/// <remarks>
/// This method is the only core implementation. It does not call
/// WritePreamble() or WritePostscript(). It also doesn't throw an
/// ArgumentNullException if the childText parameter is null. These tasks
/// are performed by the interface implementation. Therefore, it's OK
/// for a derived class to override this method and call the base
/// class implementation only if they determine that it's the right
/// course of action. The derived class can rely on KeyFrameAnimation's
/// implementation of IAddChild.AddChild or implement their own
/// following the Freezable pattern since that would be a public
/// method.
/// </remarks>
/// <param name="childText">A string representing the child text that
/// should be added. If this is a KeyFrameAnimation an exception will be
/// thrown.</param>
/// <exception cref="InvalidOperationException">Timelines have no way
/// of adding text.</exception>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void AddText(string childText)
{
throw new InvalidOperationException(SR.Get(SRID.Animation_NoTextChildren));
}
#endregion
#region Int32AnimationBase
/// <summary>
/// Calculates the value this animation believes should be the current value for the property.
/// </summary>
/// <param name="defaultOriginValue">
/// This value is the suggested origin value provided to the animation
/// to be used if the animation does not have its own concept of a
/// start value. If this animation is the first in a composition chain
/// this value will be the snapshot value if one is available or the
/// base property value if it is not; otherise this value will be the
/// value returned by the previous animation in the chain with an
/// animationClock that is not Stopped.
/// </param>
/// <param name="defaultDestinationValue">
/// This value is the suggested destination value provided to the animation
/// to be used if the animation does not have its own concept of an
/// end value. This value will be the base value if the animation is
/// in the first composition layer of animations on a property;
/// otherwise this value will be the output value from the previous
/// composition layer of animations for the property.
/// </param>
/// <param name="animationClock">
/// This is the animationClock which can generate the CurrentTime or
/// CurrentProgress value to be used by the animation to generate its
/// output value.
/// </param>
/// <returns>
/// The value this animation believes should be the current value for the property.
/// </returns>
protected sealed override Int32 GetCurrentValueCore(
Int32 defaultOriginValue,
Int32 defaultDestinationValue,
AnimationClock animationClock)
{
Debug.Assert(animationClock.CurrentState != ClockState.Stopped);
if (_keyFrames == null)
{
return defaultDestinationValue;
}
// We resolved our KeyTimes when we froze, but also got notified
// of the frozen state and therefore invalidated ourselves.
if (!_areKeyTimesValid)
{
ResolveKeyTimes();
}
if (_sortedResolvedKeyFrames == null)
{
return defaultDestinationValue;
}
TimeSpan currentTime = animationClock.CurrentTime.Value;
Int32 keyFrameCount = _sortedResolvedKeyFrames.Length;
Int32 maxKeyFrameIndex = keyFrameCount - 1;
Int32 currentIterationValue;
Debug.Assert(maxKeyFrameIndex >= 0, "maxKeyFrameIndex is less than zero which means we don't actually have any key frames.");
Int32 currentResolvedKeyFrameIndex = 0;
// Skip all the key frames with key times lower than the current time.
// currentResolvedKeyFrameIndex will be greater than maxKeyFrameIndex
// if we are past the last key frame.
while ( currentResolvedKeyFrameIndex < keyFrameCount
&& currentTime > _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime)
{
currentResolvedKeyFrameIndex++;
}
// If there are multiple key frames at the same key time, be sure to go to the last one.
while ( currentResolvedKeyFrameIndex < maxKeyFrameIndex
&& currentTime == _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex + 1]._resolvedKeyTime)
{
currentResolvedKeyFrameIndex++;
}
if (currentResolvedKeyFrameIndex == keyFrameCount)
{
// Past the last key frame.
currentIterationValue = GetResolvedKeyFrameValue(maxKeyFrameIndex);
}
else if (currentTime == _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime)
{
// Exactly on a key frame.
currentIterationValue = GetResolvedKeyFrameValue(currentResolvedKeyFrameIndex);
}
else
{
// Between two key frames.
Double currentSegmentProgress = 0.0;
Int32 fromValue;
if (currentResolvedKeyFrameIndex == 0)
{
// The current key frame is the first key frame so we have
// some special rules for determining the fromValue and an
// optimized method of calculating the currentSegmentProgress.
// If we're additive we want the base value to be a zero value
// so that if there isn't a key frame at time 0.0, we'll use
// the zero value for the time 0.0 value and then add that
// later to the base value.
if (IsAdditive)
{
fromValue = AnimatedTypeHelpers.GetZeroValueInt32(defaultOriginValue);
}
else
{
fromValue = defaultOriginValue;
}
// Current segment time divided by the segment duration.
// Note: the reason this works is that we know that we're in
// the first segment, so we can assume:
//
// currentTime.TotalMilliseconds = current segment time
// _sortedResolvedKeyFrames[0]._resolvedKeyTime.TotalMilliseconds = current segment duration
currentSegmentProgress = currentTime.TotalMilliseconds
/ _sortedResolvedKeyFrames[0]._resolvedKeyTime.TotalMilliseconds;
}
else
{
Int32 previousResolvedKeyFrameIndex = currentResolvedKeyFrameIndex - 1;
TimeSpan previousResolvedKeyTime = _sortedResolvedKeyFrames[previousResolvedKeyFrameIndex]._resolvedKeyTime;
fromValue = GetResolvedKeyFrameValue(previousResolvedKeyFrameIndex);
TimeSpan segmentCurrentTime = currentTime - previousResolvedKeyTime;
TimeSpan segmentDuration = _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime - previousResolvedKeyTime;
currentSegmentProgress = segmentCurrentTime.TotalMilliseconds
/ segmentDuration.TotalMilliseconds;
}
currentIterationValue = GetResolvedKeyFrame(currentResolvedKeyFrameIndex).InterpolateValue(fromValue, currentSegmentProgress);
}
// If we're cumulative, we need to multiply the final key frame
// value by the current repeat count and add this to the return
// value.
if (IsCumulative)
{
Double currentRepeat = (Double)(animationClock.CurrentIteration - 1);
if (currentRepeat > 0.0)
{
currentIterationValue = AnimatedTypeHelpers.AddInt32(
currentIterationValue,
AnimatedTypeHelpers.ScaleInt32(GetResolvedKeyFrameValue(maxKeyFrameIndex), currentRepeat));
}
}
// If we're additive we need to add the base value to the return value.
if (IsAdditive)
{
return AnimatedTypeHelpers.AddInt32(defaultOriginValue, currentIterationValue);
}
return currentIterationValue;
}
/// <summary>
/// Provide a custom natural Duration when the Duration property is set to Automatic.
/// </summary>
/// <param name="clock">
/// The Clock whose natural duration is desired.
/// </param>
/// <returns>
/// If the last KeyFrame of this animation is a KeyTime, then this will
/// be used as the NaturalDuration; otherwise it will be one second.
/// </returns>
protected override sealed Duration GetNaturalDurationCore(Clock clock)
{
return new Duration(LargestTimeSpanKeyTime);
}
#endregion
#region IKeyFrameAnimation
/// <summary>
/// Returns the Int32KeyFrameCollection used by this KeyFrameInt32Animation.
/// </summary>
IList IKeyFrameAnimation.KeyFrames
{
get
{
return KeyFrames;
}
set
{
KeyFrames = (Int32KeyFrameCollection)value;
}
}
/// <summary>
/// Returns the Int32KeyFrameCollection used by this KeyFrameInt32Animation.
/// </summary>
public Int32KeyFrameCollection KeyFrames
{
get
{
ReadPreamble();
// The reason we don't just set _keyFrames to the empty collection
// in the first place is that null tells us that the user has not
// asked for the collection yet. The first time they ask for the
// collection and we're unfrozen, policy dictates that we give
// them a new unfrozen collection. All subsequent times they will
// get whatever collection is present, whether frozen or unfrozen.
if (_keyFrames == null)
{
if (this.IsFrozen)
{
_keyFrames = Int32KeyFrameCollection.Empty;
}
else
{
WritePreamble();
_keyFrames = new Int32KeyFrameCollection();
OnFreezablePropertyChanged(null, _keyFrames);
WritePostscript();
}
}
return _keyFrames;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
WritePreamble();
if (value != _keyFrames)
{
OnFreezablePropertyChanged(_keyFrames, value);
_keyFrames = value;
WritePostscript();
}
}
}
/// <summary>
/// Returns true if we should serialize the KeyFrames, property for this Animation.
/// </summary>
/// <returns>True if we should serialize the KeyFrames property for this Animation; otherwise false.</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeKeyFrames()
{
ReadPreamble();
return _keyFrames != null
&& _keyFrames.Count > 0;
}
#endregion
#region Public Properties
/// <summary>
/// If this property is set to true, this animation will add its value
/// to the base value or the value of the previous animation in the
/// composition chain. Another way of saying this is that the units
/// specified in the animation are relative to the base value rather
/// than absolute units.
/// </summary>
/// <remarks>
/// In the case where the first key frame's resolved key time is not
/// 0.0 there is slightly different behavior between KeyFrameInt32Animations
/// with IsAdditive set and without. Animations with the property set to false
/// will behave as if there is a key frame at time 0.0 with the value of the
/// base value. Animations with the property set to true will behave as if
/// there is a key frame at time 0.0 with a zero value appropriate to the type
/// of the animation. These behaviors provide the results most commonly expected
/// and can be overridden by simply adding a key frame at time 0.0 with the preferred value.
/// </remarks>
public bool IsAdditive
{
get
{
return (bool)GetValue(IsAdditiveProperty);
}
set
{
SetValueInternal(IsAdditiveProperty, BooleanBoxes.Box(value));
}
}
/// <summary>
/// If this property is set to true, the value of this animation will
/// accumulate over repeat cycles. For example, if this is a point
/// animation and your key frames describe something approximating and
/// arc, setting this property to true will result in an animation that
/// would appear to bounce the point across the screen.
/// </summary>
/// <remarks>
/// This property works along with the IsAdditive property. Setting
/// this value to true has no effect unless IsAdditive is also set
/// to true.
/// </remarks>
public bool IsCumulative
{
get
{
return (bool)GetValue(IsCumulativeProperty);
}
set
{
SetValueInternal(IsCumulativeProperty, BooleanBoxes.Box(value));
}
}
#endregion
#region Private Methods
private struct KeyTimeBlock
{
public int BeginIndex;
public int EndIndex;
}
private Int32 GetResolvedKeyFrameValue(Int32 resolvedKeyFrameIndex)
{
Debug.Assert(_areKeyTimesValid, "The key frames must be resolved and sorted before calling GetResolvedKeyFrameValue");
return GetResolvedKeyFrame(resolvedKeyFrameIndex).Value;
}
private Int32KeyFrame GetResolvedKeyFrame(Int32 resolvedKeyFrameIndex)
{
Debug.Assert(_areKeyTimesValid, "The key frames must be resolved and sorted before calling GetResolvedKeyFrame");
return _keyFrames[_sortedResolvedKeyFrames[resolvedKeyFrameIndex]._originalKeyFrameIndex];
}
/// <summary>
/// Returns the largest time span specified key time from all of the key frames.
/// If there are not time span key times a time span of one second is returned
/// to match the default natural duration of the From/To/By animations.
/// </summary>
private TimeSpan LargestTimeSpanKeyTime
{
get
{
bool hasTimeSpanKeyTime = false;
TimeSpan largestTimeSpanKeyTime = TimeSpan.Zero;
if (_keyFrames != null)
{
Int32 keyFrameCount = _keyFrames.Count;
for (int index = 0; index < keyFrameCount; index++)
{
KeyTime keyTime = _keyFrames[index].KeyTime;
if (keyTime.Type == KeyTimeType.TimeSpan)
{
hasTimeSpanKeyTime = true;
if (keyTime.TimeSpan > largestTimeSpanKeyTime)
{
largestTimeSpanKeyTime = keyTime.TimeSpan;
}
}
}
}
if (hasTimeSpanKeyTime)
{
return largestTimeSpanKeyTime;
}
else
{
return TimeSpan.FromSeconds(1.0);
}
}
}
private void ResolveKeyTimes()
{
Debug.Assert(!_areKeyTimesValid, "KeyFrameInt32Animaton.ResolveKeyTimes() shouldn't be called if the key times are already valid.");
int keyFrameCount = 0;
if (_keyFrames != null)
{
keyFrameCount = _keyFrames.Count;
}
if (keyFrameCount == 0)
{
_sortedResolvedKeyFrames = null;
_areKeyTimesValid = true;
return;
}
_sortedResolvedKeyFrames = new ResolvedKeyFrameEntry[keyFrameCount];
int index = 0;
// Initialize the _originalKeyFrameIndex.
for ( ; index < keyFrameCount; index++)
{
_sortedResolvedKeyFrames[index]._originalKeyFrameIndex = index;
}
// calculationDuration represents the time span we will use to resolve
// percent key times. This is defined as the value in the following
// precedence order:
// 1. The animation's duration, but only if it is a time span, not auto or forever.
// 2. The largest time span specified key time of all the key frames.
// 3. 1 second, to match the From/To/By animations.
TimeSpan calculationDuration = TimeSpan.Zero;
Duration duration = Duration;
if (duration.HasTimeSpan)
{
calculationDuration = duration.TimeSpan;
}
else
{
calculationDuration = LargestTimeSpanKeyTime;
}
int maxKeyFrameIndex = keyFrameCount - 1;
ArrayList unspecifiedBlocks = new ArrayList();
bool hasPacedKeyTimes = false;
//
// Pass 1: Resolve Percent and Time key times.
//
index = 0;
while (index < keyFrameCount)
{
KeyTime keyTime = _keyFrames[index].KeyTime;
switch (keyTime.Type)
{
case KeyTimeType.Percent:
_sortedResolvedKeyFrames[index]._resolvedKeyTime = TimeSpan.FromMilliseconds(
keyTime.Percent * calculationDuration.TotalMilliseconds);
index++;
break;
case KeyTimeType.TimeSpan:
_sortedResolvedKeyFrames[index]._resolvedKeyTime = keyTime.TimeSpan;
index++;
break;
case KeyTimeType.Paced:
case KeyTimeType.Uniform:
if (index == maxKeyFrameIndex)
{
// If the last key frame doesn't have a specific time
// associated with it its resolved key time will be
// set to the calculationDuration, which is the
// defined in the comments above where it is set.
// Reason: We only want extra time at the end of the
// key frames if the user specifically states that
// the last key frame ends before the animation ends.
_sortedResolvedKeyFrames[index]._resolvedKeyTime = calculationDuration;
index++;
}
else if ( index == 0
&& keyTime.Type == KeyTimeType.Paced)
{
// Note: It's important that this block come after
// the previous if block because of rule precendence.
// If the first key frame in a multi-frame key frame
// collection is paced, we set its resolved key time
// to 0.0 for performance reasons. If we didn't, the
// resolved key time list would be dependent on the
// base value which can change every animation frame
// in many cases.
_sortedResolvedKeyFrames[index]._resolvedKeyTime = TimeSpan.Zero;
index++;
}
else
{
if (keyTime.Type == KeyTimeType.Paced)
{
hasPacedKeyTimes = true;
}
KeyTimeBlock block = new KeyTimeBlock();
block.BeginIndex = index;
// NOTE: We don't want to go all the way up to the
// last frame because if it is Uniform or Paced its
// resolved key time will be set to the calculation
// duration using the logic above.
//
// This is why the logic is:
// ((++index) < maxKeyFrameIndex)
// instead of:
// ((++index) < keyFrameCount)
while ((++index) < maxKeyFrameIndex)
{
KeyTimeType type = _keyFrames[index].KeyTime.Type;
if ( type == KeyTimeType.Percent
|| type == KeyTimeType.TimeSpan)
{
break;
}
else if (type == KeyTimeType.Paced)
{
hasPacedKeyTimes = true;
}
}
Debug.Assert(index < keyFrameCount,
"The end index for a block of unspecified key frames is out of bounds.");
block.EndIndex = index;
unspecifiedBlocks.Add(block);
}
break;
}
}
//
// Pass 2: Resolve Uniform key times.
//
for (int j = 0; j < unspecifiedBlocks.Count; j++)
{
KeyTimeBlock block = (KeyTimeBlock)unspecifiedBlocks[j];
TimeSpan blockBeginTime = TimeSpan.Zero;
if (block.BeginIndex > 0)
{
blockBeginTime = _sortedResolvedKeyFrames[block.BeginIndex - 1]._resolvedKeyTime;
}
// The number of segments is equal to the number of key
// frames we're working on plus 1. Think about the case
// where we're working on a single key frame. There's a
// segment before it and a segment after it.
//
// Time known Uniform Time known
// ^ ^ ^
// | | |
// | (segment 1) | (segment 2) |
Int64 segmentCount = (block.EndIndex - block.BeginIndex) + 1;
TimeSpan uniformTimeStep = TimeSpan.FromTicks((_sortedResolvedKeyFrames[block.EndIndex]._resolvedKeyTime - blockBeginTime).Ticks / segmentCount);
index = block.BeginIndex;
TimeSpan resolvedTime = blockBeginTime + uniformTimeStep;
while (index < block.EndIndex)
{
_sortedResolvedKeyFrames[index]._resolvedKeyTime = resolvedTime;
resolvedTime += uniformTimeStep;
index++;
}
}
//
// Pass 3: Resolve Paced key times.
//
if (hasPacedKeyTimes)
{
ResolvePacedKeyTimes();
}
//
// Sort resolved key frame entries.
//
Array.Sort(_sortedResolvedKeyFrames);
_areKeyTimesValid = true;
return;
}
/// <summary>
/// This should only be called from ResolveKeyTimes and only at the
/// appropriate time.
/// </summary>
private void ResolvePacedKeyTimes()
{
Debug.Assert(_keyFrames != null && _keyFrames.Count > 2,
"Caller must guard against calling this method when there are insufficient keyframes.");
// If the first key frame is paced its key time has already
// been resolved, so we start at index 1.
int index = 1;
int maxKeyFrameIndex = _sortedResolvedKeyFrames.Length - 1;
do
{
if (_keyFrames[index].KeyTime.Type == KeyTimeType.Paced)
{
//
// We've found a paced key frame so this is the
// beginning of a paced block.
//
// The first paced key frame in this block.
int firstPacedBlockKeyFrameIndex = index;
// List of segment lengths for this paced block.
List<Double> segmentLengths = new List<Double>();
// The resolved key time for the key frame before this
// block which we'll use as our starting point.
TimeSpan prePacedBlockKeyTime = _sortedResolvedKeyFrames[index - 1]._resolvedKeyTime;
// The total of the segment lengths of the paced key
// frames in this block.
Double totalLength = 0.0;
// The key value of the previous key frame which will be
// used to determine the segment length of this key frame.
Int32 prevKeyValue = _keyFrames[index - 1].Value;
do
{
Int32 currentKeyValue = _keyFrames[index].Value;
// Determine the segment length for this key frame and
// add to the total length.
totalLength += AnimatedTypeHelpers.GetSegmentLengthInt32(prevKeyValue, currentKeyValue);
// Temporarily store the distance into the total length
// that this key frame represents in the resolved
// key times array to be converted to a resolved key
// time outside of this loop.
segmentLengths.Add(totalLength);
// Prepare for the next iteration.
prevKeyValue = currentKeyValue;
index++;
}
while ( index < maxKeyFrameIndex
&& _keyFrames[index].KeyTime.Type == KeyTimeType.Paced);
// index is currently set to the index of the key frame
// after the last paced key frame. This will always
// be a valid index because we limit ourselves with
// maxKeyFrameIndex.
// We need to add the distance between the last paced key
// frame and the next key frame to get the total distance
// inside the key frame block.
totalLength += AnimatedTypeHelpers.GetSegmentLengthInt32(prevKeyValue, _keyFrames[index].Value);
// Calculate the time available in the resolved key time space.
TimeSpan pacedBlockDuration = _sortedResolvedKeyFrames[index]._resolvedKeyTime - prePacedBlockKeyTime;
// Convert lengths in segmentLengths list to resolved
// key times for the paced key frames in this block.
for (int i = 0, currentKeyFrameIndex = firstPacedBlockKeyFrameIndex; i < segmentLengths.Count; i++, currentKeyFrameIndex++)
{
// The resolved key time for each key frame is:
//
// The key time of the key frame before this paced block
// + ((the percentage of the way through the total length)
// * the resolved key time space available for the block)
_sortedResolvedKeyFrames[currentKeyFrameIndex]._resolvedKeyTime = prePacedBlockKeyTime + TimeSpan.FromMilliseconds(
(segmentLengths[i] / totalLength) * pacedBlockDuration.TotalMilliseconds);
}
}
else
{
index++;
}
}
while (index < maxKeyFrameIndex);
}
#endregion
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Runtime.CompilerServices;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
namespace Signum.React.JsonModelValidators;
/// <summary>
/// A visitor implementation that interprets <see cref="ValidationStateDictionary"/> to traverse
/// a model object graph and perform validation.
/// </summary>
internal class ValidationVisitor
{
protected readonly ValidationStack CurrentPath;
/// <summary>
/// Creates a new <see cref="ValidationVisitor"/>.
/// </summary>
/// <param name="actionContext">The <see cref="ActionContext"/> associated with the current request.</param>
/// <param name="validatorProvider">The <see cref="IModelValidatorProvider"/>.</param>
/// <param name="validatorCache">The <see cref="ValidatorCache"/> that provides a list of <see cref="IModelValidator"/>s.</param>
/// <param name="metadataProvider">The provider used for reading metadata for the model type.</param>
/// <param name="validationState">The <see cref="ValidationStateDictionary"/>.</param>
public ValidationVisitor(
ActionContext actionContext,
IModelValidatorProvider validatorProvider,
ValidatorCache validatorCache,
IModelMetadataProvider metadataProvider,
ValidationStateDictionary validationState)
{
if (actionContext == null)
{
throw new ArgumentNullException(nameof(actionContext));
}
if (validatorProvider == null)
{
throw new ArgumentNullException(nameof(validatorProvider));
}
if (validatorCache == null)
{
throw new ArgumentNullException(nameof(validatorCache));
}
Context = actionContext;
ValidatorProvider = validatorProvider;
Cache = validatorCache;
MetadataProvider = metadataProvider;
ValidationState = validationState;
ModelState = actionContext.ModelState;
CurrentPath = new ValidationStack();
}
protected IModelValidatorProvider ValidatorProvider { get; }
protected IModelMetadataProvider MetadataProvider { get; }
protected ValidatorCache Cache { get; }
protected ActionContext Context { get; }
protected ModelStateDictionary ModelState { get; }
protected ValidationStateDictionary ValidationState { get; }
protected object? Container { get; set; }
protected string? Key { get; set; }
protected object? Model { get; set; }
protected ModelMetadata? Metadata { get; set; }
protected IValidationStrategy? Strategy { get; set; }
/// <summary>
/// Indicates whether validation of a complex type should be performed if validation fails for any of its children. The default behavior is false.
/// </summary>
public bool ValidateComplexTypesIfChildValidationFails { get; set; }
/// <summary>
/// Validates a object.
/// </summary>
/// <param name="metadata">The <see cref="ModelMetadata"/> associated with the model.</param>
/// <param name="key">The model prefix key.</param>
/// <param name="model">The model object.</param>
/// <returns><c>true</c> if the object is valid, otherwise <c>false</c>.</returns>
public bool Validate(ModelMetadata metadata, string key, object model)
{
return Validate(metadata, key, model, alwaysValidateAtTopLevel: false);
}
/// <summary>
/// Validates a object.
/// </summary>
/// <param name="metadata">The <see cref="ModelMetadata"/> associated with the model.</param>
/// <param name="key">The model prefix key.</param>
/// <param name="model">The model object.</param>
/// <param name="alwaysValidateAtTopLevel">If <c>true</c>, applies validation rules even if the top-level value is <c>null</c>.</param>
/// <returns><c>true</c> if the object is valid, otherwise <c>false</c>.</returns>
public virtual bool Validate(ModelMetadata? metadata, string? key, object? model, bool alwaysValidateAtTopLevel)
{
if (model == null && key != null && !alwaysValidateAtTopLevel)
{
var entry = ModelState[key];
// Rationale: We might see the same model state key for two different objects and want to preserve any
// known invalidity.
if (entry != null && entry.ValidationState != ModelValidationState.Invalid)
{
entry.ValidationState = ModelValidationState.Valid;
}
return true;
}
return Visit(metadata, key!, model!);
}
/// <summary>
/// Validates a single node in a model object graph.
/// </summary>
/// <returns><c>true</c> if the node is valid, otherwise <c>false</c>.</returns>
protected virtual bool ValidateNode()
{
var state = ModelState.GetValidationState(Key!);
// Rationale: we might see the same model state key used for two different objects.
// We want to run validation unless it's already known that this key is invalid.
if (state != ModelValidationState.Invalid)
{
var validators = Cache.GetValidators(Metadata!, ValidatorProvider);
var count = validators.Count;
if (count > 0)
{
var context = new ModelValidationContext(
Context,
Metadata!,
MetadataProvider,
Container!,
Model!);
var results = new List<ModelValidationResult>();
for (var i = 0; i < count; i++)
{
results.AddRange(validators[i].Validate(context));
}
var resultsCount = results.Count;
for (var i = 0; i < resultsCount; i++)
{
var result = results[i];
var key = ModelNames.CreatePropertyModelName(Key, result.MemberName);
// It's OK for key to be the empty string here. This can happen when a top
// level object implements IValidatableObject.
ModelState.TryAddModelError(key, result.Message);
}
}
}
state = ModelState.GetFieldValidationState(Key!);
if (state == ModelValidationState.Invalid)
{
return false;
}
else
{
// If the field has an entry in ModelState, then record it as valid. Don't create
// extra entries if they don't exist already.
var entry = ModelState[Key!];
if (entry != null)
{
entry.ValidationState = ModelValidationState.Valid;
}
return true;
}
}
protected virtual bool Visit(ModelMetadata? metadata, string? key, object? model)
{
RuntimeHelpers.EnsureSufficientExecutionStack();
if (model != null && !CurrentPath.Push(model))
{
// This is a cycle, bail.
return true;
}
var entry = GetValidationEntry(model);
key = entry?.Key ?? key ?? string.Empty;
metadata = entry?.Metadata ?? metadata;
var strategy = entry?.Strategy;
if (ModelState.HasReachedMaxErrors)
{
SuppressValidation(key);
return false;
}
else if (entry != null && entry.SuppressValidation)
{
// Use the key on the entry, because we might not have entries in model state.
SuppressValidation(entry.Key);
CurrentPath.Pop(model!);
return true;
}
// If the metadata indicates that no validators exist AND the aggregate state for the key says that the model graph
// is not invalid (i.e. is one of Unvalidated, Valid, or Skipped) we can safely mark the graph as valid.
else if (metadata!.HasValidators == false &&
ModelState.GetFieldValidationState(key) != ModelValidationState.Invalid)
{
// No validators will be created for this graph of objects. Mark it as valid if it wasn't previously validated.
var entries = ModelState.FindKeysWithPrefix(key);
foreach (var item in entries)
{
if (item.Value.ValidationState == ModelValidationState.Unvalidated)
{
item.Value.ValidationState = ModelValidationState.Valid;
}
}
CurrentPath.Pop(model!);
return true;
}
using (StateManager.Recurse(this, key ?? string.Empty, metadata, model!, strategy))
{
if (Metadata!.IsEnumerableType)
{
return VisitComplexType(DefaultCollectionValidationStrategy.Instance);
}
if (Metadata.IsComplexType)
{
return VisitComplexType(DefaultComplexObjectValidationStrategy.Instance);
}
return VisitSimpleType();
}
}
// Covers everything VisitSimpleType does not i.e. both enumerations and complex types.
protected virtual bool VisitComplexType(IValidationStrategy defaultStrategy)
{
var isValid = true;
if (Model != null && Metadata!.ValidateChildren)
{
var strategy = Strategy ?? defaultStrategy;
isValid = VisitChildren(strategy);
}
else if (Model != null)
{
// Suppress validation for the entries matching this prefix. This will temporarily set
// the current node to 'skipped' but we're going to visit it right away, so subsequent
// code will set it to 'valid' or 'invalid'
SuppressValidation(Key);
}
// Double-checking HasReachedMaxErrors just in case this model has no properties.
// If validation has failed for any children, only validate the parent if ValidateComplexTypesIfChildValidationFails is true.
if ((isValid || ValidateComplexTypesIfChildValidationFails) && !ModelState.HasReachedMaxErrors)
{
isValid &= ValidateNode();
}
return isValid;
}
protected virtual bool VisitSimpleType()
{
if (ModelState.HasReachedMaxErrors)
{
SuppressValidation(Key);
return false;
}
return ValidateNode();
}
protected virtual bool VisitChildren(IValidationStrategy strategy)
{
var isValid = true;
var enumerator = strategy.GetChildren(Metadata!, Key!, Model!);
var parentEntry = new ValidationEntry(Metadata!, Key!, Model!);
while (enumerator.MoveNext())
{
var entry = enumerator.Current;
var metadata = entry.Metadata;
var key = entry.Key;
if (metadata.PropertyValidationFilter?.ShouldValidateEntry(entry, parentEntry) == false)
{
SuppressValidation(key);
continue;
}
isValid &= Visit(metadata, key, entry.Model);
}
return isValid;
}
protected virtual void SuppressValidation(string? key)
{
if (key == null)
{
// If the key is null, that means that we shouldn't expect any entries in ModelState for
// this value, so there's nothing to do.
return;
}
var entries = ModelState.FindKeysWithPrefix(key);
foreach (var entry in entries)
{
if (entry.Value.ValidationState != ModelValidationState.Invalid)
{
entry.Value.ValidationState = ModelValidationState.Skipped;
}
}
}
protected virtual ValidationStateEntry? GetValidationEntry(object? model)
{
if (model == null || ValidationState == null)
{
return null;
}
ValidationState.TryGetValue(model, out var entry);
return entry;
}
protected readonly struct StateManager : IDisposable
{
private readonly ValidationVisitor _visitor;
private readonly object? _container;
private readonly string? _key;
private readonly ModelMetadata? _metadata;
private readonly object? _model;
private readonly object _newModel;
private readonly IValidationStrategy? _strategy;
public static StateManager Recurse(
ValidationVisitor visitor,
string key,
ModelMetadata? metadata,
object model,
IValidationStrategy? strategy)
{
var recursifier = new StateManager(visitor, model);
visitor.Container = visitor.Model;
visitor.Key = key;
visitor.Metadata = metadata;
visitor.Model = model;
visitor.Strategy = strategy;
return recursifier;
}
public StateManager(ValidationVisitor visitor, object newModel)
{
_visitor = visitor;
_newModel = newModel;
_container = _visitor.Container;
_key = _visitor.Key;
_metadata = _visitor.Metadata;
_model = _visitor.Model;
_strategy = _visitor.Strategy;
}
public void Dispose()
{
_visitor.Container = _container;
_visitor.Key = _key;
_visitor.Metadata = _metadata;
_visitor.Model = _model;
_visitor.Strategy = _strategy;
_visitor.CurrentPath.Pop(_newModel);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Tests
{
public class ZipTests : EnumerableTests
{
[Fact]
public void ImplicitTypeParameters()
{
IEnumerable<int> first = new int[] { 1, 2, 3 };
IEnumerable<int> second = new int[] { 2, 5, 9 };
IEnumerable<int> expected = new int[] { 3, 7, 12 };
Assert.Equal(expected, first.Zip(second, (x, y) => x + y));
}
[Fact]
public void ExplicitTypeParameters()
{
IEnumerable<int> first = new int[] { 1, 2, 3 };
IEnumerable<int> second = new int[] { 2, 5, 9 };
IEnumerable<int> expected = new int[] { 3, 7, 12 };
Assert.Equal(expected, first.Zip<int, int, int>(second, (x, y) => x + y));
}
[Fact]
public void FirstIsNull()
{
IEnumerable<int> first = null;
IEnumerable<int> second = new int[] { 2, 5, 9 };
Assert.Throws<ArgumentNullException>("first", () => first.Zip<int, int, int>(second, (x, y) => x + y));
}
[Fact]
public void SecondIsNull()
{
IEnumerable<int> first = new int[] { 1, 2, 3 };
IEnumerable<int> second = null;
Assert.Throws<ArgumentNullException>("second", () => first.Zip<int, int, int>(second, (x, y) => x + y));
}
[Fact]
public void FuncIsNull()
{
IEnumerable<int> first = new int[] { 1, 2, 3 };
IEnumerable<int> second = new int[] { 2, 4, 6 };
Func<int, int, int> func = null;
Assert.Throws<ArgumentNullException>("resultSelector", () => first.Zip(second, func));
}
[Fact]
public void ExceptionThrownFromFirstsEnumerator()
{
ThrowsOnMatchEnumerable<int> first = new ThrowsOnMatchEnumerable<int>(new int[] { 1, 3, 3 }, 2);
IEnumerable<int> second = new int[] { 2, 4, 6 };
Func<int, int, int> func = (x, y) => x + y;
IEnumerable<int> expected = new int[] { 3, 7, 9 };
Assert.Equal(expected, first.Zip(second, func));
first = new ThrowsOnMatchEnumerable<int>(new int[] { 1, 2, 3 }, 2);
var zip = first.Zip(second, func);
Assert.Throws<Exception>(() => zip.ToList());
}
[Fact]
public void ExceptionThrownFromSecondsEnumerator()
{
ThrowsOnMatchEnumerable<int> second = new ThrowsOnMatchEnumerable<int>(new int[] { 1, 3, 3 }, 2);
IEnumerable<int> first = new int[] { 2, 4, 6 };
Func<int, int, int> func = (x, y) => x + y;
IEnumerable<int> expected = new int[] { 3, 7, 9 };
Assert.Equal(expected, first.Zip(second, func));
second = new ThrowsOnMatchEnumerable<int>(new int[] { 1, 2, 3 }, 2);
var zip = first.Zip(second, func);
Assert.Throws<Exception>(() => zip.ToList());
}
[Fact]
public void FirstAndSecondEmpty()
{
IEnumerable<int> first = new int[] { };
IEnumerable<int> second = new int[] { };
Func<int, int, int> func = (x, y) => x + y;
IEnumerable<int> expected = new int[] { };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void FirstEmptySecondSingle()
{
IEnumerable<int> first = new int[] { };
IEnumerable<int> second = new int[] { 2 };
Func<int, int, int> func = (x, y) => x + y;
IEnumerable<int> expected = new int[] { };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void FirstEmptySecondMany()
{
IEnumerable<int> first = new int[] { };
IEnumerable<int> second = new int[] { 2, 4, 8 };
Func<int, int, int> func = (x, y) => x + y;
IEnumerable<int> expected = new int[] { };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void SecondEmptyFirstSingle()
{
IEnumerable<int> first = new int[] { 1 };
IEnumerable<int> second = new int[] { };
Func<int, int, int> func = (x, y) => x + y;
IEnumerable<int> expected = new int[] { };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void SecondEmptyFirstMany()
{
IEnumerable<int> first = new int[] { 1, 2, 3 };
IEnumerable<int> second = new int[] { };
Func<int, int, int> func = (x, y) => x + y;
IEnumerable<int> expected = new int[] { };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void FirstAndSecondSingle()
{
IEnumerable<int> first = new int[] { 1 };
IEnumerable<int> second = new int[] { 2 };
Func<int, int, int> func = (x, y) => x + y;
IEnumerable<int> expected = new int[] { 3 };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void FirstAndSecondEqualSize()
{
IEnumerable<int> first = new int[] { 1, 2, 3 };
IEnumerable<int> second = new int[] { 2, 3, 4 };
Func<int, int, int> func = (x, y) => x + y;
IEnumerable<int> expected = new int[] { 3, 5, 7 };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void SecondOneMoreThanFirst()
{
IEnumerable<int> first = new int[] { 1, 2 };
IEnumerable<int> second = new int[] { 2, 4, 8 };
Func<int, int, int> func = (x, y) => x + y;
IEnumerable<int> expected = new int[] { 3, 6 };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void SecondManyMoreThanFirst()
{
IEnumerable<int> first = new int[] { 1, 2 };
IEnumerable<int> second = new int[] { 2, 4, 8, 16 };
Func<int, int, int> func = (x, y) => x + y;
IEnumerable<int> expected = new int[] { 3, 6 };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void FirstOneMoreThanSecond()
{
IEnumerable<int> first = new int[] { 1, 2, 3 };
IEnumerable<int> second = new int[] { 2, 4 };
Func<int, int, int> func = (x, y) => x + y;
IEnumerable<int> expected = new int[] { 3, 6 };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void FirstManyMoreThanSecond()
{
IEnumerable<int> first = new int[] { 1, 2, 3, 4 };
IEnumerable<int> second = new int[] { 2, 4 };
Func<int, int, int> func = (x, y) => x + y;
IEnumerable<int> expected = new int[] { 3, 6 };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void DelegateFuncChanged()
{
IEnumerable<int> first = new int[] { 1, 2, 3, 4 };
IEnumerable<int> second = new int[] { 2, 4, 8 };
Func<int, int, int> func = (x, y) => x + y;
IEnumerable<int> expected = new int[] { 3, 6, 11 };
Assert.Equal(expected, first.Zip(second, func));
func = (x, y) => x - y;
expected = new int[] { -1, -2, -5 };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void LambdaFuncChanged()
{
IEnumerable<int> first = new int[] { 1, 2, 3, 4 };
IEnumerable<int> second = new int[] { 2, 4, 8 };
IEnumerable<int> expected = new int[] { 3, 6, 11 };
Assert.Equal(expected, first.Zip(second, (x, y) => x + y));
expected = new int[] { -1, -2, -5 };
Assert.Equal(expected, first.Zip(second, (x, y) => x - y));
}
[Fact]
public void FirstHasFirstElementNull()
{
IEnumerable<int?> first = new[] { (int?)null, 2, 3, 4 };
IEnumerable<int> second = new int[] { 2, 4, 8 };
Func<int?, int, int?> func = (x, y) => x + y;
IEnumerable<int?> expected = new int?[] { null, 6, 11 };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void FirstHasLastElementNull()
{
IEnumerable<int?> first = new[] { 1, 2, (int?)null };
IEnumerable<int> second = new int[] { 2, 4, 6, 8 };
Func<int?, int, int?> func = (x, y) => x + y;
IEnumerable<int?> expected = new int?[] { 3, 6, null };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void FirstHasMiddleNullValue()
{
IEnumerable<int?> first = new[] { 1, (int?)null, 3 };
IEnumerable<int> second = new int[] { 2, 4, 6, 8 };
Func<int?, int, int?> func = (x, y) => x + y;
IEnumerable<int?> expected = new int?[] { 3, null, 9 };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void FirstAllElementsNull()
{
IEnumerable<int?> first = new int?[] { null, null, null };
IEnumerable<int> second = new int[] { 2, 4, 6, 8 };
Func<int?, int, int?> func = (x, y) => x + y;
IEnumerable<int?> expected = new int?[] { null, null, null };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void SecondHasFirstElementNull()
{
IEnumerable<int> first = new int[] { 1, 2, 3, 4 };
IEnumerable<int?> second = new int?[] { null, 4, 6 };
Func<int, int?, int?> func = (x, y) => x + y;
IEnumerable<int?> expected = new int?[] { null, 6, 9 };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void SecondHasLastElementNull()
{
IEnumerable<int> first = new int[] { 1, 2, 3, 4 };
IEnumerable<int?> second = new int?[] { 2, 4, null };
Func<int, int?, int?> func = (x, y) => x + y;
IEnumerable<int?> expected = new int?[] { 3, 6, null };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void SecondHasMiddleElementNull()
{
IEnumerable<int> first = new int[] { 1, 2, 3, 4 };
IEnumerable<int?> second = new int?[] { 2, null, 6 };
Func<int, int?, int?> func = (x, y) => x + y;
IEnumerable<int?> expected = new int?[] { 3, null, 9 };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void SecondHasAllElementsNull()
{
IEnumerable<int> first = new int[] { 1, 2, 3, 4 };
IEnumerable<int?> second = new int?[] { null, null, null };
Func<int, int?, int?> func = (x, y) => x + y;
IEnumerable<int?> expected = new int?[] { null, null, null };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void SecondLargerFirstAllNull()
{
IEnumerable<int?> first = new int?[] { null, null, null, null };
IEnumerable<int?> second = new int?[] { null, null, null };
Func<int?, int?, int?> func = (x, y) => x + y;
IEnumerable<int?> expected = new int?[] { null, null, null };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void FirstSameSizeSecondAllNull()
{
IEnumerable<int?> first = new int?[] { null, null, null };
IEnumerable<int?> second = new int?[] { null, null, null };
Func<int?, int?, int?> func = (x, y) => x + y;
IEnumerable<int?> expected = new int?[] { null, null, null };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void FirstSmallerSecondAllNull()
{
IEnumerable<int?> first = new int?[] { null, null, null };
IEnumerable<int?> second = new int?[] { null, null, null, null };
Func<int?, int?, int?> func = (x, y) => x + y;
IEnumerable<int?> expected = new int?[] { null, null, null };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void ForcedToEnumeratorDoesntEnumerate()
{
var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).Zip(Enumerable.Range(0, 3), (x, y) => x + y);
// Don't insist on this behaviour, but check it's correct if it happens
var en = iterator as IEnumerator<int>;
Assert.False(en != null && en.MoveNext());
}
}
}
| |
// Copyright 2015 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.
#if !(UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_5_0 || UNITY_5_1 || UNITY_IOS)
// Cardboard native audio spatializer plugin is only supported by Unity 5.2+.
// If you get script compile errors in this file, comment out the line below.
#define USE_SPATIALIZER_PLUGIN
#endif
using UnityEngine;
using System;
using System.Collections;
using System.IO;
using System.Runtime.InteropServices;
/// This is the main Cardboard audio class that communicates with the native code implementation of
/// the audio system. Native functions of the system can only be called through this class to
/// preserve the internal system functionality. Public function calls are *not* thread-safe.
public static class CardboardAudio {
/// Audio system rendering quality.
public enum Quality {
Low = 0, /// Stereo-only rendering
Medium = 1, /// Binaural rendering (first-order HRTF)
High = 2 /// Binaural rendering (third-order HRTF)
}
/// System sampling rate.
public static int SampleRate {
get { return sampleRate; }
}
private static int sampleRate = -1;
/// System number of output channels.
public static int NumChannels {
get { return numChannels; }
}
private static int numChannels = -1;
/// System number of frames per buffer.
public static int FramesPerBuffer {
get { return framesPerBuffer; }
}
private static int framesPerBuffer = -1;
/// Initializes the audio system with the current audio configuration.
/// @note This should only be called from the main Unity thread.
public static void Initialize (CardboardAudioListener listener, Quality quality) {
if (!initialized) {
// Initialize the audio system.
#if UNITY_4_5 || UNITY_4_6 || UNITY_4_7
sampleRate = AudioSettings.outputSampleRate;
numChannels = (int)AudioSettings.speakerMode;
int numBuffers = -1;
AudioSettings.GetDSPBufferSize(out framesPerBuffer, out numBuffers);
#else
AudioConfiguration config = AudioSettings.GetConfiguration();
sampleRate = config.sampleRate;
numChannels = (int)config.speakerMode;
framesPerBuffer = config.dspBufferSize;
#endif
if (numChannels != (int)AudioSpeakerMode.Stereo) {
Debug.LogError("Only 'Stereo' speaker mode is supported by Cardboard.");
return;
}
Initialize(quality, sampleRate, numChannels, framesPerBuffer);
listenerTransform = listener.transform;
initialized = true;
Debug.Log("Cardboard audio system is initialized (Quality: " + quality + ", Sample Rate: " +
sampleRate + ", Channels: " + numChannels + ", Frames Per Buffer: " +
framesPerBuffer + ").");
} else if (listener.transform != listenerTransform) {
Debug.LogError("Only one CardboardAudioListener component is allowed in the scene.");
CardboardAudioListener.Destroy(listener);
}
}
/// Shuts down the audio system.
/// @note This should only be called from the main Unity thread.
public static void Shutdown (CardboardAudioListener listener) {
if (initialized && listener.transform == listenerTransform) {
initialized = false;
Shutdown();
sampleRate = -1;
numChannels = -1;
framesPerBuffer = -1;
Debug.Log("Cardboard audio system is shutdown.");
}
}
/// Processes the next |data| buffer of the audio system.
/// @note This should only be called from the audio thread.
public static void ProcessAudioListener (float[] data, int length) {
if (initialized) {
ProcessListener(data, length);
}
}
/// Updates the audio listener.
/// @note This should only be called from the main Unity thread.
public static void UpdateAudioListener (float globalGainDb, float worldScale) {
if (initialized) {
worldScaleInverse = 1.0f / worldScale;
float globalGain = ConvertAmplitudeFromDb(globalGainDb);
Vector3 position = listenerTransform.position;
Quaternion rotation = listenerTransform.rotation;
ConvertAudioTransformFromUnity(ref position, ref rotation);
// Pass listener properties to the system.
SetListenerGain(globalGain);
SetListenerTransform(position.x, position.y, position.z, rotation.x, rotation.y, rotation.z,
rotation.w);
}
}
/// Creates a new audio source with a unique id.
/// @note This should only be called from the main Unity thread.
public static int CreateAudioSource (bool hrtfEnabled) {
int sourceId = -1;
if (initialized) {
sourceId = CreateSource(hrtfEnabled);
}
return sourceId;
}
/// Destroys the audio source with given |id|.
/// @note This should only be called from the main Unity thread.
public static void DestroyAudioSource (int id) {
if (initialized) {
DestroySource(id);
}
}
#if !USE_SPATIALIZER_PLUGIN
/// Processes the next |data| buffer of the audio source with given |id|.
/// @note This should only be called from the audio thread.
public static void ProcessAudioSource (int id, float[] data, int length) {
if (initialized) {
ProcessSource(id, length, data, data);
}
}
#endif
/// Updates the audio source with given |id| and its properties.
/// @note This should only be called from the main Unity thread.
public static void UpdateAudioSource (int id, Transform transform, float gainDb,
AudioRolloffMode rolloffMode, float minDistance,
float maxDistance, float alpha, float sharpness,
float occlusion) {
if (initialized) {
float gain = ConvertAmplitudeFromDb(gainDb);
Vector3 position = transform.position;
Quaternion rotation = transform.rotation;
float scale = worldScaleInverse * Mathf.Max(transform.lossyScale.x, transform.lossyScale.y,
transform.lossyScale.z);
ConvertAudioTransformFromUnity(ref position, ref rotation);
// Pass the source properties to the audio system.
SetSourceDirectivity(id, alpha, sharpness);
SetSourceGain(id, gain);
SetSourceOcclusionIntensity(id, occlusion);
if (rolloffMode != AudioRolloffMode.Custom) {
SetSourceDistanceAttenuationMethod(id, rolloffMode, minDistance, maxDistance);
}
SetSourceTransform(id, position.x, position.y, position.z, rotation.x, rotation.y, rotation.z,
rotation.w, scale);
}
}
/// Creates a new room with a unique id.
/// @note This should only be called from the main Unity thread.
public static int CreateAudioRoom () {
int roomId = -1;
if (initialized) {
roomId = CreateRoom();
}
return roomId;
}
/// Destroys the room with given |id|.
/// @note This should only be called from the main Unity thread.
public static void DestroyAudioRoom (int id) {
if (initialized) {
DestroyRoom(id);
}
}
/// Updates the room effects of the environment with given |room| properties.
/// @note This should only be called from the main Unity thread.
public static void UpdateAudioRoom (int id, Transform transform,
CardboardAudioRoom.SurfaceMaterial[] materials,
float reflectivity, float reverbGainDb,
float reverbBrightness, float reverbTime, Vector3 size) {
if (initialized) {
// Update room transform.
Vector3 position = transform.position;
Quaternion rotation = transform.rotation;
Vector3 scale = Vector3.Scale(size, transform.lossyScale);
scale = worldScaleInverse * new Vector3(Mathf.Abs(scale.x), Mathf.Abs(scale.y),
Mathf.Abs(scale.z));
ConvertAudioTransformFromUnity(ref position, ref rotation);
float reverbGain = ConvertAmplitudeFromDb(reverbGainDb);
SetRoomProperties(id, position.x, position.y, position.z, rotation.x, rotation.y, rotation.z,
rotation.w, scale.x, scale.y, scale.z, materials, reflectivity, reverbGain,
reverbBrightness, reverbTime);
}
}
/// Computes the occlusion intensity of a given |source| using point source detection.
/// @note This should only be called from the main Unity thread.
public static float ComputeOcclusion (Transform sourceTransform) {
float occlusion = 0.0f;
if (initialized) {
Vector3 listenerPosition = listenerTransform.position;
Vector3 sourceFromListener = sourceTransform.position - listenerPosition;
RaycastHit[] hits =
Physics.RaycastAll(listenerPosition, sourceFromListener, sourceFromListener.magnitude);
foreach (RaycastHit hit in hits) {
if (hit.transform != listenerTransform && hit.transform != sourceTransform) {
occlusion += 1.0f;
}
}
}
return occlusion;
}
/// Generates a set of points to draw a 2D polar pattern.
public static Vector2[] Generate2dPolarPattern (float alpha, float order, int resolution) {
Vector2[] points = new Vector2[resolution];
float interval = 2.0f * Mathf.PI / resolution;
for (int i = 0; i < resolution; ++i) {
float theta = i * interval;
// Magnitude |r| for |theta| in radians.
float r = Mathf.Pow(Mathf.Abs((1 - alpha) + alpha * Mathf.Cos(theta)), order);
points[i] = new Vector2(r * Mathf.Sin(theta), r * Mathf.Cos(theta));
}
return points;
}
/// Minimum distance threshold between |minDistance| and |maxDistance|.
public const float distanceEpsilon = 0.01f;
/// Max distance limit that can be set for volume rolloff.
public const float maxDistanceLimit = 1000000.0f;
/// Min distance limit that can be set for volume rolloff.
public const float minDistanceLimit = 990099.0f;
/// Maximum allowed gain value in decibels.
public const float maxGainDb = 24.0f;
/// Minimum allowed gain value in decibels.
public const float minGainDb = -24.0f;
/// Maximum allowed real world scale with respect to Unity.
public const float maxWorldScale = 1000.0f;
/// Minimum allowed real world scale with respect to Unity.
public const float minWorldScale = 0.001f;
/// Maximum allowed reverb brightness modifier value.
public const float maxReverbBrightness = 1.0f;
/// Minimum allowed reverb brightness modifier value.
public const float minReverbBrightness = -1.0f;
/// Maximum allowed reverb time modifier value.
public const float maxReverbTime = 3.0f;
/// Maximum allowed reflectivity multiplier of a room surface material.
public const float maxReflectivity = 2.0f;
/// Source occlusion detection rate in seconds.
public const float occlusionDetectionInterval = 0.2f;
/// Occlusion interpolation amount approximately per second.
public const float occlusionLerpSpeed = 6.0f;
/// Number of surfaces in a room.
public const int numRoomSurfaces = 6;
/// Converts given |db| value to its amplitude equivalent where 'dB = 20 * log10(amplitude)'.
private static float ConvertAmplitudeFromDb (float db) {
return Mathf.Pow(10.0f, 0.05f * db);
}
// Converts given |position| and |rotation| from Unity space to audio space.
private static void ConvertAudioTransformFromUnity (ref Vector3 position,
ref Quaternion rotation) {
pose.SetRightHanded(Matrix4x4.TRS(position, rotation, Vector3.one));
position = pose.Position * worldScaleInverse;
rotation = pose.Orientation;
}
// Denotes whether the system is initialized properly.
private static bool initialized = false;
// Listener transform.
private static Transform listenerTransform = null;
// 3D pose instance to be used in transform space conversion.
private static MutablePose3D pose = new MutablePose3D();
// Inverted world scale.
private static float worldScaleInverse = 1.0f;
#if UNITY_IOS
private const string pluginName = "__Internal";
#else
private const string pluginName = "audiopluginvrunity";
#endif
// Listener handlers.
[DllImport(pluginName)]
private static extern void ProcessListener ([In, Out] float[] data, int bufferSize);
[DllImport(pluginName)]
private static extern void SetListenerGain (float gain);
[DllImport(pluginName)]
private static extern void SetListenerTransform (float px, float py, float pz, float qx, float qy,
float qz, float qw);
// Source handlers.
[DllImport(pluginName)]
private static extern int CreateSource (bool enableHrtf);
[DllImport(pluginName)]
private static extern void DestroySource (int sourceId);
#if !USE_SPATIALIZER_PLUGIN
[DllImport(pluginName)]
private static extern void ProcessSource (int sourceId, int bufferSize, [In, Out] float[] input,
[In, Out] float[] output);
#endif
[DllImport(pluginName)]
private static extern void SetSourceDirectivity (int sourceId, float alpha, float order);
[DllImport(pluginName)]
private static extern void SetSourceDistanceAttenuationMethod (int sourceId,
AudioRolloffMode rolloffMode,
float minDistance,
float maxDistance);
[DllImport(pluginName)]
private static extern void SetSourceGain (int sourceId, float gain);
[DllImport(pluginName)]
private static extern void SetSourceOcclusionIntensity (int sourceId, float intensity);
[DllImport(pluginName)]
private static extern void SetSourceTransform (int sourceId, float px, float py, float pz,
float qx, float qy, float qz, float qw,
float scale);
// Room handlers.
[DllImport(pluginName)]
private static extern int CreateRoom ();
[DllImport(pluginName)]
private static extern void DestroyRoom (int roomId);
[DllImport(pluginName)]
private static extern void SetRoomProperties (int roomId, float px, float py, float pz, float qx,
float qy, float qz, float qw, float dx, float dy,
float dz,
CardboardAudioRoom.SurfaceMaterial[] materialNames,
float reflectionScalar, float reverbGain,
float reverbBrightness, float reverbTime);
// System handlers.
[DllImport(pluginName)]
private static extern void Initialize (Quality quality, int sampleRate, int numChannels,
int framesPerBuffer);
[DllImport(pluginName)]
private static extern void Shutdown ();
}
| |
// GtkSharp.Generation.OpaqueGen.cs - The Opaque Generatable.
//
// Author: Mike Kestner <mkestner@speakeasy.net>
//
// Copyright (c) 2001-2003 Mike Kestner
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the GNU General Public
// License as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GtkSharp.Generation {
using System;
using System.Collections;
using System.IO;
using System.Xml;
public class OpaqueGen : HandleBase {
public OpaqueGen (XmlElement ns, XmlElement elem) : base (ns, elem) {}
public override string FromNative(string var, bool owned)
{
return var + " == IntPtr.Zero ? null : (" + QualifiedName + ") GLib.Opaque.GetOpaque (" + var + ", typeof (" + QualifiedName + "), " + (owned ? "true" : "false") + ")";
}
private bool DisableRawCtor {
get {
return Elem.HasAttribute ("disable_raw_ctor");
}
}
public override void Generate (GenerationInfo gen_info)
{
gen_info.CurrentType = Name;
StreamWriter sw = gen_info.Writer = gen_info.OpenStream (Name);
sw.WriteLine ("namespace " + NS + " {");
sw.WriteLine ();
sw.WriteLine ("\tusing System;");
sw.WriteLine ("\tusing System.Collections;");
sw.WriteLine ("\tusing System.Runtime.InteropServices;");
sw.WriteLine ();
sw.WriteLine ("#region Autogenerated code");
SymbolTable table = SymbolTable.Table;
Method ref_, unref, dispose;
GetSpecialMethods (out ref_, out unref, out dispose);
if (IsDeprecated)
sw.WriteLine ("\t[Obsolete]");
sw.Write ("\t{0}{1}class " + Name, IsInternal ? "internal " : "public ", IsAbstract ? "abstract " : String.Empty);
string cs_parent = table.GetCSType(Elem.GetAttribute("parent"));
if (cs_parent != "")
sw.Write (" : " + cs_parent);
else
sw.Write (" : GLib.Opaque");
foreach (string iface in managed_interfaces) {
if (Parent != null && Parent.Implements (iface))
continue;
sw.Write (", " + iface);
}
sw.WriteLine (" {");
sw.WriteLine ();
GenFields (gen_info);
GenMethods (gen_info, null, null);
GenCtors (gen_info);
if (ref_ != null) {
ref_.GenerateImport (sw);
sw.WriteLine ("\t\tprotected override void Ref (IntPtr raw)");
sw.WriteLine ("\t\t{");
sw.WriteLine ("\t\t\tif (!Owned) {");
sw.WriteLine ("\t\t\t\t" + ref_.CName + " (raw);");
sw.WriteLine ("\t\t\t\tOwned = true;");
sw.WriteLine ("\t\t\t}");
sw.WriteLine ("\t\t}");
sw.WriteLine ();
if (ref_.IsDeprecated) {
sw.WriteLine ("\t\t[Obsolete(\"" + QualifiedName + " is now refcounted automatically\")]");
if (ref_.ReturnType == "void")
sw.WriteLine ("\t\tpublic void Ref () {}");
else
sw.WriteLine ("\t\tpublic " + Name + " Ref () { return this; }");
sw.WriteLine ();
}
}
bool finalizer_needed = false;
if (unref != null) {
unref.GenerateImport (sw);
sw.WriteLine ("\t\tprotected override void Unref (IntPtr raw)");
sw.WriteLine ("\t\t{");
sw.WriteLine ("\t\t\tif (Owned) {");
sw.WriteLine ("\t\t\t\t" + unref.CName + " (raw);");
sw.WriteLine ("\t\t\t\tOwned = false;");
sw.WriteLine ("\t\t\t}");
sw.WriteLine ("\t\t}");
sw.WriteLine ();
if (unref.IsDeprecated) {
sw.WriteLine ("\t\t[Obsolete(\"" + QualifiedName + " is now refcounted automatically\")]");
sw.WriteLine ("\t\tpublic void Unref () {}");
sw.WriteLine ();
}
finalizer_needed = true;
}
if (dispose != null) {
dispose.GenerateImport (sw);
sw.WriteLine ("\t\tprotected override void Free (IntPtr raw)");
sw.WriteLine ("\t\t{");
sw.WriteLine ("\t\t\t" + dispose.CName + " (raw);");
sw.WriteLine ("\t\t}");
sw.WriteLine ();
if (dispose.IsDeprecated) {
sw.WriteLine ("\t\t[Obsolete(\"" + QualifiedName + " is now freed automatically\")]");
sw.WriteLine ("\t\tpublic void " + dispose.Name + " () {}");
sw.WriteLine ();
}
finalizer_needed = true;
}
if (finalizer_needed) {
sw.WriteLine ("\t\tclass FinalizerInfo {");
sw.WriteLine ("\t\t\tIntPtr handle;");
sw.WriteLine ();
sw.WriteLine ("\t\t\tpublic FinalizerInfo (IntPtr handle)");
sw.WriteLine ("\t\t\t{");
sw.WriteLine ("\t\t\t\tthis.handle = handle;");
sw.WriteLine ("\t\t\t}");
sw.WriteLine ();
sw.WriteLine ("\t\t\tpublic bool Handler ()");
sw.WriteLine ("\t\t\t{");
if (dispose != null)
sw.WriteLine ("\t\t\t\t{0} (handle);", dispose.CName);
else if (unref != null)
sw.WriteLine ("\t\t\t\t{0} (handle);", unref.CName);
sw.WriteLine ("\t\t\t\treturn false;");
sw.WriteLine ("\t\t\t}");
sw.WriteLine ("\t\t}");
sw.WriteLine ();
sw.WriteLine ("\t\t~{0} ()", Name);
sw.WriteLine ("\t\t{");
sw.WriteLine ("\t\t\tif (!Owned)");
sw.WriteLine ("\t\t\t\treturn;");
sw.WriteLine ("\t\t\tFinalizerInfo info = new FinalizerInfo (Handle);");
sw.WriteLine ("\t\t\tGLib.Timeout.Add (50, new GLib.TimeoutHandler (info.Handler));");
sw.WriteLine ("\t\t}");
sw.WriteLine ();
}
#if false
Method copy = Methods ["Copy"] as Method;
if (copy != null && copy.Parameters.Count == 0) {
sw.WriteLine ("\t\tprotected override GLib.Opaque Copy (IntPtr raw)");
sw.WriteLine ("\t\t{");
sw.WriteLine ("\t\t\tGLib.Opaque result = new " + QualifiedName + " (" + copy.CName + " (raw));");
sw.WriteLine ("\t\t\tresult.Owned = true;");
sw.WriteLine ("\t\t\treturn result;");
sw.WriteLine ("\t\t}");
sw.WriteLine ();
}
#endif
sw.WriteLine ("#endregion");
AppendCustom(sw, gen_info.CustomDir);
sw.WriteLine ("\t}");
sw.WriteLine ("}");
sw.Close ();
gen_info.Writer = null;
Statistics.OpaqueCount++;
}
void GetSpecialMethods (out Method ref_, out Method unref, out Method dispose)
{
ref_ = CheckSpecialMethod (GetMethod ("Ref"));
unref = CheckSpecialMethod (GetMethod ("Unref"));
dispose = GetMethod ("Free");
if (dispose == null) {
dispose = GetMethod ("Destroy");
if (dispose == null)
dispose = GetMethod ("Dispose");
}
dispose = CheckSpecialMethod (dispose);
}
Method CheckSpecialMethod (Method method)
{
if (method == null)
return null;
if (method.ReturnType != "void" &&
method.ReturnType != QualifiedName)
return null;
if (method.Signature.ToString () != "")
return null;
methods.Remove (method.Name);
return method;
}
protected override void GenCtors (GenerationInfo gen_info)
{
if (!DisableRawCtor) {
gen_info.Writer.WriteLine("\t\tpublic " + Name + "(IntPtr raw) : base(raw) {}");
gen_info.Writer.WriteLine();
}
base.GenCtors (gen_info);
}
}
}
| |
namespace KabMan.Client
{
partial class XtraForm1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl();
this.checkedListBoxControl1 = new DevExpress.XtraEditors.CheckedListBoxControl();
this.simpleButton2 = new DevExpress.XtraEditors.SimpleButton();
this.simpleButton1 = new DevExpress.XtraEditors.SimpleButton();
this.filterControl1 = new DevExpress.XtraEditors.FilterControl();
this.gridControl1 = new DevExpress.XtraGrid.GridControl();
this.gridView1 = new DevExpress.XtraGrid.Views.Grid.GridView();
this.gridColumn1 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn2 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn3 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn4 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn5 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn6 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn7 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn8 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn9 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn10 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridView2 = new DevExpress.XtraGrid.Views.Grid.GridView();
this.layoutControlGroup1 = new DevExpress.XtraLayout.LayoutControlGroup();
this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem3 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem2 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem4 = new DevExpress.XtraLayout.LayoutControlItem();
this.emptySpaceItem1 = new DevExpress.XtraLayout.EmptySpaceItem();
this.layoutControlItem5 = new DevExpress.XtraLayout.LayoutControlItem();
this.barManager1 = new DevExpress.XtraBars.BarManager(this.components);
this.bar1 = new DevExpress.XtraBars.Bar();
this.barButtonItem1 = new DevExpress.XtraBars.BarButtonItem();
this.barButtonItem2 = new DevExpress.XtraBars.BarButtonItem();
this.barDockControlTop = new DevExpress.XtraBars.BarDockControl();
this.barDockControlBottom = new DevExpress.XtraBars.BarDockControl();
this.barDockControlLeft = new DevExpress.XtraBars.BarDockControl();
this.barDockControlRight = new DevExpress.XtraBars.BarDockControl();
((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit();
this.layoutControl1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.checkedListBoxControl1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.gridControl1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.gridView1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.gridView2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem4)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem5)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.barManager1)).BeginInit();
this.SuspendLayout();
//
// layoutControl1
//
this.layoutControl1.Appearance.DisabledLayoutGroupCaption.ForeColor = System.Drawing.SystemColors.GrayText;
this.layoutControl1.Appearance.DisabledLayoutGroupCaption.Options.UseForeColor = true;
this.layoutControl1.Appearance.DisabledLayoutItem.ForeColor = System.Drawing.SystemColors.GrayText;
this.layoutControl1.Appearance.DisabledLayoutItem.Options.UseForeColor = true;
this.layoutControl1.Controls.Add(this.checkedListBoxControl1);
this.layoutControl1.Controls.Add(this.simpleButton2);
this.layoutControl1.Controls.Add(this.simpleButton1);
this.layoutControl1.Controls.Add(this.filterControl1);
this.layoutControl1.Controls.Add(this.gridControl1);
this.layoutControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.layoutControl1.Location = new System.Drawing.Point(0, 26);
this.layoutControl1.Name = "layoutControl1";
this.layoutControl1.Root = this.layoutControlGroup1;
this.layoutControl1.Size = new System.Drawing.Size(783, 505);
this.layoutControl1.TabIndex = 0;
this.layoutControl1.Text = "layoutControl1";
//
// checkedListBoxControl1
//
this.checkedListBoxControl1.Items.AddRange(new DevExpress.XtraEditors.Controls.CheckedListBoxItem[] {
new DevExpress.XtraEditors.Controls.CheckedListBoxItem("Standort"),
new DevExpress.XtraEditors.Controls.CheckedListBoxItem("OP-Sys"),
new DevExpress.XtraEditors.Controls.CheckedListBoxItem("Port"),
new DevExpress.XtraEditors.Controls.CheckedListBoxItem("Kabel URM-LC"),
new DevExpress.XtraEditors.Controls.CheckedListBoxItem("1HE-Blech"),
new DevExpress.XtraEditors.Controls.CheckedListBoxItem("Kabel Trunk/Multi"),
new DevExpress.XtraEditors.Controls.CheckedListBoxItem("VT-Port"),
new DevExpress.XtraEditors.Controls.CheckedListBoxItem("Patchkabel"),
new DevExpress.XtraEditors.Controls.CheckedListBoxItem("Switch"),
new DevExpress.XtraEditors.Controls.CheckedListBoxItem("Port")});
this.checkedListBoxControl1.Location = new System.Drawing.Point(381, 7);
this.checkedListBoxControl1.Name = "checkedListBoxControl1";
this.checkedListBoxControl1.Size = new System.Drawing.Size(317, 165);
this.checkedListBoxControl1.StyleController = this.layoutControl1;
this.checkedListBoxControl1.TabIndex = 9;
//
// simpleButton2
//
this.simpleButton2.Location = new System.Drawing.Point(709, 40);
this.simpleButton2.Name = "simpleButton2";
this.simpleButton2.Size = new System.Drawing.Size(68, 22);
this.simpleButton2.StyleController = this.layoutControl1;
this.simpleButton2.TabIndex = 8;
this.simpleButton2.Text = "Neu Search";
//
// simpleButton1
//
this.simpleButton1.Location = new System.Drawing.Point(709, 7);
this.simpleButton1.Name = "simpleButton1";
this.simpleButton1.Size = new System.Drawing.Size(68, 22);
this.simpleButton1.StyleController = this.layoutControl1;
this.simpleButton1.TabIndex = 7;
this.simpleButton1.Text = "Search";
//
// filterControl1
//
this.filterControl1.Location = new System.Drawing.Point(7, 7);
this.filterControl1.Name = "filterControl1";
this.filterControl1.Size = new System.Drawing.Size(363, 165);
this.filterControl1.SourceControl = this.gridControl1;
this.filterControl1.TabIndex = 6;
this.filterControl1.Text = "filterControl1";
//
// gridControl1
//
this.gridControl1.Location = new System.Drawing.Point(7, 183);
this.gridControl1.MainView = this.gridView1;
this.gridControl1.Name = "gridControl1";
this.gridControl1.Size = new System.Drawing.Size(770, 316);
this.gridControl1.TabIndex = 4;
this.gridControl1.ViewCollection.AddRange(new DevExpress.XtraGrid.Views.Base.BaseView[] {
this.gridView1,
this.gridView2});
//
// gridView1
//
this.gridView1.Appearance.ColumnFilterButton.BackColor = System.Drawing.Color.Silver;
this.gridView1.Appearance.ColumnFilterButton.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212)))));
this.gridView1.Appearance.ColumnFilterButton.BorderColor = System.Drawing.Color.Silver;
this.gridView1.Appearance.ColumnFilterButton.ForeColor = System.Drawing.Color.Gray;
this.gridView1.Appearance.ColumnFilterButton.Options.UseBackColor = true;
this.gridView1.Appearance.ColumnFilterButton.Options.UseBorderColor = true;
this.gridView1.Appearance.ColumnFilterButton.Options.UseForeColor = true;
this.gridView1.Appearance.ColumnFilterButtonActive.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212)))));
this.gridView1.Appearance.ColumnFilterButtonActive.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(223)))), ((int)(((byte)(223)))));
this.gridView1.Appearance.ColumnFilterButtonActive.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212)))));
this.gridView1.Appearance.ColumnFilterButtonActive.ForeColor = System.Drawing.Color.Blue;
this.gridView1.Appearance.ColumnFilterButtonActive.Options.UseBackColor = true;
this.gridView1.Appearance.ColumnFilterButtonActive.Options.UseBorderColor = true;
this.gridView1.Appearance.ColumnFilterButtonActive.Options.UseForeColor = true;
this.gridView1.Appearance.Empty.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243)))));
this.gridView1.Appearance.Empty.Options.UseBackColor = true;
this.gridView1.Appearance.EvenRow.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(223)))), ((int)(((byte)(223)))));
this.gridView1.Appearance.EvenRow.BackColor2 = System.Drawing.Color.GhostWhite;
this.gridView1.Appearance.EvenRow.ForeColor = System.Drawing.Color.Black;
this.gridView1.Appearance.EvenRow.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.gridView1.Appearance.EvenRow.Options.UseBackColor = true;
this.gridView1.Appearance.EvenRow.Options.UseForeColor = true;
this.gridView1.Appearance.FilterCloseButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200)))));
this.gridView1.Appearance.FilterCloseButton.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(118)))), ((int)(((byte)(170)))), ((int)(((byte)(225)))));
this.gridView1.Appearance.FilterCloseButton.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200)))));
this.gridView1.Appearance.FilterCloseButton.ForeColor = System.Drawing.Color.Black;
this.gridView1.Appearance.FilterCloseButton.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.gridView1.Appearance.FilterCloseButton.Options.UseBackColor = true;
this.gridView1.Appearance.FilterCloseButton.Options.UseBorderColor = true;
this.gridView1.Appearance.FilterCloseButton.Options.UseForeColor = true;
this.gridView1.Appearance.FilterPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(28)))), ((int)(((byte)(80)))), ((int)(((byte)(135)))));
this.gridView1.Appearance.FilterPanel.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200)))));
this.gridView1.Appearance.FilterPanel.ForeColor = System.Drawing.Color.White;
this.gridView1.Appearance.FilterPanel.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.gridView1.Appearance.FilterPanel.Options.UseBackColor = true;
this.gridView1.Appearance.FilterPanel.Options.UseForeColor = true;
this.gridView1.Appearance.FixedLine.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(58)))), ((int)(((byte)(58)))));
this.gridView1.Appearance.FixedLine.Options.UseBackColor = true;
this.gridView1.Appearance.FocusedCell.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(225)))));
this.gridView1.Appearance.FocusedCell.ForeColor = System.Drawing.Color.Black;
this.gridView1.Appearance.FocusedCell.Options.UseBackColor = true;
this.gridView1.Appearance.FocusedCell.Options.UseForeColor = true;
this.gridView1.Appearance.FocusedRow.BackColor = System.Drawing.Color.Navy;
this.gridView1.Appearance.FocusedRow.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(50)))), ((int)(((byte)(50)))), ((int)(((byte)(178)))));
this.gridView1.Appearance.FocusedRow.ForeColor = System.Drawing.Color.White;
this.gridView1.Appearance.FocusedRow.Options.UseBackColor = true;
this.gridView1.Appearance.FocusedRow.Options.UseForeColor = true;
this.gridView1.Appearance.FooterPanel.BackColor = System.Drawing.Color.Silver;
this.gridView1.Appearance.FooterPanel.BorderColor = System.Drawing.Color.Silver;
this.gridView1.Appearance.FooterPanel.ForeColor = System.Drawing.Color.Black;
this.gridView1.Appearance.FooterPanel.Options.UseBackColor = true;
this.gridView1.Appearance.FooterPanel.Options.UseBorderColor = true;
this.gridView1.Appearance.FooterPanel.Options.UseForeColor = true;
this.gridView1.Appearance.GroupButton.BackColor = System.Drawing.Color.Silver;
this.gridView1.Appearance.GroupButton.BorderColor = System.Drawing.Color.Silver;
this.gridView1.Appearance.GroupButton.ForeColor = System.Drawing.Color.Black;
this.gridView1.Appearance.GroupButton.Options.UseBackColor = true;
this.gridView1.Appearance.GroupButton.Options.UseBorderColor = true;
this.gridView1.Appearance.GroupButton.Options.UseForeColor = true;
this.gridView1.Appearance.GroupFooter.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(202)))), ((int)(((byte)(202)))), ((int)(((byte)(202)))));
this.gridView1.Appearance.GroupFooter.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(202)))), ((int)(((byte)(202)))), ((int)(((byte)(202)))));
this.gridView1.Appearance.GroupFooter.ForeColor = System.Drawing.Color.Black;
this.gridView1.Appearance.GroupFooter.Options.UseBackColor = true;
this.gridView1.Appearance.GroupFooter.Options.UseBorderColor = true;
this.gridView1.Appearance.GroupFooter.Options.UseForeColor = true;
this.gridView1.Appearance.GroupPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(110)))), ((int)(((byte)(165)))));
this.gridView1.Appearance.GroupPanel.BackColor2 = System.Drawing.Color.White;
this.gridView1.Appearance.GroupPanel.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold);
this.gridView1.Appearance.GroupPanel.ForeColor = System.Drawing.Color.White;
this.gridView1.Appearance.GroupPanel.Options.UseBackColor = true;
this.gridView1.Appearance.GroupPanel.Options.UseFont = true;
this.gridView1.Appearance.GroupPanel.Options.UseForeColor = true;
this.gridView1.Appearance.GroupRow.BackColor = System.Drawing.Color.Gray;
this.gridView1.Appearance.GroupRow.ForeColor = System.Drawing.Color.Silver;
this.gridView1.Appearance.GroupRow.Options.UseBackColor = true;
this.gridView1.Appearance.GroupRow.Options.UseForeColor = true;
this.gridView1.Appearance.HeaderPanel.BackColor = System.Drawing.Color.Silver;
this.gridView1.Appearance.HeaderPanel.BorderColor = System.Drawing.Color.Silver;
this.gridView1.Appearance.HeaderPanel.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold);
this.gridView1.Appearance.HeaderPanel.ForeColor = System.Drawing.Color.Black;
this.gridView1.Appearance.HeaderPanel.Options.UseBackColor = true;
this.gridView1.Appearance.HeaderPanel.Options.UseBorderColor = true;
this.gridView1.Appearance.HeaderPanel.Options.UseFont = true;
this.gridView1.Appearance.HeaderPanel.Options.UseForeColor = true;
this.gridView1.Appearance.HideSelectionRow.BackColor = System.Drawing.Color.Gray;
this.gridView1.Appearance.HideSelectionRow.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200)))));
this.gridView1.Appearance.HideSelectionRow.Options.UseBackColor = true;
this.gridView1.Appearance.HideSelectionRow.Options.UseForeColor = true;
this.gridView1.Appearance.HorzLine.BackColor = System.Drawing.Color.Silver;
this.gridView1.Appearance.HorzLine.Options.UseBackColor = true;
this.gridView1.Appearance.OddRow.BackColor = System.Drawing.Color.White;
this.gridView1.Appearance.OddRow.BackColor2 = System.Drawing.Color.White;
this.gridView1.Appearance.OddRow.ForeColor = System.Drawing.Color.Black;
this.gridView1.Appearance.OddRow.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.BackwardDiagonal;
this.gridView1.Appearance.OddRow.Options.UseBackColor = true;
this.gridView1.Appearance.OddRow.Options.UseForeColor = true;
this.gridView1.Appearance.Preview.BackColor = System.Drawing.Color.White;
this.gridView1.Appearance.Preview.ForeColor = System.Drawing.Color.Navy;
this.gridView1.Appearance.Preview.Options.UseBackColor = true;
this.gridView1.Appearance.Preview.Options.UseForeColor = true;
this.gridView1.Appearance.Row.BackColor = System.Drawing.Color.White;
this.gridView1.Appearance.Row.ForeColor = System.Drawing.Color.Black;
this.gridView1.Appearance.Row.Options.UseBackColor = true;
this.gridView1.Appearance.Row.Options.UseForeColor = true;
this.gridView1.Appearance.RowSeparator.BackColor = System.Drawing.Color.White;
this.gridView1.Appearance.RowSeparator.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243)))));
this.gridView1.Appearance.RowSeparator.Options.UseBackColor = true;
this.gridView1.Appearance.SelectedRow.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(10)))), ((int)(((byte)(10)))), ((int)(((byte)(138)))));
this.gridView1.Appearance.SelectedRow.ForeColor = System.Drawing.Color.White;
this.gridView1.Appearance.SelectedRow.Options.UseBackColor = true;
this.gridView1.Appearance.SelectedRow.Options.UseForeColor = true;
this.gridView1.Appearance.VertLine.BackColor = System.Drawing.Color.Silver;
this.gridView1.Appearance.VertLine.Options.UseBackColor = true;
this.gridView1.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] {
this.gridColumn1,
this.gridColumn2,
this.gridColumn3,
this.gridColumn4,
this.gridColumn5,
this.gridColumn6,
this.gridColumn7,
this.gridColumn8,
this.gridColumn9,
this.gridColumn10});
this.gridView1.GridControl = this.gridControl1;
this.gridView1.Name = "gridView1";
this.gridView1.OptionsView.EnableAppearanceEvenRow = true;
this.gridView1.OptionsView.EnableAppearanceOddRow = true;
this.gridView1.OptionsView.ShowGroupPanel = false;
this.gridView1.OptionsView.ShowIndicator = false;
//
// gridColumn1
//
this.gridColumn1.Caption = "Standort";
this.gridColumn1.Name = "gridColumn1";
this.gridColumn1.Visible = true;
this.gridColumn1.VisibleIndex = 0;
//
// gridColumn2
//
this.gridColumn2.Caption = "OP-Sys";
this.gridColumn2.Name = "gridColumn2";
this.gridColumn2.Visible = true;
this.gridColumn2.VisibleIndex = 1;
//
// gridColumn3
//
this.gridColumn3.Caption = "Port";
this.gridColumn3.Name = "gridColumn3";
this.gridColumn3.Visible = true;
this.gridColumn3.VisibleIndex = 2;
//
// gridColumn4
//
this.gridColumn4.Caption = "Kabel URM-LC";
this.gridColumn4.Name = "gridColumn4";
this.gridColumn4.Visible = true;
this.gridColumn4.VisibleIndex = 3;
//
// gridColumn5
//
this.gridColumn5.Caption = "1HE-Blech";
this.gridColumn5.Name = "gridColumn5";
this.gridColumn5.Visible = true;
this.gridColumn5.VisibleIndex = 4;
//
// gridColumn6
//
this.gridColumn6.Caption = "Kabel";
this.gridColumn6.Name = "gridColumn6";
this.gridColumn6.Visible = true;
this.gridColumn6.VisibleIndex = 5;
//
// gridColumn7
//
this.gridColumn7.Caption = "VT-Port";
this.gridColumn7.Name = "gridColumn7";
this.gridColumn7.Visible = true;
this.gridColumn7.VisibleIndex = 6;
//
// gridColumn8
//
this.gridColumn8.Caption = "Patchkabel";
this.gridColumn8.Name = "gridColumn8";
this.gridColumn8.Visible = true;
this.gridColumn8.VisibleIndex = 7;
//
// gridColumn9
//
this.gridColumn9.Caption = "Switch";
this.gridColumn9.Name = "gridColumn9";
this.gridColumn9.Visible = true;
this.gridColumn9.VisibleIndex = 8;
//
// gridColumn10
//
this.gridColumn10.Caption = "Port";
this.gridColumn10.Name = "gridColumn10";
this.gridColumn10.Visible = true;
this.gridColumn10.VisibleIndex = 9;
//
// gridView2
//
this.gridView2.GridControl = this.gridControl1;
this.gridView2.Name = "gridView2";
//
// layoutControlGroup1
//
this.layoutControlGroup1.CustomizationFormText = "layoutControlGroup1";
this.layoutControlGroup1.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] {
this.layoutControlItem1,
this.layoutControlItem3,
this.layoutControlItem2,
this.layoutControlItem4,
this.emptySpaceItem1,
this.layoutControlItem5});
this.layoutControlGroup1.Location = new System.Drawing.Point(0, 0);
this.layoutControlGroup1.Name = "layoutControlGroup1";
this.layoutControlGroup1.Size = new System.Drawing.Size(783, 505);
this.layoutControlGroup1.Spacing = new DevExpress.XtraLayout.Utils.Padding(0, 0, 0, 0);
this.layoutControlGroup1.Text = "layoutControlGroup1";
this.layoutControlGroup1.TextVisible = false;
//
// layoutControlItem1
//
this.layoutControlItem1.Control = this.gridControl1;
this.layoutControlItem1.CustomizationFormText = "layoutControlItem1";
this.layoutControlItem1.Location = new System.Drawing.Point(0, 176);
this.layoutControlItem1.Name = "layoutControlItem1";
this.layoutControlItem1.Size = new System.Drawing.Size(781, 327);
this.layoutControlItem1.Text = "layoutControlItem1";
this.layoutControlItem1.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem1.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem1.TextToControlDistance = 0;
this.layoutControlItem1.TextVisible = false;
//
// layoutControlItem3
//
this.layoutControlItem3.Control = this.filterControl1;
this.layoutControlItem3.CustomizationFormText = "layoutControlItem3";
this.layoutControlItem3.Location = new System.Drawing.Point(0, 0);
this.layoutControlItem3.Name = "layoutControlItem3";
this.layoutControlItem3.Size = new System.Drawing.Size(374, 176);
this.layoutControlItem3.Text = "layoutControlItem3";
this.layoutControlItem3.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem3.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem3.TextToControlDistance = 0;
this.layoutControlItem3.TextVisible = false;
//
// layoutControlItem2
//
this.layoutControlItem2.Control = this.simpleButton1;
this.layoutControlItem2.CustomizationFormText = "layoutControlItem2";
this.layoutControlItem2.Location = new System.Drawing.Point(702, 0);
this.layoutControlItem2.Name = "layoutControlItem2";
this.layoutControlItem2.Size = new System.Drawing.Size(79, 33);
this.layoutControlItem2.Text = "layoutControlItem2";
this.layoutControlItem2.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem2.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem2.TextToControlDistance = 0;
this.layoutControlItem2.TextVisible = false;
//
// layoutControlItem4
//
this.layoutControlItem4.Control = this.simpleButton2;
this.layoutControlItem4.CustomizationFormText = "layoutControlItem4";
this.layoutControlItem4.Location = new System.Drawing.Point(702, 33);
this.layoutControlItem4.Name = "layoutControlItem4";
this.layoutControlItem4.Size = new System.Drawing.Size(79, 33);
this.layoutControlItem4.Text = "layoutControlItem4";
this.layoutControlItem4.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem4.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem4.TextToControlDistance = 0;
this.layoutControlItem4.TextVisible = false;
//
// emptySpaceItem1
//
this.emptySpaceItem1.CustomizationFormText = "emptySpaceItem1";
this.emptySpaceItem1.Location = new System.Drawing.Point(702, 66);
this.emptySpaceItem1.Name = "emptySpaceItem1";
this.emptySpaceItem1.Size = new System.Drawing.Size(79, 110);
this.emptySpaceItem1.Text = "emptySpaceItem1";
this.emptySpaceItem1.TextSize = new System.Drawing.Size(0, 0);
//
// layoutControlItem5
//
this.layoutControlItem5.Control = this.checkedListBoxControl1;
this.layoutControlItem5.CustomizationFormText = "layoutControlItem5";
this.layoutControlItem5.Location = new System.Drawing.Point(374, 0);
this.layoutControlItem5.Name = "layoutControlItem5";
this.layoutControlItem5.Size = new System.Drawing.Size(328, 176);
this.layoutControlItem5.Text = "layoutControlItem5";
this.layoutControlItem5.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem5.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem5.TextToControlDistance = 0;
this.layoutControlItem5.TextVisible = false;
//
// barManager1
//
this.barManager1.Bars.AddRange(new DevExpress.XtraBars.Bar[] {
this.bar1});
this.barManager1.DockControls.Add(this.barDockControlTop);
this.barManager1.DockControls.Add(this.barDockControlBottom);
this.barManager1.DockControls.Add(this.barDockControlLeft);
this.barManager1.DockControls.Add(this.barDockControlRight);
this.barManager1.Form = this;
this.barManager1.Items.AddRange(new DevExpress.XtraBars.BarItem[] {
this.barButtonItem1,
this.barButtonItem2});
this.barManager1.MaxItemId = 2;
//
// bar1
//
this.bar1.BarName = "Tools";
this.bar1.DockCol = 0;
this.bar1.DockRow = 0;
this.bar1.DockStyle = DevExpress.XtraBars.BarDockStyle.Top;
this.bar1.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.barButtonItem1),
new DevExpress.XtraBars.LinkPersistInfo(this.barButtonItem2, true)});
this.bar1.OptionsBar.AllowQuickCustomization = false;
this.bar1.OptionsBar.DrawDragBorder = false;
this.bar1.OptionsBar.UseWholeRow = true;
this.bar1.Text = "Tools";
//
// barButtonItem1
//
this.barButtonItem1.Caption = "Export to Excel";
this.barButtonItem1.Id = 0;
this.barButtonItem1.Name = "barButtonItem1";
//
// barButtonItem2
//
this.barButtonItem2.Caption = "Close";
this.barButtonItem2.Glyph = global::KabMan.Client.Properties.Resources.exit;
this.barButtonItem2.Id = 1;
this.barButtonItem2.Name = "barButtonItem2";
this.barButtonItem2.PaintStyle = DevExpress.XtraBars.BarItemPaintStyle.CaptionGlyph;
//
// XtraForm1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(783, 531);
this.Controls.Add(this.layoutControl1);
this.Controls.Add(this.barDockControlLeft);
this.Controls.Add(this.barDockControlRight);
this.Controls.Add(this.barDockControlBottom);
this.Controls.Add(this.barDockControlTop);
this.Name = "XtraForm1";
this.Text = "Report";
((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit();
this.layoutControl1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.checkedListBoxControl1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.gridControl1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.gridView1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.gridView2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem4)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem5)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.barManager1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DevExpress.XtraLayout.LayoutControl layoutControl1;
private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup1;
private DevExpress.XtraGrid.GridControl gridControl1;
private DevExpress.XtraGrid.Views.Grid.GridView gridView1;
private DevExpress.XtraGrid.Views.Grid.GridView gridView2;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn1;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn2;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn3;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn4;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn5;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn6;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn7;
private DevExpress.XtraBars.BarManager barManager1;
private DevExpress.XtraBars.Bar bar1;
private DevExpress.XtraBars.BarDockControl barDockControlTop;
private DevExpress.XtraBars.BarDockControl barDockControlBottom;
private DevExpress.XtraBars.BarDockControl barDockControlLeft;
private DevExpress.XtraBars.BarDockControl barDockControlRight;
private DevExpress.XtraBars.BarButtonItem barButtonItem1;
private DevExpress.XtraBars.BarButtonItem barButtonItem2;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn8;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn9;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn10;
private DevExpress.XtraEditors.FilterControl filterControl1;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem3;
private DevExpress.XtraEditors.SimpleButton simpleButton2;
private DevExpress.XtraEditors.SimpleButton simpleButton1;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem2;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem4;
private DevExpress.XtraLayout.EmptySpaceItem emptySpaceItem1;
private DevExpress.XtraEditors.CheckedListBoxControl checkedListBoxControl1;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem5;
}
}
| |
/*
* Velcro Physics:
* Copyright (c) 2017 Ian Qvist
*
* Original source Box2D:
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System;
using System.Diagnostics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using VelcroPhysics.Collision.Shapes;
using VelcroPhysics.Dynamics;
using VelcroPhysics.Factories;
using VelcroPhysics.MonoGame.Samples.Testbed.Framework;
using VelcroPhysics.Shared;
using VelcroPhysics.Utilities;
namespace VelcroPhysics.MonoGame.Samples.Testbed.Tests
{
/// <summary>
/// This tests stacking. It also shows how to use World.Query()
/// and AABB.TestOverlap().
/// This callback is called by World.QueryAABB(). We find all the fixtures
/// that overlap an AABB. Of those, we use AABB.TestOverlap() to determine which fixtures
/// overlap a circle. Up to 4 overlapped fixtures will be highlighted with a yellow border.
/// </summary>
public class PolyShapesCallback
{
private const int MaxCount = 4;
private int _count;
internal CircleShape Circle = new CircleShape(0, 0);
internal DebugView.DebugView DebugDraw;
internal Transform Transform;
private void DrawFixture(Fixture fixture)
{
Color color = new Color(0.95f, 0.95f, 0.6f);
Transform xf;
fixture.Body.GetTransform(out xf);
switch (fixture.Shape.ShapeType)
{
case ShapeType.Circle:
{
CircleShape circle = (CircleShape)fixture.Shape;
Vector2 center = MathUtils.Mul(ref xf, circle.Position);
float radius = circle.Radius;
DebugDraw.DrawSolidCircle(center, radius, Vector2.Zero, color);
}
break;
case ShapeType.Polygon:
{
PolygonShape poly = (PolygonShape)fixture.Shape;
int vertexCount = poly.Vertices.Count;
Debug.Assert(vertexCount <= Settings.MaxPolygonVertices);
Vector2[] vertices = new Vector2[Settings.MaxPolygonVertices];
for (int i = 0; i < vertexCount; ++i)
{
vertices[i] = MathUtils.Mul(ref xf, poly.Vertices[i]);
}
DebugDraw.DrawSolidPolygon(vertices, vertexCount, color);
}
break;
}
}
/// <summary>
/// Called for each fixture found in the query AABB.
/// </summary>
/// <param name="fixture">The fixture.</param>
/// <returns>false to terminate the query.</returns>
public bool ReportFixture(Fixture fixture)
{
if (_count == MaxCount)
{
return false;
}
Body body = fixture.Body;
Shape shape = fixture.Shape;
Transform xf;
body.GetTransform(out xf);
bool overlap = Collision.Narrowphase.Collision.TestOverlap(shape, 0, Circle, 0, ref xf, ref Transform);
if (overlap)
{
DrawFixture(fixture);
++_count;
}
return true;
}
}
public class PolyShapesTest : Test
{
private const int MaxBodies = 256;
private readonly Body[] _bodies = new Body[MaxBodies];
private readonly CircleShape _circle = new CircleShape(0, 0);
private readonly PolygonShape[] _polygons = new PolygonShape[4];
private int _bodyIndex;
private PolyShapesTest()
{
// Ground body
BodyFactory.CreateEdge(World, new Vector2(-40.0f, 0.0f), new Vector2(40.0f, 0.0f));
{
Vertices vertices = new Vertices(3);
vertices.Add(new Vector2(-0.5f, 0.0f));
vertices.Add(new Vector2(0.5f, 0.0f));
vertices.Add(new Vector2(0.0f, 1.5f));
_polygons[0] = new PolygonShape(vertices, 1);
}
{
Vertices vertices3 = new Vertices(3);
vertices3.Add(new Vector2(-0.1f, 0.0f));
vertices3.Add(new Vector2(0.1f, 0.0f));
vertices3.Add(new Vector2(0.0f, 1.5f));
_polygons[1] = new PolygonShape(vertices3, 1);
}
{
const float w = 1.0f;
float b = w / (2.0f + (float)Math.Sqrt(2.0));
float s = (float)Math.Sqrt(2.0) * b;
Vertices vertices8 = new Vertices(8);
vertices8.Add(new Vector2(0.5f * s, 0.0f));
vertices8.Add(new Vector2(0.5f * w, b));
vertices8.Add(new Vector2(0.5f * w, b + s));
vertices8.Add(new Vector2(0.5f * s, w));
vertices8.Add(new Vector2(-0.5f * s, w));
vertices8.Add(new Vector2(-0.5f * w, b + s));
vertices8.Add(new Vector2(-0.5f * w, b));
vertices8.Add(new Vector2(-0.5f * s, 0.0f));
_polygons[2] = new PolygonShape(vertices8, 1);
}
{
Vertices box = PolygonUtils.CreateRectangle(0.5f, 0.5f);
_polygons[3] = new PolygonShape(box, 1);
}
{
_circle.Radius = 0.5f;
}
_bodyIndex = 0;
}
private void Create(int index)
{
if (_bodies[_bodyIndex] != null)
{
World.RemoveBody(_bodies[_bodyIndex]);
_bodies[_bodyIndex] = null;
}
_bodies[_bodyIndex] = BodyFactory.CreateBody(World);
_bodies[_bodyIndex].BodyType = BodyType.Dynamic;
float x = Rand.RandomFloat(-2.0f, 2.0f);
_bodies[_bodyIndex].Position = new Vector2(x, 10.0f);
_bodies[_bodyIndex].Rotation = Rand.RandomFloat(-Settings.Pi, Settings.Pi);
if (index == 4)
{
_bodies[_bodyIndex].AngularDamping = 0.02f;
}
if (index < 4)
{
Fixture fixture = _bodies[_bodyIndex].CreateFixture(_polygons[index]);
fixture.Friction = 0.3f;
}
else
{
Fixture fixture = _bodies[_bodyIndex].CreateFixture(_circle);
fixture.Friction = 0.3f;
}
_bodyIndex = (_bodyIndex + 1) % MaxBodies;
}
private void DestroyBody()
{
for (int i = 0; i < MaxBodies; ++i)
{
if (_bodies[i] != null)
{
World.RemoveBody(_bodies[i]);
_bodies[i] = null;
return;
}
}
}
public override void Keyboard(KeyboardManager keyboardManager)
{
if (keyboardManager.IsNewKeyPress(Keys.D1))
{
Create(0);
}
if (keyboardManager.IsNewKeyPress(Keys.D2))
{
Create(1);
}
if (keyboardManager.IsNewKeyPress(Keys.D3))
{
Create(2);
}
if (keyboardManager.IsNewKeyPress(Keys.D4))
{
Create(3);
}
if (keyboardManager.IsNewKeyPress(Keys.D5))
{
Create(4);
}
if (keyboardManager.IsNewKeyPress(Keys.A))
{
for (int i = 0; i < MaxBodies; i += 2)
{
if (_bodies[i] != null)
{
bool enabled = _bodies[i].Enabled;
_bodies[i].Enabled = !enabled;
}
}
}
if (keyboardManager.IsNewKeyPress(Keys.D))
{
DestroyBody();
}
base.Keyboard(keyboardManager);
}
public override void Update(GameSettings settings, GameTime gameTime)
{
base.Update(settings, gameTime);
PolyShapesCallback callback = new PolyShapesCallback();
callback.Circle.Radius = 2.0f;
callback.Circle.Position = new Vector2(0.0f, 1.1f);
callback.Transform.SetIdentity();
callback.DebugDraw = DebugView;
AABB aabb;
callback.Circle.ComputeAABB(ref callback.Transform, 0, out aabb);
DebugView.BeginCustomDraw(ref GameInstance.Projection, ref GameInstance.View);
World.QueryAABB(callback.ReportFixture, ref aabb);
Color color = new Color(0.4f, 0.7f, 0.8f);
DebugView.DrawCircle(callback.Circle.Position, callback.Circle.Radius, color);
DebugView.EndCustomDraw();
DrawString("Press 1-5 to drop stuff");
DrawString("Press a to (de)activate some bodies");
DrawString("Press d to destroy a body");
}
internal static Test Create()
{
return new PolyShapesTest();
}
}
}
| |
//
// OAuth framework for TweetStation
//
// Author;
// Miguel de Icaza (miguel@gnome.org)
//
// Possible optimizations:
// Instead of sorting every time, keep things sorted
// Reuse the same dictionary, update the values
//
// Copyright 2010 Miguel de Icaza
//
// 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.Text;
using System.Net;
using System.Web;
using System.Security.Cryptography;
using ServiceStack.ServiceModel;
namespace ServiceStack.ServiceInterface.Auth
{
//
// Configuration information for an OAuth client
//
//public class OAuthConfig {
// keys, callbacks
//public string ConsumerKey, Callback, ConsumerSecret;
// Urls
//public string RequestTokenUrl, AccessTokenUrl, AuthorizeUrl;
//}
//
// The authorizer uses a provider and an optional xAuth user/password
// to perform the OAuth authorization process as well as signing
// outgoing http requests
//
// To get an access token, you use these methods in the workflow:
// AcquireRequestToken
// AuthorizeUser
//
// These static methods only require the access token:
// AuthorizeRequest
// AuthorizeTwitPic
//
public class OAuthAuthorizer
{
// Settable by the user
public string xAuthUsername, xAuthPassword;
OAuthProvider provider;
public string RequestToken, RequestTokenSecret;
public string AuthorizationToken, AuthorizationVerifier;
public string AccessToken, AccessTokenSecret;//, AccessScreenName;
//public long AccessId;
public Dictionary<string, string> AuthInfo = new Dictionary<string, string>();
// Constructor for standard OAuth
public OAuthAuthorizer(OAuthProvider provider)
{
this.provider = provider;
}
static Random random = new Random();
static DateTime UnixBaseTime = new DateTime(1970, 1, 1);
// 16-byte lower-case or digit string
static string MakeNonce()
{
var ret = new char[16];
for (int i = 0; i < ret.Length; i++)
{
int n = random.Next(35);
if (n < 10)
ret[i] = (char)(n + '0');
else
ret[i] = (char)(n - 10 + 'a');
}
return new string(ret);
}
static string MakeTimestamp()
{
return ((long)(DateTime.UtcNow - UnixBaseTime).TotalSeconds).ToString();
}
// Makes an OAuth signature out of the HTTP method, the base URI and the headers
static string MakeSignature(string method, string base_uri, Dictionary<string, string> headers)
{
var items = from k in headers.Keys
orderby k
select k + "%3D" + OAuthUtils.PercentEncode(headers[k]);
return method + "&" + OAuthUtils.PercentEncode(base_uri) + "&" +
string.Join("%26", items.ToArray());
}
static string MakeSigningKey(string consumerSecret, string oauthTokenSecret)
{
return OAuthUtils.PercentEncode(consumerSecret) + "&" + (oauthTokenSecret != null ? OAuthUtils.PercentEncode(oauthTokenSecret) : "");
}
static string MakeOAuthSignature(string compositeSigningKey, string signatureBase)
{
var sha1 = new HMACSHA1(Encoding.UTF8.GetBytes(compositeSigningKey));
return Convert.ToBase64String(sha1.ComputeHash(Encoding.UTF8.GetBytes(signatureBase)));
}
static string HeadersToOAuth(Dictionary<string, string> headers)
{
return "OAuth " + String.Join(",", (from x in headers.Keys select String.Format("{0}=\"{1}\"", x, headers[x])).ToArray());
}
public bool AcquireRequestToken()
{
var headers = new Dictionary<string, string>() {
{ "oauth_callback", OAuthUtils.PercentEncode (provider.CallbackUrl) },
{ "oauth_consumer_key", provider.ConsumerKey },
{ "oauth_nonce", MakeNonce () },
{ "oauth_signature_method", "HMAC-SHA1" },
{ "oauth_timestamp", MakeTimestamp () },
{ "oauth_version", "1.0" }};
string signature = MakeSignature("POST", provider.RequestTokenUrl, headers);
string compositeSigningKey = MakeSigningKey(provider.ConsumerSecret, null);
string oauth_signature = MakeOAuthSignature(compositeSigningKey, signature);
var wc = new WebClient();
headers.Add("oauth_signature", OAuthUtils.PercentEncode(oauth_signature));
wc.Headers[HttpRequestHeader.Authorization] = HeadersToOAuth(headers);
try
{
var result = HttpUtility.ParseQueryString(wc.UploadString(new Uri(provider.RequestTokenUrl), ""));
if (result["oauth_callback_confirmed"] != null)
{
RequestToken = result["oauth_token"];
RequestTokenSecret = result["oauth_token_secret"];
return true;
}
}
catch (Exception e)
{
Console.WriteLine(e);
// fallthrough for errors
}
return false;
}
// Invoked after the user has authorized us
//
// TODO: this should return the stream error for invalid passwords instead of
// just true/false.
public bool AcquireAccessToken()
{
var headers = new Dictionary<string, string>() {
{ "oauth_consumer_key", provider.ConsumerKey },
{ "oauth_nonce", MakeNonce () },
{ "oauth_signature_method", "HMAC-SHA1" },
{ "oauth_timestamp", MakeTimestamp () },
{ "oauth_version", "1.0" }};
var content = "";
if (xAuthUsername == null)
{
headers.Add("oauth_token", OAuthUtils.PercentEncode(AuthorizationToken));
headers.Add("oauth_verifier", OAuthUtils.PercentEncode(AuthorizationVerifier));
}
else
{
headers.Add("x_auth_username", OAuthUtils.PercentEncode(xAuthUsername));
headers.Add("x_auth_password", OAuthUtils.PercentEncode(xAuthPassword));
headers.Add("x_auth_mode", "client_auth");
content = String.Format("x_auth_mode=client_auth&x_auth_password={0}&x_auth_username={1}", OAuthUtils.PercentEncode(xAuthPassword), OAuthUtils.PercentEncode(xAuthUsername));
}
string signature = MakeSignature("POST", provider.AccessTokenUrl, headers);
string compositeSigningKey = MakeSigningKey(provider.ConsumerSecret, RequestTokenSecret);
string oauth_signature = MakeOAuthSignature(compositeSigningKey, signature);
var wc = new WebClient();
headers.Add("oauth_signature", OAuthUtils.PercentEncode(oauth_signature));
if (xAuthUsername != null)
{
headers.Remove("x_auth_username");
headers.Remove("x_auth_password");
headers.Remove("x_auth_mode");
}
wc.Headers[HttpRequestHeader.Authorization] = HeadersToOAuth(headers);
try
{
var result = HttpUtility.ParseQueryString(wc.UploadString(new Uri(provider.AccessTokenUrl), content));
if (result["oauth_token"] != null)
{
AccessToken = result["oauth_token"];
AccessTokenSecret = result["oauth_token_secret"];
AuthInfo = result.ToDictionary();
return true;
}
}
catch (WebException e)
{
var x = e.Response.GetResponseStream();
var j = new System.IO.StreamReader(x);
Console.WriteLine(j.ReadToEnd());
Console.WriteLine(e);
// fallthrough for errors
}
return false;
}
//
// Assign the result to the Authorization header, like this:
// request.Headers [HttpRequestHeader.Authorization] = AuthorizeRequest (...)
//
public static string AuthorizeRequest(OAuthProvider provider, string oauthToken, string oauthTokenSecret, string method, Uri uri, string data)
{
var headers = new Dictionary<string, string>() {
{ "oauth_consumer_key", provider.ConsumerKey },
{ "oauth_nonce", MakeNonce () },
{ "oauth_signature_method", "HMAC-SHA1" },
{ "oauth_timestamp", MakeTimestamp () },
{ "oauth_token", oauthToken },
{ "oauth_version", "1.0" }};
var signatureHeaders = new Dictionary<string, string>(headers);
// Add the data and URL query string to the copy of the headers for computing the signature
if (data != null && data != "")
{
var parsed = HttpUtility.ParseQueryString(data);
foreach (string k in parsed.Keys)
{
signatureHeaders.Add(k, OAuthUtils.PercentEncode(parsed[k]));
}
}
var nvc = HttpUtility.ParseQueryString(uri.Query);
foreach (string key in nvc)
{
if (key != null)
signatureHeaders.Add(key, OAuthUtils.PercentEncode(nvc[key]));
}
string signature = MakeSignature(method, uri.GetLeftPart(UriPartial.Path), signatureHeaders);
string compositeSigningKey = MakeSigningKey(provider.ConsumerSecret, oauthTokenSecret);
string oauth_signature = MakeOAuthSignature(compositeSigningKey, signature);
headers.Add("oauth_signature", OAuthUtils.PercentEncode(oauth_signature));
return HeadersToOAuth(headers);
}
//
// Used to authorize an HTTP request going to TwitPic
//
public static void AuthorizeTwitPic(OAuthProvider provider, HttpWebRequest wc, string oauthToken, string oauthTokenSecret)
{
var headers = new Dictionary<string, string>() {
{ "oauth_consumer_key", provider.ConsumerKey },
{ "oauth_nonce", MakeNonce () },
{ "oauth_signature_method", "HMAC-SHA1" },
{ "oauth_timestamp", MakeTimestamp () },
{ "oauth_token", oauthToken },
{ "oauth_version", "1.0" },
//{ "realm", "http://api.twitter.com" }
};
string signurl = "http://api.twitter.com/1/account/verify_credentials.xml";
// The signature is not done against the *actual* url, it is done against the verify_credentials.json one
string signature = MakeSignature("GET", signurl, headers);
string compositeSigningKey = MakeSigningKey(provider.ConsumerSecret, oauthTokenSecret);
string oauth_signature = MakeOAuthSignature(compositeSigningKey, signature);
headers.Add("oauth_signature", OAuthUtils.PercentEncode(oauth_signature));
//Util.Log ("Headers: " + HeadersToOAuth (headers));
wc.Headers.Add("X-Verify-Credentials-Authorization", HeadersToOAuth(headers));
wc.Headers.Add("X-Auth-Service-Provider", signurl);
}
}
public static class OAuthUtils
{
//
// This url encoder is different than regular Url encoding found in .NET
// as it is used to compute the signature based on a url. Every document
// on the web omits this little detail leading to wasting everyone's time.
//
// This has got to be one of the lamest specs and requirements ever produced
//
public static string PercentEncode(string s)
{
var sb = new StringBuilder();
foreach (byte c in Encoding.UTF8.GetBytes(s))
{
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.' || c == '~')
sb.Append((char)c);
else
{
sb.AppendFormat("%{0:X2}", c);
}
}
return sb.ToString();
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.IronPythonTools.Interpreter;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Parsing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace TestUtilities {
public class PythonPaths {
private static readonly List<PythonInterpreterInformation> _foundInRegistry = PythonRegistrySearch
.PerformDefaultSearch()
.Where(pii => pii.Configuration.Id.Contains("PythonCore|") || pii.Configuration.Id.Contains("ContinuumAnalytics|"))
.ToList();
public static readonly PythonVersion Python27 = GetCPythonVersion(PythonLanguageVersion.V27, InterpreterArchitecture.x86);
public static readonly PythonVersion Python35 = GetCPythonVersion(PythonLanguageVersion.V35, InterpreterArchitecture.x86);
public static readonly PythonVersion Python36 = GetCPythonVersion(PythonLanguageVersion.V36, InterpreterArchitecture.x86);
public static readonly PythonVersion Python37 = GetCPythonVersion(PythonLanguageVersion.V37, InterpreterArchitecture.x86);
public static readonly PythonVersion Python38 = GetCPythonVersion(PythonLanguageVersion.V38, InterpreterArchitecture.x86);
public static readonly PythonVersion IronPython27 = GetIronPythonVersion(false);
public static readonly PythonVersion Python27_x64 = GetCPythonVersion(PythonLanguageVersion.V27, InterpreterArchitecture.x64);
public static readonly PythonVersion Python35_x64 = GetCPythonVersion(PythonLanguageVersion.V35, InterpreterArchitecture.x64);
public static readonly PythonVersion Python36_x64 = GetCPythonVersion(PythonLanguageVersion.V36, InterpreterArchitecture.x64);
public static readonly PythonVersion Python37_x64 = GetCPythonVersion(PythonLanguageVersion.V37, InterpreterArchitecture.x64);
public static readonly PythonVersion Python38_x64 = GetCPythonVersion(PythonLanguageVersion.V38, InterpreterArchitecture.x64);
public static readonly PythonVersion Anaconda27 = GetAnacondaVersion(PythonLanguageVersion.V27, InterpreterArchitecture.x86);
public static readonly PythonVersion Anaconda27_x64 = GetAnacondaVersion(PythonLanguageVersion.V27, InterpreterArchitecture.x64);
public static readonly PythonVersion Anaconda36 = GetAnacondaVersion(PythonLanguageVersion.V36, InterpreterArchitecture.x86);
public static readonly PythonVersion Anaconda36_x64 = GetAnacondaVersion(PythonLanguageVersion.V36, InterpreterArchitecture.x64);
public static readonly PythonVersion Anaconda37 = GetAnacondaVersion(PythonLanguageVersion.V37, InterpreterArchitecture.x86);
public static readonly PythonVersion Anaconda37_x64 = GetAnacondaVersion(PythonLanguageVersion.V37, InterpreterArchitecture.x64);
public static readonly PythonVersion IronPython27_x64 = GetIronPythonVersion(true);
public static readonly PythonVersion Jython27 = GetJythonVersion(PythonLanguageVersion.V27);
private static PythonVersion GetIronPythonVersion(bool x64) {
var exeName = x64 ? "ipy64.exe" : "ipy.exe";
var installPath = IronPythonResolver.GetPythonInstallDir();
if (Directory.Exists(installPath)) {
// IronPython changed to Any CPU for ipy.exe and ipy32.exe for 32-bit in 2.7.8
if (File.Exists(Path.Combine(installPath, "ipy32.exe"))) {
exeName = x64 ? "ipy.exe" : "ipy32.exe";
}
return new PythonVersion(
new VisualStudioInterpreterConfiguration(
x64 ? "IronPython|2.7-64" : "IronPython|2.7-32",
string.Format("IronPython {0} 2.7", x64 ? "64-bit" : "32-bit"),
installPath,
Path.Combine(installPath, exeName),
architecture: x64 ? InterpreterArchitecture.x64 : InterpreterArchitecture.x86,
version: new Version(2, 7),
pathVar: "IRONPYTHONPATH"
),
ironPython: true
);
}
return null;
}
private static PythonVersion GetAnacondaVersion(PythonLanguageVersion version, InterpreterArchitecture arch) {
var res = _foundInRegistry.FirstOrDefault(ii =>
ii.Configuration.Id.StartsWith("Global|ContinuumAnalytics|") &&
ii.Configuration.Architecture == arch &&
ii.Configuration.Version == version.ToVersion()
);
if (res != null) {
return new PythonVersion(res.Configuration, cPython: true);
}
return null;
}
private static PythonVersion GetCPythonVersion(PythonLanguageVersion version, InterpreterArchitecture arch) {
var res = _foundInRegistry.FirstOrDefault(ii =>
ii.Configuration.Id.StartsWith("Global|PythonCore|") &&
ii.Configuration.Architecture == arch &&
ii.Configuration.Version == version.ToVersion()
);
if (res != null) {
return new PythonVersion(res.Configuration, cPython: true);
}
var ver = version.ToVersion();
var tag = ver + (arch == InterpreterArchitecture.x86 ? "-32" : "");
foreach (var path in new[] {
string.Format("Python{0}{1}", ver.Major, ver.Minor),
string.Format("Python{0}{1}_{2}", ver.Major, ver.Minor, arch.ToString("x")),
string.Format("Python{0}{1}-{2}", ver.Major, ver.Minor, arch.ToString("#")),
string.Format("Python{0}{1}_{2}", ver.Major, ver.Minor, arch.ToString("#")),
}) {
var prefixPath = Path.Combine(Environment.GetEnvironmentVariable("SystemDrive"), "\\", path);
var exePath = Path.Combine(prefixPath, CPythonInterpreterFactoryConstants.ConsoleExecutable);
var procArch = (arch == InterpreterArchitecture.x86) ? ProcessorArchitecture.X86 :
(arch == InterpreterArchitecture.x64) ? ProcessorArchitecture.Amd64 :
ProcessorArchitecture.None;
if (procArch == Microsoft.PythonTools.Infrastructure.NativeMethods.GetBinaryType(path)) {
return new PythonVersion(new VisualStudioInterpreterConfiguration(
CPythonInterpreterFactoryConstants.GetInterpreterId("PythonCore", tag),
"Python {0} {1}".FormatInvariant(arch, ver),
prefixPath,
exePath,
pathVar: CPythonInterpreterFactoryConstants.PathEnvironmentVariableName,
architecture: arch,
version: ver
));
}
}
return null;
}
private static PythonVersion GetJythonVersion(PythonLanguageVersion version) {
var candidates = new List<DirectoryInfo>();
var ver = version.ToVersion();
var path1 = string.Format("jython{0}{1}*", ver.Major, ver.Minor);
var path2 = string.Format("jython{0}.{1}*", ver.Major, ver.Minor);
foreach (var drive in DriveInfo.GetDrives()) {
if (drive.DriveType != DriveType.Fixed) {
continue;
}
try {
candidates.AddRange(drive.RootDirectory.EnumerateDirectories(path1));
candidates.AddRange(drive.RootDirectory.EnumerateDirectories(path2));
} catch {
}
}
foreach (var dir in candidates) {
var interpreter = dir.EnumerateFiles("jython.bat").FirstOrDefault();
if (interpreter == null) {
continue;
}
var libPath = dir.EnumerateDirectories("Lib").FirstOrDefault();
if (libPath == null || !libPath.EnumerateFiles("site.py").Any()) {
continue;
}
return new PythonVersion(new VisualStudioInterpreterConfiguration(
CPythonInterpreterFactoryConstants.GetInterpreterId(
"Jython",
version.ToVersion().ToString()
),
string.Format("Jython {0}", version.ToVersion()),
dir.FullName,
interpreter.FullName,
version: version.ToVersion()
));
}
return null;
}
public static IEnumerable<PythonVersion> AnacondaVersions {
get {
if (Anaconda37 != null) yield return Anaconda37;
if (Anaconda37_x64 != null) yield return Anaconda37_x64;
if (Anaconda36 != null) yield return Anaconda36;
if (Anaconda36_x64 != null) yield return Anaconda36_x64;
if (Anaconda27 != null) yield return Anaconda27;
if (Anaconda27_x64 != null) yield return Anaconda27_x64;
}
}
public static IEnumerable<PythonVersion> Versions {
get {
if (Python27 != null) yield return Python27;
if (Python35 != null) yield return Python35;
if (Python36 != null) yield return Python36;
if (Python37 != null) yield return Python37;
if (IronPython27 != null) yield return IronPython27;
if (Python27_x64 != null) yield return Python27_x64;
if (Python35_x64 != null) yield return Python35_x64;
if (Python36_x64 != null) yield return Python36_x64;
if (Python37_x64 != null) yield return Python37_x64;
if (IronPython27_x64 != null) yield return IronPython27_x64;
if (Jython27 != null) yield return Jython27;
}
}
/// <summary>
/// Get the installed Python versions that match the specified name expression and filter.
/// </summary>
/// <param name="nameExpr">Name or '|' separated list of names that match the fields on <c>PythonPaths</c>. Ex: "Python36", "Python36|Python36_x64"</param>
/// <param name="filter">Additional filter.</param>
/// <returns>Installed Python versions that match the names and filter.</returns>
public static PythonVersion[] GetVersionsByName(string nameExpr, Predicate<PythonVersion> filter = null) {
return nameExpr
.Split('|')
.Select(v => typeof(PythonPaths).GetField(v, BindingFlags.Static | BindingFlags.Public)?.GetValue(null) as PythonVersion)
.Where(v => v != null && (filter != null ? filter(v) : true))
.ToArray();
}
}
public class PythonVersion {
public readonly InterpreterConfiguration Configuration;
public readonly bool IsCPython;
public readonly bool IsIronPython;
public PythonVersion(InterpreterConfiguration config, bool ironPython = false, bool cPython = false) {
Configuration = config;
IsCPython = cPython;
IsIronPython = ironPython;
}
public PythonVersion(string version) {
PythonVersion selected;
if (version == "Anaconda27") {
selected = PythonPaths.Anaconda27 ?? PythonPaths.Anaconda27_x64;
} else if (version == "Anaconda36") {
selected = PythonPaths.Anaconda36 ?? PythonPaths.Anaconda36_x64;
} else {
var v = System.Version.Parse(version).ToLanguageVersion();
var candididates = PythonPaths.Versions.Where(pv => pv.IsCPython && pv.Version == v).ToArray();
if (candididates.Length > 1) {
selected = candididates.FirstOrDefault(c => c.Isx64) ?? candididates.First();
} else {
selected = candididates.FirstOrDefault();
}
}
selected.AssertInstalled();
Configuration = selected.Configuration;
IsCPython = selected.IsCPython;
IsIronPython = selected.IsIronPython;
}
public override string ToString() => Configuration.Description;
public string PrefixPath => Configuration.GetPrefixPath();
public string InterpreterPath => Configuration.InterpreterPath;
public PythonLanguageVersion Version => Configuration.Version.ToLanguageVersion();
public string Id => Configuration.Id;
public bool Isx64 => Configuration.Architecture == InterpreterArchitecture.x64;
public InterpreterArchitecture Architecture => Configuration.Architecture;
}
public static class PythonVersionExtensions {
public static void AssertInstalled(this PythonVersion pyVersion) {
if (pyVersion == null || !File.Exists(pyVersion.InterpreterPath)) {
if(pyVersion == null) {
Assert.Inconclusive("Python interpreter is not installed. pyVersion is null. ");
} else {
Assert.Inconclusive(string.Format("Python version {0} is not installed.", pyVersion.Configuration.Version.ToString()));
}
}
}
public static void AssertInstalled(this PythonVersion pyVersion, string customMessage) {
if (pyVersion == null || !File.Exists(pyVersion.InterpreterPath)) {
Assert.Inconclusive(customMessage);
}
}
/// <summary>
/// Creates a Python virtual environment in specified directory and installs the specified packages.
/// </summary>
public static void CreateVirtualEnv(this PythonVersion pyVersion, string envPath, IEnumerable<string> packages) {
pyVersion.CreateVirtualEnv(envPath);
var envPythonExePath = Path.Combine(envPath, "scripts", "python.exe");
foreach (var package in packages.MaybeEnumerate()) {
using (var output = ProcessOutput.RunHiddenAndCapture(envPythonExePath, "-m", "pip", "install", package)) {
Assert.IsTrue(output.Wait(TimeSpan.FromSeconds(30)));
Assert.AreEqual(0, output.ExitCode);
}
}
}
/// <summary>
/// Creates a Python virtual environment in specified directory.
/// </summary>
public static void CreateVirtualEnv(this PythonVersion pyVersion, string envPath) {
var virtualEnvModule = (pyVersion.Version < PythonLanguageVersion.V30) ? "virtualenv" : "venv";
using (var p = ProcessOutput.RunHiddenAndCapture(pyVersion.InterpreterPath, "-m", virtualEnvModule, envPath)) {
Console.WriteLine(p.Arguments);
Assert.IsTrue(p.Wait(TimeSpan.FromMinutes(3)));
Console.WriteLine(string.Join(Environment.NewLine, p.StandardOutputLines.Concat(p.StandardErrorLines)));
Assert.AreEqual(0, p.ExitCode);
}
Assert.IsTrue(File.Exists(Path.Combine(envPath, "scripts", "python.exe")));
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#define DEBUG
using NLog.Config;
namespace NLog.UnitTests
{
using System;
using System.Globalization;
using System.Threading;
using System.Diagnostics;
using Xunit;
public class NLogTraceListenerTests : NLogTestBase, IDisposable
{
private readonly CultureInfo previousCultureInfo;
public NLogTraceListenerTests()
{
previousCultureInfo = Thread.CurrentThread.CurrentCulture;
// set the culture info with the decimal separator (comma) different from InvariantCulture separator (point)
Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");
}
public void Dispose()
{
// restore previous culture info
Thread.CurrentThread.CurrentCulture = previousCultureInfo;
}
#if !NETSTANDARD1_5
[Fact]
public void TraceWriteTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
Trace.Listeners.Clear();
Trace.Listeners.Add(new NLogTraceListener { Name = "Logger1" });
Trace.Write("Hello");
AssertDebugLastMessage("debug", "Logger1 Debug Hello");
Trace.Write("Hello", "Cat1");
AssertDebugLastMessage("debug", "Logger1 Debug Cat1: Hello");
Trace.Write(3.1415);
AssertDebugLastMessage("debug", $"Logger1 Debug {3.1415}");
Trace.Write(3.1415, "Cat2");
AssertDebugLastMessage("debug", $"Logger1 Debug Cat2: {3.1415}");
}
[Fact]
public void TraceWriteLineTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
Trace.Listeners.Clear();
Trace.Listeners.Add(new NLogTraceListener { Name = "Logger1" });
Trace.WriteLine("Hello");
AssertDebugLastMessage("debug", "Logger1 Debug Hello");
Trace.WriteLine("Hello", "Cat1");
AssertDebugLastMessage("debug", "Logger1 Debug Cat1: Hello");
Trace.WriteLine(3.1415);
AssertDebugLastMessage("debug", $"Logger1 Debug {3.1415}");
Trace.WriteLine(3.1415, "Cat2");
AssertDebugLastMessage("debug", $"Logger1 Debug Cat2: {3.1415}");
}
[Fact]
public void TraceWriteNonDefaultLevelTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='debug' />
</rules>
</nlog>");
Trace.Listeners.Clear();
Trace.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace });
Trace.Write("Hello");
AssertDebugLastMessage("debug", "Logger1 Trace Hello");
}
[Fact]
public void TraceConfiguration()
{
var listener = new NLogTraceListener();
listener.Attributes.Add("defaultLogLevel", "Warn");
listener.Attributes.Add("forceLogLevel", "Error");
listener.Attributes.Add("autoLoggerName", "1");
listener.Attributes.Add("DISABLEFLUSH", "true");
Assert.Equal(LogLevel.Warn, listener.DefaultLogLevel);
Assert.Equal(LogLevel.Error, listener.ForceLogLevel);
Assert.True(listener.AutoLoggerName);
Assert.True(listener.DisableFlush);
}
[Fact]
public void TraceFailTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
Trace.Listeners.Clear();
Trace.Listeners.Add(new NLogTraceListener { Name = "Logger1" });
Trace.Fail("Message");
AssertDebugLastMessage("debug", "Logger1 Error Message");
Trace.Fail("Message", "Detailed Message");
AssertDebugLastMessage("debug", "Logger1 Error Message Detailed Message");
}
[Fact]
public void AutoLoggerNameTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
Trace.Listeners.Clear();
Trace.Listeners.Add(new NLogTraceListener { Name = "Logger1", AutoLoggerName = true });
Trace.Write("Hello");
AssertDebugLastMessage("debug", GetType().FullName + " Debug Hello");
}
[Fact]
public void TraceDataTests()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='debug' />
</rules>
</nlog>");
TraceSource ts = CreateTraceSource();
ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace });
ts.TraceData(TraceEventType.Critical, 123, 42);
AssertDebugLastMessage("debug", "MySource1 Fatal 42 123");
ts.TraceData(TraceEventType.Critical, 145, 42, 3.14, "foo");
AssertDebugLastMessage("debug", $"MySource1 Fatal 42, {3.14.ToString(CultureInfo.CurrentCulture)}, foo 145");
}
#if MONO
[Fact(Skip="Not working under MONO - not sure if unit test is wrong, or the code")]
#else
[Fact]
#endif
public void LogInformationTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='debug' />
</rules>
</nlog>");
TraceSource ts = CreateTraceSource();
ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace });
ts.TraceInformation("Quick brown fox");
AssertDebugLastMessage("debug", "MySource1 Info Quick brown fox 0");
ts.TraceInformation("Mary had {0} lamb", "a little");
AssertDebugLastMessage("debug", "MySource1 Info Mary had a little lamb 0");
}
[Fact]
public void TraceEventTests()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='debug' />
</rules>
</nlog>");
TraceSource ts = CreateTraceSource();
ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace });
ts.TraceEvent(TraceEventType.Information, 123, "Quick brown {0} jumps over the lazy {1}.", "fox", "dog");
AssertDebugLastMessage("debug", "MySource1 Info Quick brown fox jumps over the lazy dog. 123");
ts.TraceEvent(TraceEventType.Information, 123);
AssertDebugLastMessage("debug", "MySource1 Info 123");
ts.TraceEvent(TraceEventType.Verbose, 145, "Bar");
AssertDebugLastMessage("debug", "MySource1 Trace Bar 145");
ts.TraceEvent(TraceEventType.Error, 145, "Foo");
AssertDebugLastMessage("debug", "MySource1 Error Foo 145");
ts.TraceEvent(TraceEventType.Suspend, 145, "Bar");
AssertDebugLastMessage("debug", "MySource1 Debug Bar 145");
ts.TraceEvent(TraceEventType.Resume, 145, "Foo");
AssertDebugLastMessage("debug", "MySource1 Debug Foo 145");
ts.TraceEvent(TraceEventType.Warning, 145, "Bar");
AssertDebugLastMessage("debug", "MySource1 Warn Bar 145");
ts.TraceEvent(TraceEventType.Critical, 145, "Foo");
AssertDebugLastMessage("debug", "MySource1 Fatal Foo 145");
}
#if MONO
[Fact(Skip="Not working under MONO - not sure if unit test is wrong, or the code")]
#else
[Fact]
#endif
public void ForceLogLevelTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='debug' />
</rules>
</nlog>");
TraceSource ts = CreateTraceSource();
ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace, ForceLogLevel = LogLevel.Warn });
// force all logs to be Warn, DefaultLogLevel has no effect on TraceSource
ts.TraceInformation("Quick brown fox");
AssertDebugLastMessage("debug", "MySource1 Warn Quick brown fox 0");
ts.TraceInformation("Mary had {0} lamb", "a little");
AssertDebugLastMessage("debug", "MySource1 Warn Mary had a little lamb 0");
}
[Fact]
public void FilterTraceTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='debug' />
</rules>
</nlog>");
TraceSource ts = CreateTraceSource();
ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace, ForceLogLevel = LogLevel.Warn, Filter = new EventTypeFilter(SourceLevels.Error) });
// force all logs to be Warn, DefaultLogLevel has no effect on TraceSource
ts.TraceEvent(TraceEventType.Error, 0, "Quick brown fox");
AssertDebugLastMessage("debug", "MySource1 Warn Quick brown fox 0");
ts.TraceInformation("Mary had {0} lamb", "a little");
AssertDebugLastMessage("debug", "MySource1 Warn Quick brown fox 0");
}
#endif
[Fact]
public void TraceTargetWriteLineTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='trace' type='Trace' layout='${logger} ${level} ${message}' rawWrite='true' />
</targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='trace' />
</rules>
</nlog>");
var logger = LogManager.GetLogger("MySource1");
var sw = new System.IO.StringWriter();
try
{
Trace.Listeners.Clear();
Trace.Listeners.Add(new TextWriterTraceListener(sw));
foreach (var logLevel in LogLevel.AllLevels)
{
if (logLevel == LogLevel.Off)
continue;
logger.Log(logLevel, "Quick brown fox");
Trace.Flush();
Assert.Equal($"MySource1 {logLevel} Quick brown fox" + Environment.NewLine, sw.GetStringBuilder().ToString());
sw.GetStringBuilder().Length = 0;
}
Trace.Flush();
}
finally
{
Trace.Listeners.Clear();
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void TraceTargetEnableTraceFailTest(bool enableTraceFail)
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString($@"
<nlog>
<targets>
<target name='trace' type='Trace' layout='${{logger}} ${{level}} ${{message}}' enableTraceFail='{enableTraceFail}' />
</targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='trace' />
</rules>
</nlog>");
var logger = LogManager.GetLogger(nameof(TraceTargetEnableTraceFailTest));
var sw = new System.IO.StringWriter();
try
{
Trace.Listeners.Clear();
Trace.Listeners.Add(new TextWriterTraceListener(sw));
foreach (var logLevel in LogLevel.AllLevels)
{
if (logLevel == LogLevel.Off)
continue;
logger.Log(logLevel, "Quick brown fox");
Trace.Flush();
if (logLevel == LogLevel.Fatal)
{
if (enableTraceFail)
Assert.Equal($"Fail: {logger.Name} Fatal Quick brown fox" + Environment.NewLine, sw.GetStringBuilder().ToString());
else
Assert.NotEqual($"Fail: {logger.Name} Fatal Quick brown fox" + Environment.NewLine, sw.GetStringBuilder().ToString());
}
Assert.Contains($"{logger.Name} {logLevel} Quick brown fox" + Environment.NewLine, sw.GetStringBuilder().ToString());
sw.GetStringBuilder().Length = 0;
}
}
finally
{
Trace.Listeners.Clear();
}
}
private static TraceSource CreateTraceSource()
{
var ts = new TraceSource("MySource1", SourceLevels.All);
#if MONO
// for some reason needed on Mono
ts.Switch = new SourceSwitch("MySource1", "Verbose");
ts.Switch.Level = SourceLevels.All;
#endif
return ts;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using Microsoft.Azure.Commands.Compute.Automation.Models;
using Microsoft.Azure.Management.Compute.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Compute.Automation
{
[Cmdlet("New", "AzureRmContainerServiceConfig", SupportsShouldProcess = true)]
[OutputType(typeof(PSContainerService))]
public partial class NewAzureRmContainerServiceConfigCommand : Microsoft.Azure.Commands.ResourceManager.Common.AzureRMCmdlet
{
[Parameter(
Mandatory = false,
Position = 0,
ValueFromPipelineByPropertyName = true)]
[ResourceManager.Common.ArgumentCompleters.LocationCompleter("Microsoft.ContainerService/containerServices")]
public string Location { get; set; }
[Parameter(
Mandatory = false,
Position = 1,
ValueFromPipelineByPropertyName = true)]
public Hashtable Tag { get; set; }
[Parameter(
Mandatory = false,
Position = 2,
ValueFromPipelineByPropertyName = true)]
public ContainerServiceOrchestratorTypes? OrchestratorType { get; set; }
[Parameter(
Mandatory = false,
Position = 3,
ValueFromPipelineByPropertyName = true)]
public int? MasterCount { get; set; }
[Parameter(
Mandatory = false,
Position = 4,
ValueFromPipelineByPropertyName = true)]
public string MasterDnsPrefix { get; set; }
[Parameter(
Mandatory = false,
Position = 5,
ValueFromPipelineByPropertyName = true)]
public ContainerServiceAgentPoolProfile[] AgentPoolProfile { get; set; }
[Parameter(
Mandatory = false,
Position = 6,
ValueFromPipelineByPropertyName = true)]
public string WindowsProfileAdminUsername { get; set; }
[Parameter(
Mandatory = false,
Position = 7,
ValueFromPipelineByPropertyName = true)]
public string WindowsProfileAdminPassword { get; set; }
[Parameter(
Mandatory = false,
Position = 8,
ValueFromPipelineByPropertyName = true)]
public string AdminUsername { get; set; }
[Parameter(
Mandatory = false,
Position = 9,
ValueFromPipelineByPropertyName = true)]
public string[] SshPublicKey { get; set; }
[Parameter(
Mandatory = false,
Position = 10,
ValueFromPipelineByPropertyName = true)]
public bool VmDiagnosticsEnabled { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string CustomProfileOrchestrator { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string ServicePrincipalProfileClientId { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string ServicePrincipalProfileSecret { get; set; }
protected override void ProcessRecord()
{
if (ShouldProcess("ContainerService", "New"))
{
Run();
}
}
private void Run()
{
// OrchestratorProfile
Microsoft.Azure.Management.Compute.Models.ContainerServiceOrchestratorProfile vOrchestratorProfile = null;
// CustomProfile
Microsoft.Azure.Management.Compute.Models.ContainerServiceCustomProfile vCustomProfile = null;
// ServicePrincipalProfile
Microsoft.Azure.Management.Compute.Models.ContainerServiceServicePrincipalProfile vServicePrincipalProfile = null;
// MasterProfile
Microsoft.Azure.Management.Compute.Models.ContainerServiceMasterProfile vMasterProfile = null;
// WindowsProfile
Microsoft.Azure.Management.Compute.Models.ContainerServiceWindowsProfile vWindowsProfile = null;
// LinuxProfile
Microsoft.Azure.Management.Compute.Models.ContainerServiceLinuxProfile vLinuxProfile = null;
// DiagnosticsProfile
Microsoft.Azure.Management.Compute.Models.ContainerServiceDiagnosticsProfile vDiagnosticsProfile = null;
if (this.OrchestratorType.HasValue)
{
if (vOrchestratorProfile == null)
{
vOrchestratorProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceOrchestratorProfile();
}
vOrchestratorProfile.OrchestratorType = this.OrchestratorType.Value;
}
if (this.CustomProfileOrchestrator != null)
{
if (vCustomProfile == null)
{
vCustomProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceCustomProfile();
}
vCustomProfile.Orchestrator = this.CustomProfileOrchestrator;
}
if (this.ServicePrincipalProfileClientId != null)
{
if (vServicePrincipalProfile == null)
{
vServicePrincipalProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceServicePrincipalProfile();
}
vServicePrincipalProfile.ClientId = this.ServicePrincipalProfileClientId;
}
if (this.ServicePrincipalProfileSecret != null)
{
if (vServicePrincipalProfile == null)
{
vServicePrincipalProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceServicePrincipalProfile();
}
vServicePrincipalProfile.Secret = this.ServicePrincipalProfileSecret;
}
if (this.MasterCount != null)
{
if (vMasterProfile == null)
{
vMasterProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceMasterProfile();
}
vMasterProfile.Count = this.MasterCount;
}
if (this.MasterDnsPrefix != null)
{
if (vMasterProfile == null)
{
vMasterProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceMasterProfile();
}
vMasterProfile.DnsPrefix = this.MasterDnsPrefix;
}
if (this.WindowsProfileAdminUsername != null)
{
if (vWindowsProfile == null)
{
vWindowsProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceWindowsProfile();
}
vWindowsProfile.AdminUsername = this.WindowsProfileAdminUsername;
}
if (this.WindowsProfileAdminPassword != null)
{
if (vWindowsProfile == null)
{
vWindowsProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceWindowsProfile();
}
vWindowsProfile.AdminPassword = this.WindowsProfileAdminPassword;
}
if (this.AdminUsername != null)
{
if (vLinuxProfile == null)
{
vLinuxProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceLinuxProfile();
}
vLinuxProfile.AdminUsername = this.AdminUsername;
}
if (this.SshPublicKey != null)
{
if (vLinuxProfile == null)
{
vLinuxProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceLinuxProfile();
}
if (vLinuxProfile.Ssh == null)
{
vLinuxProfile.Ssh = new Microsoft.Azure.Management.Compute.Models.ContainerServiceSshConfiguration();
}
if (vLinuxProfile.Ssh.PublicKeys == null)
{
vLinuxProfile.Ssh.PublicKeys = new List<Microsoft.Azure.Management.Compute.Models.ContainerServiceSshPublicKey>();
}
foreach (var element in this.SshPublicKey)
{
var vPublicKeys = new Microsoft.Azure.Management.Compute.Models.ContainerServiceSshPublicKey();
vPublicKeys.KeyData = element;
vLinuxProfile.Ssh.PublicKeys.Add(vPublicKeys);
}
}
if (vDiagnosticsProfile == null)
{
vDiagnosticsProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceDiagnosticsProfile();
}
if (vDiagnosticsProfile.VmDiagnostics == null)
{
vDiagnosticsProfile.VmDiagnostics = new Microsoft.Azure.Management.Compute.Models.ContainerServiceVMDiagnostics();
}
vDiagnosticsProfile.VmDiagnostics.Enabled = this.VmDiagnosticsEnabled;
var vContainerService = new PSContainerService
{
Location = this.Location,
Tags = (this.Tag == null) ? null : this.Tag.Cast<DictionaryEntry>().ToDictionary(ht => (string)ht.Key, ht => (string)ht.Value),
AgentPoolProfiles = this.AgentPoolProfile,
OrchestratorProfile = vOrchestratorProfile,
CustomProfile = vCustomProfile,
ServicePrincipalProfile = vServicePrincipalProfile,
MasterProfile = vMasterProfile,
WindowsProfile = vWindowsProfile,
LinuxProfile = vLinuxProfile,
DiagnosticsProfile = vDiagnosticsProfile,
};
WriteObject(vContainerService);
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class EveryplayRecButtons : MonoBehaviour
{
public enum ButtonsOrigin
{
TopLeft = 0,
TopRight,
BottomLeft,
BottomRight
};
public Texture2D atlasTexture;
public ButtonsOrigin origin = ButtonsOrigin.TopLeft;
public Vector2 containerMargin = new Vector2(16, 16);
#if UNITY_ANDROID || UNITY_IPHONE || UNITY_IOS
private Vector2 containerOffset = Vector2.zero;
private float containerScaling = 1.0f;
private const int atlasWidth = 256;
private const int atlasHeight = 256;
private const int atlasPadding = 2;
private int buttonTitleHorizontalMargin = 16;
private int buttonTitleVerticalMargin = 20;
private int buttonMargin = 8;
private bool faceCamPermissionGranted = false;
private bool startFaceCamWhenPermissionGranted = false;
private class TextureAtlasSrc
{
public Rect atlasRect = new Rect(0, 0, 0, 0);
public Rect normalizedAtlasRect = new Rect(0, 0, 0, 0);
public TextureAtlasSrc(int width, int height, int x, int y, float scale)
{
atlasRect.x = x + atlasPadding;
atlasRect.y = y + atlasPadding;
atlasRect.width = width * scale;
atlasRect.height = height * scale;
normalizedAtlasRect.width = width / (float) atlasWidth;
normalizedAtlasRect.height = height / (float) atlasHeight;
normalizedAtlasRect.x = atlasRect.x / (float) atlasWidth;
normalizedAtlasRect.y = 1.0f - (atlasRect.y + height) / (float) atlasHeight;
}
}
private delegate void ButtonTapped();
private class Button
{
public bool enabled;
public Rect screenRect;
public TextureAtlasSrc bg;
public TextureAtlasSrc title;
public ButtonTapped onTap;
public Button(TextureAtlasSrc bg, TextureAtlasSrc title, ButtonTapped buttonTapped)
{
this.enabled = true;
this.bg = bg;
this.title = title;
this.screenRect.width = bg.atlasRect.width;
this.screenRect.height = bg.atlasRect.height;
this.onTap = buttonTapped;
}
}
private class ToggleButton : Button
{
public TextureAtlasSrc toggleOn;
public TextureAtlasSrc toggleOff;
public bool toggled = false;
public ToggleButton(TextureAtlasSrc bg, TextureAtlasSrc title, ButtonTapped buttonTapped, TextureAtlasSrc toggleOn, TextureAtlasSrc toggleOff) : base(bg, title, buttonTapped)
{
this.toggleOn = toggleOn;
this.toggleOff = toggleOff;
}
}
private TextureAtlasSrc editVideoAtlasSrc;
private TextureAtlasSrc faceCamAtlasSrc;
private TextureAtlasSrc openEveryplayAtlasSrc;
private TextureAtlasSrc shareVideoAtlasSrc;
private TextureAtlasSrc startRecordingAtlasSrc;
private TextureAtlasSrc stopRecordingAtlasSrc;
private TextureAtlasSrc facecamToggleOnAtlasSrc;
private TextureAtlasSrc facecamToggleOffAtlasSrc;
private TextureAtlasSrc bgHeaderAtlasSrc;
private TextureAtlasSrc bgFooterAtlasSrc;
private TextureAtlasSrc bgAtlasSrc;
private TextureAtlasSrc buttonAtlasSrc;
private Button shareVideoButton;
private Button editVideoButton;
private Button openEveryplayButton;
private Button startRecordingButton;
private Button stopRecordingButton;
private ToggleButton faceCamToggleButton;
private Button tappedButton = null;
private List<Button> visibleButtons;
void Awake()
{
// Scale by resolution
containerScaling = GetScalingByResolution();
// Texture atlas sources
editVideoAtlasSrc = new TextureAtlasSrc(112, 19, 0, 0, containerScaling);
faceCamAtlasSrc = new TextureAtlasSrc(103, 19, 116, 0, containerScaling);
openEveryplayAtlasSrc = new TextureAtlasSrc(178, 23, 0, 23, containerScaling);
shareVideoAtlasSrc = new TextureAtlasSrc(134, 19, 0, 50, containerScaling);
startRecordingAtlasSrc = new TextureAtlasSrc(171, 23, 0, 73, containerScaling);
stopRecordingAtlasSrc = new TextureAtlasSrc(169, 23, 0, 100, containerScaling);
facecamToggleOnAtlasSrc = new TextureAtlasSrc(101, 42, 0, 127, containerScaling);
facecamToggleOffAtlasSrc = new TextureAtlasSrc(101, 42, 101, 127, containerScaling);
bgHeaderAtlasSrc = new TextureAtlasSrc(256, 9, 0, 169, containerScaling);
bgFooterAtlasSrc = new TextureAtlasSrc(256, 9, 0, 169, containerScaling);
bgAtlasSrc = new TextureAtlasSrc(256, 6, 0, 178, containerScaling);
buttonAtlasSrc = new TextureAtlasSrc(220, 64, 0, 190, containerScaling);
buttonTitleHorizontalMargin = Mathf.RoundToInt(buttonTitleHorizontalMargin * containerScaling);
buttonTitleVerticalMargin = Mathf.RoundToInt(buttonTitleVerticalMargin * containerScaling);
buttonMargin = Mathf.RoundToInt(buttonMargin * containerScaling);
// Buttons
shareVideoButton = new Button(buttonAtlasSrc, shareVideoAtlasSrc, ShareVideo);
editVideoButton = new Button(buttonAtlasSrc, editVideoAtlasSrc, EditVideo);
openEveryplayButton = new Button(buttonAtlasSrc, openEveryplayAtlasSrc, OpenEveryplay);
startRecordingButton = new Button(buttonAtlasSrc, startRecordingAtlasSrc, StartRecording);
stopRecordingButton = new Button(buttonAtlasSrc, stopRecordingAtlasSrc, StopRecording);
faceCamToggleButton = new ToggleButton(buttonAtlasSrc, faceCamAtlasSrc, FaceCamToggle, facecamToggleOnAtlasSrc, facecamToggleOffAtlasSrc);
visibleButtons = new List<Button>();
// Use header texture for footer by flipping it
bgFooterAtlasSrc.normalizedAtlasRect.y = bgFooterAtlasSrc.normalizedAtlasRect.y + bgFooterAtlasSrc.normalizedAtlasRect.height;
bgFooterAtlasSrc.normalizedAtlasRect.height = -bgFooterAtlasSrc.normalizedAtlasRect.height;
// Set initially visible buttons
SetButtonVisible(startRecordingButton, true);
SetButtonVisible(openEveryplayButton, true);
SetButtonVisible(faceCamToggleButton, true);
// Set initially
if (!Everyplay.IsRecordingSupported())
{
startRecordingButton.enabled = false;
stopRecordingButton.enabled = false;
}
Everyplay.RecordingStarted += RecordingStarted;
Everyplay.RecordingStopped += RecordingStopped;
Everyplay.ReadyForRecording += ReadyForRecording;
Everyplay.FaceCamRecordingPermission += FaceCamRecordingPermission;
}
void Destroy()
{
Everyplay.RecordingStarted -= RecordingStarted;
Everyplay.RecordingStopped -= RecordingStopped;
Everyplay.ReadyForRecording -= ReadyForRecording;
Everyplay.FaceCamRecordingPermission -= FaceCamRecordingPermission;
}
private void SetButtonVisible(Button button, bool visible)
{
if (visibleButtons.Contains(button))
{
if (!visible)
{
visibleButtons.Remove(button);
}
}
else
{
if (visible)
{
visibleButtons.Add(button);
}
}
}
private void ReplaceVisibleButton(Button button, Button replacementButton)
{
int index = visibleButtons.IndexOf(button);
if (index >= 0)
{
visibleButtons[index] = replacementButton;
}
}
private void StartRecording()
{
Everyplay.StartRecording();
}
private void StopRecording()
{
Everyplay.StopRecording();
}
private void RecordingStarted()
{
ReplaceVisibleButton(startRecordingButton, stopRecordingButton);
SetButtonVisible(shareVideoButton, false);
SetButtonVisible(editVideoButton, false);
SetButtonVisible(faceCamToggleButton, false);
}
private void RecordingStopped()
{
ReplaceVisibleButton(stopRecordingButton, startRecordingButton);
SetButtonVisible(shareVideoButton, true);
SetButtonVisible(editVideoButton, true);
SetButtonVisible(faceCamToggleButton, true);
}
private void ReadyForRecording(bool enabled)
{
startRecordingButton.enabled = enabled;
stopRecordingButton.enabled = enabled;
}
private void FaceCamRecordingPermission(bool granted)
{
faceCamPermissionGranted = granted;
if (startFaceCamWhenPermissionGranted)
{
faceCamToggleButton.toggled = granted;
Everyplay.FaceCamStartSession();
if (Everyplay.FaceCamIsSessionRunning())
{
startFaceCamWhenPermissionGranted = false;
}
}
}
private void FaceCamToggle()
{
if (faceCamPermissionGranted)
{
faceCamToggleButton.toggled = !faceCamToggleButton.toggled;
if (faceCamToggleButton.toggled)
{
if (!Everyplay.FaceCamIsSessionRunning())
{
Everyplay.FaceCamStartSession();
}
}
else
{
if (Everyplay.FaceCamIsSessionRunning())
{
Everyplay.FaceCamStopSession();
}
}
}
else
{
Everyplay.FaceCamRequestRecordingPermission();
startFaceCamWhenPermissionGranted = true;
}
}
private void OpenEveryplay()
{
Everyplay.Show();
}
private void EditVideo()
{
Everyplay.PlayLastRecording();
}
private void ShareVideo()
{
Everyplay.ShowSharingModal();
}
void Update()
{
#if UNITY_EDITOR || UNITY_STANDALONE
if (Input.GetMouseButtonDown(0))
{
foreach (Button button in visibleButtons)
{
if (button.enabled && button.screenRect.Contains(new Vector2(Input.mousePosition.x - containerOffset.x, Screen.height - Input.mousePosition.y - containerOffset.y)))
{
tappedButton = button;
}
}
}
else if (Input.GetMouseButtonUp(0))
{
foreach (Button button in visibleButtons)
{
if (button.enabled && button.screenRect.Contains(new Vector2(Input.mousePosition.x - containerOffset.x, Screen.height - Input.mousePosition.y - containerOffset.y)))
{
if (button.onTap != null)
{
button.onTap();
}
}
}
tappedButton = null;
}
#else
foreach (Touch touch in Input.touches)
{
if (touch.phase == TouchPhase.Began)
{
foreach (Button button in visibleButtons)
{
if (button.screenRect.Contains(new Vector2(touch.position.x - containerOffset.x, Screen.height - touch.position.y - containerOffset.y)))
{
tappedButton = button;
}
}
}
else if (touch.phase == TouchPhase.Ended)
{
foreach (Button button in visibleButtons)
{
if (button.screenRect.Contains(new Vector2(touch.position.x - containerOffset.x, Screen.height - touch.position.y - containerOffset.y)))
{
if (button.onTap != null)
{
button.onTap();
}
}
}
tappedButton = null;
}
else if (touch.phase == TouchPhase.Canceled)
{
tappedButton = null;
}
}
#endif
}
void OnGUI()
{
if (Event.current.type.Equals(EventType.Repaint))
{
int containerHeight = CalculateContainerHeight();
UpdateContainerOffset(containerHeight);
DrawBackround(containerHeight);
DrawButtons();
}
}
private void DrawTexture(float x, float y, float width, float height, Texture2D texture, Rect uvRect)
{
x += containerOffset.x;
y += containerOffset.y;
GUI.DrawTextureWithTexCoords(new Rect(x, y, width, height), texture, uvRect, true);
}
private void DrawButtons()
{
foreach (Button button in visibleButtons)
{
if (button.enabled)
{
DrawButton(button, (tappedButton == button) ? Color.gray : Color.white);
}
else
{
DrawButton(button, new Color(0.5f, 0.5f, 0.5f, 0.3f));
}
}
}
private void DrawBackround(int containerHeight)
{
DrawTexture(0, 0, bgHeaderAtlasSrc.atlasRect.width, bgHeaderAtlasSrc.atlasRect.height, atlasTexture, bgHeaderAtlasSrc.normalizedAtlasRect);
DrawTexture(0, bgHeaderAtlasSrc.atlasRect.height, bgAtlasSrc.atlasRect.width, containerHeight - bgHeaderAtlasSrc.atlasRect.height - bgFooterAtlasSrc.atlasRect.height, atlasTexture, bgAtlasSrc.normalizedAtlasRect);
DrawTexture(0, containerHeight - bgFooterAtlasSrc.atlasRect.height, bgFooterAtlasSrc.atlasRect.width, bgFooterAtlasSrc.atlasRect.height, atlasTexture, bgFooterAtlasSrc.normalizedAtlasRect);
}
private void DrawButton(Button button, Color tintColor)
{
Color oldColor = GUI.color;
bool isToggleButton = typeof(ToggleButton).IsAssignableFrom(button.GetType());
if (isToggleButton)
{
ToggleButton toggleButton = (ToggleButton) button;
if (button != null)
{
float x = (button.screenRect.x + button.screenRect.width) - toggleButton.toggleOn.atlasRect.width;
float y = button.screenRect.y + button.screenRect.height / 2 - toggleButton.toggleOn.atlasRect.height / 2;
TextureAtlasSrc buttonSrc = toggleButton.toggled ? toggleButton.toggleOn : toggleButton.toggleOff;
GUI.color = tintColor;
DrawTexture(x, y, buttonSrc.atlasRect.width, buttonSrc.atlasRect.height, atlasTexture, buttonSrc.normalizedAtlasRect);
GUI.color = oldColor;
}
}
else
{
GUI.color = tintColor;
DrawTexture(button.screenRect.x, button.screenRect.y, button.bg.atlasRect.width, button.bg.atlasRect.height, atlasTexture, button.bg.normalizedAtlasRect);
GUI.color = oldColor;
}
float rightMargin = isToggleButton ? 0 : buttonTitleHorizontalMargin;
if (!button.enabled)
{
GUI.color = tintColor;
}
DrawTexture(button.screenRect.x + rightMargin, button.screenRect.y + buttonTitleVerticalMargin, button.title.atlasRect.width, button.title.atlasRect.height, atlasTexture, button.title.normalizedAtlasRect);
if (!button.enabled)
{
GUI.color = oldColor;
}
}
private int CalculateContainerHeight()
{
float buttonsHeight = 0;
float yOffset = bgHeaderAtlasSrc.atlasRect.height + (buttonMargin * 2 - bgHeaderAtlasSrc.atlasRect.height);
foreach (Button button in visibleButtons)
{
button.screenRect.x = (bgAtlasSrc.atlasRect.width - button.screenRect.width) / 2;
button.screenRect.y = yOffset;
yOffset += buttonMargin + button.screenRect.height;
buttonsHeight += buttonMargin + button.screenRect.height;
}
int containerHeight = Mathf.RoundToInt(buttonsHeight + bgHeaderAtlasSrc.atlasRect.height + bgFooterAtlasSrc.atlasRect.height);
return containerHeight;
}
private void UpdateContainerOffset(int containerHeight)
{
if (origin == ButtonsOrigin.TopRight)
{
containerOffset.x = Screen.width - containerMargin.x * containerScaling - bgAtlasSrc.atlasRect.width;
containerOffset.y = containerMargin.y * containerScaling;
}
else if (origin == ButtonsOrigin.BottomLeft)
{
containerOffset.x = containerMargin.x * containerScaling;
containerOffset.y = Screen.height - containerMargin.y * containerScaling - containerHeight;
}
else if (origin == ButtonsOrigin.BottomRight)
{
containerOffset.x = Screen.width - containerMargin.x * containerScaling - bgAtlasSrc.atlasRect.width;
containerOffset.y = Screen.height - containerMargin.y * containerScaling - containerHeight;
}
else
{
containerOffset.x = containerMargin.x * containerScaling;
containerOffset.y = containerMargin.y * containerScaling;
}
}
private float GetScalingByResolution()
{
int high = Mathf.Max(Screen.height, Screen.width);
int low = Mathf.Min(Screen.height, Screen.width);
if (high < 640 || (high == 1024 && low == 768))
{
return 0.5f;
}
return 1.0f;
}
#endif
}
| |
/*
* 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 ParquetEncodingTests.Bytes
{
using ParquetSharp.Bytes;
using ParquetSharp.External;
using Xunit;
public class TestCapacityByteArrayOutputStream
{
[Fact]
public void testWrite()
{
CapacityByteArrayOutputStream capacityByteArrayOutputStream = newCapacityBAOS(10);
const int expectedSize = 54;
for (int i = 0; i < expectedSize; i++)
{
capacityByteArrayOutputStream.WriteByte((byte)i);
Assert.Equal(i + 1, capacityByteArrayOutputStream.size());
}
validate(capacityByteArrayOutputStream, expectedSize);
}
[Fact]
public void testWriteArray()
{
CapacityByteArrayOutputStream capacityByteArrayOutputStream = newCapacityBAOS(10);
int v = 23;
writeArraysOf3(capacityByteArrayOutputStream, v);
validate(capacityByteArrayOutputStream, v * 3);
}
[Fact]
public void testWriteArrayAndInt()
{
CapacityByteArrayOutputStream capacityByteArrayOutputStream = newCapacityBAOS(10);
for (int i = 0; i < 23; i++)
{
byte[] toWrite = { (byte)(i * 3), (byte)(i * 3 + 1) };
capacityByteArrayOutputStream.Write(toWrite);
capacityByteArrayOutputStream.WriteByte((byte)(i * 3 + 2));
Assert.Equal((i + 1) * 3, capacityByteArrayOutputStream.size());
}
validate(capacityByteArrayOutputStream, 23 * 3);
}
protected CapacityByteArrayOutputStream newCapacityBAOS(int initialSize)
{
return new CapacityByteArrayOutputStream(initialSize, 1000000, new HeapByteBufferAllocator());
}
[Fact]
public void testReset()
{
CapacityByteArrayOutputStream capacityByteArrayOutputStream = newCapacityBAOS(10);
for (int i = 0; i < 54; i++)
{
capacityByteArrayOutputStream.WriteByte((byte)i);
Assert.Equal(i + 1, capacityByteArrayOutputStream.size());
}
capacityByteArrayOutputStream.reset();
for (int i = 0; i < 54; i++)
{
capacityByteArrayOutputStream.WriteByte((byte)(54 + i));
Assert.Equal(i + 1, capacityByteArrayOutputStream.size());
}
byte[] byteArray = BytesInput.from(capacityByteArrayOutputStream).toByteArray();
Assert.Equal(54, byteArray.Length);
for (int i = 0; i < 54; i++)
{
Assert.Equal((byte)(54 + i), byteArray[i]); //, i + " in " + Arrays.toString(byteArray));
}
}
[Fact]
public void testWriteArrayBiggerThanSlab()
{
CapacityByteArrayOutputStream capacityByteArrayOutputStream = newCapacityBAOS(10);
int v = 23;
writeArraysOf3(capacityByteArrayOutputStream, v);
int n = v * 3;
byte[] toWrite = { // bigger than 2 slabs of size of 10
(byte)n, (byte)(n + 1), (byte)(n + 2), (byte)(n + 3), (byte)(n + 4), (byte)(n + 5),
(byte)(n + 6), (byte)(n + 7), (byte)(n + 8), (byte)(n + 9), (byte)(n + 10),
(byte)(n + 11), (byte)(n + 12), (byte)(n + 13), (byte)(n + 14), (byte)(n + 15),
(byte)(n + 16), (byte)(n + 17), (byte)(n + 18), (byte)(n + 19), (byte)(n + 20)};
capacityByteArrayOutputStream.Write(toWrite);
n = n + toWrite.Length;
Assert.Equal(n, capacityByteArrayOutputStream.size());
validate(capacityByteArrayOutputStream, n);
capacityByteArrayOutputStream.reset();
// check it works after reset too
capacityByteArrayOutputStream.Write(toWrite);
Assert.Equal(toWrite.Length, capacityByteArrayOutputStream.size());
byte[] byteArray = BytesInput.from(capacityByteArrayOutputStream).toByteArray();
Assert.Equal(toWrite.Length, byteArray.Length);
for (int i = 0; i < toWrite.Length; i++)
{
Assert.Equal(toWrite[i], byteArray[i]);
}
}
[Fact]
public void testWriteArrayManySlabs()
{
CapacityByteArrayOutputStream capacityByteArrayOutputStream = newCapacityBAOS(10);
int it = 500;
int v = 23;
for (int j = 0; j < it; j++)
{
for (int i = 0; i < v; i++)
{
byte[] toWrite = { (byte)(i * 3), (byte)(i * 3 + 1), (byte)(i * 3 + 2) };
capacityByteArrayOutputStream.Write(toWrite);
Assert.Equal((i + 1) * 3 + v * 3 * j, capacityByteArrayOutputStream.size());
}
}
byte[] byteArray = BytesInput.from(capacityByteArrayOutputStream).toByteArray();
Assert.Equal(v * 3 * it, byteArray.Length);
for (int i = 0; i < v * 3 * it; i++)
{
Assert.Equal(i % (v * 3), byteArray[i]);
}
// verifying we have not created 500 * 23 / 10 slabs
Assert.True(capacityByteArrayOutputStream.getSlabCount() <= 20, "slab count: " + capacityByteArrayOutputStream.getSlabCount());
capacityByteArrayOutputStream.reset();
writeArraysOf3(capacityByteArrayOutputStream, v);
validate(capacityByteArrayOutputStream, v * 3);
// verifying we use less slabs now
Assert.True(capacityByteArrayOutputStream.getSlabCount() <= 2, "slab count: " + capacityByteArrayOutputStream.getSlabCount());
}
[Fact]
public void testReplaceByte()
{
// test replace the first value
{
CapacityByteArrayOutputStream cbaos = newCapacityBAOS(5);
cbaos.WriteByte(10);
Assert.Equal(0, cbaos.getCurrentIndex());
cbaos.setByte(0, (byte)7);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
cbaos.writeTo(baos);
Assert.Equal(7, baos.toByteArray()[0]);
}
// test replace value in the first slab
{
CapacityByteArrayOutputStream cbaos = newCapacityBAOS(5);
cbaos.WriteByte(10);
cbaos.WriteByte(13);
cbaos.WriteByte(15);
cbaos.WriteByte(17);
Assert.Equal(3, cbaos.getCurrentIndex());
cbaos.WriteByte(19);
cbaos.setByte(3, (byte)7);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
cbaos.writeTo(baos);
TestHelpers.assertArrayEquals(new byte[] { 10, 13, 15, 7, 19 }, baos.toByteArray());
}
// test replace in *not* the first slab
{
CapacityByteArrayOutputStream cbaos = newCapacityBAOS(5);
// advance part way through the 3rd slab
for (int i = 0; i < 12; i++)
{
cbaos.WriteByte((byte)(100 + i));
}
Assert.Equal(11, cbaos.getCurrentIndex());
cbaos.setByte(6, (byte)7);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
cbaos.writeTo(baos);
TestHelpers.assertArrayEquals(
new byte[] { 100, 101, 102, 103, 104, 105, 7, 107, 108, 109, 110, 111 },
baos.toByteArray());
}
// test replace last value of a slab
{
CapacityByteArrayOutputStream cbaos = newCapacityBAOS(5);
// advance part way through the 3rd slab
for (int i = 0; i < 12; i++)
{
cbaos.WriteByte((byte)(100 + i));
}
Assert.Equal(11, cbaos.getCurrentIndex());
cbaos.setByte(9, (byte)7);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
cbaos.writeTo(baos);
TestHelpers.assertArrayEquals(
new byte[] { 100, 101, 102, 103, 104, 105, 106, 107, 108, 7, 110, 111 },
baos.toByteArray());
}
// test replace last value
{
CapacityByteArrayOutputStream cbaos = newCapacityBAOS(5);
// advance part way through the 3rd slab
for (int i = 0; i < 12; i++)
{
cbaos.WriteByte((byte)(100 + i));
}
Assert.Equal(11, cbaos.getCurrentIndex());
cbaos.setByte(11, (byte)7);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
cbaos.writeTo(baos);
TestHelpers.assertArrayEquals(
new byte[] { 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 7 },
baos.toByteArray());
}
}
private void writeArraysOf3(CapacityByteArrayOutputStream capacityByteArrayOutputStream, int n)
{
for (int i = 0; i < n; i++)
{
byte[] toWrite = { (byte)(i * 3), (byte)(i * 3 + 1), (byte)(i * 3 + 2) };
capacityByteArrayOutputStream.Write(toWrite);
Assert.Equal((i + 1) * 3, capacityByteArrayOutputStream.size());
}
}
private void validate(
CapacityByteArrayOutputStream capacityByteArrayOutputStream,
int expectedSize)
{
byte[] byteArray = BytesInput.from(capacityByteArrayOutputStream).toByteArray();
Assert.Equal(expectedSize, byteArray.Length);
for (int i = 0; i < expectedSize; i++)
{
Assert.Equal(i, byteArray[i]);
}
}
}
}
| |
#region Copyright notice and license
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using Grpc.Core.Logging;
using Grpc.Core.Utils;
namespace Grpc.Core.Internal
{
internal interface IServerCallHandler
{
Task HandleCall(ServerRpcNew newRpc, CompletionQueueSafeHandle cq);
}
internal class UnaryServerCallHandler<TRequest, TResponse> : IServerCallHandler
where TRequest : class
where TResponse : class
{
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<UnaryServerCallHandler<TRequest, TResponse>>();
readonly Method<TRequest, TResponse> method;
readonly UnaryServerMethod<TRequest, TResponse> handler;
public UnaryServerCallHandler(Method<TRequest, TResponse> method, UnaryServerMethod<TRequest, TResponse> handler)
{
this.method = method;
this.handler = handler;
}
public async Task HandleCall(ServerRpcNew newRpc, CompletionQueueSafeHandle cq)
{
var asyncCall = new AsyncCallServer<TRequest, TResponse>(
method.ResponseMarshaller.Serializer,
method.RequestMarshaller.Deserializer,
newRpc.Server);
asyncCall.Initialize(newRpc.Call, cq);
var finishedTask = asyncCall.ServerSideCallAsync();
var requestStream = new ServerRequestStream<TRequest, TResponse>(asyncCall);
var responseStream = new ServerResponseStream<TRequest, TResponse>(asyncCall);
Status status;
AsyncCallServer<TRequest,TResponse>.ResponseWithFlags? responseWithFlags = null;
var context = HandlerUtils.NewContext(newRpc, responseStream, asyncCall.CancellationToken);
try
{
GrpcPreconditions.CheckArgument(await requestStream.MoveNext().ConfigureAwait(false));
var request = requestStream.Current;
var response = await handler(request, context).ConfigureAwait(false);
status = context.Status;
responseWithFlags = new AsyncCallServer<TRequest, TResponse>.ResponseWithFlags(response, HandlerUtils.GetWriteFlags(context.WriteOptions));
}
catch (Exception e)
{
if (!(e is RpcException))
{
Logger.Warning(e, "Exception occured in handler.");
}
status = HandlerUtils.GetStatusFromExceptionAndMergeTrailers(e, context.ResponseTrailers);
}
try
{
await asyncCall.SendStatusFromServerAsync(status, context.ResponseTrailers, responseWithFlags).ConfigureAwait(false);
}
catch (Exception)
{
asyncCall.Cancel();
throw;
}
await finishedTask.ConfigureAwait(false);
}
}
internal class ServerStreamingServerCallHandler<TRequest, TResponse> : IServerCallHandler
where TRequest : class
where TResponse : class
{
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<ServerStreamingServerCallHandler<TRequest, TResponse>>();
readonly Method<TRequest, TResponse> method;
readonly ServerStreamingServerMethod<TRequest, TResponse> handler;
public ServerStreamingServerCallHandler(Method<TRequest, TResponse> method, ServerStreamingServerMethod<TRequest, TResponse> handler)
{
this.method = method;
this.handler = handler;
}
public async Task HandleCall(ServerRpcNew newRpc, CompletionQueueSafeHandle cq)
{
var asyncCall = new AsyncCallServer<TRequest, TResponse>(
method.ResponseMarshaller.Serializer,
method.RequestMarshaller.Deserializer,
newRpc.Server);
asyncCall.Initialize(newRpc.Call, cq);
var finishedTask = asyncCall.ServerSideCallAsync();
var requestStream = new ServerRequestStream<TRequest, TResponse>(asyncCall);
var responseStream = new ServerResponseStream<TRequest, TResponse>(asyncCall);
Status status;
var context = HandlerUtils.NewContext(newRpc, responseStream, asyncCall.CancellationToken);
try
{
GrpcPreconditions.CheckArgument(await requestStream.MoveNext().ConfigureAwait(false));
var request = requestStream.Current;
await handler(request, responseStream, context).ConfigureAwait(false);
status = context.Status;
}
catch (Exception e)
{
if (!(e is RpcException))
{
Logger.Warning(e, "Exception occured in handler.");
}
status = HandlerUtils.GetStatusFromExceptionAndMergeTrailers(e, context.ResponseTrailers);
}
try
{
await asyncCall.SendStatusFromServerAsync(status, context.ResponseTrailers, null).ConfigureAwait(false);
}
catch (Exception)
{
asyncCall.Cancel();
throw;
}
await finishedTask.ConfigureAwait(false);
}
}
internal class ClientStreamingServerCallHandler<TRequest, TResponse> : IServerCallHandler
where TRequest : class
where TResponse : class
{
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<ClientStreamingServerCallHandler<TRequest, TResponse>>();
readonly Method<TRequest, TResponse> method;
readonly ClientStreamingServerMethod<TRequest, TResponse> handler;
public ClientStreamingServerCallHandler(Method<TRequest, TResponse> method, ClientStreamingServerMethod<TRequest, TResponse> handler)
{
this.method = method;
this.handler = handler;
}
public async Task HandleCall(ServerRpcNew newRpc, CompletionQueueSafeHandle cq)
{
var asyncCall = new AsyncCallServer<TRequest, TResponse>(
method.ResponseMarshaller.Serializer,
method.RequestMarshaller.Deserializer,
newRpc.Server);
asyncCall.Initialize(newRpc.Call, cq);
var finishedTask = asyncCall.ServerSideCallAsync();
var requestStream = new ServerRequestStream<TRequest, TResponse>(asyncCall);
var responseStream = new ServerResponseStream<TRequest, TResponse>(asyncCall);
Status status;
AsyncCallServer<TRequest, TResponse>.ResponseWithFlags? responseWithFlags = null;
var context = HandlerUtils.NewContext(newRpc, responseStream, asyncCall.CancellationToken);
try
{
var response = await handler(requestStream, context).ConfigureAwait(false);
status = context.Status;
responseWithFlags = new AsyncCallServer<TRequest, TResponse>.ResponseWithFlags(response, HandlerUtils.GetWriteFlags(context.WriteOptions));
}
catch (Exception e)
{
if (!(e is RpcException))
{
Logger.Warning(e, "Exception occured in handler.");
}
status = HandlerUtils.GetStatusFromExceptionAndMergeTrailers(e, context.ResponseTrailers);
}
try
{
await asyncCall.SendStatusFromServerAsync(status, context.ResponseTrailers, responseWithFlags).ConfigureAwait(false);
}
catch (Exception)
{
asyncCall.Cancel();
throw;
}
await finishedTask.ConfigureAwait(false);
}
}
internal class DuplexStreamingServerCallHandler<TRequest, TResponse> : IServerCallHandler
where TRequest : class
where TResponse : class
{
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<DuplexStreamingServerCallHandler<TRequest, TResponse>>();
readonly Method<TRequest, TResponse> method;
readonly DuplexStreamingServerMethod<TRequest, TResponse> handler;
public DuplexStreamingServerCallHandler(Method<TRequest, TResponse> method, DuplexStreamingServerMethod<TRequest, TResponse> handler)
{
this.method = method;
this.handler = handler;
}
public async Task HandleCall(ServerRpcNew newRpc, CompletionQueueSafeHandle cq)
{
var asyncCall = new AsyncCallServer<TRequest, TResponse>(
method.ResponseMarshaller.Serializer,
method.RequestMarshaller.Deserializer,
newRpc.Server);
asyncCall.Initialize(newRpc.Call, cq);
var finishedTask = asyncCall.ServerSideCallAsync();
var requestStream = new ServerRequestStream<TRequest, TResponse>(asyncCall);
var responseStream = new ServerResponseStream<TRequest, TResponse>(asyncCall);
Status status;
var context = HandlerUtils.NewContext(newRpc, responseStream, asyncCall.CancellationToken);
try
{
await handler(requestStream, responseStream, context).ConfigureAwait(false);
status = context.Status;
}
catch (Exception e)
{
if (!(e is RpcException))
{
Logger.Warning(e, "Exception occured in handler.");
}
status = HandlerUtils.GetStatusFromExceptionAndMergeTrailers(e, context.ResponseTrailers);
}
try
{
await asyncCall.SendStatusFromServerAsync(status, context.ResponseTrailers, null).ConfigureAwait(false);
}
catch (Exception)
{
asyncCall.Cancel();
throw;
}
await finishedTask.ConfigureAwait(false);
}
}
internal class UnimplementedMethodCallHandler : IServerCallHandler
{
public static readonly UnimplementedMethodCallHandler Instance = new UnimplementedMethodCallHandler();
DuplexStreamingServerCallHandler<byte[], byte[]> callHandlerImpl;
public UnimplementedMethodCallHandler()
{
var marshaller = new Marshaller<byte[]>((payload) => payload, (payload) => payload);
var method = new Method<byte[], byte[]>(MethodType.DuplexStreaming, "", "", marshaller, marshaller);
this.callHandlerImpl = new DuplexStreamingServerCallHandler<byte[], byte[]>(method, new DuplexStreamingServerMethod<byte[], byte[]>(UnimplementedMethod));
}
/// <summary>
/// Handler used for unimplemented method.
/// </summary>
private Task UnimplementedMethod(IAsyncStreamReader<byte[]> requestStream, IServerStreamWriter<byte[]> responseStream, ServerCallContext ctx)
{
ctx.Status = new Status(StatusCode.Unimplemented, "");
return TaskUtils.CompletedTask;
}
public Task HandleCall(ServerRpcNew newRpc, CompletionQueueSafeHandle cq)
{
return callHandlerImpl.HandleCall(newRpc, cq);
}
}
internal static class HandlerUtils
{
public static Status GetStatusFromExceptionAndMergeTrailers(Exception e, Metadata callContextResponseTrailers)
{
var rpcException = e as RpcException;
if (rpcException != null)
{
// There are two sources of metadata entries on the server-side:
// 1. serverCallContext.ResponseTrailers
// 2. trailers in RpcException thrown by user code in server side handler.
// As metadata allows duplicate keys, the logical thing to do is
// to just merge trailers from RpcException into serverCallContext.ResponseTrailers.
foreach (var entry in rpcException.Trailers)
{
callContextResponseTrailers.Add(entry);
}
// use the status thrown by handler.
return rpcException.Status;
}
return new Status(StatusCode.Unknown, "Exception was thrown by handler.");
}
public static WriteFlags GetWriteFlags(WriteOptions writeOptions)
{
return writeOptions != null ? writeOptions.Flags : default(WriteFlags);
}
public static ServerCallContext NewContext<TRequest, TResponse>(ServerRpcNew newRpc, ServerResponseStream<TRequest, TResponse> serverResponseStream, CancellationToken cancellationToken)
where TRequest : class
where TResponse : class
{
DateTime realtimeDeadline = newRpc.Deadline.ToClockType(ClockType.Realtime).ToDateTime();
return new ServerCallContext(newRpc.Call, newRpc.Method, newRpc.Host, realtimeDeadline,
newRpc.RequestMetadata, cancellationToken, serverResponseStream.WriteResponseHeadersAsync, serverResponseStream);
}
}
}
| |
/*
* Copyright (c) 2011-2016, Will Strohl
* 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 Will Strohl, Disqus Module, nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using DotNetNuke.Entities.Controllers;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Modules.WillStrohlDisqus.Components;
using DotNetNuke.Services.Localization;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Scheduling;
namespace DotNetNuke.Modules.WillStrohlDisqus
{
/// <summary>
/// A base class for all module views to use
/// </summary>
public class WillStrohlDisqusModuleBase : Entities.Modules.PortalModuleBase
{
#region Private Members
private string p_DisqusApplicationName = string.Empty;
private string p_DisqusApiSecret = string.Empty;
private bool p_RequireDnnLogin = false;
private bool p_ScheduleEnabled = false;
private bool p_DisqusDeveloperMode = false;
private bool p_DisqusSsoEnabled = false;
private string p_DisqusSsoApiKey = string.Empty;
#endregion
#region Properties
/// <summary>
/// DisqusApplicationName
/// </summary>
/// <returns>The name of the Disqus Application that was created on Disqus.com</returns>
protected string DisqusApplicationName
{
get
{
// check to see if there is a module setting first
if (this.Settings["ApplicationName"] != null)
{
// converting from using module settings to site settings
// get the module setting value
p_DisqusApplicationName = this.Settings["ApplicationName"].ToString();
// copy the module setting to the site settings
PortalController.UpdatePortalSetting(PortalId, "wnsDisqusApplicationName", p_DisqusApplicationName, true, PortalSettings.CultureCode);
// delete the module setting
var ctlModule = new Entities.Modules.ModuleController();
ctlModule.DeleteModuleSetting(ModuleId, "ApplicationName");
}
else
{
string strAppName = PortalController.GetPortalSetting("ApplicationName", PortalId, string.Empty);
if (string.IsNullOrEmpty(strAppName) == false)
{
PortalController.UpdatePortalSetting(PortalId, "wnsDisqusApplicationName", strAppName, true, PortalSettings.CultureCode);
PortalController.DeletePortalSetting(PortalId, "ApplicationName");
}
p_DisqusApplicationName = PortalController.GetPortalSetting("wnsDisqusApplicationName", PortalId, string.Empty);
}
return p_DisqusApplicationName;
}
set { p_DisqusApplicationName = value; }
}
/// <summary>
/// DisqusApiSecret
/// </summary>
/// <returns>The API secret for the Disqus Application that was created on Disqus.com</returns>
protected string DisqusApiSecret
{
get
{
// check to see if there is a module setting first
if (this.Settings["ApiSecret"] != null)
{
// converting from using module settings to site settings
// get the module setting value
p_DisqusApiSecret = this.Settings["ApiSecret"].ToString();
// copy the module setting to the site settings
PortalController.UpdatePortalSetting(PortalId, "wnsDisqusApiSecret", p_DisqusApiSecret, true, PortalSettings.CultureCode);
// delete the module setting
var ctlModule = new Entities.Modules.ModuleController();
ctlModule.DeleteModuleSetting(ModuleId, "ApiSecret");
}
else
{
string strApiKey = PortalController.GetPortalSetting("ApiSecret", PortalId, string.Empty);
if (string.IsNullOrEmpty(strApiKey) == false)
{
PortalController.UpdatePortalSetting(PortalId, "wnsDisqusApiSecret", strApiKey, true, PortalSettings.CultureCode);
PortalController.DeletePortalSetting(PortalId, "ApiSecret");
}
p_DisqusApiSecret = PortalController.GetPortalSetting("wnsDisqusApiSecret", PortalId, string.Empty);
}
return p_DisqusApiSecret;
}
set { p_DisqusApiSecret = value; }
}
/// <summary>
/// RequireDnnLogin
/// </summary>
protected bool RequireDnnLogin
{
get
{
try
{
string strDnnLogin = PortalController.GetPortalSetting("RequireDnnLogin", PortalId, string.Empty);
if (string.IsNullOrEmpty(strDnnLogin) == false)
{
PortalController.UpdatePortalSetting(PortalId, "wnsDisqusRequireDnnLogin", strDnnLogin, true, PortalSettings.CultureCode);
PortalController.DeletePortalSetting(PortalId, "RequireDnnLogin");
}
p_RequireDnnLogin = bool.Parse(PortalController.GetPortalSetting("wnsDisqusRequireDnnLogin", PortalId, string.Empty));
}
catch
{
// the setting doesn't exist yet
p_RequireDnnLogin = false;
}
return p_RequireDnnLogin;
}
set { p_RequireDnnLogin = value; }
}
/// <summary>
/// ScheduleEnabled
/// </summary>
protected bool ScheduleEnabled
{
get
{
try
{
p_ScheduleEnabled = Convert.ToBoolean(HostController.Instance.GetString(FeatureController.HOST_SETTING_COMMENT_SCHEDULE, "false"));
ScheduleItem oSchedule = SchedulingProvider.Instance().GetSchedule(FeatureController.DISQUS_COMMENT_SCHEDULE_NAME, string.Empty);
if (oSchedule != null)
{
p_ScheduleEnabled = oSchedule.Enabled;
}
else
{
p_ScheduleEnabled = false;
}
}
catch(Exception ex)
{
Exceptions.LogException(ex);
// the setting doesn't exist yet
p_ScheduleEnabled = false;
}
return p_ScheduleEnabled;
}
set { p_ScheduleEnabled = value; }
}
/// <summary>
/// DisqusDeveloperMode
/// </summary>
protected bool DisqusDeveloperMode
{
get
{
try
{
string strDeveloperMode = PortalController.GetPortalSetting("wnsDisqusDeveloperMode", PortalId, "false");
p_DisqusDeveloperMode = bool.Parse(strDeveloperMode);
}
catch
{
// the setting doesn't exist yet
p_DisqusDeveloperMode = false;
}
return p_DisqusDeveloperMode;
}
set { p_DisqusDeveloperMode = value; }
}
/// <summary>
/// DisqusSsoEnabled
/// </summary>
protected bool DisqusSsoEnabled
{
get
{
try
{
string strSsoEnabled = PortalController.GetPortalSetting("wnsDisqusSsoEnabled", PortalId, "false");
p_DisqusSsoEnabled = bool.Parse(strSsoEnabled);
}
catch
{
// the setting doesn't exist yet
p_DisqusSsoEnabled = false;
}
return p_DisqusSsoEnabled;
}
set { p_DisqusSsoEnabled = value; }
}
/// <summary>
/// DisqusSsoApiKey
/// </summary>
protected string DisqusSsoApiKey
{
get
{
try
{
p_DisqusSsoApiKey = PortalController.GetPortalSetting("wnsDisqusSsoApiKey", PortalId, string.Empty);
}
catch
{
// the setting doesn't exist yet
p_DisqusSsoApiKey = string.Empty;
}
return p_DisqusSsoApiKey;
}
set { p_DisqusSsoApiKey = value; }
}
#endregion
#region Localization
/// <summary>
/// GetLocalizedString - A shortcut to localizing a string object
/// </summary>
/// <param name="localizationKey">a unique string key representing the localization value</param>
/// <returns></returns>
protected string GetLocalizedString(string localizationKey)
{
if (!string.IsNullOrEmpty(localizationKey))
{
return Localization.GetString(localizationKey, this.LocalResourceFile);
}
else
{
return string.Empty;
}
}
/// <summary>
/// GetLocalizedString - A shortcut to localizing a string object
/// </summary>
/// <param name="localizationKey">a unique string key representing the localization value</param>
/// <param name="localResourceFilePath">the path to the localization file</param>
/// <returns></returns>
protected string GetLocalizedString(string localizationKey, string localResourceFilePath)
{
if (!string.IsNullOrEmpty(localizationKey))
{
return Localization.GetString(localizationKey, localResourceFilePath);
}
else
{
return string.Empty;
}
}
#endregion
#region Event Handlers
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.PageLoad);
}
private void PageLoad(object sender, System.EventArgs e)
{
// request that the DNN framework load the jQuery script into the markup
DotNetNuke.Framework.jQuery.RequestDnnPluginsRegistration();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace OrchardCore.StorageProviders.FileSystem
{
public class FileSystemStore : IFileStore
{
private readonly string _localPath;
private readonly string _requestUrlPrefix;
private readonly string _pathPrefix;
private readonly string _publicPathPrefix;
public FileSystemStore(string localPath, string requestUrlPrefix, string pathPrefix)
{
_localPath = localPath;
_requestUrlPrefix = String.IsNullOrWhiteSpace(requestUrlPrefix) ? "" : "/" + NormalizePath(requestUrlPrefix);
_pathPrefix = pathPrefix;
_publicPathPrefix = String.IsNullOrEmpty(_requestUrlPrefix) ? _pathPrefix : Combine(_requestUrlPrefix, _pathPrefix);
}
public string Combine(params string[] paths)
{
var combined = String.Join("/", paths.Select(x => NormalizePath(x).Trim('/')));
// Preserve the initial '/' if it's present
if (paths.Length > 0 && paths[0].StartsWith("/"))
{
combined = "/" + combined;
}
// Remove the initial '/' if it was not present
if (paths.Length > 0 && !paths[0].StartsWith("/") && combined.StartsWith("/"))
{
combined = combined.TrimStart('/');
}
return combined;
}
private string NormalizePath(string path)
{
return path.Replace('\\', '/').Replace("//", "/").TrimEnd('/');
}
public Task<bool> TryCopyFileAsync(string originalPath, string duplicatePath)
{
try
{
File.Copy(GetPhysicalPath(originalPath), GetPhysicalPath(duplicatePath));
return Task.FromResult(true);
}
catch
{
return Task.FromResult(false);
}
}
public Task<bool> TryDeleteFileAsync(string subpath)
{
try
{
File.Delete(GetPhysicalPath(subpath));
return Task.FromResult(true);
}
catch
{
return Task.FromResult(false);
}
}
public Task<bool> TryDeleteFolderAsync(string subpath)
{
try
{
Directory.Delete(GetPhysicalPath(subpath), true);
return Task.FromResult(true);
}
catch
{
return Task.FromResult(false);
}
}
public Task<IEnumerable<IFile>> GetDirectoryContentAsync(string subpath = null)
{
var results = new List<IFile>();
// Add directories
results.AddRange(Directory
.GetDirectories(GetPhysicalPath(subpath))
.Select(f =>
{
var fileInfo = new DirectoryInfo(f);
var fileSubPath = f.Substring(_localPath.Length);
return new FileSystemFile(fileSubPath, _publicPathPrefix, fileInfo);
}).ToArray()
);
// Add files
results.AddRange(Directory
.GetFiles(GetPhysicalPath(subpath))
.Select(f =>
{
var fileInfo = new FileInfo(f);
var fileSubPath = f.Substring(_localPath.Length);
return new FileSystemFile(fileSubPath, _publicPathPrefix, fileInfo);
}).ToArray()
);
return Task.FromResult((IEnumerable<IFile>)results);
}
public Task<IFile> GetFileAsync(string subpath)
{
var physicalPath = GetPhysicalPath(subpath);
var fileInfo = new FileInfo(physicalPath);
if (fileInfo.Exists)
{
return Task.FromResult<IFile>(new FileSystemFile(subpath, _publicPathPrefix, fileInfo));
}
return Task.FromResult<IFile>(null);
}
public Task<IFile> GetFolderAsync(string subpath)
{
var physicalPath = GetPhysicalPath(subpath);
var directoryInfo = new DirectoryInfo(physicalPath);
if (directoryInfo.Exists)
{
return Task.FromResult<IFile>(new FileSystemFile(subpath, _publicPathPrefix, directoryInfo));
}
return Task.FromResult<IFile>(null);
}
public Task<bool> TryCreateFolderAsync(string subpath)
{
try
{
// Use CreateSubdirectory to ensure the directory doesn't go over its boundaries
new DirectoryInfo(_localPath).CreateSubdirectory(subpath);
return Task.FromResult(true);
}
catch
{
return Task.FromResult(false);
}
}
public Task<IFile> MapFileAsync(string absoluteUrl)
{
if (!absoluteUrl.StartsWith(_pathPrefix, StringComparison.OrdinalIgnoreCase))
{
return Task.FromResult(default(IFile));
}
return GetFileAsync(absoluteUrl.Substring(_pathPrefix.Length));
}
public Task<bool> TryMoveFileAsync(string oldPath, string newPath)
{
try
{
File.Move(GetPhysicalPath(oldPath), GetPhysicalPath(newPath));
return Task.FromResult(true);
}
catch
{
return Task.FromResult(true);
}
}
public Task<bool> TryMoveFolderAsync(string oldPath, string newPath)
{
try
{
Directory.Move(GetPhysicalPath(oldPath), GetPhysicalPath(newPath));
return Task.FromResult(true);
}
catch
{
return Task.FromResult(false);
}
}
public async Task<bool> TrySaveStreamAsync(string filename, Stream inputStream)
{
try
{
var path = Path.GetDirectoryName(filename);
var mediaFolder = await GetFolderAsync(path);
if (mediaFolder == null)
{
await TryCreateFolderAsync(path);
}
var fileInfo = new FileInfo(GetPhysicalPath(filename));
// Ensure the file will be in the targetted folder
var directoryInfo = fileInfo.Directory;
var rootDirectory = new DirectoryInfo(_localPath);
if (!directoryInfo.FullName.StartsWith(rootDirectory.FullName))
{
throw new ArgumentException("Attemp to create a file outside of the Media folder: " + filename);
}
using (var outputStream = fileInfo.Create())
{
await inputStream.CopyToAsync(outputStream);
}
}
catch
{
return false;
}
return true;
}
private string GetPhysicalPath(string subpath)
{
subpath = "/" + NormalizePath(subpath);
string physicalPath = string.IsNullOrEmpty(subpath) ? _localPath : _localPath + subpath;
return ValidatePath(_localPath, physicalPath);
}
/// <summary>
/// Determines if a path lies within the base path boundaries.
/// If not, an exception is thrown.
/// </summary>
/// <param name="basePath">The base path which boundaries are not to be transposed.</param>
/// <param name="physicalPath">The path to determine.</param>
/// <rereturns>The mapped path if valid.</rereturns>
/// <exception cref="ArgumentException">If the path is invalid.</exception>
public static string ValidatePath(string basePath, string physicalPath)
{
// Check that we are indeed within the storage directory boundaries
var valid = Path.GetFullPath(physicalPath).StartsWith(Path.GetFullPath(basePath), StringComparison.OrdinalIgnoreCase);
if (!valid)
{
throw new ArgumentException("Invalid path");
}
return physicalPath;
}
public string GetPublicUrl(string subpath)
{
return Combine(_publicPathPrefix, subpath);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
/*============================================================
**
**
** Purpose: part of ComEventHelpers APIs which allow binding
** managed delegates to COM's connection point based events.
**
**/
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Reflection;
namespace System.Runtime.InteropServices {
// see code:ComEventsHelper#ComEventsArchitecture
internal class ComEventsMethod {
// This delegate wrapper class handles dynamic invocation of delegates. The reason for the wrapper's
// existence is that under certain circumstances we need to coerce arguments to types expected by the
// delegates signature. Normally, reflection (Delegate.DynamicInvoke) handles types coercion
// correctly but one known case is when the expected signature is 'ref Enum' - in this case
// reflection by design does not do the coercion. Since we need to be compatible with COM interop
// handling of this scenario - we are pre-processing delegate's signature by looking for 'ref enums'
// and cache the types required for such coercion.
internal class DelegateWrapper {
private Delegate _d;
private bool _once = false;
private int _expectedParamsCount;
private Type[] _cachedTargetTypes;
public DelegateWrapper(Delegate d) {
_d = d;
}
public Delegate Delegate {
get { return _d; }
set { _d = value; }
}
public object Invoke(object[] args) {
if (_d == null)
return null;
if (_once == false) {
PreProcessSignature();
_once = true;
}
if (_cachedTargetTypes != null && _expectedParamsCount == args.Length) {
for (int i = 0; i < _expectedParamsCount; i++) {
if (_cachedTargetTypes[i] != null) {
args[i] = Enum.ToObject(_cachedTargetTypes[i], args[i]);
}
}
}
return _d.DynamicInvoke(args);
}
private void PreProcessSignature() {
ParameterInfo[] parameters = _d.Method.GetParameters();
_expectedParamsCount = parameters.Length;
Type[] enumTypes = new Type[_expectedParamsCount];
bool needToHandleCoercion = false;
for (int i = 0; i < _expectedParamsCount; i++) {
ParameterInfo pi = parameters[i];
// recognize only 'ref Enum' signatures and cache
// both enum type and the underlying type.
if (pi.ParameterType.IsByRef &&
pi.ParameterType.HasElementType &&
pi.ParameterType.GetElementType().IsEnum) {
needToHandleCoercion = true;
enumTypes[i] = pi.ParameterType.GetElementType();
}
}
if (needToHandleCoercion == true) {
_cachedTargetTypes = enumTypes;
}
}
}
#region private fields
/// <summary>
/// Invoking ComEventsMethod means invoking a multi-cast delegate attached to it.
/// Since multicast delegate's built-in chaining supports only chaining instances of the same type,
/// we need to complement this design by using an explicit linked list data structure.
/// </summary>
private DelegateWrapper [] _delegateWrappers;
private int _dispid;
private ComEventsMethod _next;
#endregion
#region ctor
internal ComEventsMethod(int dispid) {
_delegateWrappers = null;
_dispid = dispid;
}
#endregion
#region static internal methods
internal static ComEventsMethod Find(ComEventsMethod methods, int dispid) {
while (methods != null && methods._dispid != dispid) {
methods = methods._next;
}
return methods;
}
internal static ComEventsMethod Add(ComEventsMethod methods, ComEventsMethod method) {
method._next = methods;
return method;
}
internal static ComEventsMethod Remove(ComEventsMethod methods, ComEventsMethod method) {
if (methods == method) {
methods = methods._next;
} else {
ComEventsMethod current = methods;
while (current != null && current._next != method)
current = current._next;
if (current != null)
current._next = method._next;
}
return methods;
}
#endregion
#region public properties / methods
internal int DispId {
get { return _dispid; }
}
internal bool Empty {
get { return _delegateWrappers == null || _delegateWrappers.Length == 0; }
}
internal void AddDelegate(Delegate d) {
int count = 0;
if (_delegateWrappers != null) {
count = _delegateWrappers.Length;
}
for (int i = 0; i < count; i++) {
if (_delegateWrappers[i].Delegate.GetType() == d.GetType()) {
_delegateWrappers[i].Delegate = Delegate.Combine(_delegateWrappers[i].Delegate, d);
return;
}
}
DelegateWrapper [] newDelegateWrappers = new DelegateWrapper[count + 1];
if (count > 0) {
_delegateWrappers.CopyTo(newDelegateWrappers, 0);
}
DelegateWrapper wrapper = new DelegateWrapper(d);
newDelegateWrappers[count] = wrapper;
_delegateWrappers = newDelegateWrappers;
}
internal void RemoveDelegate(Delegate d) {
int count = _delegateWrappers.Length;
int removeIdx = -1;
for (int i = 0; i < count; i++) {
if (_delegateWrappers[i].Delegate.GetType() == d.GetType()) {
removeIdx = i;
break;
}
}
if (removeIdx < 0)
return;
Delegate newDelegate = Delegate.Remove(_delegateWrappers[removeIdx].Delegate, d);
if (newDelegate != null) {
_delegateWrappers[removeIdx].Delegate = newDelegate;
return;
}
// now remove the found entry from the _delegates array
if (count == 1) {
_delegateWrappers = null;
return;
}
DelegateWrapper [] newDelegateWrappers = new DelegateWrapper[count - 1];
int j = 0;
while (j < removeIdx) {
newDelegateWrappers[j] = _delegateWrappers[j];
j++;
}
while (j < count-1) {
newDelegateWrappers[j] = _delegateWrappers[j + 1];
j++;
}
_delegateWrappers = newDelegateWrappers;
}
internal object Invoke(object[] args) {
BCLDebug.Assert(Empty == false, "event sink is executed but delegates list is empty");
// Issue: see code:ComEventsHelper#ComEventsRetValIssue
object result = null;
DelegateWrapper[] invocationList = _delegateWrappers;
foreach (DelegateWrapper wrapper in invocationList) {
if (wrapper == null || wrapper.Delegate == null)
continue;
result = wrapper.Invoke(args);
}
return result;
}
#endregion
}
}
| |
// This file was created automatically, do not modify the contents of this file.
// ReSharper disable InvalidXmlDocComment
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable MemberCanBePrivate.Global
using System;
using System.Runtime.InteropServices;
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\AIModule\Classes\EnvironmentQuery\Tests\EnvQueryTest_Pathfinding.h:31
namespace UnrealEngine
{
[ManageType("ManageEnvQueryTest_Pathfinding")]
public partial class ManageEnvQueryTest_Pathfinding : UEnvQueryTest_Pathfinding, IManageWrapper
{
public ManageEnvQueryTest_Pathfinding(IntPtr adress)
: base(adress)
{
}
#region DLLInmport
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryTest_Pathfinding_UpdateNodeVersion(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryTest_Pathfinding_BeginDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryTest_Pathfinding_FinishDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryTest_Pathfinding_MarkAsEditorOnlySubobject(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryTest_Pathfinding_PostCDOContruct(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryTest_Pathfinding_PostEditImport(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryTest_Pathfinding_PostInitProperties(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryTest_Pathfinding_PostLoad(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryTest_Pathfinding_PostNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryTest_Pathfinding_PostRepNotifies(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryTest_Pathfinding_PostSaveRoot(IntPtr self, bool bCleanupIsRequired);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryTest_Pathfinding_PreDestroyFromReplication(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryTest_Pathfinding_PreNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryTest_Pathfinding_ShutdownAfterError(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryTest_Pathfinding_CreateCluster(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryTest_Pathfinding_OnClusterMarkedAsPendingKill(IntPtr self);
#endregion
#region Methods
public override void UpdateNodeVersion()
=> E__Supper__UEnvQueryTest_Pathfinding_UpdateNodeVersion(this);
/// <summary>
/// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an
/// <para>asynchronous cleanup process. </para>
/// </summary>
public override void BeginDestroy()
=> E__Supper__UEnvQueryTest_Pathfinding_BeginDestroy(this);
/// <summary>
/// Called to finish destroying the object. After UObject::FinishDestroy is called, the object's memory should no longer be accessed.
/// <para>@warning Because properties are destroyed here, Super::FinishDestroy() should always be called at the end of your child class's FinishDestroy() method, rather than at the beginning. </para>
/// </summary>
public override void FinishDestroy()
=> E__Supper__UEnvQueryTest_Pathfinding_FinishDestroy(this);
/// <summary>
/// Called during subobject creation to mark this component as editor only, which causes it to get stripped in packaged builds
/// </summary>
public override void MarkAsEditorOnlySubobject()
=> E__Supper__UEnvQueryTest_Pathfinding_MarkAsEditorOnlySubobject(this);
/// <summary>
/// Called after the C++ constructor has run on the CDO for a class. This is an obscure routine used to deal with the recursion
/// <para>in the construction of the default materials </para>
/// </summary>
public override void PostCDOContruct()
=> E__Supper__UEnvQueryTest_Pathfinding_PostCDOContruct(this);
/// <summary>
/// Called after importing property values for this object (paste, duplicate or .t3d import)
/// <para>Allow the object to perform any cleanup for properties which shouldn't be duplicated or </para>
/// are unsupported by the script serialization
/// </summary>
public override void PostEditImport()
=> E__Supper__UEnvQueryTest_Pathfinding_PostEditImport(this);
/// <summary>
/// Called after the C++ constructor and after the properties have been initialized, including those loaded from config.
/// <para>This is called before any serialization or other setup has happened. </para>
/// </summary>
public override void PostInitProperties()
=> E__Supper__UEnvQueryTest_Pathfinding_PostInitProperties(this);
/// <summary>
/// Do any object-specific cleanup required immediately after loading an object.
/// <para>This is not called for newly-created objects, and by default will always execute on the game thread. </para>
/// </summary>
public override void PostLoad()
=> E__Supper__UEnvQueryTest_Pathfinding_PostLoad(this);
/// <summary>
/// Called right after receiving a bunch
/// </summary>
public override void PostNetReceive()
=> E__Supper__UEnvQueryTest_Pathfinding_PostNetReceive(this);
/// <summary>
/// Called right after calling all OnRep notifies (called even when there are no notifies)
/// </summary>
public override void PostRepNotifies()
=> E__Supper__UEnvQueryTest_Pathfinding_PostRepNotifies(this);
/// <summary>
/// Called from within SavePackage on the passed in base/root object.
/// <para>This function is called after the package has been saved and can perform cleanup. </para>
/// </summary>
/// <param name="bCleanupIsRequired">Whether PreSaveRoot dirtied state that needs to be cleaned up</param>
public override void PostSaveRoot(bool bCleanupIsRequired)
=> E__Supper__UEnvQueryTest_Pathfinding_PostSaveRoot(this, bCleanupIsRequired);
/// <summary>
/// Called right before being marked for destruction due to network replication
/// </summary>
public override void PreDestroyFromReplication()
=> E__Supper__UEnvQueryTest_Pathfinding_PreDestroyFromReplication(this);
/// <summary>
/// Called right before receiving a bunch
/// </summary>
public override void PreNetReceive()
=> E__Supper__UEnvQueryTest_Pathfinding_PreNetReceive(this);
/// <summary>
/// After a critical error, perform any mission-critical cleanup, such as restoring the video mode orreleasing hardware resources.
/// </summary>
public override void ShutdownAfterError()
=> E__Supper__UEnvQueryTest_Pathfinding_ShutdownAfterError(this);
/// <summary>
/// Called after PostLoad to create UObject cluster
/// </summary>
public override void CreateCluster()
=> E__Supper__UEnvQueryTest_Pathfinding_CreateCluster(this);
/// <summary>
/// Called during Garbage Collection to perform additional cleanup when the cluster is about to be destroyed due to PendingKill flag being set on it.
/// </summary>
public override void OnClusterMarkedAsPendingKill()
=> E__Supper__UEnvQueryTest_Pathfinding_OnClusterMarkedAsPendingKill(this);
#endregion
public static implicit operator IntPtr(ManageEnvQueryTest_Pathfinding self)
{
return self?.NativePointer ?? IntPtr.Zero;
}
public static implicit operator ManageEnvQueryTest_Pathfinding(ObjectPointerDescription PtrDesc)
{
return NativeManager.GetWrapper<ManageEnvQueryTest_Pathfinding>(PtrDesc);
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
using NPOI.SS.UserModel;
using System;
using Spreadsheet=NPOI.OpenXmlFormats.Spreadsheet;
using NPOI.OpenXmlFormats.Spreadsheet;
using NPOI.OpenXmlFormats.Dml;
using Dml = NPOI.OpenXmlFormats.Dml;
using NPOI.XSSF.Model;
using NPOI.Util;
namespace NPOI.XSSF.UserModel
{
/**
* Represents a font used in a workbook.
*
* @author Gisella Bronzetti
*/
public class XSSFFont : IFont
{
/**
* By default, Microsoft Office Excel 2007 uses the Calibry font in font size 11
*/
public const String DEFAULT_FONT_NAME = "Calibri";
/**
* By default, Microsoft Office Excel 2007 uses the Calibry font in font size 11
*/
public const short DEFAULT_FONT_SIZE = 11;
/**
* Default font color is black
* @see NPOI.SS.usermodel.IndexedColors#BLACK
*/
public static short DEFAULT_FONT_COLOR = IndexedColors.Black.Index;
private ThemesTable _themes;
private CT_Font _ctFont;
private short _index;
/**
* Create a new XSSFFont
*
* @param font the underlying CT_Font bean
*/
public XSSFFont(CT_Font font)
{
_ctFont = font;
_index = 0;
}
public XSSFFont(CT_Font font, int index)
{
_ctFont = font;
_index = (short)index;
}
/**
* Create a new XSSFont. This method is protected to be used only by XSSFWorkbook
*/
public XSSFFont()
{
this._ctFont = new CT_Font();
FontName = DEFAULT_FONT_NAME;
FontHeightInPoints =DEFAULT_FONT_SIZE;
}
/**
* get the underlying CT_Font font
*/
public CT_Font GetCTFont()
{
return _ctFont;
}
/**
* get a bool value for the boldness to use.
*
* @return bool - bold
*/
public bool IsBold
{
get
{
CT_BooleanProperty bold = _ctFont.SizeOfBArray() == 0 ? null : _ctFont.GetBArray(0);
return (bold != null && bold.val);
}
set
{
if (value)
{
CT_BooleanProperty ctBold = _ctFont.SizeOfBArray() == 0 ? _ctFont.AddNewB() : _ctFont.GetBArray(0);
ctBold.val = value;
}
else
{
_ctFont.SetBArray(null);
}
}
}
/**
* get character-set to use.
*
* @return int - character-set (0-255)
* @see NPOI.SS.usermodel.FontCharset
*/
public short Charset
{
get
{
CT_IntProperty charset = _ctFont.sizeOfCharsetArray() == 0 ? null : _ctFont.GetCharsetArray(0);
int val = charset == null ? FontCharset.ANSI.Value : FontCharset.ValueOf(charset.val).Value;
return (short)val;
}
set
{
}
}
/**
* get the indexed color value for the font
* References a color defined in IndexedColors.
*
* @return short - indexed color to use
* @see IndexedColors
*/
public short Color
{
get
{
Spreadsheet.CT_Color color = _ctFont.sizeOfColorArray() == 0 ? null : _ctFont.GetColorArray(0);
if (color == null) return IndexedColors.Black.Index;
//if (!color.indexedSpecified) return IndexedColors.Black.Index;
long index = color.indexed;
if (index == XSSFFont.DEFAULT_FONT_COLOR)
{
return IndexedColors.Black.Index;
}
else if (index == IndexedColors.Red.Index)
{
return IndexedColors.Red.Index;
}
else
{
return (short)index;
}
}
set
{
Spreadsheet.CT_Color ctColor = _ctFont.sizeOfColorArray() == 0 ? _ctFont.AddNewColor() : _ctFont.GetColorArray(0);
switch (value)
{
case (short)FontColor.Normal:
ctColor.indexed = (uint)(XSSFFont.DEFAULT_FONT_COLOR);
ctColor.indexedSpecified = true;
break;
case (short)FontColor.Red:
ctColor.indexed = (uint)(IndexedColors.Red.Index);
ctColor.indexedSpecified = true;
break;
default:
ctColor.indexed = (uint)(value);
ctColor.indexedSpecified = true;
break;
}
}
}
/**
* get the color value for the font
* References a color defined as Standard Alpha Red Green Blue color value (ARGB).
*
* @return XSSFColor - rgb color to use
*/
public XSSFColor GetXSSFColor()
{
Spreadsheet.CT_Color ctColor = _ctFont.sizeOfColorArray() == 0 ? null : _ctFont.GetColorArray(0);
if (ctColor != null)
{
XSSFColor color = new XSSFColor(ctColor);
if (_themes != null)
{
_themes.InheritFromThemeAsRequired(color);
}
return color;
}
else
{
return null;
}
}
/**
* get the color value for the font
* References a color defined in theme.
*
* @return short - theme defined to use
*/
public short GetThemeColor()
{
Spreadsheet.CT_Color color = _ctFont.sizeOfColorArray() == 0 ? null : _ctFont.GetColorArray(0);
long index = ((color == null) || !color.themeSpecified) ? 0 : color.theme;
return (short)index;
}
/// <summary>
/// Get the font height in unit's of 1/20th of a point.
/// </summary>
public double FontHeight
{
get
{
return FontHeightRaw * 20.0;
}
set
{
FontHeightRaw = value / 20.0;
}
}
/// <summary>
/// Get the font height in points.
/// </summary>
public double FontHeightInPoints
{
get
{
return FontHeightRaw;
}
set
{
FontHeightRaw = value;
}
}
private double FontHeightRaw
{
get
{
CT_FontSize size = _ctFont.sizeOfSzArray() == 0 ? null : _ctFont.GetSzArray(0);
if (size != null)
{
double fontHeight = size.val;
return fontHeight;
}
return DEFAULT_FONT_SIZE;
}
set {
CT_FontSize fontSize = _ctFont.sizeOfSzArray() == 0 ? _ctFont.AddNewSz() : _ctFont.GetSzArray(0);
fontSize.val = value;
}
}
/**
* get the name of the font (i.e. Arial)
*
* @return String - a string representing the name of the font to use
*/
public String FontName
{
get
{
CT_FontName name = _ctFont.name;
return name == null ? DEFAULT_FONT_NAME : name.val;
}
set
{
CT_FontName fontName = _ctFont.name==null?_ctFont.AddNewName():_ctFont.name;
fontName.val = value == null ? DEFAULT_FONT_NAME : value;
}
}
/**
* get a bool value that specify whether to use italics or not
*
* @return bool - value for italic
*/
public bool IsItalic
{
get
{
CT_BooleanProperty italic = _ctFont.sizeOfIArray() == 0 ? null : _ctFont.GetIArray(0);
return italic != null && italic.val;
}
set
{
if (value)
{
CT_BooleanProperty bool1 = _ctFont.sizeOfIArray() == 0 ? _ctFont.AddNewI() : _ctFont.GetIArray(0);
bool1.val = value;
}
else
{
_ctFont.SetIArray(null);
}
}
}
/**
* get a bool value that specify whether to use a strikeout horizontal line through the text or not
*
* @return bool - value for strikeout
*/
public bool IsStrikeout
{
get
{
CT_BooleanProperty strike = _ctFont.sizeOfStrikeArray() == 0 ? null : _ctFont.GetStrikeArray(0);
return strike != null && strike.val;
}
set
{
if (!value) _ctFont.SetStrikeArray(null);
else
{
CT_BooleanProperty strike = _ctFont.sizeOfStrikeArray() == 0 ? _ctFont.AddNewStrike() : _ctFont.GetStrikeArray(0);
strike.val = value;
}
}
}
/**
* get normal,super or subscript.
*
* @return short - offset type to use (none,super,sub)
* @see Font#SS_NONE
* @see Font#SS_SUPER
* @see Font#SS_SUB
*/
public FontSuperScript TypeOffset
{
get
{
CT_VerticalAlignFontProperty vAlign = _ctFont.sizeOfVertAlignArray() == 0 ? null : _ctFont.GetVertAlignArray(0);
if (vAlign == null)
{
return FontSuperScript.None;
}
ST_VerticalAlignRun val = vAlign.val;
switch (val)
{
case ST_VerticalAlignRun.baseline:
return FontSuperScript.None;
case ST_VerticalAlignRun.subscript:
return FontSuperScript.Sub;
case ST_VerticalAlignRun.superscript:
return FontSuperScript.Super;
default:
throw new POIXMLException("Wrong offset value " + val);
}
}
set
{
if (value == (short)FontSuperScript.None)
{
_ctFont.SetVertAlignArray(null);
}
else
{
CT_VerticalAlignFontProperty offSetProperty = _ctFont.sizeOfVertAlignArray() == 0 ? _ctFont.AddNewVertAlign() : _ctFont.GetVertAlignArray(0);
switch (value)
{
case FontSuperScript.None:
offSetProperty.val = ST_VerticalAlignRun.baseline;
break;
case FontSuperScript.Sub:
offSetProperty.val = ST_VerticalAlignRun.subscript;
break;
case FontSuperScript.Super:
offSetProperty.val = ST_VerticalAlignRun.superscript;
break;
default:
throw new InvalidOperationException("Invalid type offset: " + value);
}
}
}
}
/**
* get type of text underlining to use
*
* @return byte - underlining type
* @see NPOI.SS.usermodel.FontUnderline
*/
public FontUnderlineType Underline
{
get
{
CT_UnderlineProperty underline = _ctFont.sizeOfUArray() == 0 ? null : _ctFont.GetUArray(0);
if (underline != null)
{
FontUnderline val = FontUnderline.ValueOf((int)underline.val);
return (FontUnderlineType)val.ByteValue;
}
return (FontUnderlineType)FontUnderline.NONE.ByteValue;
}
set
{
SetUnderline(value);
}
}
/**
* get the boldness to use
* @return boldweight
* @see #BOLDWEIGHT_NORMAL
* @see #BOLDWEIGHT_BOLD
*/
[Obsolete("deprecated POI 3.15 beta 2. Use IsBold instead.")]
public short Boldweight
{
get
{
return (IsBold ? (short)FontBoldWeight.Bold : (short)FontBoldWeight.Normal);
}
set
{
this.IsBold = (value == (short)FontBoldWeight.Bold);
}
}
/**
* set character-set to use.
*
* @param charset - charset
* @see FontCharset
*/
public void SetCharSet(byte charset)
{
int cs = charset & 0xff;
SetCharSet(cs);
}
/**
* set character-set to use.
*
* @param charset - charset
* @see FontCharset
*/
public void SetCharSet(int charset)
{
FontCharset FontCharset = FontCharset.ValueOf(charset);
if (FontCharset != null)
{
SetCharSet(FontCharset);
}
else
{
throw new POIXMLException("Attention: An attempt was made to set an unknown character set");
}
}
/**
* set character-set to use.
*
* @param charSet
*/
public void SetCharSet(FontCharset charset)
{
CT_IntProperty charSetProperty;
if (_ctFont.sizeOfCharsetArray() == 0)
{
charSetProperty = _ctFont.AddNewCharset();
}
else
{
charSetProperty = _ctFont.GetCharsetArray(0);
}
// We know that FontCharset only has valid entries in it,
// so we can just set the int value from it
charSetProperty.val = charset.Value;
}
/**
* set the color for the font in Standard Alpha Red Green Blue color value
*
* @param color - color to use
*/
public void SetColor(XSSFColor color)
{
if (color == null) _ctFont.SetColorArray(null);
else
{
Spreadsheet.CT_Color ctColor = _ctFont.sizeOfColorArray() == 0 ? _ctFont.AddNewColor() : _ctFont.GetColorArray(0);
if (ctColor.IsSetIndexed())
{
ctColor.UnsetIndexed();
}
ctColor.SetRgb(color.RGB);
}
}
/**
* set the theme color for the font to use
*
* @param theme - theme color to use
*/
public void SetThemeColor(short theme)
{
Spreadsheet.CT_Color ctColor = _ctFont.sizeOfColorArray() == 0 ? _ctFont.AddNewColor() : _ctFont.GetColorArray(0);
ctColor.theme = (uint)theme;
}
/**
* set an enumeration representing the style of underlining that is used.
* The none style is equivalent to not using underlining at all.
* The possible values for this attribute are defined by the FontUnderline
*
* @param underline - FontUnderline enum value
*/
internal void SetUnderline(FontUnderlineType underline)
{
if (underline == FontUnderlineType.None)
{
_ctFont.SetUArray(null);
}
else
{
CT_UnderlineProperty ctUnderline = _ctFont.sizeOfUArray() == 0 ? _ctFont.AddNewU() : _ctFont.GetUArray(0);
ST_UnderlineValues val = (ST_UnderlineValues)FontUnderline.ValueOf(underline).Value;
ctUnderline.val = val;
}
}
public override String ToString()
{
return _ctFont.ToString();
}
///**
// * Perform a registration of ourselves
// * to the style table
// */
public long RegisterTo(StylesTable styles)
{
this._themes = styles.GetTheme();
short idx = (short)styles.PutFont(this, true);
this._index = idx;
return idx;
}
/**
* Records the Themes Table that is associated with
* the current font, used when looking up theme
* based colours and properties.
*/
public void SetThemesTable(ThemesTable themes)
{
this._themes = themes;
}
/**
* get the font scheme property.
* is used only in StylesTable to create the default instance of font
*
* @return FontScheme
* @see NPOI.XSSF.model.StylesTable#CreateDefaultFont()
*/
public FontScheme GetScheme()
{
NPOI.OpenXmlFormats.Spreadsheet.CT_FontScheme scheme = _ctFont.sizeOfSchemeArray() == 0 ? null : _ctFont.GetSchemeArray(0);
return scheme == null ? FontScheme.NONE : FontScheme.ValueOf((int)scheme.val);
}
/**
* set font scheme property
*
* @param scheme - FontScheme enum value
* @see FontScheme
*/
public void SetScheme(FontScheme scheme)
{
NPOI.OpenXmlFormats.Spreadsheet.CT_FontScheme ctFontScheme = _ctFont.sizeOfSchemeArray() == 0 ? _ctFont.AddNewScheme() : _ctFont.GetSchemeArray(0);
ST_FontScheme val = (ST_FontScheme)scheme.Value;
ctFontScheme.val = val;
}
/**
* get the font family to use.
*
* @return the font family to use
* @see NPOI.SS.usermodel.FontFamily
*/
public int Family
{
get
{
CT_IntProperty family = _ctFont.sizeOfFamilyArray() == 0 ? _ctFont.AddNewFamily() : _ctFont.GetFamilyArray(0);
return family == null ? FontFamily.NOT_APPLICABLE.Value : FontFamily.ValueOf(family.val).Value;
}
set
{
CT_IntProperty family = _ctFont.sizeOfFamilyArray() == 0 ? _ctFont.AddNewFamily() : _ctFont.GetFamilyArray(0);
family.val = value;
}
}
/**
* set an enumeration representing the font family this font belongs to.
* A font family is a set of fonts having common stroke width and serif characteristics.
*
* @param family font family
* @link #SetFamily(int value)
*/
public void SetFamily(FontFamily family)
{
Family = family.Value;
}
/**
* get the index within the XSSFWorkbook (sequence within the collection of Font objects)
* @return unique index number of the underlying record this Font represents (probably you don't care
* unless you're comparing which one is which)
*/
public short Index
{
get
{
return _index;
}
}
public override int GetHashCode()
{
return _ctFont.ToString().GetHashCode();
}
public override bool Equals(Object o)
{
if (!(o is XSSFFont)) return false;
XSSFFont cf = (XSSFFont)o;
return _ctFont.ToString().Equals(cf.GetCTFont().ToString());
}
public void CloneStyleFrom(IFont src)
{
if (src != null)
{
if (src is XSSFFont)
{
_ctFont = ((XSSFFont)src)._ctFont;
}
else
{
FontName = src.FontName;
FontHeight = src.FontHeight;
IsBold = src.IsBold;
Boldweight = src.Boldweight;
IsItalic = src.IsItalic;
IsStrikeout = src.IsStrikeout;
Color = src.Color;
Underline = src.Underline;
Charset = src.Charset;
TypeOffset = src.TypeOffset;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using CalorieCounter.API.Areas.HelpPage.ModelDescriptions;
using CalorieCounter.API.Areas.HelpPage.Models;
namespace CalorieCounter.API.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
/* ====================================================================
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 TestCases.Util
{
using System;
using NUnit.Framework;
using NPOI.Util;
/**
* Class to Test ShortList
*
* @author Marc Johnson
*/
[TestFixture]
public class TestShortList
{
[Test]
public void TestConstructors()
{
ShortList list = new ShortList();
Assert.IsTrue(list.IsEmpty());
list.Add((short)0);
list.Add((short)1);
ShortList list2 = new ShortList(list);
//Assert.AreEqual(list, list2);
Assert.IsTrue(list.Equals(list2));
ShortList list3 = new ShortList(2);
Assert.IsTrue(list3.IsEmpty());
}
[Test]
public void TestAdd()
{
ShortList list = new ShortList();
short[] testArray =
{
0, 1, 2, 3, 5
};
for (int j = 0; j < testArray.Length; j++)
{
list.Add(testArray[j]);
}
for (int j = 0; j < testArray.Length; j++)
{
Assert.AreEqual(testArray[j], list.Get(j));
}
Assert.AreEqual(testArray.Length, list.Count);
// add at the beginning
list.Add(0, (short)-1);
Assert.AreEqual((short)-1, list.Get(0));
Assert.AreEqual(testArray.Length + 1, list.Count);
for (int j = 0; j < testArray.Length; j++)
{
Assert.AreEqual(testArray[j], list.Get(j + 1));
}
// add in the middle
list.Add(5, (short)4);
Assert.AreEqual((short)4, list.Get(5));
Assert.AreEqual(testArray.Length + 2, list.Count);
for (int j = 0; j < list.Count; j++)
{
Assert.AreEqual((short)(j - 1), list.Get(j));
}
// add at the end
list.Add(list.Count, (short)6);
Assert.AreEqual(testArray.Length + 3, list.Count);
for (int j = 0; j < list.Count; j++)
{
Assert.AreEqual((short)(j - 1), list.Get(j));
}
// add past end
try
{
list.Add(list.Count + 1, (short)8);
Assert.Fail("should have thrown exception");
}
catch (IndexOutOfRangeException)
{
// as expected
}
// Test growth
list = new ShortList(0);
for (short j = 0; j < 1000; j++)
{
list.Add(j);
}
Assert.AreEqual(1000, list.Count);
for (short j = 0; j < 1000; j++)
{
Assert.AreEqual(j, list.Get(j));
}
list = new ShortList(0);
for (short j = 0; j < 1000; j++)
{
list.Add(0, j);
}
Assert.AreEqual(1000, list.Count);
for (short j = 0; j < 1000; j++)
{
Assert.AreEqual(j, list.Get(999 - j));
}
}
[Test]
public void TestAddAll()
{
ShortList list = new ShortList();
for (short j = 0; j < 5; j++)
{
list.Add(j);
}
ShortList list2 = new ShortList(0);
list2.AddAll(list);
list2.AddAll(list);
Assert.AreEqual(2 * list.Count, list2.Count);
for (short j = 0; j < 5; j++)
{
Assert.AreEqual(list2.Get(j), j);
Assert.AreEqual(list2.Get(j + list.Count), j);
}
ShortList empty = new ShortList();
int limit = list.Count;
for (int j = 0; j < limit; j++)
{
Assert.IsTrue(list.AddAll(j, empty));
Assert.AreEqual(limit, list.Count);
}
try
{
list.AddAll(limit + 1, empty);
Assert.Fail("should have thrown an exception");
}
catch (IndexOutOfRangeException)
{
// as expected
}
// try add at beginning
empty.AddAll(0, list);
//Assert.AreEqual(empty, list);
Assert.IsTrue(empty.Equals(list));
// try in the middle
empty.AddAll(1, list);
Assert.AreEqual(2 * list.Count, empty.Count);
Assert.AreEqual(list.Get(0), empty.Get(0));
Assert.AreEqual(list.Get(0), empty.Get(1));
Assert.AreEqual(list.Get(1), empty.Get(2));
Assert.AreEqual(list.Get(1), empty.Get(6));
Assert.AreEqual(list.Get(2), empty.Get(3));
Assert.AreEqual(list.Get(2), empty.Get(7));
Assert.AreEqual(list.Get(3), empty.Get(4));
Assert.AreEqual(list.Get(3), empty.Get(8));
Assert.AreEqual(list.Get(4), empty.Get(5));
Assert.AreEqual(list.Get(4), empty.Get(9));
// try at the end
empty.AddAll(empty.Count, list);
Assert.AreEqual(3 * list.Count, empty.Count);
Assert.AreEqual(list.Get(0), empty.Get(0));
Assert.AreEqual(list.Get(0), empty.Get(1));
Assert.AreEqual(list.Get(0), empty.Get(10));
Assert.AreEqual(list.Get(1), empty.Get(2));
Assert.AreEqual(list.Get(1), empty.Get(6));
Assert.AreEqual(list.Get(1), empty.Get(11));
Assert.AreEqual(list.Get(2), empty.Get(3));
Assert.AreEqual(list.Get(2), empty.Get(7));
Assert.AreEqual(list.Get(2), empty.Get(12));
Assert.AreEqual(list.Get(3), empty.Get(4));
Assert.AreEqual(list.Get(3), empty.Get(8));
Assert.AreEqual(list.Get(3), empty.Get(13));
Assert.AreEqual(list.Get(4), empty.Get(5));
Assert.AreEqual(list.Get(4), empty.Get(9));
Assert.AreEqual(list.Get(4), empty.Get(14));
}
[Test]
public void TestClear()
{
ShortList list = new ShortList();
for (short j = 0; j < 500; j++)
{
list.Add(j);
}
Assert.AreEqual(500, list.Count);
list.Clear();
Assert.AreEqual(0, list.Count);
for (short j = 0; j < 500; j++)
{
list.Add((short)(j + 1));
}
Assert.AreEqual(500, list.Count);
for (short j = 0; j < 500; j++)
{
Assert.AreEqual(j + 1, list.Get(j));
}
}
[Test]
public void TestContains()
{
ShortList list = new ShortList();
for (short j = 0; j < 1000; j += 2)
{
list.Add(j);
}
for (short j = 0; j < 1000; j++)
{
if (j % 2 == 0)
{
Assert.IsTrue(list.Contains(j));
}
else
{
Assert.IsTrue(!list.Contains(j));
}
}
}
[Test]
public void TestContainsAll()
{
ShortList list = new ShortList();
Assert.IsTrue(list.ContainsAll(list));
for (short j = 0; j < 10; j++)
{
list.Add(j);
}
ShortList list2 = new ShortList(list);
Assert.IsTrue(list2.ContainsAll(list));
Assert.IsTrue(list.ContainsAll(list2));
list2.Add((short)10);
Assert.IsTrue(list2.ContainsAll(list));
Assert.IsTrue(!list.ContainsAll(list2));
list.Add((short)11);
Assert.IsTrue(!list2.ContainsAll(list));
Assert.IsTrue(!list.ContainsAll(list2));
}
[Test]
public void TestEquals()
{
ShortList list = new ShortList();
//Assert.AreEqual(list, list);
Assert.IsTrue(list.Equals(list));
Assert.IsTrue(!list.Equals(null));
ShortList list2 = new ShortList(200);
//Assert.AreEqual(list, list2);
Assert.IsTrue(list.Equals(list2));
//Assert.AreEqual(list2, list);
Assert.IsTrue(list2.Equals(list));
Assert.AreEqual(list.GetHashCode(), list2.GetHashCode());
list.Add((short)0);
list.Add((short)1);
list2.Add((short)1);
list2.Add((short)0);
Assert.IsTrue(!list.Equals(list2));
list2.RemoveValue((short)1);
list2.Add((short)1);
//Assert.AreEqual(list, list2);
Assert.IsTrue(list.Equals(list2));
//Assert.AreEqual(list2, list);
Assert.IsTrue(list2.Equals(list));
list2.Add((short)2);
Assert.IsTrue(!list.Equals(list2));
Assert.IsTrue(!list2.Equals(list));
}
[Test]
public void TestGet()
{
ShortList list = new ShortList();
for (short j = 0; j < 1000; j++)
{
list.Add(j);
}
for (short j = 0; j < 1001; j++)
{
try
{
Assert.AreEqual(j, list.Get(j));
if (j == 1000)
{
Assert.Fail("should have gotten exception");
}
}
catch (IndexOutOfRangeException)
{
if (j != 1000)
{
Assert.Fail("unexpected IndexOutOfRangeException");
}
}
}
}
[Test]
public void TestIndexOf()
{
ShortList list = new ShortList();
for (short j = 0; j < 1000; j++)
{
list.Add((short)(j / 2));
}
for (short j = 0; j < 1000; j++)
{
if (j < 500)
{
Assert.AreEqual(j * 2, list.IndexOf(j));
}
else
{
Assert.AreEqual(-1, list.IndexOf(j));
}
}
}
[Test]
public void TestIsEmpty()
{
ShortList list1 = new ShortList();
ShortList list2 = new ShortList(1000);
ShortList list3 = new ShortList(list1);
Assert.IsTrue(list1.IsEmpty());
Assert.IsTrue(list2.IsEmpty());
Assert.IsTrue(list3.IsEmpty());
list1.Add((short)1);
list2.Add((short)2);
list3 = new ShortList(list2);
Assert.IsTrue(!list1.IsEmpty());
Assert.IsTrue(!list2.IsEmpty());
Assert.IsTrue(!list3.IsEmpty());
list1.Clear();
list2.Remove(0);
list3.RemoveValue((short)2);
Assert.IsTrue(list1.IsEmpty());
Assert.IsTrue(list2.IsEmpty());
Assert.IsTrue(list3.IsEmpty());
}
[Test]
public void TestLastIndexOf()
{
ShortList list = new ShortList();
for (short j = 0; j < 1000; j++)
{
list.Add((short)(j / 2));
}
for (short j = 0; j < 1000; j++)
{
if (j < 500)
{
Assert.AreEqual(1 + j * 2, list.LastIndexOf(j));
}
else
{
Assert.AreEqual(-1, list.IndexOf(j));
}
}
}
[Test]
public void TestRemove()
{
ShortList list = new ShortList();
for (short j = 0; j < 1000; j++)
{
list.Add(j);
}
for (short j = 0; j < 1000; j++)
{
Assert.AreEqual(j, list.Remove(0));
Assert.AreEqual((short)(999 - j), list.Count);
}
for (short j = 0; j < 1000; j++)
{
list.Add(j);
}
for (short j = 0; j < 1000; j++)
{
Assert.AreEqual((short)(999 - j),
list.Remove((short)(999 - j)));
Assert.AreEqual(999 - j, list.Count);
}
try
{
list.Remove(0);
Assert.Fail("should have caught IndexOutOfRangeException");
}
catch (IndexOutOfRangeException)
{
// as expected
}
}
[Test]
public void TestRemoveValue()
{
ShortList list = new ShortList();
for (short j = 0; j < 1000; j++)
{
list.Add((short)(j / 2));
}
for (short j = 0; j < 1000; j++)
{
if (j < 500)
{
Assert.IsTrue(list.RemoveValue(j));
Assert.IsTrue(list.RemoveValue(j));
}
Assert.IsTrue(!list.RemoveValue(j));
}
}
[Test]
public void TestRemoveAll()
{
ShortList list = new ShortList();
for (short j = 0; j < 1000; j++)
{
list.Add(j);
}
ShortList listCopy = new ShortList(list);
ShortList listOdd = new ShortList();
ShortList listEven = new ShortList();
for (short j = 0; j < 1000; j++)
{
if (j % 2 == 0)
{
listEven.Add(j);
}
else
{
listOdd.Add(j);
}
}
list.RemoveAll(listEven);
Assert.IsTrue(list.Equals(listOdd));// Assert.AreEqual(list, listOdd);
list.RemoveAll(listOdd);
Assert.IsTrue(list.IsEmpty());
listCopy.RemoveAll(listOdd);
//Assert.AreEqual(listCopy, listEven);
Assert.IsTrue(listCopy.Equals(listEven));
listCopy.RemoveAll(listEven);
Assert.IsTrue(listCopy.IsEmpty());
}
[Test]
public void TestRetainAll()
{
ShortList list = new ShortList();
for (short j = 0; j < 1000; j++)
{
list.Add(j);
}
ShortList listCopy = new ShortList(list);
ShortList listOdd = new ShortList();
ShortList listEven = new ShortList();
for (short j = 0; j < 1000; j++)
{
if (j % 2 == 0)
{
listEven.Add(j);
}
else
{
listOdd.Add(j);
}
}
list.RetainAll(listOdd);
Assert.IsTrue(list.Equals(listOdd));// Assert.AreEqual(list, listOdd);
list.RetainAll(listEven);
Assert.IsTrue(list.IsEmpty());
listCopy.RetainAll(listEven);
//Assert.AreEqual(listCopy, listEven);
Assert.IsTrue(listCopy.Equals(listEven));
listCopy.RetainAll(listOdd);
Assert.IsTrue(listCopy.IsEmpty());
}
[Test]
public void TestSet()
{
ShortList list = new ShortList();
for (short j = 0; j < 1000; j++)
{
list.Add(j);
}
for (short j = 0; j < 1001; j++)
{
try
{
list.Set(j, (short)(j + 1));
if (j == 1000)
{
Assert.Fail("Should have gotten exception");
}
Assert.AreEqual(j + 1, list.Get(j));
}
catch (IndexOutOfRangeException)
{
if (j != 1000)
{
Assert.Fail("premature exception");
}
}
}
}
[Test]
public void TestSize()
{
ShortList list = new ShortList();
for (short j = 0; j < 1000; j++)
{
Assert.AreEqual(j, list.Count);
list.Add(j);
Assert.AreEqual(j + 1, list.Count);
}
for (short j = 0; j < 1000; j++)
{
Assert.AreEqual(1000 - j, list.Count);
list.RemoveValue(j);
Assert.AreEqual(999 - j, list.Count);
}
}
[Test]
public void TestToArray()
{
ShortList list = new ShortList();
for (short j = 0; j < 1000; j++)
{
list.Add(j);
}
short[] a1 = list.ToArray();
Assert.AreEqual(a1.Length, list.Count);
for (short j = 0; j < 1000; j++)
{
Assert.AreEqual(a1[j], list.Get(j));
}
short[] a2 = new short[list.Count];
short[] a3 = list.ToArray(a2);
Assert.AreSame(a2, a3);
for (short j = 0; j < 1000; j++)
{
Assert.AreEqual(a2[j], list.Get(j));
}
short[] ashort = new short[list.Count - 1];
short[] aLong = new short[list.Count + 1];
short[] a4 = list.ToArray(ashort);
short[] a5 = list.ToArray(aLong);
Assert.IsTrue(a4 != ashort);
Assert.IsTrue(a5 != aLong);
Assert.AreEqual(a4.Length, list.Count);
for (short j = 0; j < 1000; j++)
{
Assert.AreEqual(a3[j], list.Get(j));
}
Assert.AreEqual(a5.Length, list.Count);
for (short j = 0; j < 1000; j++)
{
Assert.AreEqual(a5[j], list.Get(j));
}
}
}
}
| |
//
// XamlParser.cs
//
// Author:
// Stephane Delcroix <stephane@mi8.be>
//
// Copyright (c) 2013 Mobile Inception
// Copyright (c) 2013-2014 Xamarin, Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Xml;
namespace Xamarin.Forms.Xaml
{
internal static class XamlParser
{
public static void ParseXaml(RootNode rootNode, XmlReader reader)
{
var attributes = ParseXamlAttributes(reader);
rootNode.Properties.AddRange(attributes);
ParseXamlElementFor(rootNode, reader);
}
static void ParseXamlElementFor(IElementNode node, XmlReader reader)
{
Debug.Assert(reader.NodeType == XmlNodeType.Element);
var elementName = reader.Name;
var isEmpty = reader.IsEmptyElement;
if (isEmpty)
return;
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.EndElement:
Debug.Assert(reader.Name == elementName); //make sure we close the right element
return;
case XmlNodeType.Element:
// 1. Property Element.
if (reader.Name.Contains("."))
{
XmlName name;
if (reader.Name.StartsWith(elementName + ".", StringComparison.Ordinal))
name = new XmlName(reader.NamespaceURI, reader.Name.Substring(elementName.Length + 1));
else //Attached DP
name = new XmlName(reader.NamespaceURI, reader.LocalName);
var prop = ReadNode(reader);
if (prop != null)
node.Properties.Add(name, prop);
}
// 2. Xaml2009 primitives, x:Arguments, ...
else if (reader.NamespaceURI == "http://schemas.microsoft.com/winfx/2009/xaml" && reader.LocalName == "Arguments")
{
var prop = ReadNode(reader);
if (prop != null)
node.Properties.Add(XmlName.xArguments, prop);
// 3. DataTemplate (should be handled by 4.)
}
else if (node.XmlType.NamespaceUri == "http://xamarin.com/schemas/2014/forms" &&
(node.XmlType.Name == "DataTemplate" || node.XmlType.Name == "ControlTemplate"))
{
var prop = ReadNode(reader, true);
if (prop != null)
node.Properties.Add(XmlName._CreateContent, prop);
// 4. Implicit content, implicit collection, or collection syntax. Add to CollectionItems, resolve case later.
}
else
{
var item = ReadNode(reader, true);
if (item != null)
node.CollectionItems.Add(item);
}
break;
case XmlNodeType.Whitespace:
break;
case XmlNodeType.Text:
node.CollectionItems.Add(new ValueNode(reader.Value.Trim(), (IXmlNamespaceResolver)reader));
break;
default:
Debug.WriteLine("Unhandled node {0} {1} {2}", reader.NodeType, reader.Name, reader.Value);
break;
}
}
}
static INode ReadNode(XmlReader reader, bool nested = false)
{
var skipFirstRead = nested;
Debug.Assert(reader.NodeType == XmlNodeType.Element);
var name = reader.Name;
List<INode> nodes = new List<INode>();
INode node = null;
while (skipFirstRead || reader.Read())
{
skipFirstRead = false;
switch (reader.NodeType)
{
case XmlNodeType.EndElement:
Debug.Assert(reader.Name == name);
if (nodes.Count == 0) //Empty element
return null;
if (nodes.Count == 1)
return nodes[0];
return new ListNode(nodes, (IXmlNamespaceResolver)reader, ((IXmlLineInfo)reader).LineNumber,
((IXmlLineInfo)reader).LinePosition);
case XmlNodeType.Element:
var isEmpty = reader.IsEmptyElement && reader.Name == name;
var elementName = reader.Name;
var elementNsUri = reader.NamespaceURI;
var elementXmlInfo = (IXmlLineInfo)reader;
var attributes = ParseXamlAttributes(reader);
IList<XmlType> typeArguments = null;
if (attributes.Any(kvp => kvp.Key == XmlName.xTypeArguments))
{
typeArguments =
((ValueNode)attributes.First(kvp => kvp.Key == XmlName.xTypeArguments).Value).Value as IList<XmlType>;
}
node = new ElementNode(new XmlType(elementNsUri, elementName, typeArguments), elementNsUri,
reader as IXmlNamespaceResolver, elementXmlInfo.LineNumber, elementXmlInfo.LinePosition);
((IElementNode)node).Properties.AddRange(attributes);
ParseXamlElementFor((IElementNode)node, reader);
nodes.Add(node);
if (isEmpty || nested)
return node;
break;
case XmlNodeType.Text:
node = new ValueNode(reader.Value.Trim(), (IXmlNamespaceResolver)reader, ((IXmlLineInfo)reader).LineNumber,
((IXmlLineInfo)reader).LinePosition);
nodes.Add(node);
break;
case XmlNodeType.Whitespace:
break;
default:
Debug.WriteLine("Unhandled node {0} {1} {2}", reader.NodeType, reader.Name, reader.Value);
break;
}
}
throw new XamlParseException("Closing PropertyElement expected", (IXmlLineInfo)reader);
}
static IList<KeyValuePair<XmlName, INode>> ParseXamlAttributes(XmlReader reader)
{
Debug.Assert(reader.NodeType == XmlNodeType.Element);
var attributes = new List<KeyValuePair<XmlName, INode>>();
for (var i = 0; i < reader.AttributeCount; i++)
{
reader.MoveToAttribute(i);
//skip xmlns
if (reader.NamespaceURI == "http://www.w3.org/2000/xmlns/")
continue;
var propertyName = new XmlName(reader.NamespaceURI, reader.LocalName);
object value = reader.Value;
if (reader.NamespaceURI == "http://schemas.microsoft.com/winfx/2006/xaml")
{
switch (reader.Name)
{
case "x:Key":
propertyName = XmlName.xKey;
break;
case "x:Name":
propertyName = XmlName.xName;
break;
case "x:Class":
continue;
default:
Debug.WriteLine("Unhandled {0}", reader.Name);
continue;
}
}
if (reader.NamespaceURI == "http://schemas.microsoft.com/winfx/2009/xaml")
{
switch (reader.Name)
{
case "x:Key":
propertyName = XmlName.xKey;
break;
case "x:Name":
propertyName = XmlName.xName;
break;
case "x:TypeArguments":
propertyName = XmlName.xTypeArguments;
value = TypeArgumentsParser.ParseExpression((string)value, (IXmlNamespaceResolver)reader, (IXmlLineInfo)reader);
break;
case "x:Class":
continue;
case "x:FactoryMethod":
propertyName = XmlName.xFactoryMethod;
break;
default:
Debug.WriteLine("Unhandled {0}", reader.Name);
continue;
}
}
var propertyNode = GetValueNode(value, reader);
attributes.Add(new KeyValuePair<XmlName, INode>(propertyName, propertyNode));
}
reader.MoveToElement();
return attributes;
}
static IValueNode GetValueNode(object value, XmlReader reader)
{
var valueString = value as string;
if (valueString != null && valueString.Trim().StartsWith("{}", StringComparison.Ordinal))
{
return new ValueNode(valueString.Substring(2), (IXmlNamespaceResolver)reader, ((IXmlLineInfo)reader).LineNumber,
((IXmlLineInfo)reader).LinePosition);
}
if (valueString != null && valueString.Trim().StartsWith("{", StringComparison.Ordinal))
{
return new MarkupNode(valueString.Trim(), reader as IXmlNamespaceResolver, ((IXmlLineInfo)reader).LineNumber,
((IXmlLineInfo)reader).LinePosition);
}
return new ValueNode(value, (IXmlNamespaceResolver)reader, ((IXmlLineInfo)reader).LineNumber,
((IXmlLineInfo)reader).LinePosition);
}
public static Type GetElementType(XmlType xmlType, IXmlLineInfo xmlInfo, Assembly currentAssembly,
out XamlParseException exception)
{
var namespaceURI = xmlType.NamespaceUri;
var elementName = xmlType.Name;
var typeArguments = xmlType.TypeArguments;
exception = null;
List<Tuple<string, Assembly>> lookupAssemblies = new List<Tuple<string, Assembly>>();
List<string> lookupNames = new List<string>();
if (!XmlnsHelper.IsCustom(namespaceURI))
{
lookupAssemblies.Add(new Tuple<string, Assembly>("Xamarin.Forms", typeof (View).GetTypeInfo().Assembly));
lookupAssemblies.Add(new Tuple<string, Assembly>("Xamarin.Forms.Xaml", typeof (XamlLoader).GetTypeInfo().Assembly));
}
else if (namespaceURI == "http://schemas.microsoft.com/winfx/2009/xaml" ||
namespaceURI == "http://schemas.microsoft.com/winfx/2006/xaml")
{
lookupAssemblies.Add(new Tuple<string, Assembly>("Xamarin.Forms.Xaml", typeof (XamlLoader).GetTypeInfo().Assembly));
lookupAssemblies.Add(new Tuple<string, Assembly>("System", typeof (object).GetTypeInfo().Assembly));
lookupAssemblies.Add(new Tuple<string, Assembly>("System", typeof (Uri).GetTypeInfo().Assembly)); //System.dll
}
else
{
string ns;
string typename;
string asmstring;
Assembly asm;
XmlnsHelper.ParseXmlns(namespaceURI, out typename, out ns, out asmstring);
asm = asmstring == null ? currentAssembly : Assembly.Load(new AssemblyName(asmstring));
lookupAssemblies.Add(new Tuple<string, Assembly>(ns, asm));
}
lookupNames.Add(elementName);
if (namespaceURI == "http://schemas.microsoft.com/winfx/2009/xaml")
lookupNames.Add(elementName + "Extension");
for (var i = 0; i < lookupNames.Count; i++)
{
var name = lookupNames[i];
if (name.Contains(":"))
name = name.Substring(name.LastIndexOf(':') + 1);
if (typeArguments != null)
name += "`" + typeArguments.Count; //this will return an open generic Type
lookupNames[i] = name;
}
Type type = null;
foreach (var asm in lookupAssemblies)
{
if (type != null)
break;
foreach (var name in lookupNames)
{
if (type != null)
break;
type = asm.Item2.GetType(asm.Item1 + "." + name);
}
}
if (type != null && typeArguments != null)
{
XamlParseException innerexception = null;
var args = typeArguments.Select(delegate(XmlType xmltype)
{
XamlParseException xpe;
var t = GetElementType(xmltype, xmlInfo, currentAssembly, out xpe);
if (xpe != null)
{
innerexception = xpe;
return null;
}
return t;
}).ToArray();
if (innerexception != null)
{
exception = innerexception;
return null;
}
type = type.MakeGenericType(args);
}
if (type == null)
{
exception = new XamlParseException(string.Format("Type {0} not found in xmlns {1}", elementName, namespaceURI),
xmlInfo);
return null;
}
return type;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.IO;
using System.Linq;
using System.Text;
using Dapper;
using Microsoft.Data.SqlClient;
using SimpleStack.Orm.Expressions.Statements;
namespace SimpleStack.Orm.SqlServer
{
/// <summary>A SQL server ORM lite dialect provider.</summary>
public class SqlServerDialectProvider : DialectProviderBase
{
/// <summary>
/// Initializes a new instance of the
/// NServiceKit.OrmLite.SqlServer.SqlServerOrmLiteDialectProvider class.
/// </summary>
public SqlServerDialectProvider():base(new SqlServerTypeMapper())
{
base.AutoIncrementDefinition = "IDENTITY(1,1)";
base.SelectIdentitySql = "SELECT SCOPE_IDENTITY()";
}
/// <summary>Creates a connection.</summary>
/// <param name="connectionString">The connection string.</param>
/// <param name="options"> Options for controlling the operation.</param>
/// <returns>The new connection.</returns>
public override DbConnection CreateIDbConnection(string connectionString)
{
var isFullConnectionString = connectionString.Contains(";");
if (!isFullConnectionString)
{
var filePath = connectionString;
var filePathWithExt = filePath.ToLower().EndsWith(".mdf")
? filePath
: filePath + ".mdf";
var fileName = Path.GetFileName(filePathWithExt);
var dbName = fileName.Substring(0, fileName.Length - ".mdf".Length);
connectionString = string.Format(
@"Data Source=.\SQLEXPRESS;AttachDbFilename={0};Initial Catalog={1};Integrated Security=True;User Instance=True;",
filePathWithExt, dbName);
}
return new SqlConnection(connectionString);
}
/// <summary>Query if 'dbCmd' does table exist.</summary>
/// <param name="connection"> The database command.</param>
/// <param name="tableName">Name of the table.</param>
/// <returns>true if it succeeds, false if it fails.</returns>
public override bool DoesTableExist(IDbConnection connection, string tableName, string schemaName = null)
{
var sql = String.Format("SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '{0}'"
,tableName);
if (!string.IsNullOrEmpty(schemaName))
sql += $" AND TABLE_SCHEMA = '{schemaName}'";
var result = connection.ExecuteScalar<int>(sql);
return result > 0;
}
public override string GetCreateSchemaStatement(string schema, bool ignoreIfExists)
{
return ignoreIfExists ?
$@"IF NOT EXISTS ( SELECT * FROM sys.schemas WHERE name = N'{schema}' )
EXEC('CREATE SCHEMA [app]')" :
$"CREATE SCHEMA {schema}";
}
/// <summary>Gets or sets a value indicating whether this object use unicode.</summary>
/// <value>true if use unicode, false if not.</value>
/// <summary>Gets foreign key on delete clause.</summary>
/// <param name="foreignKey">The foreign key.</param>
/// <returns>The foreign key on delete clause.</returns>
public override string GetForeignKeyOnDeleteClause(ForeignKeyConstraint foreignKey)
{
return "RESTRICT" == (foreignKey.OnDelete ?? "").ToUpper()
? ""
: base.GetForeignKeyOnDeleteClause(foreignKey);
}
/// <summary>Gets foreign key on update clause.</summary>
/// <param name="foreignKey">The foreign key.</param>
/// <returns>The foreign key on update clause.</returns>
public override string GetForeignKeyOnUpdateClause(ForeignKeyConstraint foreignKey)
{
return "RESTRICT" == (foreignKey.OnDelete ?? "").ToUpper()
? ""
: base.GetForeignKeyOnUpdateClause(foreignKey);
}
/// <summary>Gets drop foreign key constraints.</summary>
/// <param name="modelDef">The model definition.</param>
/// <returns>The drop foreign key constraints.</returns>
public override string GetDropForeignKeyConstraints(ModelDefinition modelDef)
{
//TODO: find out if this should go in base class?
var sb = new StringBuilder();
foreach (var fieldDef in modelDef.FieldDefinitions)
{
if (fieldDef.ForeignKey != null)
{
var foreignKeyName = fieldDef.ForeignKey.GetForeignKeyName(
modelDef,
GetModelDefinition(fieldDef.ForeignKey.ReferenceType),
NamingStrategy,
fieldDef);
var tableName = GetQuotedTableName(modelDef);
sb.AppendLine(String.Format("IF EXISTS (SELECT name FROM sys.foreign_keys WHERE name = '{0}')", foreignKeyName));
sb.AppendLine("BEGIN");
sb.AppendLine(String.Format(" ALTER TABLE {0} DROP {1};", tableName, foreignKeyName));
sb.AppendLine("END");
}
}
return sb.ToString();
}
/// <summary>Converts this object to an add column statement.</summary>
/// <param name="modelType">Type of the model.</param>
/// <param name="fieldDef"> The field definition.</param>
/// <returns>The given data converted to a string.</returns>
public override string ToAddColumnStatement(Type modelType, FieldDefinition fieldDef)
{
var column = GetColumnDefinition(fieldDef.FieldName,
fieldDef.FieldType,
fieldDef.IsPrimaryKey,
fieldDef.AutoIncrement,
fieldDef.IsNullable,
fieldDef.FieldLength,
fieldDef.Scale,
fieldDef.DefaultValue);
return string.Format("ALTER TABLE {0} ADD {1};",
GetQuotedTableName(GetModel(modelType).ModelName),
column);
}
/// <summary>Converts this object to an alter column statement.</summary>
/// <param name="modelType">Type of the model.</param>
/// <param name="fieldDef"> The field definition.</param>
/// <returns>The given data converted to a string.</returns>
public override string ToAlterColumnStatement(Type modelType, FieldDefinition fieldDef)
{
var column = GetColumnDefinition(fieldDef.FieldName,
fieldDef.FieldType,
fieldDef.IsPrimaryKey,
fieldDef.AutoIncrement,
fieldDef.IsNullable,
fieldDef.FieldLength,
fieldDef.Scale,
fieldDef.DefaultValue);
return string.Format("ALTER TABLE {0} ALTER COLUMN {1};",
GetQuotedTableName(GetModel(modelType).ModelName),
column);
}
public override CommandDefinition ToSelectStatement(SelectStatement statement, CommandFlags flags)
{
if (statement.Offset == null && (statement.MaxRows == null || statement.MaxRows == int.MaxValue))
{
return base.ToSelectStatement(statement, flags);
}
//Ensure we have an OrderBy clause, this is required by SQLServer paging (and makes more sense anyway)
if (statement.OrderByExpression.Length == 0)
{
// Add Order BY 1
statement.OrderByExpression.Append(1);
}
return base.ToSelectStatement(statement, flags);
}
public override string GetLimitExpression(int? skip, int? rows)
{
if (!skip.HasValue && !rows.HasValue)
return string.Empty;
var sql = new StringBuilder();
//OFFSET 10 ROWS FETCH NEXT 5 ROWS ONLY;
sql.Append("OFFSET ");
sql.Append(skip ?? 0);
sql.Append(" ROWS");
if (rows.HasValue)
{
sql.Append(" FETCH NEXT ");
sql.Append(rows.Value);
sql.Append(" ROWS ONLY");
}
return sql.ToString();
}
public override string GetDatePartFunction(string name, string quotedColName)
{
return $"DATEPART({name.ToLower()},{quotedColName})";
}
public override string GetStringFunction(string functionName, string quotedColumnName, IDictionary<string, object> parameters,
params string[] availableParameters)
{
switch (functionName.ToLower())
{
case "length":
return "LEN(" + quotedColumnName + ")";
case "trim":
return $"ltrim(rtrim({quotedColumnName}))";
case "substring":
//Ensure Offset is start at 1 instead of 0
int offset = ((int) parameters[availableParameters[0]]) + 1;
parameters[availableParameters[0]] = offset;
if (parameters.Count == 2)
{
return $"substring({quotedColumnName},{availableParameters[0]},{availableParameters[1]})";
}
return $"substring({quotedColumnName},{availableParameters[0]})";
}
return base.GetStringFunction(functionName, quotedColumnName, parameters, availableParameters);
}
public override IEnumerable<IColumnDefinition> GetTableColumnDefinitions(IDbConnection connection, string tableName, string schemaName = null)
{
string fullTableName = string.IsNullOrEmpty(schemaName) ? tableName : $"{schemaName}.{tableName}";
string sqlQuery = @"SELECT c.name COLUMN_NAME,
t.name DATA_TYPE,
dc.definition COLUMN_DEFAULT,
c.max_length CHARACTER_MAXIMUM_LENGTH,
c.is_nullable IS_NULLABLE,
c.[precision] NUMERIC_PRECISION,
c.[scale] NUMERIC_SCALE,
cl.definition COMPUTED_DEFINITION
FROM sys.columns c
LEFT JOIN sys.computed_columns cl ON cl.column_id = c.column_id
LEFT JOIN sys.default_constraints dc ON dc.object_id = c.default_object_id
INNER JOIN sys.types t ON t.user_type_id = c.user_type_id
where c.object_id = OBJECT_ID(@TableName);";
string uniqueQuery = @"SELECT COL_NAME(ic.object_id,ic.column_id) AS COLUMN_NAME , is_unique IS_UNIQUE, is_primary_key IS_PRIMARYKEY
FROM sys.indexes AS i
INNER JOIN sys.index_columns AS ic
ON i.object_id = ic.object_id AND i.index_id = ic.index_id
WHERE i.object_id = OBJECT_ID(@TableName)
AND is_unique = 1";
var indexes = connection.Query(uniqueQuery, new {TableName = fullTableName}).ToArray();
foreach (var c in connection.Query(sqlQuery, new {TableName = fullTableName}))
{
var i = indexes.FirstOrDefault(x => x.COLUMN_NAME == c.COLUMN_NAME);
yield return new ColumnDefinition
{
Name = c.COLUMN_NAME,
Definition = c.DATA_TYPE,
DefaultValue = c.COLUMN_DEFAULT,
PrimaryKey = i != null && i.IS_PRIMARYKEY ?? false,
Unique = i != null && i.IS_UNIQUE ?? false,
Length = (c.DATA_TYPE == "nvarchar" || c.DATA_TYPE == "ntext" || c.DATA_TYPE == "nchar") ? c.CHARACTER_MAXIMUM_LENGTH / 2 : c.CHARACTER_MAXIMUM_LENGTH,
Nullable = c.IS_NULLABLE,
Precision = c.NUMERIC_PRECISION,
Scale = c.NUMERIC_SCALE,
DbType = GetDbType(c.DATA_TYPE),
ComputedExpression = c.COMPUTED_DEFINITION
};
}
}
protected virtual DbType GetDbType(string dataType)
{
switch (dataType.ToLower())
{
case "char":
return DbType.AnsiStringFixedLength;
case "varchar":
return DbType.AnsiString;
case "nvarchar":
return DbType.String;
case "nchar":
return DbType.StringFixedLength;
case "text":
return DbType.AnsiString;
case "ntext":
return DbType.String;
case "bit":
return DbType.Boolean;
case "smallint":
return DbType.Int16;
case "int":
return DbType.Int32;
case "bigint":
return DbType.Int64;
case "real":
return DbType.Single;
case "binary":
case "varbinary":
return DbType.Binary;
case "numeric":
case "decimal":
return DbType.Decimal;
case "date":
return DbType.Date;
case "time":
return DbType.Time;
case "timestamp":
case "datetime":
case "smalldatetime":
return DbType.DateTime;
case "datetime2":
return DbType.DateTime2;
case "datetimeoffset":
return DbType.DateTimeOffset;
case "uniqueidentifier":
return DbType.Guid;
case "money":
case "smallmoney":
return DbType.Currency;
case "xml":
return DbType.Xml;
default:
return DbType.Object;
}
}
}
}
| |
/**
/// Memcached C# client
/// Copyright (c) 2005
///
/// Based on code written originally by Greg Whalin
/// http://www.whalin.com/memcached/
///
/// This library is free software; you can redistribute it and/or
/// modify it under the terms of the GNU Lesser General Public
/// License as published by the Free Software Foundation; either
/// version 2.1 of the License, or (at your option) any later
/// version.
///
/// This library is distributed in the hope that it will be
/// useful, but WITHOUT ANY WARRANTY; without even the implied
/// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
/// PURPOSE. See the GNU Lesser General Public License for more
/// details.
///
/// You should have received a copy of the GNU Lesser General Public
/// License along with this library; if not, write to the Free Software
/// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
///
/// @author Tim Gebhardt <tim@gebhardtcomputing.com>
/// @version 1.0
**/
namespace Memcached.ClientLibrary
{
using System;
using System.Resources;
using System.Text;
/**
/// COMMENT FROM ORIGINAL JAVA CLIENT LIBRARY. NOT SURE HOW MUCH IT
/// APPLIES TO THIS LIBRARY.
///
///
/// Handle encoding standard Java types directly which can result in significant
/// memory savings:
///
/// Currently the Memcached driver for Java supports the setSerialize() option.
/// This can increase performance in some situations but has a few issues:
///
/// Code that performs class casting will throw ClassCastExceptions when
/// setSerialize is enabled. For example:
///
/// mc.set("foo", new Integer(1)); Integer output = (Integer)mc.get("foo");
///
/// Will work just file when setSerialize is true but when its false will just throw
/// a ClassCastException.
///
/// Also internally it doesn't support bool and since toString is called wastes a
/// lot of memory and causes additional performance issue. For example an Integer
/// can take anywhere from 1 byte to 10 bytes.
///
/// Due to the way the memcached slabytes allocator works it seems like a LOT of wasted
/// memory to store primitive types as serialized objects (from a performance and
/// memory perspective). In our applications we have millions of small objects and
/// wasted memory would become a big problem.
///
/// For example a Serialized bool takes 47 bytes which means it will fit into the
/// 64byte LRU. Using 1 byte means it will fit into the 8 byte LRU thus saving 8x
/// the memory. This also saves the CPU performance since we don't have to
/// serialize bytes back and forth and we can compute the byte[] value directly.
///
/// One problem would be when the user calls get() because doing so would require
/// the app to know the type of the object stored as a bytearray inside memcached
/// (since the user will probably cast).
///
/// If we assume the basic types are interned we could use the first byte as the
/// type with the remaining bytes as the value. Then on get() we could read the
/// first byte to determine the type and then construct the correct object for it.
/// This would prevent the ClassCastException I talked about above.
///
/// We could remove the setSerialize() option and just assume that standard VM types
/// are always internd in this manner.
///
/// mc.set("foo", new bool.TRUE); bool bytes = (bool)mc.get("foo");
///
/// And the type casts would work because internally we would create a new bool
/// to return back to the client.
///
/// This would reduce memory footprint and allow for a virtual implementation of the
/// Externalizable interface which is much faster than Serialzation.
///
/// Currently the memory improvements would be:
///
/// java.lang.bool - 8x performance improvement (now just two bytes)
/// java.lang.Integer - 16x performance improvement (now just 5 bytes)
///
/// Most of the other primitive types would benefit from this optimization.
/// java.lang.Character being another obvious example.
///
/// I know it seems like I'm being really picky here but for our application I'd
/// save 1G of memory right off the bat. We'd go down from 1.152G of memory used
/// down to 144M of memory used which is much better IMO.
**/
public sealed class NativeHandler
{
//FIXME: what about other common types? Also what about
//Collections of native types? I could reconstruct these on the remote end
//if necessary. Though I'm not sure of the performance advantage here.
public const byte ByteMarker = 1;
public const byte BoolMarker = 2;
public const byte Int32Marker = 3;
public const byte Int64Marker = 4;
public const byte CharMarker = 5;
public const byte StringMarker = 6;
public const byte StringBuilderMarker = 7;
public const byte SingleMarker = 8;
public const byte Int16Marker = 9;
public const byte DoubleMarker = 10;
public const byte DateTimeMarker = 11;
private NativeHandler() {}
public static bool IsHandled(object value)
{
if(value is bool ||
value is byte ||
value is string ||
value is char ||
value is StringBuilder ||
value is short ||
value is long ||
value is double ||
value is float ||
value is DateTime ||
value is Int32)
{
return true;
}
return false;
}
// **** Encode methods ******************************************************
public static byte[] Encode(object value)
{
if(value == null)
return new byte[0];
if(value is bool)
return Encode((bool)value);
if(value is Int32)
return Encode((Int32)value);
if(value is char)
return Encode((char)value);
if(value is byte)
return Encode((byte)value);
if(value is short)
return Encode((short)value);
if(value is long)
return Encode((long)value);
if(value is double)
return Encode((double)value);
if(value is float)
return Encode((float)value);
string tempstr = value as string;
if(tempstr != null)
return Encode(tempstr);
StringBuilder tempsb = value as StringBuilder;
if(tempsb != null)
return Encode(tempsb);
if(value is DateTime)
return Encode((DateTime) value);
return null;
}
public static byte[] Encode(DateTime value)
{
byte[] bytes = GetBytes(value.Ticks);
bytes[0] = DateTimeMarker;
return bytes;
}
public static byte[] Encode(bool value)
{
byte[] bytes = new byte[2];
bytes[0] = BoolMarker;
if(value)
{
bytes[1] = 1;
}
else
{
bytes[1] = 0;
}
return bytes;
}
public static byte[] Encode(int value)
{
byte[] bytes = GetBytes(value);
bytes[0] = Int32Marker;
return bytes;
}
public static byte[] Encode(char value)
{
byte[] result = Encode((short) value);
result[0] = CharMarker;
return result;
}
public static byte[] Encode(string value)
{
if(value == null)
return new byte[1]{ StringMarker };
byte[] asBytes = UTF8Encoding.UTF8.GetBytes(value);
byte[] result = new byte[asBytes.Length + 1];
result[0] = StringMarker;
Array.Copy(asBytes, 0, result, 1, asBytes.Length);
return result;
}
public static byte[] Encode(byte value)
{
byte[] bytes = new byte[2];
bytes[0] = ByteMarker;
bytes[1] = value;
return bytes;
}
public static byte[] Encode(StringBuilder value)
{
if(value == null)
return new byte[1]{ StringBuilderMarker };
byte[] bytes = Encode(value.ToString());
bytes[0] = StringBuilderMarker;
return bytes;
}
public static byte[] Encode(short value)
{
byte[] bytes = Encode((int)value);
bytes[0] = Int16Marker;
return bytes;
}
public static byte[] Encode(long value)
{
byte[] bytes = GetBytes(value);
bytes[0] = Int64Marker;
return bytes;
}
public static byte[] Encode(double value)
{
byte[] temp = BitConverter.GetBytes(value);
byte[] bytes = new byte[temp.Length + 1];
bytes[0] = DoubleMarker;
Array.Copy(temp, 0, bytes, 1, temp.Length);
return bytes;
}
public static byte[] Encode(float value)
{
byte[] temp = BitConverter.GetBytes(value);
byte[] bytes = new byte[temp.Length + 1];
bytes[0] = SingleMarker;
Array.Copy(temp, 0, bytes, 1, temp.Length);
return bytes;
}
public static byte[] GetBytes(long value)
{
byte b0 = (byte)((value >> 56) & 0xFF);
byte b1 = (byte)((value >> 48) & 0xFF);
byte b2 = (byte)((value >> 40) & 0xFF);
byte b3 = (byte)((value >> 32) & 0xFF);
byte b4 = (byte)((value >> 24) & 0xFF);
byte b5 = (byte)((value >> 16) & 0xFF);
byte b6 = (byte)((value >> 8) & 0xFF);
byte b7 = (byte)((value >> 0) & 0xFF);
byte[] bytes = new byte[9];
bytes[1] = b0;
bytes[2] = b1;
bytes[3] = b2;
bytes[4] = b3;
bytes[5] = b4;
bytes[6] = b5;
bytes[7] = b6;
bytes[8] = b7;
return bytes;
}
public static byte[] GetBytes(int value)
{
byte b0 = (byte)((value >> 24) & 0xFF);
byte b1 = (byte)((value >> 16) & 0xFF);
byte b2 = (byte)((value >> 8) & 0xFF);
byte b3 = (byte)((value >> 0) & 0xFF);
byte[] bytes = new byte[5];
bytes[1] = b0;
bytes[2] = b1;
bytes[3] = b2;
bytes[4] = b3;
return bytes;
}
// **** Decode methods ******************************************************
public static Object Decode(byte[] bytes)
{
//something strange is going on.
if(bytes == null || bytes.Length == 0)
return null;
//determine what type this is:
if(bytes[0] == BoolMarker)
return DecodeBool(bytes);
if(bytes[0] == Int32Marker)
return DecodeInteger(bytes);
if(bytes[0] == StringMarker)
return DecodeString(bytes);
if(bytes[0] == CharMarker)
return DecodeCharacter(bytes);
if(bytes[0] == ByteMarker)
return DecodeByte(bytes);
if(bytes[0] == StringBuilderMarker)
return DecodeStringBuilder(bytes);
if(bytes[0] == Int16Marker)
return DecodeShort(bytes);
if(bytes[0] == Int64Marker)
return DecodeLong(bytes);
if(bytes[0] == DoubleMarker)
return DecodeDouble(bytes);
if(bytes[0] == SingleMarker)
return DecodeFloat(bytes);
if(bytes[0] == DateTimeMarker)
return DecodeDate(bytes);
return null;
}
public static DateTime DecodeDate(byte[] bytes)
{
return new DateTime(ToLong(bytes));
}
public static bool DecodeBool(byte[] bytes)
{
if(bytes == null)
throw new ArgumentNullException("bytes", GetLocalizedString("parameter cannot be null"));
bool value = bytes[1] == 1;
return value;
}
public static Int32 DecodeInteger(byte[] bytes)
{
return ToInt(bytes) ;
}
public static string DecodeString(byte[] bytes)
{
if(bytes == null)
return null;
return UTF8Encoding.UTF8.GetString(bytes, 1, bytes.Length -1);
}
public static char DecodeCharacter(byte[] bytes)
{
return (char)DecodeInteger(bytes);
}
public static byte DecodeByte(byte[] bytes)
{
if(bytes == null)
throw new ArgumentNullException("bytes", GetLocalizedString("parameter cannot be null"));
byte value = bytes[1];
return value;
}
public static StringBuilder DecodeStringBuilder(byte[] bytes)
{
return new StringBuilder(DecodeString(bytes));
}
public static short DecodeShort(byte[] bytes)
{
return (short)DecodeInteger(bytes);
}
public static long DecodeLong(byte[] bytes)
{
return ToLong(bytes);
}
public static double DecodeDouble(byte[] bytes)
{
return BitConverter.ToDouble(bytes, 1);
}
public static float DecodeFloat(byte[] bytes)
{
return BitConverter.ToSingle(bytes, 1);
}
public static int ToInt(byte[] bytes)
{
if(bytes == null)
throw new ArgumentNullException("bytes", GetLocalizedString("parameter cannot be null"));
//This works by taking each of the bit patterns and converting them to
//ints taking into account 2s complement and then adding them..
return ((((int) bytes[4]) & 0xFF) << 32) +
((((int) bytes[3]) & 0xFF) << 40) +
((((int) bytes[2]) & 0xFF) << 48) +
((((int) bytes[1]) & 0xFF) << 56) ;
}
public static long ToLong(byte[] bytes)
{
if(bytes == null)
throw new ArgumentNullException("bytes", GetLocalizedString("parameter cannot be null"));
//FIXME: this is sad in that it takes up 16 bytes instead of JUST 8
//bytes and wastes memory. We could use a memcached flag to enable
//special treatment for 64bit types
//This works by taking each of the bit patterns and converting them to
//ints taking into account 2s complement and then adding them..
return (((long) bytes[8]) & 0xFF) +
((((long) bytes[7]) & 0xFF) << 8) +
((((long) bytes[6]) & 0xFF) << 16) +
((((long) bytes[5]) & 0xFF) << 24) +
((((long) bytes[4]) & 0xFF) << 32) +
((((long) bytes[3]) & 0xFF) << 40) +
((((long) bytes[2]) & 0xFF) << 48) +
((((long) bytes[1]) & 0xFF) << 56) ;
}
private static ResourceManager _resourceManager = new ResourceManager("Memcached.ClientLibrary.StringMessages", typeof(SockIOPool).Assembly);
private static string GetLocalizedString(string key)
{
return _resourceManager.GetString(key);
}
}
}
| |
/**
* Least Recently Used cache
* Caches the most recently used items up to the given capacity dumping
* the least used items first
*
* Initial Revision: August 6, 2010 David C. Daeschler
* (c) 2010 InWorldz, LLC.
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace OpenSim.Framework
{
/// <summary>
/// Implements a least recently used cache. Basically a linked list with hash indexes and a
/// limited size
///
/// TODO: Implement IDictionary
/// </summary>
public class LRUCache<K, T> : IEnumerable<KeyValuePair<K,T>>
{
public delegate void ItemPurgedDelegate(T item);
public event ItemPurgedDelegate OnItemPurged;
private class KVPComparer<CK, CT> : IEqualityComparer<KeyValuePair<CK, CT>>
{
public bool Equals(KeyValuePair<CK, CT> x, KeyValuePair<CK, CT> y)
{
bool eq = EqualityComparer<CK>.Default.Equals(x.Key, y.Key);
return eq;
}
public int GetHashCode(KeyValuePair<CK, CT> obj)
{
return EqualityComparer<CK>.Default.GetHashCode(obj.Key);
}
}
private C5.HashedLinkedList<KeyValuePair<K,T>> _storage;
private int _capacity;
private Dictionary<K, int> _objectSizes;
private int _totalSize;
/// <summary>
/// Constructs an LRUCache with the given maximum size
/// </summary>
/// <param name="capacity"></param>
public LRUCache(int capacity) : this(capacity, false)
{
}
/// <summary>
/// Constructs an LRUCache with the given maximum size
/// </summary>
/// <param name="capacity"></param>
/// <param name="useSizing">Whether or not to use explicit object sizes</param>
public LRUCache(int capacity, bool useSizing)
{
_storage = new C5.HashedLinkedList<KeyValuePair<K, T>>(new KVPComparer<K, T>());
_capacity = capacity;
_totalSize = 0;
if (useSizing)
{
_objectSizes = new Dictionary<K, int>();
}
}
#region ICollection<T>
/// <summary>
/// Try to return the item that matches the hash of the given item
/// </summary>
/// <param name="item"></param>
/// <param name="foundItem"></param>
/// <returns></returns>
public bool TryGetValue(K key, out T foundItem)
{
KeyValuePair<K, T> kvp = new KeyValuePair<K,T>(key, default(T));
if (_storage.Find(ref kvp))
{
foundItem = kvp.Value;
//readd if we found it to update its position
_storage.Remove(kvp);
_storage.Add(kvp);
return true;
}
else
{
foundItem = default(T);
return false;
}
}
/// <summary>
/// Adds an item/moves an item up in the LRU cache and returns whether or not
/// the item with the given key already existed
/// </summary>
/// <param name="key"></param>
/// <param name="item"></param>
/// <returns>If the object already existed</returns>
public bool Add(K key, T item)
{
return this.Add(key, item, 1);
}
/// <summary>
/// Adds an item/moves an item up in the LRU cache and returns whether or not
/// the item with the given key already existed
/// </summary>
/// <param name="key"></param>
/// <param name="item"></param>
/// <param name="size">Size of the item</param>
/// <returns>If the object already existed</returns>
public bool Add(K key, T item, int size)
{
KeyValuePair<K, T> kvp = new KeyValuePair<K, T>(key, item);
//does this list already contain the item?
//if so remove it so it gets moved to the bottom
bool removed = _storage.Remove(kvp);
//are we at capacity?
if ((!removed) && _totalSize >= _capacity)
{
EnsureCapacity(size);
}
//insert the new item
_storage.Add(kvp);
if (!removed)
{
_totalSize += size;
if (_objectSizes != null) _objectSizes[key] = size;
}
return removed;
}
private void EnsureCapacity(int requiredSize)
{
while (this.RemainingCapacity < requiredSize && _storage.Count > 0)
{
//remove the top item
KeyValuePair<K, T> pair = _storage.RemoveFirst();
this.AccountForRemoval(pair.Key);
if (this.OnItemPurged != null)
{
OnItemPurged(pair.Value);
}
}
}
public void Clear()
{
_storage.Clear();
_totalSize = 0;
if (_objectSizes != null) _objectSizes.Clear();
}
public bool Contains(K key)
{
KeyValuePair<K, T> kvp = new KeyValuePair<K, T>(key, default(T));
return _storage.Contains(kvp);
}
public int Count
{
get { return _storage.Count; }
}
public int Size
{
get { return _totalSize; }
}
public int RemainingCapacity
{
get { return _capacity - _totalSize; }
}
public bool IsReadOnly
{
get { return _storage.IsReadOnly; }
}
public bool Remove(K key)
{
KeyValuePair<K, T> kvp = new KeyValuePair<K, T>(key, default(T));
if (_storage.Remove(kvp))
{
AccountForRemoval(key);
return true;
}
else
{
return false;
}
}
private void AccountForRemoval(K key)
{
if (_objectSizes != null)
{
_totalSize -= _objectSizes[key];
_objectSizes.Remove(key);
}
else
{
_totalSize--;
}
}
#endregion
public IEnumerator<KeyValuePair<K, T>> GetEnumerator()
{
return _storage.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return _storage.GetEnumerator();
}
}
}
| |
//-------------------------------------------------------------------------------
// <copyright file="BindingRoot.cs" company="Ninject Project Contributors">
// Copyright (c) 2007-2009, Enkari, Ltd.
// Copyright (c) 2009-2011 Ninject Project Contributors
// Authors: Nate Kohari (nate@enkari.com)
// Remo Gloor (remo.gloor@gmail.com)
//
// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL).
// you may not use this file except in compliance with one of the Licenses.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// or
// http://www.microsoft.com/opensource/licenses.mspx
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-------------------------------------------------------------------------------
namespace Telerik.JustMock.AutoMock.Ninject.Syntax
{
using System;
using System.Linq;
using Telerik.JustMock.AutoMock.Ninject.Infrastructure;
using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Disposal;
using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Introspection;
using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings;
/// <summary>
/// Provides a path to register bindings.
/// </summary>
public abstract class BindingRoot : DisposableObject, IBindingRoot
{
/// <summary>
/// Gets the kernel.
/// </summary>
/// <value>The kernel.</value>
protected abstract IKernel KernelInstance { get; }
/// <summary>
/// Declares a binding for the specified service.
/// </summary>
/// <typeparam name="T">The service to bind.</typeparam>
/// <returns>The fluent syntax</returns>
public IBindingToSyntax<T> Bind<T>()
{
Type service = typeof(T);
var binding = new Binding(service);
this.AddBinding(binding);
return new BindingBuilder<T>(binding, this.KernelInstance, service.Format());
}
/// <summary>
/// Declares a binding for the specified service.
/// </summary>
/// <typeparam name="T1">The first service to bind.</typeparam>
/// <typeparam name="T2">The second service to bind.</typeparam>
/// <returns>The fluent syntax</returns>
public IBindingToSyntax<T1, T2> Bind<T1, T2>()
{
var firstBinding = new Binding(typeof(T1));
this.AddBinding(firstBinding);
this.AddBinding(new Binding(typeof(T2), firstBinding.BindingConfiguration));
var servceNames = new[] { typeof(T1).Format(), typeof(T2).Format() };
return new BindingBuilder<T1, T2>(firstBinding.BindingConfiguration, this.KernelInstance, string.Join(", ", servceNames));
}
/// <summary>
/// Declares a binding for the specified service.
/// </summary>
/// <typeparam name="T1">The first service to bind.</typeparam>
/// <typeparam name="T2">The second service to bind.</typeparam>
/// <typeparam name="T3">The third service to bind.</typeparam>
/// <returns>The fluent syntax</returns>
public IBindingToSyntax<T1, T2, T3> Bind<T1, T2, T3>()
{
var firstBinding = new Binding(typeof(T1));
this.AddBinding(firstBinding);
this.AddBinding(new Binding(typeof(T2), firstBinding.BindingConfiguration));
this.AddBinding(new Binding(typeof(T3), firstBinding.BindingConfiguration));
var servceNames = new[] { typeof(T1).Format(), typeof(T2).Format(), typeof(T3).Format() };
return new BindingBuilder<T1, T2, T3>(firstBinding.BindingConfiguration, this.KernelInstance, string.Join(", ", servceNames));
}
/// <summary>
/// Declares a binding for the specified service.
/// </summary>
/// <typeparam name="T1">The first service to bind.</typeparam>
/// <typeparam name="T2">The second service to bind.</typeparam>
/// <typeparam name="T3">The third service to bind.</typeparam>
/// <typeparam name="T4">The fourth service to bind.</typeparam>
/// <returns>The fluent syntax</returns>
public IBindingToSyntax<T1, T2, T3, T4> Bind<T1, T2, T3, T4>()
{
var firstBinding = new Binding(typeof(T1));
this.AddBinding(firstBinding);
this.AddBinding(new Binding(typeof(T2), firstBinding.BindingConfiguration));
this.AddBinding(new Binding(typeof(T3), firstBinding.BindingConfiguration));
this.AddBinding(new Binding(typeof(T4), firstBinding.BindingConfiguration));
var servceNames = new[] { typeof(T1).Format(), typeof(T2).Format(), typeof(T3).Format(), typeof(T4).Format() };
return new BindingBuilder<T1, T2, T3, T4>(firstBinding.BindingConfiguration, this.KernelInstance, string.Join(", ", servceNames));
}
/// <summary>
/// Declares a binding for the specified service.
/// </summary>
/// <param name="services">The services to bind.</param>
/// <returns>The fluent syntax</returns>
public IBindingToSyntax<object> Bind(params Type[] services)
{
Ensure.ArgumentNotNull(services, "service");
if (services.Length == 0)
{
throw new ArgumentException("The services must contain at least one type", "services");
}
var firstBinding = new Binding(services[0]);
this.AddBinding(firstBinding);
foreach (var service in services.Skip(1))
{
this.AddBinding(new Binding(service, firstBinding.BindingConfiguration));
}
return new BindingBuilder<object>(firstBinding, this.KernelInstance, string.Join(", ", services.Select(service => service.Format()).ToArray()));
}
/// <summary>
/// Unregisters all bindings for the specified service.
/// </summary>
/// <typeparam name="T">The service to unbind.</typeparam>
public void Unbind<T>()
{
Unbind(typeof(T));
}
/// <summary>
/// Unregisters all bindings for the specified service.
/// </summary>
/// <param name="service">The service to unbind.</param>
public abstract void Unbind(Type service);
/// <summary>
/// Removes any existing bindings for the specified service, and declares a new one.
/// </summary>
/// <typeparam name="T1">The first service to re-bind.</typeparam>
/// <returns>The fluent syntax</returns>
public IBindingToSyntax<T1> Rebind<T1>()
{
Unbind<T1>();
return Bind<T1>();
}
/// <summary>
/// Removes any existing bindings for the specified services, and declares a new one.
/// </summary>
/// <typeparam name="T1">The first service to re-bind.</typeparam>
/// <typeparam name="T2">The second service to re-bind.</typeparam>
/// <returns>The fluent syntax.</returns>
public IBindingToSyntax<T1, T2> Rebind<T1, T2>()
{
Unbind<T1>();
Unbind<T2>();
return Bind<T1, T2>();
}
/// <summary>
/// Removes any existing bindings for the specified services, and declares a new one.
/// </summary>
/// <typeparam name="T1">The first service to re-bind.</typeparam>
/// <typeparam name="T2">The second service to re-bind.</typeparam>
/// <typeparam name="T3">The third service to re-bind.</typeparam>
/// <returns>The fluent syntax.</returns>
public IBindingToSyntax<T1, T2, T3> Rebind<T1, T2, T3>()
{
Unbind<T1>();
Unbind<T2>();
Unbind<T3>();
return Bind<T1, T2, T3>();
}
/// <summary>
/// Removes any existing bindings for the specified services, and declares a new one.
/// </summary>
/// <typeparam name="T1">The first service to re-bind.</typeparam>
/// <typeparam name="T2">The second service to re-bind.</typeparam>
/// <typeparam name="T3">The third service to re-bind.</typeparam>
/// <typeparam name="T4">The fourth service to re-bind.</typeparam>
/// <returns>The fluent syntax.</returns>
public IBindingToSyntax<T1, T2, T3, T4> Rebind<T1, T2, T3, T4>()
{
Unbind<T1>();
Unbind<T2>();
Unbind<T3>();
Unbind<T4>();
return Bind<T1, T2, T3, T4>();
}
/// <summary>
/// Removes any existing bindings for the specified service, and declares a new one.
/// </summary>
/// <param name="services">The services to re-bind.</param>
/// <returns>The fluent syntax</returns>
public IBindingToSyntax<object> Rebind(params Type[] services)
{
foreach (var service in services)
{
Unbind(service);
}
return Bind(services);
}
/// <summary>
/// Registers the specified binding.
/// </summary>
/// <param name="binding">The binding to add.</param>
public abstract void AddBinding(IBinding binding);
/// <summary>
/// Unregisters the specified binding.
/// </summary>
/// <param name="binding">The binding to remove.</param>
public abstract void RemoveBinding(IBinding binding);
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Collections;
using System.Collections.ObjectModel;
using System.IO;
using System.Threading;
namespace Apache.Geode.Client.UnitTests
{
using NUnit.Framework;
using Apache.Geode.DUnitFramework;
using Apache.Geode.Client;
[Serializable]
public class CustomPartitionResolver<TValue> : IPartitionResolver<int, TValue>
{
public CustomPartitionResolver()
{
}
public string GetName()
{
return (string)"CustomPartitionResolver";
}
public Object GetRoutingObject(EntryEvent<int, TValue> key)
{
Util.Log("CustomPartitionResolver::GetRoutingObject");
return key.Key + 5;
}
public static CustomPartitionResolver<TValue> Create()
{
return new CustomPartitionResolver<TValue>();
}
}
[Serializable]
public class CustomPartitionResolver1<TValue> : IFixedPartitionResolver<int, TValue>
{
public CustomPartitionResolver1()
{
}
public string GetName()
{
return (string)"CustomPartitionResolver1";
}
public Object GetRoutingObject(EntryEvent<int, TValue> key)
{
Util.Log("CustomPartitionResolver1::GetRoutingObject");
int nkey = key.Key;
return nkey + 5;
}
public static CustomPartitionResolver1<TValue> Create()
{
return new CustomPartitionResolver1<TValue>();
}
public string GetPartitionName(EntryEvent<int, TValue> entryEvent)
{
Util.Log("CustomPartitionResolver1::GetPartitionName");
int newkey = entryEvent.Key % 6;
if (newkey == 0)
{
return "P1";
}
else if (newkey == 1)
{
return "P2";
}
else if (newkey == 2)
{
return "P3";
}
else if (newkey == 3)
{
return "P4";
}
else if (newkey == 4)
{
return "P5";
}
else if (newkey == 5)
{
return "P6";
}
else
{
return "Invalid";
}
}
}
[Serializable]
public class CustomPartitionResolver2<TValue> : IFixedPartitionResolver<int, TValue>
{
public CustomPartitionResolver2()
{
}
public string GetName()
{
return (string)"CustomPartitionResolver2";
}
public Object GetRoutingObject(EntryEvent<int, TValue> key)
{
Util.Log("CustomPartitionResolver2::GetRoutingObject");
return key.Key + 4;
}
public static CustomPartitionResolver2<TValue> Create()
{
return new CustomPartitionResolver2<TValue>();
}
public string GetPartitionName(EntryEvent<int, TValue> entryEvent)
{
Util.Log("CustomPartitionResolver2::GetPartitionName");
string key = entryEvent.Key.ToString();
int numKey = Convert.ToInt32(key);
int newkey = numKey % 6;
if (newkey == 0)
{
return "P1";
}
else if (newkey == 1)
{
return "P2";
}
else if (newkey == 2)
{
return "P3";
}
else if (newkey == 3)
{
return "P4";
}
else if (newkey == 4)
{
return "P5";
}
else if (newkey == 5)
{
return "P6";
}
else
{
return "Invalid";
}
}
}
[Serializable]
public class CustomPartitionResolver3<TValue> : IFixedPartitionResolver<int, TValue>
{
public CustomPartitionResolver3()
{
}
public string GetName()
{
return (string)"CustomPartitionResolver3";
}
public Object GetRoutingObject(EntryEvent<int, TValue> key)
{
Util.Log("CustomPartitionResolver3::GetRoutingObject");
return key.Key % 5;
}
public static CustomPartitionResolver3<TValue> Create()
{
return new CustomPartitionResolver3<TValue>();
}
public string GetPartitionName(EntryEvent<int, TValue> entryEvent)
{
Util.Log("CustomPartitionResolver3::GetPartitionName");
string key = entryEvent.Key.ToString();
int numKey = Convert.ToInt32(key);
int newkey = numKey % 3;
if (newkey == 0)
{
return "P1";
}
else if (newkey == 1)
{
return "P2";
}
else if (newkey == 2)
{
return "P3";
}
else
{
return "Invalid";
}
}
}
public class TradeKey : ICacheableKey
{
public int m_id;
public int m_accountid;
public TradeKey()
{
}
public TradeKey(int id)
{
m_id = id;
m_accountid = 1 + id;
}
public TradeKey(int id, int accId)
{
m_id = id;
m_accountid = accId;
}
public void FromData(DataInput input)
{
m_id = input.ReadInt32();
m_accountid = input.ReadInt32();
}
public void ToData(DataOutput output)
{
output.WriteInt32(m_id);
output.WriteInt32(m_accountid);
}
public UInt32 ClassId
{
get
{
return 0x04;
}
}
public UInt64 ObjectSize
{
get
{
UInt32 objectSize = 0;
objectSize += (UInt32)sizeof(Int32);
objectSize += (UInt32)sizeof(Int32);
return objectSize;
}
}
public static IGeodeSerializable CreateDeserializable()
{
return new TradeKey();
}
public bool Equals(ICacheableKey other)
{
if (other == null)
return false;
TradeKey bc = other as TradeKey;
if (bc == null)
return false;
if (bc == this)
return true;
if (bc.m_id == this.m_id)
{
return true;
}
return false;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
[Serializable]
public class TradeKeyResolver : IPartitionResolver<TradeKey, Object>
{
public TradeKeyResolver()
{
}
public string GetName()
{
return (string)"TradeKeyResolver";
}
public Object GetRoutingObject(EntryEvent<TradeKey, Object> key)
{
Util.Log("TradeKeyResolver::GetRoutingObject");
TradeKey tkey = (TradeKey)key.Key;
Util.Log("TradeKeyResolver::GetRoutingObject done {0} ", tkey.m_id + 5);
return tkey.m_id + 5;
}
public static TradeKeyResolver Create()
{
return new TradeKeyResolver();
}
}
[TestFixture]
[Category("group4")]
[Category("unicast_only")]
[Category("generics")]
public class ThinClientRegionTests : ThinClientRegionSteps
{
#region Private members
private UnitProcess m_client1, m_client2;
#endregion
protected override ClientBase[] GetClients()
{
m_client1 = new UnitProcess();
m_client2 = new UnitProcess();
return new ClientBase[] { m_client1, m_client2 };
}
[TestFixtureTearDown]
public override void EndTests()
{
CacheHelper.StopJavaServers();
base.EndTests();
}
[TearDown]
public override void EndTest()
{
try
{
m_client1.Call(DestroyRegions);
m_client2.Call(DestroyRegions);
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
finally
{
CacheHelper.StopJavaServers();
CacheHelper.StopJavaLocators();
}
base.EndTest();
}
public void RegisterOtherType()
{
try
{
CacheHelper.DCache.TypeRegistry.RegisterTypeGeneric(OtherType.CreateDeserializable);
}
catch (IllegalStateException)
{
// ignored since we run multiple times for pool and non pool cases.
}
}
public void DoPutsOtherTypeWithEx(OtherType.ExceptionType exType)
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
for (int keyNum = 1; keyNum <= 10; ++keyNum)
{
try
{
region["key-" + keyNum] = new OtherType(keyNum, keyNum * keyNum, exType);
if (exType != OtherType.ExceptionType.None)
{
Assert.Fail("Expected an exception in Put");
}
}
catch (GeodeIOException ex)
{
if (exType == OtherType.ExceptionType.Geode)
{
// Successfully changed exception back and forth
Util.Log("Got expected exception in Put: " + ex);
}
else if (exType == OtherType.ExceptionType.GeodeGeode)
{
if (ex.InnerException is CacheServerException)
{
// Successfully changed exception back and forth
Util.Log("Got expected exception in Put: " + ex);
}
else
{
throw;
}
}
else
{
throw;
}
}
catch (CacheServerException ex)
{
if (exType == OtherType.ExceptionType.GeodeSystem)
{
if (ex.InnerException is IOException)
{
// Successfully changed exception back and forth
Util.Log("Got expected exception in Put: " + ex);
}
else
{
throw;
}
}
else
{
throw;
}
}
catch (IOException ex)
{
if (exType == OtherType.ExceptionType.System)
{
// Successfully changed exception back and forth
Util.Log("Got expected system exception in Put: " + ex);
}
else
{
throw;
}
}
catch (ApplicationException ex)
{
if (exType == OtherType.ExceptionType.SystemGeode)
{
if (ex.InnerException is CacheServerException)
{
// Successfully changed exception back and forth
Util.Log("Got expected system exception in Put: " + ex);
}
else
{
throw;
}
}
else if (exType == OtherType.ExceptionType.SystemSystem)
{
if (ex.InnerException is IOException)
{
// Successfully changed exception back and forth
Util.Log("Got expected system exception in Put: " + ex);
}
else
{
throw;
}
}
else
{
throw;
}
}
}
}
public void RegexInterestAllStep2() //client 2 //pxr2
{
Util.Log("RegexInterestAllStep2 Enters.");
IRegion<object, object> region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
IRegion<object, object> region1 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]);
//CreateEntry(m_regionNames[0], m_keys[1], m_vals[1]);
//CreateEntry(m_regionNames[1], m_keys[1], m_vals[1]);
region0.GetSubscriptionService().RegisterAllKeys(false, true);
region1.GetSubscriptionService().RegisterAllKeys(false, true);
if (region0.Count != 1 || region1.Count != 1)
{
Assert.Fail("Expected one entry in region");
}
Util.Log("RegexInterestAllStep2 complete.");
}
public void CheckAndPutKey()
{
IRegion<object, object> region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
IRegionService regServ = region0.RegionService;
Cache cache = regServ as Cache;
Assert.IsNotNull(cache);
if (region0.ContainsKey("keyKey01"))
{
Assert.Fail("Did not expect keyKey01 to be on Server");
}
region0["keyKey01"] = "valueValue01";
if (!region0.ContainsKey("keyKey01"))
{
Assert.Fail("Expected keyKey01 to be on Server");
}
}
public void ClearRegionStep1()
{
IRegion<object, object> region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
region0.GetSubscriptionService().RegisterAllKeys();
CreateEntry(m_regionNames[0], m_keys[0], m_nvals[0]);
CreateEntry(m_regionNames[0], m_keys[1], m_nvals[1]);
if (region0.Count != 2)
{
Assert.Fail("Expected region size 2");
}
}
public void ClearRegionListenersStep1()
{
IRegion<object, object> region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
region0.GetSubscriptionService().RegisterAllKeys();
AttributesMutator<object, object> attrMutator = region0.AttributesMutator;
TallyListener<object, object> listener = new TallyListener<object, object>();
attrMutator.SetCacheListener(listener);
TallyWriter<object, object> writer = new TallyWriter<object, object>();
attrMutator.SetCacheWriter(writer);
}
public void ClearRegionStep2()
{
//Console.WriteLine("IRegion<object, object> Name = {0}", m_regionNames[0]);
IRegion<object, object> region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
if (region0 == null)
{
Console.WriteLine("Region0 is Null");
}
else
{
//Console.WriteLine("NIL:Before clear call");
region0.Clear();
//Console.WriteLine("NIL:After clear call");
if (region0.Count != 0)
{
Assert.Fail("Expected region size 0");
}
}
Thread.Sleep(20000);
}
public void ClearRegionListenersStep2()
{
IRegion<object, object> region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
if (region0.Count != 2)
{
Assert.Fail("Expected region size 2");
}
}
public void ClearRegionListenersStep3()
{
IRegion<object, object> region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
if (region0.Count != 0)
{
Assert.Fail("Expected region size 0");
}
Apache.Geode.Client.RegionAttributes<object, object> attr = region0.Attributes;
TallyListener<object, object> listener = attr.CacheListener as TallyListener<object, object>;
TallyWriter<object, object> writer = attr.CacheWriter as TallyWriter<object, object>;
if (listener.Clears != 1)
{
Assert.Fail("Expected listener clear count 1");
}
if (writer.Clears != 1)
{
Assert.Fail("Expected writer clear count 1");
}
CreateEntry(m_regionNames[0], m_keys[0], m_nvals[0]);
CreateEntry(m_regionNames[0], m_keys[1], m_nvals[1]);
if (region0.Count != 2)
{
Assert.Fail("Expected region size 2");
}
region0.GetLocalView().Clear();
if (listener.Clears != 2)
{
Assert.Fail("Expected listener clear count 2");
}
if (writer.Clears != 2)
{
Assert.Fail("Expected writer clear count 2");
}
if (region0.Count != 0)
{
Assert.Fail("Expected region size 0");
}
}
public void ClearRegionStep3()
{
IRegion<object, object> region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
if (region0.Count != 2)
{
Assert.Fail("Expected region size 2");
}
if (!region0.ContainsKey(m_keys[0]))
{
Assert.Fail("m_key[0] is not on Server");
}
if (!region0.ContainsKey(m_keys[1]))
{
Assert.Fail("m_key[1] is not on Server");
}
}
public void GetInterests()
{
string[] testregex = { "Key-*1", "Key-*2", "Key-*3", "Key-*4", "Key-*5", "Key-*6" };
IRegion<object, object> region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
region0.GetSubscriptionService().RegisterRegex(testregex[0]);
region0.GetSubscriptionService().RegisterRegex(testregex[1]);
ICollection<object> myCollection1 = new Collection<object>();
myCollection1.Add((object)m_keys[0]);
region0.GetSubscriptionService().RegisterKeys(myCollection1);
ICollection<object> myCollection2 = new Collection<object>();
myCollection2.Add((object)m_keys[1]);
region0.GetSubscriptionService().RegisterKeys(myCollection2);
ICollection<string> regvCol = region0.GetSubscriptionService().GetInterestListRegex();
string[] regv = new string[regvCol.Count];
regvCol.CopyTo(regv, 0);
if (regv.Length != 2)
{
Assert.Fail("regex list length is not 2");
}
for (int i = 0; i < regv.Length; i++)
{
Util.Log("regv[{0}]={1}", i, regv[i]);
bool found = false;
for (int j = 0; j < regv.Length; j++)
{
if (regv[i].Equals(testregex[j]))
{
found = true;
break;
}
}
if (!found)
{
Assert.Fail("Unexpected regex");
}
}
ICollection<object> keyvCol = region0.GetSubscriptionService().GetInterestList();
string[] keyv = new string[keyvCol.Count];
keyvCol.CopyTo(keyv, 0);
if (keyv.Length != 2)
{
Assert.Fail("interest list length is not 2");
}
for (int i = 0; i < keyv.Length; i++)
{
Util.Log("keyv[{0}]={1}", i, keyv[i].ToString());
bool found = false;
for (int j = 0; j < keyv.Length; j++)
{
if (keyv[i].ToString().Equals(m_keys[j]))
{
found = true;
break;
}
}
if (!found)
{
Assert.Fail("Unexpected key");
}
}
}
public void RegexInterestAllStep3(string locators)
{
IRegion<object, object> region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
IRegion<object, object> region1 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]);
region0.GetSubscriptionService().UnregisterAllKeys();
region1.GetSubscriptionService().UnregisterAllKeys();
region0.GetLocalView().DestroyRegion();
region1.GetLocalView().DestroyRegion();
CreateTCRegions_Pool(RegionNames, locators, "__TESTPOOL1_", true);
region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
region1 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]);
CreateEntry(m_regionNames[0], m_keys[0], m_nvals[0]);
region0.GetSubscriptionService().RegisterRegex(".*", false, true);
region1.GetSubscriptionService().RegisterRegex(".*", false, true);
if (region0.Count != 1)
{
Assert.Fail("Expected one entry in region");
}
if (region1.Count != 1)
{
Assert.Fail("Expected one entry in region");
}
VerifyCreated(m_regionNames[0], m_keys[0]);
VerifyCreated(m_regionNames[1], m_keys[2]);
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]);
Util.Log("RegexInterestAllStep3 complete.");
}
public void RegexInterestAllStep4()
{
IRegion<object, object> region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
region0.GetSubscriptionService().RegisterAllKeys(false, false);
if (region0.Count != 1)
{
Assert.Fail("Expected one entry in region");
}
if (!region0.ContainsKey(m_keys[0]))
{
Assert.Fail("Expected region to contain the key");
}
if (region0.ContainsValueForKey(m_keys[0]))
{
Assert.Fail("Expected region to not contain the value");
}
IRegion<object, object> region1 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]);
region1.GetSubscriptionService().RegisterRegex(".*", false, false);
if (region1.Count != 1)
{
Assert.Fail("Expected one entry in region");
}
if (!region1.ContainsKey(m_keys[2]))
{
Assert.Fail("Expected region to contain the key");
}
if (region1.ContainsValueForKey(m_keys[2]))
{
Assert.Fail("Expected region to not contain the value");
}
CreateEntry(m_regionNames[0], m_keys[1], m_vals[1]);
UpdateEntry(m_regionNames[0], m_keys[0], m_vals[0], false);
CreateEntry(m_regionNames[1], m_keys[3], m_vals[3]);
}
public void RegexInterestAllStep5()
{
IRegion<object, object> region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
IRegion<object, object> region1 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]);
if (region1.Count != 2 || region0.Count != 2)
{
Assert.Fail("Expected two entry in region");
}
VerifyCreated(m_regionNames[0], m_keys[0]);
VerifyCreated(m_regionNames[1], m_keys[2]);
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[0], m_keys[1], m_vals[1]);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]);
}
public void RegexInterestAllStep6()
{
UpdateEntry(m_regionNames[0], m_keys[0], m_nvals[0], false);
UpdateEntry(m_regionNames[1], m_keys[2], m_nvals[2], false);
}
public void RegexInterestAllStep7() //client 2
{
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]);
VerifyEntry(m_regionNames[0], m_keys[1], m_vals[1], false);
VerifyEntry(m_regionNames[1], m_keys[2], m_nvals[2]);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3], false);
}
public void RegexInterestAllStep8()
{
IRegion<object, object> region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
IRegion<object, object> region1 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]);
region0.GetSubscriptionService().UnregisterAllKeys();
region1.GetSubscriptionService().UnregisterAllKeys();
}
public void RegexInterestAllStep9()
{
UpdateEntry(m_regionNames[0], m_keys[0], m_vals[0], false);
VerifyEntry(m_regionNames[0], m_keys[1], m_vals[1], false);
UpdateEntry(m_regionNames[1], m_keys[2], m_vals[2], false);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3], false);
}
public void RegexInterestAllStep10()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]);
VerifyEntry(m_regionNames[0], m_keys[1], m_vals[1]);
VerifyEntry(m_regionNames[1], m_keys[2], m_nvals[2]);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]);
}
//public void GetAll(string endpoints, bool pool, bool locator)
//{
// Util.Log("Enters GetAll");
// IRegion<object, object> region0 = CacheHelper.GetVerifyRegion(m_regionNames[0]);
// List<ICacheableKey> resultKeys = new List<ICacheableKey>();
// CacheableKey key0 = m_keys[0];
// CacheableKey key1 = m_keys[1];
// resultKeys.Add(key0);
// resultKeys.Add(key1);
// region0.LocalDestroyRegion();
// region0 = null;
// if (pool) {
// if (locator) {
// region0 = CacheHelper.CreateTCRegion_Pool(RegionNames[0], true, false, null, null, endpoints, "__TESTPOOL1_", true); //caching enable false
// }
// else {
// region0 = CacheHelper.CreateTCRegion_Pool(RegionNames[0], true, false, null, endpoints, null, "__TESTPOOL1_", true); //caching enable false
// }
// }
// else {
// region0 = CacheHelper.CreateTCRegion(RegionNames[0], true, false, null, endpoints, true); //caching enable false
// }
// try {
// region0.GetAll(resultKeys.ToArray(), null, null, true);
// Assert.Fail("Expected IllegalArgumentException");
// }
// catch (IllegalArgumentException ex) {
// Util.Log("Got expected IllegalArgumentException" + ex.Message);
// }
// //recreate region with caching enabled true
// region0.LocalDestroyRegion();
// region0 = null;
// if (pool) {
// if (locator) {
// region0 = CacheHelper.CreateTCRegion_Pool(RegionNames[0], true, true, null, null, endpoints, "__TESTPOOL1_", true); //caching enable true
// }
// else {
// region0 = CacheHelper.CreateTCRegion_Pool(RegionNames[0], true, true, null, endpoints, null, "__TESTPOOL1_", true); //caching enable true
// }
// }
// else {
// region0 = CacheHelper.CreateTCRegion(RegionNames[0], true, true, null, endpoints, true); //caching enable true
// }
// Dictionary<ICacheableKey, IGeodeSerializable> values = new Dictionary<ICacheableKey, IGeodeSerializable>();
// Dictionary<ICacheableKey, Exception> exceptions = new Dictionary<ICacheableKey, Exception>();
// resultKeys.Clear();
// try {
// region0.GetAll(resultKeys.ToArray(), values, exceptions);
// Assert.Fail("Expected IllegalArgumentException");
// }
// catch (IllegalArgumentException ex) {
// Util.Log("Got expected IllegalArgumentException" + ex.Message);
// }
// resultKeys.Add(key0);
// resultKeys.Add(key1);
// try {
// region0.GetAll(resultKeys.ToArray(), null, null, false);
// Assert.Fail("Expected IllegalArgumentException");
// }
// catch (IllegalArgumentException ex) {
// Util.Log("Got expected IllegalArgumentException" + ex.Message);
// }
// region0.GetAll(resultKeys.ToArray(), values, exceptions);
// if (values.Count != 2) {
// Assert.Fail("Expected 2 values");
// }
// if (exceptions.Count != 0) {
// Assert.Fail("No exception expected");
// }
// try {
// CacheableString val0 = (CacheableString)values[(resultKeys[0])];
// CacheableString val1 = (CacheableString)values[(resultKeys[1])];
// if (!(val0.ToString().Equals(m_nvals[0])) || !(val1.ToString().Equals(m_nvals[1]))) {
// Assert.Fail("Got unexpected value");
// }
// }
// catch (Exception ex) {
// Assert.Fail("Key should have been found" + ex.Message);
// }
// IRegion<object, object> region1 = CacheHelper.GetVerifyRegion(m_regionNames[1]);
// CacheableKey key2 = m_keys[2];
// CacheableKey key3 = m_keys[3];
// region1.LocalInvalidate(key2);
// resultKeys.Clear();
// resultKeys.Add(key2);
// resultKeys.Add(key3);
// values.Clear();
// exceptions.Clear();
// region1.GetAll(resultKeys.ToArray(), values, exceptions, true);
// if (values.Count != 2) {
// Assert.Fail("Expected 2 values");
// }
// if (exceptions.Count != 0) {
// Assert.Fail("Expected no exception");
// }
// try {
// CacheableString val2 = (CacheableString)values[(resultKeys[0])];
// CacheableString val3 = (CacheableString)values[(resultKeys[1])];
// if (!(val2.ToString().Equals(m_nvals[2])) || !(val3.ToString().Equals(m_vals[3]))) {
// Assert.Fail("Got unexpected value");
// }
// }
// catch (Exception ex) {
// Assert.Fail("Key should have been found" + ex.Message);
// }
// if (region1.Size != 2) {
// Assert.Fail("Expected 2 entry in the region");
// }
// RegionEntry[] regionEntry = region1.GetEntries(false);//Not of subregions
// if (regionEntry.Length != 2) {
// Assert.Fail("Should have two values in the region");
// }
// VerifyEntry(RegionNames[1], m_keys[2], m_nvals[2], true);
// VerifyEntry(RegionNames[1], m_keys[3], m_vals[3], true);
// region1.LocalInvalidate(key3);
// values = null;
// exceptions.Clear();
// region1.GetAll(resultKeys.ToArray(), values, exceptions, true);
// if (region1.Size != 2) {
// Assert.Fail("Expected 2 entry in the region");
// }
// regionEntry = region1.GetEntries(false);
// if (regionEntry.Length != 2) {
// Assert.Fail("Should have two values in the region");
// }
// VerifyEntry(RegionNames[1], m_keys[2], m_nvals[2], true);
// VerifyEntry(RegionNames[1], m_keys[3], m_nvals[3], true);
// Util.Log("Exits GetAll");
//}
//private void UpdateEntry(string p, string p_2, string p_3)
//{
// throw new Exception("The method or operation is not implemented.");
//}
public void PutAllStep3()
{
IRegion<object, object> region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
IRegion<object, object> region1 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]);
List<object> resultKeys = new List<object>();
object key0 = m_keys[0];
object key1 = m_keys[1];
resultKeys.Add(key0);
resultKeys.Add(key1);
region0.GetSubscriptionService().RegisterKeys(resultKeys.ToArray());
Util.Log("Step three completes");
}
public void PutAllStep4()
{
Dictionary<object, object> map0 = new Dictionary<object, object>();
Dictionary<object, object> map1 = new Dictionary<object, object>();
object key0 = m_keys[0];
object key1 = m_keys[1];
string val0 = m_vals[0];
string val1 = m_vals[1];
map0.Add(key0, val0);
map0.Add(key1, val1);
object key2 = m_keys[2];
object key3 = m_keys[3];
string val2 = m_vals[2];
string val3 = m_vals[3];
map1.Add(key2, val2);
map1.Add(key3, val3);
IRegion<object, object> region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
IRegion<object, object> region1 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]);
region0.PutAll(map0);
region1.PutAll(map1);
Util.Log("Put All Complets");
}
public void PutAllStep5()
{
VerifyCreated(m_regionNames[0], m_keys[0]);
VerifyCreated(m_regionNames[0], m_keys[1]);
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[0], m_keys[1], m_vals[1]);
DoNetsearch(m_regionNames[1], m_keys[2], m_vals[2], true);
DoNetsearch(m_regionNames[1], m_keys[3], m_vals[3], true);
Util.Log("StepFive complete.");
}
public void PutAllStep6()
{
Dictionary<object, object> map0 = new Dictionary<object, object>();
Dictionary<object, object> map1 = new Dictionary<object, object>();
object key0 = m_keys[0];
object key1 = m_keys[1];
string val0 = m_nvals[0];
string val1 = m_nvals[1];
map0.Add(key0, val0);
map0.Add(key1, val1);
object key2 = m_keys[2];
object key3 = m_keys[3];
string val2 = m_nvals[2];
string val3 = m_nvals[3];
map1.Add(key2, val2);
map1.Add(key3, val3);
IRegion<object, object> region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
IRegion<object, object> region1 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]);
region0.PutAll(map0);
region1.PutAll(map1);
Util.Log("Step6 Complets");
}
public void PutAllStep7() //client 1
{
//Region0 is changed at client 1 because keys[0] and keys[1] were registered.PutAllStep3
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]);
VerifyEntry(m_regionNames[0], m_keys[1], m_nvals[1]);
// region1 is not changed at client beacuse no regsiter interest.
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]);
Util.Log("PutAllStep7 complete.");
}
public virtual void RemoveAllStep1()
{
CreateEntry(m_regionNames[0], m_keys[0], m_vals[0]);
CreateEntry(m_regionNames[0], m_keys[1], m_vals[1]);
CreateEntry(m_regionNames[0], m_keys[2], m_vals[2]);
CreateEntry(m_regionNames[1], m_keys[3], m_vals[3]);
CreateEntry(m_regionNames[1], m_keys[4], m_vals[4]);
CreateEntry(m_regionNames[1], m_keys[5], m_vals[5]);
Util.Log("RemoveAllStep1 complete.");
}
public virtual void RemoveAllStep2()
{
IRegion<object, object> reg0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
IRegion<object, object> reg1 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]);
ICollection<object> keys0 = new List<object>();
ICollection<object> keys1 = new List<object>();
for (int i = 0; i < 3; i++)
{
keys0.Add(m_keys[i]);
keys1.Add(m_keys[i + 3]);
}
//try remove all
reg0.RemoveAll(keys0);
reg1.RemoveAll(keys1);
Util.Log("RemoveAllStep2 complete.");
}
public virtual void RemoveAllStep3()
{
VerifyDestroyed(m_regionNames[0], m_keys[0]);
VerifyDestroyed(m_regionNames[0], m_keys[1]);
VerifyDestroyed(m_regionNames[0], m_keys[2]);
VerifyDestroyed(m_regionNames[1], m_keys[3]);
VerifyDestroyed(m_regionNames[1], m_keys[4]);
VerifyDestroyed(m_regionNames[1], m_keys[5]);
IRegion<object, object> region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
IRegion<object, object> region1 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]);
Assert.AreEqual(region0.Count, 0, "Remove all should remove the entries specified");
Assert.AreEqual(region1.Count, 0, "Remove all should remove the entries specified");
Util.Log("RemoveAllStep3 complete.");
}
public virtual void RemoveAllSingleHopStep()
{
IRegion<object, object> region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
ICollection<object> keys = new Collection<object>();
for (int y = 0; y < 1000; y++)
{
Util.Log("put:{0}", y);
region0[y] = y;
keys.Add(y);
}
region0.RemoveAll(keys);
Assert.AreEqual(0, region0.Count);
Util.Log("RemoveAllSingleHopStep completed");
}
void runDistOps()
{
CacheHelper.SetupJavaServers(true, "cacheserver.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator 1 started.");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(CreateNonExistentRegion, CacheHelper.Locators);
m_client1.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", false);
Util.Log("StepOne (pool locators) complete.");
m_client2.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", false);
Util.Log("StepTwo (pool locators) complete.");
m_client1.Call(StepThree);
Util.Log("StepThree complete.");
m_client2.Call(StepFour);
Util.Log("StepFour complete.");
m_client1.Call(CheckServerKeys);
m_client1.Call(StepFive, true);
Util.Log("StepFive complete.");
m_client2.Call(StepSix, true);
Util.Log("StepSix complete.");
m_client1.Call(Close);
Util.Log("Client 1 closed");
m_client2.Call(Close);
Util.Log("Client 2 closed");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator 1 stopped.");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
void runDistOps2()
{
CacheHelper.SetupJavaServers(true, "cacheserver.xml", "cacheserver2.xml", "cacheserver3.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator 1 started.");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1);
Util.Log("Cacheserver 2 started.");
CacheHelper.StartJavaServerWithLocators(3, "GFECS3", 1);
Util.Log("Cacheserver 3 started.");
m_client1.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", false);
Util.Log("StepOne (pool locators) complete.");
m_client2.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", false);
Util.Log("StepTwo (pool locators) complete.");
m_client1.Call(StepThree);
Util.Log("StepThree complete.");
m_client2.Call(StepFour);
Util.Log("StepFour complete.");
m_client1.Call(StepFive, true);
Util.Log("StepFive complete.");
m_client2.Call(StepSix, true);
Util.Log("StepSix complete.");
//m_client1.Call(GetAll, pool, locator);
m_client1.Call(Close);
Util.Log("Client 1 closed");
m_client2.Call(Close);
Util.Log("Client 2 closed");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaServer(2);
Util.Log("Cacheserver 2 stopped.");
CacheHelper.StopJavaServer(3);
Util.Log("Cacheserver 3 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator 1 stopped.");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
void runCheckPutGet()
{
CacheHelper.SetupJavaServers(true, "cacheServer_pdxreadserialized.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator 1 started.");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
PutGetTests putGetTest = new PutGetTests();
m_client1.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", false);
Util.Log("Client 1 (pool locators) regions created");
m_client2.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", false);
Util.Log("Client 2 (pool locators) regions created");
m_client1.Call(putGetTest.SetRegion, RegionNames[0]);
m_client2.Call(putGetTest.SetRegion, RegionNames[0]);
long dtTicks = DateTime.Now.Ticks;
CacheableHelper.RegisterBuiltins(dtTicks);
putGetTest.TestAllKeyValuePairs(m_client1, m_client2,
RegionNames[0], true, dtTicks);
m_client1.Call(Close);
Util.Log("Client 1 closed");
m_client2.Call(Close);
Util.Log("Client 2 closed");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator 1 stopped.");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
void runCheckPutGetWithAppDomain()
{
CacheHelper.SetupJavaServers(true, "cacheServer_pdxreadserialized.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator 1 started.");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
PutGetTests putGetTest = new PutGetTests();
m_client1.Call(InitializeAppDomain);
long dtTime = DateTime.Now.Ticks;
m_client1.Call(CreateTCRegions_Pool_AD, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", false, false, dtTime);
Util.Log("Client 1 (pool locators) regions created");
m_client1.Call(SetRegionAD, RegionNames[0]);
//m_client2.Call(putGetTest.SetRegion, RegionNames[0]);
// CacheableHelper.RegisterBuiltins();
//putGetTest.TestAllKeyValuePairs(m_client1, m_client2,
//RegionNames[0], true, pool);
m_client1.Call(TestAllKeyValuePairsAD, RegionNames[0], true, dtTime);
//m_client1.Call(CloseCacheAD);
Util.Log("Client 1 closed");
CacheHelper.CloseCache();
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator 1 stopped.");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
void putGetTest()
{
}
void runPdxAppDomainTest(bool caching, bool readPdxSerialized)
{
CacheHelper.SetupJavaServers(true, "cacheServer_pdxreadserialized.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator 1 started.");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(InitializeAppDomain);
m_client1.Call(CreateTCRegions_Pool_AD2, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", false, false, caching, readPdxSerialized);
Util.Log("Client 1 (pool locators) regions created");
m_client1.Call(SetRegionAD, RegionNames[0]);
m_client1.Call(pdxPutGetTest, caching, readPdxSerialized);
m_client1.Call(pdxGetPutTest, caching, readPdxSerialized);
//m_client2.Call(putGetTest.SetRegion, RegionNames[0]);
// CacheableHelper.RegisterBuiltins();
//putGetTest.TestAllKeyValuePairs(m_client1, m_client2,
//RegionNames[0], true, pool);
// m_client1.Call(TestAllKeyValuePairsAD, RegionNames[0], true, pool);
m_client1.Call(CloseCacheAD);
Util.Log("Client 1 closed");
//CacheHelper.CloseCache();
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator 1 stopped.");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
void runPartitionResolver()
{
CacheHelper.SetupJavaServers(true, "cacheserver1_pr.xml",
"cacheserver2_pr.xml", "cacheserver3_pr.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator 1 started.");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1);
Util.Log("Cacheserver 2 started.");
CacheHelper.StartJavaServerWithLocators(3, "GFECS3", 1);
Util.Log("Cacheserver 3 started.");
PutGetTests putGetTest = new PutGetTests();
// Create and Add partition resolver to the regions.
//CustomPartitionResolver<object> cpr = CustomPartitionResolver<object>.Create();
m_client1.Call(CreateTCRegions_Pool2_WithPartitionResolver, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", false, true);
Util.Log("Client 1 (pool locators) regions created");
m_client2.Call(CreateTCRegions_Pool2_WithPartitionResolver, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", false, true);
Util.Log("Client 2 (pool locators) regions created");
m_client1.Call(putGetTest.SetRegion, RegionNames[1]);
m_client2.Call(putGetTest.SetRegion, RegionNames[1]);
putGetTest.DoPRSHPartitionResolverTasks(m_client1, m_client2, RegionNames[1]);
m_client1.Call(putGetTest.SetRegion, RegionNames[0]);
m_client2.Call(putGetTest.SetRegion, RegionNames[0]);
putGetTest.DoPRSHPartitionResolverTasks(m_client1, m_client2, RegionNames[0]);
m_client1.Call(Close);
Util.Log("Client 1 closed");
m_client2.Call(Close);
Util.Log("Client 2 closed");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaServer(2);
Util.Log("Cacheserver 2 stopped.");
CacheHelper.StopJavaServer(3);
Util.Log("Cacheserver 3 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator 1 stopped.");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
void runTradeKeyResolver()
{
CacheHelper.SetupJavaServers(true, "cacheserver1_TradeKey.xml",
"cacheserver2_TradeKey.xml", "cacheserver3_TradeKey.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator 1 started.");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1);
Util.Log("Cacheserver 2 started.");
CacheHelper.StartJavaServerWithLocators(3, "GFECS3", 1);
Util.Log("Cacheserver 3 started.");
m_client1.Call(CreateTCRegion2, TradeKeyRegion, true, true, TradeKeyResolver.Create(),
CacheHelper.Locators, true);
Util.Log("Client 1 (pool locators) region created");
PutGetTests putGetTest = new PutGetTests();
m_client1.Call(putGetTest.DoPRSHTradeResolverTasks, TradeKeyRegion);
m_client1.Call(Close);
Util.Log("Client 1 closed");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaServer(2);
Util.Log("Cacheserver 2 stopped.");
CacheHelper.StopJavaServer(3);
Util.Log("Cacheserver 3 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator 1 stopped.");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
void runFixedPartitionResolver()
{
CacheHelper.SetupJavaServers(true, "cacheserver1_fpr.xml",
"cacheserver2_fpr.xml", "cacheserver3_fpr.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator 1 started.");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1);
Util.Log("Cacheserver 2 started.");
CacheHelper.StartJavaServerWithLocators(3, "GFECS3", 1);
Util.Log("Cacheserver 3 started.");
PutGetTests putGetTest = new PutGetTests();
m_client1.Call(CreateTCRegions_Pool1, PartitionRegion1,
CacheHelper.Locators, "__TESTPOOL1_", false);
Util.Log("Client 1 (pool locators) PartitionRegion1 created");
m_client1.Call(CreateTCRegions_Pool1, PartitionRegion2,
CacheHelper.Locators, "__TESTPOOL1_", false);
Util.Log("Client 1 (pool locators) PartitionRegion2 created");
m_client1.Call(CreateTCRegions_Pool1, PartitionRegion3,
CacheHelper.Locators, "__TESTPOOL1_", false);
Util.Log("Client 1 (pool locators) PartitionRegion3 created");
m_client1.Call(putGetTest.SetRegion, PartitionRegion1);
putGetTest.DoPRSHFixedPartitionResolverTasks(m_client1, PartitionRegion1);
m_client1.Call(putGetTest.SetRegion, PartitionRegion2);
putGetTest.DoPRSHFixedPartitionResolverTasks(m_client1, PartitionRegion2);
m_client1.Call(putGetTest.SetRegion, PartitionRegion3);
putGetTest.DoPRSHFixedPartitionResolverTasks(m_client1, PartitionRegion3);
m_client1.Call(Close);
Util.Log("Client 1 closed");
m_client2.Call(Close);
Util.Log("Client 2 closed");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaServer(2);
Util.Log("Cacheserver 2 stopped.");
CacheHelper.StopJavaServer(3);
Util.Log("Cacheserver 3 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator 1 stopped.");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
void runCheckPut()
{
CacheHelper.SetupJavaServers(true, "cacheserver_hashcode.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator 1 started.");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
PutGetTests putGetTest = new PutGetTests();
m_client1.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", false);
Util.Log("Client 1 (pool locators) regions created");
m_client2.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", false);
Util.Log("Client 2 (pool locators) regions created");
m_client1.Call(putGetTest.SetRegion, RegionNames[0]);
m_client2.Call(putGetTest.SetRegion, RegionNames[0]);
long dtTime = DateTime.Now.Ticks;
CacheableHelper.RegisterBuiltinsJavaHashCode(dtTime);
putGetTest.TestAllKeys(m_client1, m_client2, RegionNames[0], dtTime);
m_client1.Call(Close);
Util.Log("Client 1 closed");
m_client2.Call(Close);
Util.Log("Client 2 closed");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator 1 stopped.");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
void runCheckNativeException()
{
CacheHelper.SetupJavaServers(true, "cacheserver.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator 1 started.");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(RegisterOtherType);
m_client1.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", false);
Util.Log("StepOne (pool locators) complete.");
m_client1.Call(DoPutsOtherTypeWithEx, OtherType.ExceptionType.None);
m_client1.Call(DoPutsOtherTypeWithEx, OtherType.ExceptionType.Geode);
m_client1.Call(DoPutsOtherTypeWithEx, OtherType.ExceptionType.System);
m_client1.Call(DoPutsOtherTypeWithEx, OtherType.ExceptionType.GeodeGeode);
m_client1.Call(DoPutsOtherTypeWithEx, OtherType.ExceptionType.GeodeSystem);
m_client1.Call(DoPutsOtherTypeWithEx, OtherType.ExceptionType.SystemGeode);
m_client1.Call(DoPutsOtherTypeWithEx, OtherType.ExceptionType.SystemSystem);
m_client1.Call(Close);
Util.Log("Client 1 closed");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator 1 stopped.");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
void runFailover()
{
CacheHelper.SetupJavaServers(true, "cacheserver.xml", "cacheserver2.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator 1 started.");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", false);
Util.Log("StepOne (pool locators) complete.");
m_client2.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", false);
Util.Log("StepTwo (pool locators) complete.");
m_client1.Call(StepThree);
Util.Log("StepThree complete.");
m_client2.Call(StepFour);
Util.Log("StepFour complete.");
CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1);
Util.Log("Cacheserver 2 started.");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
m_client1.Call(StepFiveFailover);
Util.Log("StepFive complete.");
m_client2.Call(StepSix, false);
Util.Log("StepSix complete.");
m_client1.Call(Close);
Util.Log("Client 1 closed");
m_client2.Call(Close);
Util.Log("Client 2 closed");
CacheHelper.StopJavaServer(2);
Util.Log("Cacheserver 2 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator 1 stopped.");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
void runNotification()
{
CacheHelper.SetupJavaServers(true, "cacheserver.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
Util.Log("StepOne (pool locators) complete.");
m_client2.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
Util.Log("StepTwo (pool locators) complete.");
m_client1.Call(RegisterAllKeysR0WithoutValues);
m_client1.Call(RegisterAllKeysR1WithoutValues);
m_client2.Call(RegisterAllKeysR0WithoutValues);
m_client2.Call(RegisterAllKeysR1WithoutValues);
m_client1.Call(StepThree);
Util.Log("StepThree complete.");
m_client2.Call(StepFour);
Util.Log("StepFour complete.");
m_client1.Call(StepFive, true);
Util.Log("StepFive complete.");
m_client2.Call(StepSixNotify, false);
Util.Log("StepSix complete.");
m_client1.Call(StepSevenNotify, false);
Util.Log("StepSeven complete.");
m_client2.Call(StepEightNotify, false);
Util.Log("StepEight complete.");
m_client1.Call(StepNineNotify, false);
Util.Log("StepNine complete.");
m_client2.Call(StepTen);
Util.Log("StepTen complete.");
m_client1.Call(StepEleven);
Util.Log("StepEleven complete.");
m_client1.Call(Close);
Util.Log("Client 1 closed");
m_client2.Call(Close);
Util.Log("Client 2 closed");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator 1 stopped.");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
void runFailover2()
{
// This test is for client failover with client notification.
CacheHelper.SetupJavaServers(true, "cacheserver.xml", "cacheserver2.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator 1 started.");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
Util.Log("StepOne (pool locators) complete.");
m_client2.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
Util.Log("StepTwo (pool locators) complete.");
m_client1.Call(RegisterAllKeysR0WithoutValues);
m_client1.Call(RegisterAllKeysR1WithoutValues);
m_client2.Call(RegisterAllKeysR0WithoutValues);
m_client2.Call(RegisterAllKeysR1WithoutValues);
m_client1.Call(StepThree);
Util.Log("StepThree complete.");
m_client2.Call(StepFour);
Util.Log("StepFour complete.");
CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1);
Util.Log("Cacheserver 2 started.");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
m_client1.Call(CheckServerKeys);
m_client1.Call(StepFive, false);
Util.Log("StepFive complete.");
m_client2.Call(StepSixNotify, false);
Util.Log("StepSix complete.");
m_client1.Call(StepSevenNotify, false);
Util.Log("StepSeven complete.");
m_client2.Call(StepEightNotify, false);
Util.Log("StepEight complete.");
m_client1.Call(StepNineNotify, false);
Util.Log("StepNine complete.");
m_client2.Call(StepTen);
Util.Log("StepTen complete.");
m_client1.Call(StepEleven);
Util.Log("StepEleven complete.");
m_client1.Call(Close);
Util.Log("Client 1 closed");
m_client2.Call(Close);
Util.Log("Client 2 closed");
CacheHelper.StopJavaServer(2);
Util.Log("Cacheserver 2 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator 1 stopped.");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
void runFailover3()
{
CacheHelper.SetupJavaServers(true,
"cacheserver.xml", "cacheserver2.xml", "cacheserver3.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator 1 started.");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", false);
Util.Log("StepOne (pool locators) complete.");
m_client2.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", false);
Util.Log("StepTwo (pool locators) complete.");
m_client1.Call(StepThree);
Util.Log("StepThree complete.");
m_client2.Call(StepFour);
Util.Log("StepFour complete.");
CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1);
Util.Log("Cacheserver 2 started.");
CacheHelper.StartJavaServerWithLocators(3, "GFECS3", 1);
Util.Log("Cacheserver 3 started.");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
m_client1.Call(StepFive, false);
Util.Log("StepFive complete.");
m_client2.Call(StepSix, false);
Util.Log("StepSix complete.");
m_client1.Call(Close);
Util.Log("Client 1 closed");
m_client2.Call(Close);
Util.Log("Client 2 closed");
CacheHelper.StopJavaServer(2);
Util.Log("Cacheserver 2 stopped.");
CacheHelper.StopJavaServer(3);
Util.Log("Cacheserver 3 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator 1 stopped.");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
void runFailoverInterestAll()
{
runFailoverInterestAll(false);
}
void runFailoverInterestAll(bool ssl)
{
CacheHelper.SetupJavaServers(true, "cacheserver_notify_subscription.xml",
"cacheserver_notify_subscription2.xml");
CacheHelper.StartJavaLocator(1, "GFELOC", null, ssl);
Util.Log("Locator 1 started.");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1, ssl);
Util.Log("Cacheserver 1 started.");
m_client1.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true, ssl);
m_client1.Call(StepThree);
Util.Log("StepThree complete.");
m_client2.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true, ssl);
Util.Log("CreateTCRegions complete.");
m_client2.Call(RegexInterestAllStep2);
Util.Log("RegexInterestAllStep2 complete.");
m_client2.Call(RegexInterestAllStep3, CacheHelper.Locators);
Util.Log("RegexInterestAllStep3 complete.");
m_client1.Call(RegexInterestAllStep4);
Util.Log("RegexInterestAllStep4 complete.");
m_client2.Call(RegexInterestAllStep5);
Util.Log("RegexInterestAllStep5 complete.");
CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1, ssl);
CacheHelper.StopJavaServer(1); //failover happens
Util.Log("Cacheserver 2 started and failover forced");
m_client1.Call(RegexInterestAllStep6);
Util.Log("RegexInterestAllStep6 complete.");
System.Threading.Thread.Sleep(5000); // sleep to let updates arrive
m_client2.Call(RegexInterestAllStep7);
Util.Log("RegexInterestAllStep7 complete.");
m_client2.Call(RegexInterestAllStep8);
Util.Log("RegexInterestAllStep8 complete.");
m_client1.Call(RegexInterestAllStep9);
Util.Log("RegexInterestAllStep9 complete.");
m_client2.Call(RegexInterestAllStep10);
Util.Log("RegexInterestAllStep10 complete.");
m_client1.Call(Close);
Util.Log("Client 1 closed");
m_client2.Call(Close);
Util.Log("Client 2 closed");
CacheHelper.StopJavaServer(2);
Util.Log("Cacheserver 2 stopped.");
CacheHelper.StopJavaLocator(1, true, ssl);
Util.Log("Locator 1 stopped.");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
void runPutAll()
{
CacheHelper.SetupJavaServers(true, "cacheserver_notify_subscription.xml",
"cacheserver_notify_subscription2.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator 1 started.");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1);
Util.Log("Cacheserver 2 started.");
m_client1.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true); //Client Notification true for client 1
m_client2.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true); //Cleint notification true for client 2
Util.Log("IRegion<object, object> creation complete.");
m_client1.Call(PutAllStep3);
Util.Log("PutAllStep3 complete.");
m_client2.Call(PutAllStep4);
Util.Log("PutAllStep4 complete.");
m_client1.Call(PutAllStep5);
Util.Log("PutAllStep5 complete.");
m_client2.Call(PutAllStep6);
Util.Log("PutAllStep6 complete.");
m_client1.Call(PutAllStep7);
Util.Log("PutAllStep7 complete.");
m_client1.Call(Close);
Util.Log("Client 1 closed");
m_client2.Call(Close);
Util.Log("Client 2 closed");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaServer(2);
Util.Log("Cacheserver 2 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator 1 stopped.");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
void runRemoveAll()
{
CacheHelper.SetupJavaServers(true, "cacheserver.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator 1 started.");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", false);
Util.Log("StepOne (pool locators) complete.");
m_client2.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", false);
Util.Log("StepTwo (pool locators) complete.");
m_client1.Call(RemoveAllStep1);
Util.Log("RemoveAllStep1 complete.");
m_client1.Call(RemoveAllStep2);
Util.Log("RemoveAllStep2 complete.");
m_client2.Call(RemoveAllStep3);
Util.Log("RemoveAllStep3 complete.");
m_client1.Call(Close);
Util.Log("Client 1 closed");
m_client2.Call(Close);
Util.Log("Client 2 closed");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator 1 stopped.");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
void runRemoveAllWithSingleHop()
{
CacheHelper.SetupJavaServers(true, "cacheserver1_pr.xml",
"cacheserver2_pr.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator 1 started.");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1);
Util.Log("Cacheserver 2 started.");
m_client1.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", false);
Util.Log("Client 1 (pool locators) regions created");
Util.Log("Region creation complete.");
m_client1.Call(RemoveAllSingleHopStep);
Util.Log("RemoveAllSingleHopStep complete.");
m_client1.Call(Close);
Util.Log("Client 1 closed");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaServer(2);
Util.Log("Cacheserver 2 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator 1 stopped.");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
void runRemoveOps()
{
CacheHelper.SetupJavaServers(true, "cacheserver.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator 1 started.");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", false);
Util.Log("StepOne (pool locators) complete.");
m_client2.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", false);
Util.Log("StepTwo (pool locators) complete.");
m_client1.Call(StepThree);
Util.Log("StepThree complete.");
m_client1.Call(RemoveStepFive);
Util.Log("RemoveStepFive complete.");
m_client2.Call(RemoveStepSix);
Util.Log("RemoveStepSix complete.");
m_client1.Call(Close);
Util.Log("Client 1 closed");
m_client2.Call(Close);
Util.Log("Client 2 closed");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator 1 stopped.");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
void runRemoveOps1()
{
CacheHelper.SetupJavaServers(true, "cacheserver1_expiry.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator 1 started.");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(CreateTCRegions_Pool, RegionNames2,
CacheHelper.Locators, "__TESTPOOL1_", false);
Util.Log("StepOne (pool locators) complete.");
m_client2.Call(CreateTCRegions_Pool, RegionNames2,
CacheHelper.Locators, "__TESTPOOL1_", false);
Util.Log("StepTwo (pool locators) complete.");
m_client2.Call(RemoveStepEight);
Util.Log("RemoveStepEight complete.");
m_client1.Call(Close);
Util.Log("Client 1 closed");
m_client2.Call(Close);
Util.Log("Client 2 closed");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator 1 stopped.");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
void runIdictionaryOps()
{
CacheHelper.SetupJavaServers(true, "cacheserver.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator 1 started.");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(CreateTCRegions_Pool, RegionNames2,
CacheHelper.Locators, "__TESTPOOL1_", false);
Util.Log("StepOne (pool locators) complete.");
m_client1.Call(IdictionaryRegionOperations, "DistRegionAck");
Util.Log("IdictionaryRegionOperations complete.");
m_client1.Call(IdictionaryRegionNullKeyOperations, "DistRegionAck");
Util.Log("IdictionaryRegionNullKeyOperations complete.");
m_client1.Call(IdictionaryRegionArrayOperations, "DistRegionAck");
Util.Log("IdictionaryRegionArrayOperations complete.");
m_client1.Call(Close);
Util.Log("Client 1 closed");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator 1 stopped.");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
public void EmptyByteArrayTest()
{
IRegion<int, byte[]> region = CacheHelper.GetVerifyRegion<int, byte[]>(RegionNames3[0]);
IRegionService regServ = region.RegionService;
Cache cache = regServ as Cache;
Assert.IsNotNull(cache);
region[0] = new byte[0];
Util.Log("Put empty byteArray in region");
Assert.AreEqual(0, region[0].Length);
region[1] = new byte[2];
Util.Log("Put non empty byteArray in region");
Assert.AreEqual(2, region[1].Length);
region[2] = System.Text.Encoding.ASCII.GetBytes("TestString");
Util.Log("Put string in region");
Assert.AreEqual(0, "TestString".CompareTo(System.Text.Encoding.ASCII.GetString(region[2]).ToString()));
Util.Log("EmptyByteArrayTest completed successfully");
}
#region Tests
[Test]
public void PutEmptyByteArrayTest()
{
CacheHelper.SetupJavaServers("cacheserver.xml");
CacheHelper.StartJavaServer(1, "GFECS1");
Util.Log("Cacheserver 1 started.");
m_client1.Call(CreateTCRegions_Pool, RegionNames3,
(string)null, "__TESTPOOL1_", true);
Util.Log("StepOne of region creation complete.");
m_client1.Call(EmptyByteArrayTest);
Util.Log("EmptyByteArrayTest completed.");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
}
[Test]
public void CheckKeyOnServer()
{
CacheHelper.SetupJavaServers("cacheserver.xml");
CacheHelper.StartJavaServer(1, "GFECS1");
Util.Log("Cacheserver 1 started.");
m_client1.Call(CreateTCRegions_Pool, RegionNames,
(string)null, "__TESTPOOL1_", true);
Util.Log("StepOne of region creation complete.");
m_client1.Call(CheckAndPutKey);
Util.Log("Check for ContainsKeyOnServer complete.");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
}
[Test]
public void RegionClearTest()
{
CacheHelper.SetupJavaServers("cacheserver_notify_subscription.xml");
CacheHelper.StartJavaServer(1, "GFECS1");
Util.Log("Cacheserver 1 started.");
m_client1.Call(CreateTCRegions_Pool, RegionNames,
(string)null, "__TESTPOOL1_", true);
Util.Log("client 1 StepOne of region creation complete.");
m_client2.Call(CreateTCRegions_Pool, RegionNames,
(string)null, "__TESTPOOL1_", true);
Util.Log("client 2 StepOne of region creation complete.");
m_client1.Call(ClearRegionListenersStep1);
m_client2.Call(ClearRegionStep1);
m_client1.Call(ClearRegionListenersStep2);
m_client2.Call(ClearRegionStep2);
m_client1.Call(ClearRegionListenersStep3);
m_client2.Call(ClearRegionStep3);
Util.Log("StepTwo of check for RegionClearTest complete.");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
}
[Test]
public void GetInterestsOnClient()
{
CacheHelper.SetupJavaServers("cacheserver_notify_subscription.xml");
CacheHelper.StartJavaServer(1, "GFECS1");
Util.Log("Cacheserver 1 started.");
m_client1.Call(CreateTCRegions_Pool, RegionNames,
(string)null, "__TESTPOOL1_", true);
Util.Log("StepOne of region creation complete.");
m_client1.Call(GetInterests);
Util.Log("StepTwo of check for GetInterestsOnClient complete.");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
}
[Test]
public void DistOps()
{
runDistOps();
}
[Test]
public void DistOps2()
{
runDistOps2();
}
[Test]
public void Notification()
{
runNotification();
}
[Test]
public void CheckPutGet()
{
runCheckPutGet();
}
[Test]
public void CheckPutGetWithAppDomain()
{
runCheckPutGetWithAppDomain();
}
[Test]
public void PdxAppDomainTest()
{
runPdxAppDomainTest(false, true); // pool with locators
runPdxAppDomainTest(true, true); // pool with locators
runPdxAppDomainTest(false, false); // pool with locators
runPdxAppDomainTest(true, false); // pool with locators
}
[Test]
public void JavaHashCode()
{
runCheckPut();
}
[Test]
public void CheckPartitionResolver()
{
runPartitionResolver();
}
[Test]
public void TradeKeyPartitionResolver()
{
runTradeKeyResolver();
}
[Test]
public void CheckFixedPartitionResolver()
{
runFixedPartitionResolver();
}
[Test]
public void CheckNativeException()
{
runCheckNativeException();
}
[Test]
public void Failover()
{
runFailover();
}
[Test]
public void Failover2()
{
runFailover2();
}
[Test]
public void Failover3()
{
runFailover3();
}
[Test]
public void FailOverInterestAll()
{
runFailoverInterestAll();
}
[Test]
public void FailOverInterestAllWithSSL()
{
runFailoverInterestAll(true);
}
[Test]
public void PutAll()
{
runPutAll();
}
[Test]
public void RemoveAll()
{
runRemoveAll();
}
[Test]
public void RemoveAllWithSingleHop()
{
runRemoveAllWithSingleHop();
}
[Test]
public void RemoveOps()
{
runRemoveOps();
}
[Test]
public void RemoveOps1()
{
runRemoveOps1();
}
[Test]
public void IdictionaryOps()
{
runIdictionaryOps();
}
#endregion
}
}
| |
// Copyright 2009 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using NodaTime.Calendars;
using NodaTime.TimeZones.IO;
using NodaTime.Utility;
using System;
namespace NodaTime.TimeZones
{
/// <summary>
/// Extends <see cref="ZoneYearOffset"/> with a name and savings.
/// </summary>
/// <remarks>
/// <para>
/// This represents a recurring transition from or to a daylight savings time. The name is the
/// name of the time zone during this period (e.g. PST or PDT). The savings is usually 0 or the
/// daylight offset. This is also used to support some of the tricky transitions that occurred
/// before the time zones were normalized (i.e. when they were still tightly longitude-based,
/// with multiple towns in the same country observing different times).
/// </para>
/// <para>
/// Immutable, thread safe.
/// </para>
/// </remarks>
internal sealed class ZoneRecurrence : IEquatable<ZoneRecurrence?>
{
private readonly LocalInstant maxLocalInstant;
private readonly LocalInstant minLocalInstant;
public string Name { get; }
public Offset Savings { get; }
public ZoneYearOffset YearOffset { get; }
public int FromYear { get; }
public int ToYear { get; }
public bool IsInfinite => ToYear == Int32.MaxValue;
/// <summary>
/// Initializes a new instance of the <see cref="ZoneRecurrence"/> class.
/// </summary>
/// <param name="name">The name of the time zone period e.g. PST.</param>
/// <param name="savings">The savings for this period.</param>
/// <param name="yearOffset">The year offset of when this period starts in a year.</param>
/// <param name="fromYear">The first year in which this recurrence is valid</param>
/// <param name="toYear">The last year in which this recurrence is valid</param>
public ZoneRecurrence(String name, Offset savings, ZoneYearOffset yearOffset, int fromYear, int toYear)
{
Preconditions.CheckNotNull(name, nameof(name));
Preconditions.CheckNotNull(yearOffset, nameof(yearOffset));
Preconditions.CheckArgument(fromYear == int.MinValue || (fromYear >= -9998 && fromYear <= 9999), nameof(fromYear),
"fromYear must be in the range [-9998, 9999] or Int32.MinValue");
Preconditions.CheckArgument(toYear == int.MaxValue || (toYear >= -9998 && toYear <= 9999), nameof(toYear),
"toYear must be in the range [-9998, 9999] or Int32.MaxValue");
this.Name = name;
this.Savings = savings;
this.YearOffset = yearOffset;
this.FromYear = fromYear;
this.ToYear = toYear;
this.minLocalInstant = fromYear == int.MinValue ? LocalInstant.BeforeMinValue : yearOffset.GetOccurrenceForYear(fromYear);
this.maxLocalInstant = toYear == int.MaxValue ? LocalInstant.AfterMaxValue : yearOffset.GetOccurrenceForYear(toYear);
}
/// <summary>
/// Returns a new recurrence which has the same values as this, but a different name.
/// </summary>
internal ZoneRecurrence WithName(string name) =>
new ZoneRecurrence(name, Savings, YearOffset, FromYear, ToYear);
/// <summary>
/// Returns a new recurrence with the same values as this, but just for a single year.
/// </summary>
internal ZoneRecurrence ForSingleYear(int year)
{
return new ZoneRecurrence(Name, Savings, YearOffset, year, year);
}
#region IEquatable<ZoneRecurrence> Members
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// true if the current object is equal to the <paramref name="other"/> parameter;
/// otherwise, false.
/// </returns>
public bool Equals(ZoneRecurrence? other)
{
if (other is null)
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return Savings == other.Savings && FromYear == other.FromYear && ToYear == other.ToYear && Name == other.Name && YearOffset.Equals(other.YearOffset);
}
#endregion
/// <summary>
/// Returns the first transition which occurs strictly after the given instant.
/// </summary>
/// <remarks>
/// If the given instant is before the starting year, the year of the given instant is
/// adjusted to the beginning of the starting year. The first transition after the
/// adjusted instant is determined. If the next adjustment is after the ending year, this
/// method returns null; otherwise the next transition is returned.
/// </remarks>
/// <param name="instant">The <see cref="Instant"/> lower bound for the next transition.</param>
/// <param name="standardOffset">The <see cref="Offset"/> standard offset.</param>
/// <param name="previousSavings">The <see cref="Offset"/> savings adjustment at the given Instant.</param>
/// <returns>The next transition, or null if there is no next transition. The transition may be
/// infinite, i.e. after the end of representable time.</returns>
internal Transition? Next(Instant instant, Offset standardOffset, Offset previousSavings)
{
Offset ruleOffset = YearOffset.GetRuleOffset(standardOffset, previousSavings);
Offset newOffset = standardOffset + Savings;
LocalInstant safeLocal = instant.SafePlus(ruleOffset);
int targetYear;
if (safeLocal < minLocalInstant)
{
// Asked for a transition after some point before the first transition: crop to first year (so we get the first transition)
targetYear = FromYear;
}
else if (safeLocal >= maxLocalInstant)
{
// Asked for a transition after our final transition... or both are beyond the end of time (in which case
// we can return an infinite transition). This branch will always be taken for transitions beyond the end
// of time.
return maxLocalInstant == LocalInstant.AfterMaxValue ? new Transition(Instant.AfterMaxValue, newOffset) : (Transition?) null;
}
else if (safeLocal == LocalInstant.BeforeMinValue)
{
// We've been asked to find the next transition after some point which is a valid instant, but is before the
// start of valid local time after applying the rule offset. For example, passing Instant.MinValue for a rule which says
// "transition uses wall time, which is UTC-5". Proceed as if we'd been asked for something in -9998.
// I *think* that works...
targetYear = GregorianYearMonthDayCalculator.MinGregorianYear;
}
else
{
// Simple case: we were asked for a "normal" value in the range of years for which this recurrence is valid.
targetYear = CalendarSystem.Iso.YearMonthDayCalculator.GetYear(safeLocal.DaysSinceEpoch, out int ignoredDayOfYear);
}
LocalInstant transition = YearOffset.GetOccurrenceForYear(targetYear);
Instant safeTransition = transition.SafeMinus(ruleOffset);
if (safeTransition > instant)
{
return new Transition(safeTransition, newOffset);
}
// We've got a transition earlier than we were asked for. Try next year.
// Note that this will still be within the FromYear/ToYear range, otherwise
// safeLocal >= maxLocalInstant would have been triggered earlier.
targetYear++;
// Handle infinite transitions
if (targetYear > GregorianYearMonthDayCalculator.MaxGregorianYear)
{
return new Transition(Instant.AfterMaxValue, newOffset);
}
// It's fine for this to be "end of time", and it can't be "start of time" because we're at least finding a transition in -9997.
safeTransition = YearOffset.GetOccurrenceForYear(targetYear).SafeMinus(ruleOffset);
return new Transition(safeTransition, newOffset);
}
/// <summary>
/// Returns the last transition which occurs before or on the given instant.
/// </summary>
/// <param name="instant">The <see cref="Instant"/> lower bound for the next transition.</param>
/// <param name="standardOffset">The <see cref="Offset"/> standard offset.</param>
/// <param name="previousSavings">The <see cref="Offset"/> savings adjustment at the given Instant.</param>
/// <returns>The previous transition, or null if there is no previous transition. The transition may be
/// infinite, i.e. before the start of representable time.</returns>
internal Transition? PreviousOrSame(Instant instant, Offset standardOffset, Offset previousSavings)
{
Offset ruleOffset = YearOffset.GetRuleOffset(standardOffset, previousSavings);
Offset newOffset = standardOffset + Savings;
LocalInstant safeLocal = instant.SafePlus(ruleOffset);
int targetYear;
if (safeLocal > maxLocalInstant)
{
// Asked for a transition before some point after our last year: crop to last year.
targetYear = ToYear;
}
// Deliberately < here; "previous or same" means if safeLocal==minLocalInstant, we should compute it for this year.
else if (safeLocal < minLocalInstant)
{
// Asked for a transition before our first one
return null;
}
else if (!safeLocal.IsValid)
{
if (safeLocal == LocalInstant.BeforeMinValue)
{
// We've been asked to find the next transition before some point which is a valid instant, but is before the
// start of valid local time after applying the rule offset. It's possible that the next transition *would*
// be representable as an instant (e.g. 1pm Dec 31st -9999 with an offset of -5) but it's reasonable to
// just return an infinite transition.
return new Transition(Instant.BeforeMinValue, newOffset);
}
else
{
// We've been asked to find the next transition before some point which is a valid instant, but is after the
// end of valid local time after applying the rule offset. For example, passing Instant.MaxValue for a rule which says
// "transition uses wall time, which is UTC+5". Proceed as if we'd been asked for something in 9999.
// I *think* that works...
targetYear = GregorianYearMonthDayCalculator.MaxGregorianYear;
}
}
else
{
// Simple case: we were asked for a "normal" value in the range of years for which this recurrence is valid.
targetYear = CalendarSystem.Iso.YearMonthDayCalculator.GetYear(safeLocal.DaysSinceEpoch, out int ignoredDayOfYear);
}
LocalInstant transition = YearOffset.GetOccurrenceForYear(targetYear);
Instant safeTransition = transition.SafeMinus(ruleOffset);
if (safeTransition <= instant)
{
return new Transition(safeTransition, newOffset);
}
// We've got a transition later than we were asked for. Try next year.
// Note that this will still be within the FromYear/ToYear range, otherwise
// safeLocal < minLocalInstant would have been triggered earlier.
targetYear--;
// Handle infinite transitions
if (targetYear < GregorianYearMonthDayCalculator.MinGregorianYear)
{
return new Transition(Instant.BeforeMinValue, newOffset);
}
// It's fine for this to be "start of time", and it can't be "end of time" because we're at latest finding a transition in 9998.
safeTransition = YearOffset.GetOccurrenceForYear(targetYear).SafeMinus(ruleOffset);
return new Transition(safeTransition, newOffset);
}
/// <summary>
/// Piggy-backs onto Next, but fails with an InvalidOperationException if there's no such transition.
/// </summary>
internal Transition NextOrFail(Instant instant, Offset standardOffset, Offset previousSavings)
{
Transition? next = Next(instant, standardOffset, previousSavings);
if (next is null)
{
throw new InvalidOperationException(
$"Noda Time bug or bad data: Expected a transition later than {instant}; standard offset = {standardOffset}; previousSavings = {previousSavings}; recurrence = {this}");
}
return next.Value;
}
/// <summary>
/// Piggy-backs onto PreviousOrSame, but fails with a descriptive InvalidOperationException if there's no such transition.
/// </summary>
internal Transition PreviousOrSameOrFail(Instant instant, Offset standardOffset, Offset previousSavings)
{
Transition? previous = PreviousOrSame(instant, standardOffset, previousSavings);
if (previous is null)
{
throw new InvalidOperationException(
$"Noda Time bug or bad data: Expected a transition earlier than {instant}; standard offset = {standardOffset}; previousSavings = {previousSavings}; recurrence = {this}");
}
return previous.Value;
}
/// <summary>
/// Writes this object to the given <see cref="DateTimeZoneWriter"/>.
/// </summary>
/// <param name="writer">Where to send the output.</param>
internal void Write(IDateTimeZoneWriter writer)
{
writer.WriteString(Name);
writer.WriteOffset(Savings);
YearOffset.Write(writer);
// We'll never have time zones with recurrences between the beginning of time and 0AD,
// so we can treat anything negative as 0, and go to the beginning of time when reading.
writer.WriteCount(Math.Max(FromYear, 0));
writer.WriteCount(ToYear);
}
/// <summary>
/// Reads a recurrence from the specified reader.
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns>The recurrence read from the reader.</returns>
public static ZoneRecurrence Read(IDateTimeZoneReader reader)
{
Preconditions.CheckNotNull(reader, nameof(reader));
string name = reader.ReadString();
Offset savings = reader.ReadOffset();
ZoneYearOffset yearOffset = ZoneYearOffset.Read(reader);
int fromYear = reader.ReadCount();
if (fromYear == 0)
{
fromYear = int.MinValue;
}
int toYear = reader.ReadCount();
return new ZoneRecurrence(name, savings, yearOffset, fromYear, toYear);
}
#region Object overrides
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance;
/// otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object? obj) => Equals(obj as ZoneRecurrence);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data
/// structures like a hash table.
/// </returns>
public override int GetHashCode() => HashCodeHelper.Hash(Savings, Name, YearOffset);
/// <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() => $"{Name} {Savings} {YearOffset} [{FromYear}-{ToYear}]";
#endregion // Object overrides
/// <summary>
/// Returns either "this" (if this zone recurrence already has a from year of int.MinValue)
/// or a new zone recurrence which is identical but with a from year of int.MinValue.
/// </summary>
internal ZoneRecurrence ToStartOfTime() =>
FromYear == int.MinValue ? this : new ZoneRecurrence(Name, Savings, YearOffset, int.MinValue, ToYear);
}
}
| |
// 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.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Tests
{
public class File_NotifyFilter_Tests : FileSystemWatcherTest
{
[DllImport("api-ms-win-security-provider-l1-1-0.dll", EntryPoint = "SetNamedSecurityInfoW",
CallingConvention = CallingConvention.Winapi, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
private static extern uint SetSecurityInfoByHandle(string name, uint objectType, uint securityInformation,
IntPtr owner, IntPtr group, IntPtr dacl, IntPtr sacl);
private const uint ERROR_SUCCESS = 0;
private const uint DACL_SECURITY_INFORMATION = 0x00000004;
private const uint SE_FILE_OBJECT = 0x1;
[Theory]
[MemberData(nameof(FilterTypes))]
public void FileSystemWatcher_File_NotifyFilter_Attributes(NotifyFilters filter)
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var file = new TempFile(Path.Combine(testDirectory.Path, "file")))
using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path)))
{
watcher.NotifyFilter = filter;
var attributes = File.GetAttributes(file.Path);
Action action = () => File.SetAttributes(file.Path, attributes | FileAttributes.ReadOnly);
Action cleanup = () => File.SetAttributes(file.Path, attributes);
WatcherChangeTypes expected = 0;
if (filter == NotifyFilters.Attributes)
expected |= WatcherChangeTypes.Changed;
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && ((filter & LinuxFiltersForAttribute) > 0))
expected |= WatcherChangeTypes.Changed;
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) && ((filter & OSXFiltersForModify) > 0))
expected |= WatcherChangeTypes.Changed;
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) && ((filter & NotifyFilters.Security) > 0))
expected |= WatcherChangeTypes.Changed; // Attribute change on OSX is a ChangeOwner operation which passes the Security NotifyFilter.
ExpectEvent(watcher, expected, action, cleanup, file.Path);
}
}
[Theory]
[MemberData(nameof(FilterTypes))]
public void FileSystemWatcher_File_NotifyFilter_CreationTime(NotifyFilters filter)
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var file = new TempFile(Path.Combine(testDirectory.Path, "file")))
using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path)))
{
watcher.NotifyFilter = filter;
Action action = () => File.SetCreationTime(file.Path, DateTime.Now + TimeSpan.FromSeconds(10));
WatcherChangeTypes expected = 0;
if (filter == NotifyFilters.CreationTime)
expected |= WatcherChangeTypes.Changed;
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && ((filter & LinuxFiltersForAttribute) > 0))
expected |= WatcherChangeTypes.Changed;
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) && ((filter & OSXFiltersForModify) > 0))
expected |= WatcherChangeTypes.Changed;
ExpectEvent(watcher, expected, action, expectedPath: file.Path);
}
}
[Theory]
[MemberData(nameof(FilterTypes))]
public void FileSystemWatcher_File_NotifyFilter_DirectoryName(NotifyFilters filter)
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, "dir")))
using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(dir.Path)))
{
string sourcePath = dir.Path;
string targetPath = Path.Combine(testDirectory.Path, "targetDir");
watcher.NotifyFilter = filter;
Action action = () => Directory.Move(sourcePath, targetPath);
Action cleanup = () => Directory.Move(targetPath, sourcePath);
WatcherChangeTypes expected = 0;
if (filter == NotifyFilters.DirectoryName)
expected |= WatcherChangeTypes.Renamed;
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && (filter == NotifyFilters.FileName))
expected |= WatcherChangeTypes.Renamed;
ExpectEvent(watcher, expected, action, cleanup, targetPath);
}
}
[Theory]
[MemberData(nameof(FilterTypes))]
public void FileSystemWatcher_File_NotifyFilter_LastAccessTime(NotifyFilters filter)
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var file = new TempFile(Path.Combine(testDirectory.Path, "file")))
using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path)))
{
watcher.NotifyFilter = filter;
Action action = () => File.SetLastAccessTime(file.Path, DateTime.Now + TimeSpan.FromSeconds(10));
WatcherChangeTypes expected = 0;
if (filter == NotifyFilters.LastAccess)
expected |= WatcherChangeTypes.Changed;
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && ((filter & LinuxFiltersForAttribute) > 0))
expected |= WatcherChangeTypes.Changed;
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) && ((filter & OSXFiltersForModify) > 0))
expected |= WatcherChangeTypes.Changed;
ExpectEvent(watcher, expected, action, expectedPath: file.Path);
}
}
[Theory]
[MemberData(nameof(FilterTypes))]
public void FileSystemWatcher_File_NotifyFilter_LastWriteTime(NotifyFilters filter)
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var file = new TempFile(Path.Combine(testDirectory.Path, "file")))
using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path)))
{
watcher.NotifyFilter = filter;
Action action = () => File.SetLastWriteTime(file.Path, DateTime.Now + TimeSpan.FromSeconds(10));
WatcherChangeTypes expected = 0;
if (filter == NotifyFilters.LastWrite)
expected |= WatcherChangeTypes.Changed;
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && ((filter & LinuxFiltersForAttribute) > 0))
expected |= WatcherChangeTypes.Changed;
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) && ((filter & OSXFiltersForModify) > 0))
expected |= WatcherChangeTypes.Changed;
ExpectEvent(watcher, expected, action, expectedPath: file.Path);
}
}
[Theory]
[MemberData(nameof(FilterTypes))]
public void FileSystemWatcher_File_NotifyFilter_Size(NotifyFilters filter)
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var file = new TempFile(Path.Combine(testDirectory.Path, "file")))
using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path)))
{
watcher.NotifyFilter = filter;
Action action = () => File.AppendAllText(file.Path, "longText!");
Action cleanup = () => File.AppendAllText(file.Path, "short");
WatcherChangeTypes expected = 0;
if (filter == NotifyFilters.Size || filter == NotifyFilters.LastWrite)
expected |= WatcherChangeTypes.Changed;
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && ((filter & LinuxFiltersForModify) > 0))
expected |= WatcherChangeTypes.Changed;
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) && ((filter & OSXFiltersForModify) > 0))
expected |= WatcherChangeTypes.Changed;
else if (PlatformDetection.IsWindows7 && filter == NotifyFilters.Attributes) // win7 FSW Size change passes the Attribute filter
expected |= WatcherChangeTypes.Changed;
ExpectEvent(watcher, expected, action, expectedPath: file.Path);
}
}
[Theory]
[MemberData(nameof(FilterTypes))]
[PlatformSpecific(PlatformID.Windows)]
public void FileSystemWatcher_File_NotifyFilter_Security(NotifyFilters filter)
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var file = new TempFile(Path.Combine(testDirectory.Path, "file")))
using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path)))
{
watcher.NotifyFilter = filter;
Action action = () =>
{
// ACL support is not yet available, so pinvoke directly.
uint result = SetSecurityInfoByHandle(file.Path,
SE_FILE_OBJECT,
DACL_SECURITY_INFORMATION, // Only setting the DACL
owner: IntPtr.Zero,
group: IntPtr.Zero,
dacl: IntPtr.Zero, // full access to everyone
sacl: IntPtr.Zero);
Assert.Equal(ERROR_SUCCESS, result);
};
Action cleanup = () =>
{
// Recreate the file.
File.Delete(file.Path);
File.AppendAllText(file.Path, "text");
};
WatcherChangeTypes expected = 0;
if (filter == NotifyFilters.Security)
expected |= WatcherChangeTypes.Changed;
else if (PlatformDetection.IsWindows7 && filter == NotifyFilters.Attributes) // win7 FSW Security change passes the Attribute filter
expected |= WatcherChangeTypes.Changed;
ExpectEvent(watcher, expected, action, expectedPath: file.Path);
}
}
/// <summary>
/// Tests a changed event on a directory when filtering for LastWrite and FileName.
/// </summary>
[Fact]
public void FileSystemWatcher_File_NotifyFilter_LastWriteAndFileName()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, "dir")))
using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(dir.Path)))
{
NotifyFilters filter = NotifyFilters.LastWrite | NotifyFilters.FileName;
watcher.NotifyFilter = filter;
Action action = () => Directory.SetLastWriteTime(dir.Path, DateTime.Now + TimeSpan.FromSeconds(10));
ExpectEvent(watcher, WatcherChangeTypes.Changed, action, expectedPath: dir.Path);
}
}
/// <summary>
/// Tests the watcher behavior when two events - a Modification and a Creation - happen closely
/// after each other.
/// </summary>
[Fact]
public void FileSystemWatcher_File_NotifyFilter_ModifyAndCreate()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var file = new TempFile(Path.Combine(testDirectory.Path, "file")))
using (var watcher = new FileSystemWatcher(testDirectory.Path, "*"))
{
watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName;
string otherFile = Path.Combine(testDirectory.Path, "file2");
Action action = () =>
{
File.Create(otherFile).Dispose();
File.SetLastWriteTime(file.Path, DateTime.Now + TimeSpan.FromSeconds(10));
};
Action cleanup = () => File.Delete(otherFile);
WatcherChangeTypes expected = 0;
expected |= WatcherChangeTypes.Created | WatcherChangeTypes.Changed;
ExpectEvent(watcher, expected, action, cleanup, new string[] { otherFile, file.Path });
}
}
/// <summary>
/// Tests the watcher behavior when two events - a Modification and a Deletion - happen closely
/// after each other.
/// </summary>
[Fact]
public void FileSystemWatcher_File_NotifyFilter_ModifyAndDelete()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var file = new TempFile(Path.Combine(testDirectory.Path, "file")))
using (var watcher = new FileSystemWatcher(testDirectory.Path, "*"))
{
watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName;
string otherFile = Path.Combine(testDirectory.Path, "file2");
Action action = () =>
{
File.Delete(otherFile);
File.SetLastWriteTime(file.Path, DateTime.Now + TimeSpan.FromSeconds(10));
};
Action cleanup = () =>
{
File.Create(otherFile).Dispose();
};
cleanup();
WatcherChangeTypes expected = 0;
expected |= WatcherChangeTypes.Deleted | WatcherChangeTypes.Changed;
ExpectEvent(watcher, expected, action, cleanup, new string[] { otherFile, file.Path });
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Dfm
{
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
public class TagNameBlockPathQueryOption : DfmFencesBlockPathQueryOption
{
// C family code snippet comment block: // <[/]snippetname>
private static readonly Regex CFamilyCodeSnippetCommentStartLineRegex = new Regex(@"^\s*\/{2}\s*\<\s*(?<name>[\w\.]+)\s*\>\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly Regex CFamilyCodeSnippetCommentEndLineRegex = new Regex(@"^\s*\/{2}\s*\<\s*\/\s*(?<name>[\w\.]+)\s*\>\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
// Basic family code snippet comment block: ' <[/]snippetname>
private static readonly Regex BasicFamilyCodeSnippetCommentStartLineRegex = new Regex(@"^\s*\'\s*\<\s*(?<name>[\w\.]+)\s*\>\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly Regex BasicFamilyCodeSnippetCommentEndLineRegex = new Regex(@"^\s*\'\s*\<\s*\/\s*(?<name>[\w\.]+)\s*\>\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
// Markup language family code snippet block: <!-- <[/]snippetname> -->
private static readonly Regex MarkupLanguageFamilyCodeSnippetCommentStartLineRegex = new Regex(@"^\s*\<\!\-{2}\s*\<\s*(?<name>[\w\.]+)\s*\>\s*\-{2}\>\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly Regex MarkupLanguageFamilyCodeSnippetCommentEndLineRegex = new Regex(@"^\s*\<\!\-{2}\s*\<\s*\/\s*(?<name>[\w\.]+)\s*\>\s*\-{2}\>\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
// Sql family code snippet block: -- <[/]snippetname>
private static readonly Regex SqlFamilyCodeSnippetCommentStartLineRegex = new Regex(@"^\s*\-{2}\s*\<\s*(?<name>[\w\.]+)\s*\>\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly Regex SqlFamilyCodeSnippetCommentEndLineRegex = new Regex(@"^\s*\-{2}\s*\<\s*\/\s*(?<name>[\w\.]+)\s*\>\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
// Script family snippet comment block: # <[/]snippetname>
private static readonly Regex ScriptFamilyCodeSnippetCommentStartLineRegex = new Regex(@"^\s*#\s*\<\s*(?<name>[\w\.]+)\s*\>\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly Regex ScriptFamilyCodeSnippetCommentEndLineRegex = new Regex(@"^\s*#\s*\<\s*\/\s*(?<name>[\w\.]+)\s*\>\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
// Lisp code snippet comment block: rem <[/]snippetname>
private static readonly Regex BatchFileCodeSnippetRegionStartLineRegex = new Regex(@"^\s*rem\s+\<\s*(?<name>[\w\.]+)\s*\>\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly Regex BatchFileCodeSnippetRegionEndLineRegex = new Regex(@"^\s*rem\s+\<\s*\/\s*(?<name>[\w\.]+)\s*\>\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
// C# code snippet region block: start -> #region snippetname, end -> #endregion
private static readonly Regex CSharpCodeSnippetRegionStartLineRegex = new Regex(@"^\s*#\s*region(?:\s+(?<name>.+?))?\s*$", RegexOptions.Compiled);
private static readonly Regex CSharpCodeSnippetRegionEndLineRegex = new Regex(@"^\s*#\s*endregion(?:\s.*)?$", RegexOptions.Compiled);
// Erlang code snippet comment block: % <[/]snippetname>
private static readonly Regex ErlangCodeSnippetRegionStartLineRegex = new Regex(@"^\s*%\s*\<\s*(?<name>[\w\.]+)\s*\>\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly Regex ErlangCodeSnippetRegionEndLineRegex = new Regex(@"^\s*%\s*\<\s*\/\s*(?<name>[\w\.]+)\s*\>\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
// Lisp code snippet comment block: ; <[/]snippetname>
private static readonly Regex LispCodeSnippetRegionStartLineRegex = new Regex(@"^\s*;\s*\<\s*(?<name>[\w\.]+)\s*\>\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly Regex LispCodeSnippetRegionEndLineRegex = new Regex(@"^\s*;\s*\<\s*\/\s*(?<name>[\w\.]+)\s*\>\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
// VB code snippet Region block: start -> # Region "snippetname", end -> # End Region
private static readonly Regex VBCodeSnippetRegionRegionStartLineRegex = new Regex(@"^\s*#\s*Region(?:\s+(?<name>.+?))?\s*$", RegexOptions.Compiled);
private static readonly Regex VBCodeSnippetRegionRegionEndLineRegex = new Regex(@"^\s*#\s*End\s+Region(?:\s.*)?$", RegexOptions.Compiled);
// Language names and aliases fllow http://highlightjs.readthedocs.org/en/latest/css-classes-reference.html#language-names-and-aliases
// Language file extensions follow https://github.com/github/linguist/blob/master/lib/linguist/languages.yml
// Currently only supports parts of the language names, aliases and extensions
// Later we can move the repository's supported/custom language names, aliases, extensions and corresponding comments regexes to docfx build configuration
private static readonly IReadOnlyDictionary<string, List<ICodeSnippetExtractor>> CodeLanguageExtractors = GetCodeLanguageExtractors();
public string TagName { get; set; }
private DfmTagNameResolveResult _resolveResult;
private readonly ConcurrentDictionary<string, Lazy<ConcurrentDictionary<string, List<DfmTagNameResolveResult>>>> _dfmTagNameLineRangeCache =
new ConcurrentDictionary<string, Lazy<ConcurrentDictionary<string, List<DfmTagNameResolveResult>>>>(StringComparer.OrdinalIgnoreCase);
private static Dictionary<string, List<ICodeSnippetExtractor>> GetCodeLanguageExtractors()
{
return new CodeLanguageExtractorsBuilder()
.AddAlias("actionscript", ".as")
.AddAlias("arduino", ".ino")
.AddAlias("assembly", "nasm", ".asm")
.AddAlias("batchfile", ".bat", ".cmd")
.AddAlias("cpp", "c", "c++", "objective-c", "obj-c", "objc", "objectivec", ".c", ".cpp", ".h", ".hpp", ".cc")
.AddAlias("csharp", "cs", ".cs")
.AddAlias("cuda", ".cu", ".cuh")
.AddAlias("d", "dlang", ".d")
.AddAlias("erlang", ".erl")
.AddAlias("fsharp", "fs", ".fs", ".fsi", ".fsx")
.AddAlias("go", "golang", ".go")
.AddAlias("haskell", ".hs")
.AddAlias("html", ".html", ".cshtml", "cshtml", ".vbhtml", "vbhtml", ".jsp", "aspx-cs", "aspx-csharp", "aspx-vb" ,".asp", ".aspx", ".ascx")
.AddAlias("java", ".java")
.AddAlias("javascript", "js", "node", ".js")
.AddAlias("lisp", ".lisp", ".lsp")
.AddAlias("lua", ".lua")
.AddAlias("matlab", ".matlab")
.AddAlias("pascal", ".pas")
.AddAlias("perl", ".pl")
.AddAlias("php", ".php")
.AddAlias("powershell", "posh", ".ps1")
.AddAlias("processing", ".pde")
.AddAlias("python", ".py")
.AddAlias("r", ".r")
.AddAlias("ruby", "ru", ".ru", ".ruby")
.AddAlias("rust", ".rs")
.AddAlias("scala", ".scala")
.AddAlias("shell", "sh", "bash", ".sh", ".bash")
.AddAlias("smalltalk", ".st")
.AddAlias("sql", ".sql")
.AddAlias("swift", ".swift")
.AddAlias("typescript", "ts", ".ts")
.AddAlias("xaml", ".xaml")
.AddAlias("xml", "xsl", "xslt", "xsd", "wsdl", ".xml", ".csdl", ".edmx", ".xsl", ".xslt", ".xsd", ".wsdl")
.AddAlias("vb", "vbnet", "vbscript", ".vb", ".bas", ".vbs", ".vba")
// family
.Add(
new FlatNameCodeSnippetExtractor(BasicFamilyCodeSnippetCommentStartLineRegex, BasicFamilyCodeSnippetCommentEndLineRegex),
"vb")
.Add(
new FlatNameCodeSnippetExtractor(CFamilyCodeSnippetCommentStartLineRegex, CFamilyCodeSnippetCommentEndLineRegex),
"actionscript", "arduino", "assembly", "cpp", "csharp", "cuda", "d", "fsharp", "go", "java", "javascript", "pascal", "php", "processing", "rust", "scala", "smalltalk", "swift", "typescript")
.Add(
new FlatNameCodeSnippetExtractor(MarkupLanguageFamilyCodeSnippetCommentStartLineRegex, MarkupLanguageFamilyCodeSnippetCommentEndLineRegex),
"xml", "xaml", "html")
.Add(
new FlatNameCodeSnippetExtractor(SqlFamilyCodeSnippetCommentStartLineRegex, SqlFamilyCodeSnippetCommentEndLineRegex),
"haskell", "lua", "sql")
.Add(
new FlatNameCodeSnippetExtractor(ScriptFamilyCodeSnippetCommentStartLineRegex, ScriptFamilyCodeSnippetCommentEndLineRegex),
"perl", "powershell", "python", "r", "ruby", "shell")
// specical language
.Add(
new FlatNameCodeSnippetExtractor(BatchFileCodeSnippetRegionStartLineRegex, BatchFileCodeSnippetRegionEndLineRegex),
"batchfile")
.Add(
new RecursiveNameCodeSnippetExtractor(CSharpCodeSnippetRegionStartLineRegex, CSharpCodeSnippetRegionEndLineRegex),
"csharp")
.Add(
new FlatNameCodeSnippetExtractor(ErlangCodeSnippetRegionStartLineRegex, ErlangCodeSnippetRegionEndLineRegex),
"erlang", "matlab")
.Add(
new FlatNameCodeSnippetExtractor(LispCodeSnippetRegionStartLineRegex, LispCodeSnippetRegionEndLineRegex),
"lisp")
.Add(
new RecursiveNameCodeSnippetExtractor(VBCodeSnippetRegionRegionStartLineRegex, VBCodeSnippetRegionRegionEndLineRegex),
"vb")
.ToDictionay();
}
public override bool ValidateAndPrepare(string[] lines, DfmFencesToken token)
{
// NOTE: Parsing language and removing comment lines only do for tag name representation
var lang = GetCodeLanguageOrExtension(token);
if (!CodeLanguageExtractors.TryGetValue(lang, out List<ICodeSnippetExtractor> extractors))
{
ErrorMessage = $"{lang} is not supported languaging name, alias or extension for parsing code snippet with tag name, you can use line numbers instead";
return false;
}
_resolveResult = ResolveTagNamesFromPath(token.Path, lines, TagName, extractors);
ErrorMessage = _resolveResult.ErrorMessage;
return _resolveResult.IsSuccessful;
}
public override IEnumerable<string> GetQueryLines(string[] lines)
{
for (int i = _resolveResult.StartLine; i <= Math.Min(_resolveResult.EndLine, lines.Length); i++)
{
if (_resolveResult.ExcludesLines == null || !_resolveResult.ExcludesLines.Contains(i))
{
yield return lines[i - 1];
}
}
}
private DfmTagNameResolveResult ResolveTagNamesFromPath(string fencesPath, string[] fencesCodeLines, string tagName, List<ICodeSnippetExtractor> codeSnippetExtractors)
{
var lazyResolveResults =
_dfmTagNameLineRangeCache.GetOrAdd(fencesPath,
path => new Lazy<ConcurrentDictionary<string, List<DfmTagNameResolveResult>>>(
() =>
{
// TODO: consider different code snippet representation with same name
return new ConcurrentDictionary<string, List<DfmTagNameResolveResult>>(
(from codeSnippetExtractor in codeSnippetExtractors
let resolveResults = codeSnippetExtractor.GetAll(fencesCodeLines)
from codeSnippet in resolveResults
group codeSnippet by codeSnippet.Key)
.ToDictionary(g => g.Key, g => g.Select(p => p.Value).ToList()), StringComparer.OrdinalIgnoreCase);
}));
ConcurrentDictionary<string, List<DfmTagNameResolveResult>> tagNamesDictionary;
try
{
tagNamesDictionary = lazyResolveResults.Value;
}
catch (Exception e)
{
return new DfmTagNameResolveResult
{
IsSuccessful = false,
ErrorMessage = $"error resolve tag names from {fencesPath}: {e.Message}",
};
}
if (!tagNamesDictionary.TryGetValue(tagName, out List<DfmTagNameResolveResult> results) && !tagNamesDictionary.TryGetValue($"snippet{tagName}", out results))
{
return new DfmTagNameResolveResult
{
IsSuccessful = false,
ErrorMessage = $"Tag name {tagName} is not found",
};
}
var result = results[0];
if (results.Count > 1)
{
result.ErrorMessage = $"Tag name duplicates at line {string.Join(", ", results.Select(r => r.StartLine))}, the first is chosen. {result.ErrorMessage}";
}
return result;
}
private static string GetCodeLanguageOrExtension(DfmFencesToken token)
{
return !string.IsNullOrEmpty(token.Lang) ? token.Lang : Path.GetExtension(token.Path);
}
}
}
| |
using System;
using Xwt.Drawing;
namespace Xwt.GoogleMaterialDesignIcons
{
public class ImageIcons
{
static Image GetIcon (string id)
{
string resourceId = typeof(ImageIcons).Assembly.FullName.Split (',') [0] + ".Resources.Image." + id + "32px.png";
return Image.FromResource (typeof(ImageIcons), resourceId);
}
public static Image AddAPhoto { get { return GetIcon (ImageIconId.AddAPhoto); } }
public static Image AddToPhotos { get { return GetIcon (ImageIconId.AddToPhotos); } }
public static Image Adjust { get { return GetIcon (ImageIconId.Adjust); } }
public static Image Assistant { get { return GetIcon (ImageIconId.Assistant); } }
public static Image AssistantPhoto { get { return GetIcon (ImageIconId.AssistantPhoto); } }
public static Image Audiotrack { get { return GetIcon (ImageIconId.Audiotrack); } }
public static Image BlurCircular { get { return GetIcon (ImageIconId.BlurCircular); } }
public static Image BlurLinear { get { return GetIcon (ImageIconId.BlurLinear); } }
public static Image BlurOff { get { return GetIcon (ImageIconId.BlurOff); } }
public static Image BlurOn { get { return GetIcon (ImageIconId.BlurOn); } }
public static Image Brightness1 { get { return GetIcon (ImageIconId.Brightness1); } }
public static Image Brightness2 { get { return GetIcon (ImageIconId.Brightness2); } }
public static Image Brightness3 { get { return GetIcon (ImageIconId.Brightness3); } }
public static Image Brightness4 { get { return GetIcon (ImageIconId.Brightness4); } }
public static Image Brightness5 { get { return GetIcon (ImageIconId.Brightness5); } }
public static Image Brightness6 { get { return GetIcon (ImageIconId.Brightness6); } }
public static Image Brightness7 { get { return GetIcon (ImageIconId.Brightness7); } }
public static Image BrokenImage { get { return GetIcon (ImageIconId.BrokenImage); } }
public static Image Brush { get { return GetIcon (ImageIconId.Brush); } }
public static Image BurstMode { get { return GetIcon (ImageIconId.BurstMode); } }
public static Image Camera { get { return GetIcon (ImageIconId.Camera); } }
public static Image CameraAlt { get { return GetIcon (ImageIconId.CameraAlt); } }
public static Image CameraFront { get { return GetIcon (ImageIconId.CameraFront); } }
public static Image CameraRear { get { return GetIcon (ImageIconId.CameraRear); } }
public static Image CameraRoll { get { return GetIcon (ImageIconId.CameraRoll); } }
public static Image CenterFocusStrong { get { return GetIcon (ImageIconId.CenterFocusStrong); } }
public static Image CenterFocusWeak { get { return GetIcon (ImageIconId.CenterFocusWeak); } }
public static Image Collections { get { return GetIcon (ImageIconId.Collections); } }
public static Image Colorize { get { return GetIcon (ImageIconId.Colorize); } }
public static Image ColorLens { get { return GetIcon (ImageIconId.ColorLens); } }
public static Image Compare { get { return GetIcon (ImageIconId.Compare); } }
public static Image ControlPoint { get { return GetIcon (ImageIconId.ControlPoint); } }
public static Image ControlPointDuplicate { get { return GetIcon (ImageIconId.ControlPointDuplicate); } }
public static Image Crop169 { get { return GetIcon (ImageIconId.Crop169); } }
public static Image Crop32 { get { return GetIcon (ImageIconId.Crop32); } }
public static Image Crop { get { return GetIcon (ImageIconId.Crop); } }
public static Image Crop54 { get { return GetIcon (ImageIconId.Crop54); } }
public static Image Crop75 { get { return GetIcon (ImageIconId.Crop75); } }
public static Image CropDin { get { return GetIcon (ImageIconId.CropDin); } }
public static Image CropFree { get { return GetIcon (ImageIconId.CropFree); } }
public static Image CropLandscape { get { return GetIcon (ImageIconId.CropLandscape); } }
public static Image CropOriginal { get { return GetIcon (ImageIconId.CropOriginal); } }
public static Image CropPortrait { get { return GetIcon (ImageIconId.CropPortrait); } }
public static Image CropRotate { get { return GetIcon (ImageIconId.CropRotate); } }
public static Image CropSquare { get { return GetIcon (ImageIconId.CropSquare); } }
public static Image Dehaze { get { return GetIcon (ImageIconId.Dehaze); } }
public static Image Details { get { return GetIcon (ImageIconId.Details); } }
public static Image Edit { get { return GetIcon (ImageIconId.Edit); } }
public static Image Exposure { get { return GetIcon (ImageIconId.Exposure); } }
public static Image ExposureNeg1 { get { return GetIcon (ImageIconId.ExposureNeg1); } }
public static Image ExposureNeg2 { get { return GetIcon (ImageIconId.ExposureNeg2); } }
public static Image ExposurePlus1 { get { return GetIcon (ImageIconId.ExposurePlus1); } }
public static Image ExposurePlus2 { get { return GetIcon (ImageIconId.ExposurePlus2); } }
public static Image ExposureZero { get { return GetIcon (ImageIconId.ExposureZero); } }
public static Image Filter1 { get { return GetIcon (ImageIconId.Filter1); } }
public static Image Filter2 { get { return GetIcon (ImageIconId.Filter2); } }
public static Image Filter3 { get { return GetIcon (ImageIconId.Filter3); } }
public static Image Filter4 { get { return GetIcon (ImageIconId.Filter4); } }
public static Image Filter { get { return GetIcon (ImageIconId.Filter); } }
public static Image Filter5 { get { return GetIcon (ImageIconId.Filter5); } }
public static Image Filter6 { get { return GetIcon (ImageIconId.Filter6); } }
public static Image Filter7 { get { return GetIcon (ImageIconId.Filter7); } }
public static Image Filter8 { get { return GetIcon (ImageIconId.Filter8); } }
public static Image Filter9 { get { return GetIcon (ImageIconId.Filter9); } }
public static Image Filter9Plus { get { return GetIcon (ImageIconId.Filter9Plus); } }
public static Image FilterBAndW { get { return GetIcon (ImageIconId.FilterBAndW); } }
public static Image FilterCenterFocus { get { return GetIcon (ImageIconId.FilterCenterFocus); } }
public static Image FilterDrama { get { return GetIcon (ImageIconId.FilterDrama); } }
public static Image FilterFrames { get { return GetIcon (ImageIconId.FilterFrames); } }
public static Image FilterHdr { get { return GetIcon (ImageIconId.FilterHdr); } }
public static Image FilterNone { get { return GetIcon (ImageIconId.FilterNone); } }
public static Image FilterTiltShift { get { return GetIcon (ImageIconId.FilterTiltShift); } }
public static Image FilterVintage { get { return GetIcon (ImageIconId.FilterVintage); } }
public static Image Flare { get { return GetIcon (ImageIconId.Flare); } }
public static Image FlashAuto { get { return GetIcon (ImageIconId.FlashAuto); } }
public static Image FlashOff { get { return GetIcon (ImageIconId.FlashOff); } }
public static Image FlashOn { get { return GetIcon (ImageIconId.FlashOn); } }
public static Image Flip { get { return GetIcon (ImageIconId.Flip); } }
public static Image Gradient { get { return GetIcon (ImageIconId.Gradient); } }
public static Image Grain { get { return GetIcon (ImageIconId.Grain); } }
public static Image GridOff { get { return GetIcon (ImageIconId.GridOff); } }
public static Image GridOn { get { return GetIcon (ImageIconId.GridOn); } }
public static Image HdrOff { get { return GetIcon (ImageIconId.HdrOff); } }
public static Image HdrOn { get { return GetIcon (ImageIconId.HdrOn); } }
public static Image HdrStrong { get { return GetIcon (ImageIconId.HdrStrong); } }
public static Image HdrWeak { get { return GetIcon (ImageIconId.HdrWeak); } }
public static Image Healing { get { return GetIcon (ImageIconId.Healing); } }
public static Image Image { get { return GetIcon (ImageIconId.Image); } }
public static Image ImageAspectRatio { get { return GetIcon (ImageIconId.ImageAspectRatio); } }
public static Image Iso { get { return GetIcon (ImageIconId.Iso); } }
public static Image Landscape { get { return GetIcon (ImageIconId.Landscape); } }
public static Image LeakAdd { get { return GetIcon (ImageIconId.LeakAdd); } }
public static Image LeakRemove { get { return GetIcon (ImageIconId.LeakRemove); } }
public static Image Lens { get { return GetIcon (ImageIconId.Lens); } }
public static Image LinkedCamera { get { return GetIcon (ImageIconId.LinkedCamera); } }
public static Image Looks3 { get { return GetIcon (ImageIconId.Looks3); } }
public static Image Looks4 { get { return GetIcon (ImageIconId.Looks4); } }
public static Image Looks { get { return GetIcon (ImageIconId.Looks); } }
public static Image Looks5 { get { return GetIcon (ImageIconId.Looks5); } }
public static Image Looks6 { get { return GetIcon (ImageIconId.Looks6); } }
public static Image LooksOne { get { return GetIcon (ImageIconId.LooksOne); } }
public static Image LooksTwo { get { return GetIcon (ImageIconId.LooksTwo); } }
public static Image Loupe { get { return GetIcon (ImageIconId.Loupe); } }
public static Image MonochromePhotos { get { return GetIcon (ImageIconId.MonochromePhotos); } }
public static Image MovieCreation { get { return GetIcon (ImageIconId.MovieCreation); } }
public static Image MovieFilter { get { return GetIcon (ImageIconId.MovieFilter); } }
public static Image MusicNote { get { return GetIcon (ImageIconId.MusicNote); } }
public static Image Nature { get { return GetIcon (ImageIconId.Nature); } }
public static Image NaturePeople { get { return GetIcon (ImageIconId.NaturePeople); } }
public static Image NavigateBefore { get { return GetIcon (ImageIconId.NavigateBefore); } }
public static Image NavigateNext { get { return GetIcon (ImageIconId.NavigateNext); } }
public static Image Palette { get { return GetIcon (ImageIconId.Palette); } }
public static Image Panorama { get { return GetIcon (ImageIconId.Panorama); } }
public static Image PanoramaFishEye { get { return GetIcon (ImageIconId.PanoramaFishEye); } }
public static Image PanoramaHorizontal { get { return GetIcon (ImageIconId.PanoramaHorizontal); } }
public static Image PanoramaVertical { get { return GetIcon (ImageIconId.PanoramaVertical); } }
public static Image PanoramaWideAngle { get { return GetIcon (ImageIconId.PanoramaWideAngle); } }
public static Image Photo { get { return GetIcon (ImageIconId.Photo); } }
public static Image PhotoAlbum { get { return GetIcon (ImageIconId.PhotoAlbum); } }
public static Image PhotoCamera { get { return GetIcon (ImageIconId.PhotoCamera); } }
public static Image PhotoFilter { get { return GetIcon (ImageIconId.PhotoFilter); } }
public static Image PhotoLibrary { get { return GetIcon (ImageIconId.PhotoLibrary); } }
public static Image PictureAsPdf { get { return GetIcon (ImageIconId.PictureAsPdf); } }
public static Image Portrait { get { return GetIcon (ImageIconId.Portrait); } }
public static Image RemoveRedEye { get { return GetIcon (ImageIconId.RemoveRedEye); } }
public static Image Rotate90DegreesCcw { get { return GetIcon (ImageIconId.Rotate90DegreesCcw); } }
public static Image RotateLeft { get { return GetIcon (ImageIconId.RotateLeft); } }
public static Image RotateRight { get { return GetIcon (ImageIconId.RotateRight); } }
public static Image Slideshow { get { return GetIcon (ImageIconId.Slideshow); } }
public static Image Straighten { get { return GetIcon (ImageIconId.Straighten); } }
public static Image Style { get { return GetIcon (ImageIconId.Style); } }
public static Image SwitchCamera { get { return GetIcon (ImageIconId.SwitchCamera); } }
public static Image SwitchVideo { get { return GetIcon (ImageIconId.SwitchVideo); } }
public static Image TagFaces { get { return GetIcon (ImageIconId.TagFaces); } }
public static Image Texture { get { return GetIcon (ImageIconId.Texture); } }
public static Image Timelapse { get { return GetIcon (ImageIconId.Timelapse); } }
public static Image Timer10 { get { return GetIcon (ImageIconId.Timer10); } }
public static Image Timer3 { get { return GetIcon (ImageIconId.Timer3); } }
public static Image Timer { get { return GetIcon (ImageIconId.Timer); } }
public static Image TimerOff { get { return GetIcon (ImageIconId.TimerOff); } }
public static Image Tonality { get { return GetIcon (ImageIconId.Tonality); } }
public static Image Transform { get { return GetIcon (ImageIconId.Transform); } }
public static Image Tune { get { return GetIcon (ImageIconId.Tune); } }
public static Image ViewComfy { get { return GetIcon (ImageIconId.ViewComfy); } }
public static Image ViewCompact { get { return GetIcon (ImageIconId.ViewCompact); } }
public static Image WbAuto { get { return GetIcon (ImageIconId.WbAuto); } }
public static Image WbCloudy { get { return GetIcon (ImageIconId.WbCloudy); } }
public static Image WbIncandescent { get { return GetIcon (ImageIconId.WbIncandescent); } }
public static Image WbIridescent { get { return GetIcon (ImageIconId.WbIridescent); } }
public static Image WbSunny { get { return GetIcon (ImageIconId.WbSunny); } }
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using Skybrud.Social.Google.Analytics.Interfaces;
namespace Skybrud.Social.Google.Analytics.Objects {
public class AnalyticsFilterOptions {
#region Private fields
private List<IAnalyticsFilterBlock> _filters = new List<IAnalyticsFilterBlock>();
#endregion
#region Properties
public bool HasBlocks {
get { return _filters.Any(); }
}
public IAnalyticsFilterBlock[] Blocks {
get { return _filters.ToArray(); }
set { _filters = (value == null ? new List<IAnalyticsFilterBlock>() : Normalize(value.ToList())); }
}
#endregion
#region Member methods
/// <summary>
/// Adds a filter to the list of filters. If a filter already has been added, the new
/// filter will be prefixed with an OR operator.
/// </summary>
/// <param name="filter">The filter to add.</param>
public AnalyticsFilterOptions Add(IAnalyticsFilter filter) {
return Add(filter, AnalyticsFilterOperator.Or);
}
/// <summary>
/// Adds a filter to the list of filters. If a filter already has been added, the new
/// filter will be prefixed with the specified operator.
/// </summary>
/// <param name="filter">The filter to add.</param>
/// <param name="op">The operator to use.</param>
public AnalyticsFilterOptions Add(IAnalyticsFilter filter, AnalyticsFilterOperator op) {
if (filter == null) throw new ArgumentNullException("filter");
op = op ?? AnalyticsFilterOperator.Or;
if (_filters.Any()) {
if (_filters.Last() is AnalyticsFilterOperator) {
_filters.RemoveAt(_filters.Count - 1);
}
_filters.Add(op);
}
_filters.Add(filter);
return this;
}
public AnalyticsFilterOptions Where(IAnalyticsFilter filter) {
return Add(filter, AnalyticsFilterOperator.Or);
}
public AnalyticsFilterOptions And(IAnalyticsFilter filter) {
return Add(filter, AnalyticsFilterOperator.And);
}
public AnalyticsFilterOptions Or(IAnalyticsFilter filter) {
return Add(filter, AnalyticsFilterOperator.Or);
}
/// <summary>
/// Removes any existing filters.
/// </summary>
public AnalyticsFilterOptions Reset() {
_filters = new List<IAnalyticsFilterBlock>();
return this;
}
/// <summary>
/// Normalizes the list of filters.
/// </summary>
/// <param name="list">The list to normalize.</param>
/// <returns>The normalized list.</returns>
private List<IAnalyticsFilterBlock> Normalize(List<IAnalyticsFilterBlock> list) {
List<IAnalyticsFilterBlock> temp = new List<IAnalyticsFilterBlock>();
foreach (IAnalyticsFilterBlock current in list) {
// Get the previous valid block (last in temp)
var prev = temp.LastOrDefault();
// Normalizing
if (prev == null) {
if (current is AnalyticsFilterOperator) {
continue;
}
} else if (current is AnalyticsFilterOperator) {
if (prev is AnalyticsFilterOperator) {
temp.RemoveAt(temp.Count - 1);
}
} else if (current is IAnalyticsFilter) {
if (prev is IAnalyticsFilter) {
temp.Add(AnalyticsFilterOperator.Or);
}
}
// Add the block
temp.Add(current);
}
return temp;
}
/// <summary>
/// Generates a string representation of the filter options.
/// </summary>
public override string ToString() {
string temp = "";
foreach (var block in _filters) {
var filter = block as IAnalyticsFilter;
if (filter == null) {
temp += block.ToString();
} else {
temp += filter.Name + filter.OperatorValue + EscapeFilterValue(filter.Value);
}
}
return temp;
}
private string EscapeFilterValue(object value) {
// Make sure the value is property formatted (eg. if the value is a double)
string str = String.Format(CultureInfo.InvariantCulture, "{0}", value);
// Escape special characters (according to https://developers.google.com/analytics/devguides/reporting/core/v3/reference#filterExpressions)
str = str.Replace("\\", "\\\\,");
str = str.Replace(";", "\\;");
str = str.Replace(",", "\\,");
return str;
}
#endregion
#region Static methods
/// <summary>
/// Converts the string representation of the filter options.
/// </summary>
/// <param name="str">A string containing the filter options to convert.</param>
/// <returns>The converted filter options.</returns>
public static AnalyticsFilterOptions Parse(string str) {
AnalyticsFilterOptions options = new AnalyticsFilterOptions();
string[] a = str.Split(';');
for (int i = 0; i < a.Length; i++) {
string[] b = a[i].Split(',');
if (i > 0) options._filters.Add(AnalyticsFilterOperator.And);
for (int j = 0; j < b.Length; j++) {
if (j > 0) options._filters.Add(AnalyticsFilterOperator.Or);
Match m = Regex.Match(b[j], "^(ga:[a-zA-Z]+)(.{1,2})(.+?)$");
if (!m.Success) {
throw new Exception("Unable to parse filter '" + b[j] + "'");
}
AnalyticsMetric metric;
AnalyticsMetricOperator metricOperator;
AnalyticsDimension dimension;
AnalyticsDimensionOperator dimensionOperator;
if (AnalyticsMetric.TryParse(m.Groups[1].Value, out metric) && AnalyticsMetricOperator.TryParse(m.Groups[2].Value, out metricOperator)) {
options._filters.Add(new AnalyticsMetricFilter(metric, metricOperator, SocialUtils.UrlDecode(m.Groups[3].Value)));
} else if (AnalyticsDimension.TryParse(m.Groups[1].Value, out dimension) && AnalyticsDimensionOperator.TryParse(m.Groups[2].Value, out dimensionOperator)) {
options._filters.Add(new AnalyticsDimensionFilter(dimension, dimensionOperator, SocialUtils.UrlDecode(m.Groups[3].Value)));
} else {
// Currently the parsing will only work if the specified dimension or
// metric name matches a defined constant, so if Google adds a new
// dimension or metric, the constants must be updated before the parsing
// will work. I'm not sure how often Google adds new dimensions or metric,
// so perhaps this isn't a problem
throw new Exception("Unable to parse filter '" + b[j] + "'");
}
}
}
return options;
}
/// <summary>
/// Converts the string representation of the filter options. A return value indicates
/// whether the conversion succeeded.
/// </summary>
/// <param name="str">A string containing the filter options to convert.</param>
/// <param name="options">The converted options if successful.</param>
/// <returns><var>true</var> if str was converted successfully; otherwise, <var>false</var>.</returns>
public static bool TryParse(string str, out AnalyticsFilterOptions options) {
try {
options = Parse(str);
return true;
} catch {
options = null;
return false;
}
}
#endregion
#region Operator overloading
public static implicit operator AnalyticsFilterOptions(string str) {
return Parse(str);
}
public static implicit operator AnalyticsFilterOptions(IAnalyticsFilter[] array) {
return new AnalyticsFilterOptions { Blocks = array };
}
public static implicit operator AnalyticsFilterOptions(IAnalyticsFilterBlock[] array) {
return new AnalyticsFilterOptions { Blocks = array };
}
public static implicit operator AnalyticsFilterOptions(AnalyticsMetricFilter filter) {
return new AnalyticsFilterOptions().Add(filter);
}
public static implicit operator AnalyticsFilterOptions(AnalyticsDimensionFilter filter) {
return new AnalyticsFilterOptions().Add(filter);
}
#endregion
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using DotSpatial.Data;
using DotSpatial.NTSExtension;
using DotSpatial.Serialization;
namespace DotSpatial.Symbology
{
/// <summary>
/// Symbolizer for point features.
/// </summary>
public class PointSymbolizer : FeatureSymbolizer, IPointSymbolizer
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="PointSymbolizer"/> class.
/// </summary>
public PointSymbolizer()
{
Configure();
}
/// <summary>
/// Initializes a new instance of the <see cref="PointSymbolizer"/> class with only one symbol.
/// </summary>
/// <param name="symbol">The symbol to use for creating this symbolizer.</param>
public PointSymbolizer(ISymbol symbol)
{
Smoothing = true;
Symbols = new CopyList<ISymbol>
{
symbol
};
}
/// <summary>
/// Initializes a new instance of the <see cref="PointSymbolizer"/> class.
/// </summary>
/// <param name="presetSymbols">The symbols that are used.</param>
public PointSymbolizer(IEnumerable<ISymbol> presetSymbols)
{
Smoothing = true;
Symbols = new CopyList<ISymbol>();
foreach (ISymbol symbol in presetSymbols)
{
Symbols.Add(symbol);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="PointSymbolizer"/> class with one member that constructed
/// based on the values specified.
/// </summary>
/// <param name="color">The color of the symbol.</param>
/// <param name="shape">The shape of the symbol.</param>
/// <param name="size">The size of the symbol.</param>
public PointSymbolizer(Color color, PointShape shape, double size)
{
Smoothing = true;
Symbols = new CopyList<ISymbol>();
ISimpleSymbol ss = new SimpleSymbol(color, shape, size);
Symbols.Add(ss);
}
/// <summary>
/// Initializes a new instance of the <see cref="PointSymbolizer"/> class that has a member that is constructed
/// from the specified image.
/// </summary>
/// <param name="image">The image to use as a point symbol.</param>
/// <param name="size">The desired output size of the larger dimension of the image.</param>
public PointSymbolizer(Image image, double size)
{
Symbols = new CopyList<ISymbol>();
IPictureSymbol ps = new PictureSymbol(image);
ps.Size = new Size2D(size, size);
Symbols.Add(ps);
}
/// <summary>
/// Initializes a new instance of the <see cref="PointSymbolizer"/> class that has a character symbol based on the specified characteristics.
/// </summary>
/// <param name="character">The character to draw.</param>
/// <param name="fontFamily">The font family to use for rendering the font.</param>
/// <param name="color">The font color.</param>
/// <param name="size">The size of the symbol.</param>
public PointSymbolizer(char character, string fontFamily, Color color, double size)
{
Symbols = new CopyList<ISymbol>();
CharacterSymbol cs = new CharacterSymbol(character, fontFamily, color, size);
Symbols.Add(cs);
}
/// <summary>
/// Initializes a new instance of the <see cref="PointSymbolizer"/> class.
/// </summary>
/// <param name="selected">Indicates whether to use the color for selected symbols.</param>
public PointSymbolizer(bool selected)
{
Configure();
if (!selected) return;
ISimpleSymbol ss = Symbols[0] as ISimpleSymbol;
if (ss != null)
{
ss.Color = Color.Cyan;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="PointSymbolizer"/> class.
/// Sets the symbol type to geographic and generates a size that is 1/100 the width of the specified extents.
/// </summary>
/// <param name="selected">Indicates whether to use the color for selected symbols.</param>
/// <param name="extents">Used for calculating the size of the symbol.</param>
public PointSymbolizer(bool selected, IRectangle extents)
{
Configure();
ScaleMode = ScaleMode.Geographic;
Smoothing = false;
ISymbol s = Symbols[0];
if (s == null) return;
s.Size.Width = extents.Width / 100;
s.Size.Height = extents.Width / 100;
ISimpleSymbol ss = Symbols[0] as ISimpleSymbol;
if (ss != null && selected) ss.Color = Color.Cyan;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the set of layered symbols. The symbol with the highest index is drawn on top.
/// </summary>
[Serialize("Symbols")]
public IList<ISymbol> Symbols { get; set; }
#endregion
#region Methods
/// <summary>
/// Draws the specified value.
/// </summary>
/// <param name="g">The Graphics object to draw to.</param>
/// <param name="target">The Rectangle defining the bounds to draw in.</param>
public override void Draw(Graphics g, Rectangle target)
{
Size2D size = GetSize();
double scaleH = target.Width / size.Width;
double scaleV = target.Height / size.Height;
double scale = Math.Min(scaleH, scaleV);
Matrix old = g.Transform;
Matrix shift = g.Transform;
shift.Translate(target.X + (target.Width / 2), target.Y + (target.Height / 2));
g.Transform = shift;
Draw(g, scale);
g.Transform = old;
}
/// <summary>
/// Draws the point symbol to the specified graphics object by cycling through each of the layers and
/// drawing the content. This assumes that the graphics object has been translated to the specified point.
/// </summary>
/// <param name="g">Graphics object that is used for drawing.</param>
/// <param name="scaleSize">Scale size represents the constant to multiply to the geographic measures in order to turn them into pixel coordinates. </param>
public void Draw(Graphics g, double scaleSize)
{
GraphicsState s = g.Save();
if (Smoothing)
{
g.SmoothingMode = SmoothingMode.AntiAlias;
g.TextRenderingHint = TextRenderingHint.AntiAlias;
}
else
{
g.SmoothingMode = SmoothingMode.None;
g.TextRenderingHint = TextRenderingHint.SystemDefault;
}
foreach (ISymbol symbol in Symbols)
{
symbol.Draw(g, scaleSize);
}
g.Restore(s); // Changed by jany_ (2015-07-06) remove smoothing because we might not want to smooth whatever is drawn with g afterwards
}
/// <summary>
/// Returns the color of the top-most layer symbol.
/// </summary>
/// <returns>The fill color.</returns>
public Color GetFillColor()
{
if (Symbols == null) return Color.Empty;
if (Symbols.Count == 0) return Color.Empty;
IColorable c = Symbols[Symbols.Count - 1] as IColorable;
return c?.Color ?? Color.Empty;
}
/// <inheritdoc />
public override Size GetLegendSymbolSize()
{
Size2D sz = GetSize();
int w = (int)sz.Width;
int h = (int)sz.Height;
if (w < 1) w = 1;
if (w > 128) w = 128;
if (h < 1) h = 1;
if (h > 128) h = 128;
return new Size(w, h);
}
/// <summary>
/// Returns the encapsulating size when considering all of the symbol layers that make up this symbolizer.
/// </summary>
/// <returns>A Size2D.</returns>
public Size2D GetSize()
{
return Symbols.GetBoundingSize();
}
/// <summary>
/// Multiplies all the linear measurements, like width, height, and offset values by the specified value.
/// </summary>
/// <param name="value">The double precision value to multiply all of the values against.</param>
public void Scale(double value)
{
foreach (ISymbol symbol in Symbols)
{
symbol.Scale(value);
}
}
/// <summary>
/// Sets the color of the top-most layer symbol.
/// </summary>
/// <param name="color">The color to assign to the top-most layer.</param>
public void SetFillColor(Color color)
{
if (Symbols == null) return;
if (Symbols.Count == 0) return;
Symbols[Symbols.Count - 1].SetColor(color);
}
/// <summary>
/// Sets the outline, assuming that the symbolizer either supports outlines, or
/// else by using a second symbol layer.
/// </summary>
/// <param name="outlineColor">The color of the outline.</param>
/// <param name="width">The width of the outline in pixels.</param>
public override void SetOutline(Color outlineColor, double width)
{
if (Symbols == null) return;
if (Symbols.Count == 0) return;
foreach (ISymbol symbol in Symbols)
{
IOutlinedSymbol oSymbol = symbol as IOutlinedSymbol;
if (oSymbol == null) continue;
oSymbol.OutlineColor = outlineColor;
oSymbol.OutlineWidth = width;
oSymbol.UseOutline = true;
}
base.SetOutline(outlineColor, width);
}
/// <summary>
/// This assumes that you wish to simply scale the various sizes.
/// It will adjust all of the sizes so that the maximum size is the same as the specified size.
/// </summary>
/// <param name="value">The Size2D of the new maximum size.</param>
public void SetSize(Size2D value)
{
Size2D oldSize = Symbols.GetBoundingSize();
double dX = value.Width / oldSize.Width;
double dY = value.Height / oldSize.Height;
foreach (ISymbol symbol in Symbols)
{
Size2D os = symbol.Size;
symbol.Size = new Size2D(os.Width * dX, os.Height * dY);
}
}
/// <summary>
/// This controls randomly creating a single random symbol from the symbol types, and randomizing it.
/// </summary>
/// <param name="generator">The generator used to create the random symbol.</param>
protected override void OnRandomize(Random generator)
{
SymbolType type = generator.NextEnum<SymbolType>();
Symbols.Clear();
switch (type)
{
case SymbolType.Custom:
Symbols.Add(new SimpleSymbol());
break;
case SymbolType.Character:
Symbols.Add(new CharacterSymbol());
break;
case SymbolType.Picture:
Symbols.Add(new CharacterSymbol());
break;
case SymbolType.Simple:
Symbols.Add(new SimpleSymbol());
break;
}
// This part will actually randomize the sub-member
base.OnRandomize(generator);
}
private void Configure()
{
Symbols = new CopyList<ISymbol>();
ISimpleSymbol ss = new SimpleSymbol();
ss.Color = SymbologyGlobal.RandomColor();
ss.Opacity = 1F;
ss.PointShape = PointShape.Rectangle;
Smoothing = true;
ScaleMode = ScaleMode.Symbolic;
Symbols.Add(ss);
}
#endregion
}
}
| |
using MS.Win32;
using System;
namespace System.Windows.Input
{
/// <summary>
/// Provides static methods to convert between Win32 VirtualKeys
/// and our Key enum.
/// </summary>
public static class KeyInterop
{
/// <summary>
/// Convert a Win32 VirtualKey into our Key enum.
/// </summary>
public static Key KeyFromVirtualKey(int virtualKey)
{
Key key = Key.None;
switch(virtualKey)
{
case NativeMethods.VK_CANCEL:
key = Key.Cancel;
break;
case NativeMethods.VK_BACK:
key = Key.Back;
break;
case NativeMethods.VK_TAB:
key = Key.Tab;
break;
case NativeMethods.VK_CLEAR:
key = Key.Clear;
break;
case NativeMethods.VK_RETURN:
key = Key.Return;
break;
case NativeMethods.VK_PAUSE:
key = Key.Pause;
break;
case NativeMethods.VK_CAPITAL:
key = Key.Capital;
break;
case NativeMethods.VK_KANA:
key = Key.KanaMode;
break;
case NativeMethods.VK_JUNJA:
key = Key.JunjaMode;
break;
case NativeMethods.VK_FINAL:
key = Key.FinalMode;
break;
case NativeMethods.VK_KANJI:
key = Key.KanjiMode;
break;
case NativeMethods.VK_ESCAPE:
key = Key.Escape;
break;
case NativeMethods.VK_CONVERT:
key = Key.ImeConvert;
break;
case NativeMethods.VK_NONCONVERT:
key = Key.ImeNonConvert;
break;
case NativeMethods.VK_ACCEPT:
key = Key.ImeAccept;
break;
case NativeMethods.VK_MODECHANGE:
key = Key.ImeModeChange;
break;
case NativeMethods.VK_SPACE:
key = Key.Space;
break;
case NativeMethods.VK_PRIOR:
key = Key.Prior;
break;
case NativeMethods.VK_NEXT:
key = Key.Next;
break;
case NativeMethods.VK_END:
key = Key.End;
break;
case NativeMethods.VK_HOME:
key = Key.Home;
break;
case NativeMethods.VK_LEFT:
key = Key.Left;
break;
case NativeMethods.VK_UP:
key = Key.Up;
break;
case NativeMethods.VK_RIGHT:
key = Key.Right;
break;
case NativeMethods.VK_DOWN:
key = Key.Down;
break;
case NativeMethods.VK_SELECT:
key = Key.Select;
break;
case NativeMethods.VK_PRINT:
key = Key.Print;
break;
case NativeMethods.VK_EXECUTE:
key = Key.Execute;
break;
case NativeMethods.VK_SNAPSHOT:
key = Key.Snapshot;
break;
case NativeMethods.VK_INSERT:
key = Key.Insert;
break;
case NativeMethods.VK_DELETE:
key = Key.Delete;
break;
case NativeMethods.VK_HELP:
key = Key.Help;
break;
case NativeMethods.VK_0:
key = Key.D0;
break;
case NativeMethods.VK_1:
key = Key.D1;
break;
case NativeMethods.VK_2:
key = Key.D2;
break;
case NativeMethods.VK_3:
key = Key.D3;
break;
case NativeMethods.VK_4:
key = Key.D4;
break;
case NativeMethods.VK_5:
key = Key.D5;
break;
case NativeMethods.VK_6:
key = Key.D6;
break;
case NativeMethods.VK_7:
key = Key.D7;
break;
case NativeMethods.VK_8:
key = Key.D8;
break;
case NativeMethods.VK_9:
key = Key.D9;
break;
case NativeMethods.VK_A:
key = Key.A;
break;
case NativeMethods.VK_B:
key = Key.B;
break;
case NativeMethods.VK_C:
key = Key.C;
break;
case NativeMethods.VK_D:
key = Key.D;
break;
case NativeMethods.VK_E:
key = Key.E;
break;
case NativeMethods.VK_F:
key = Key.F;
break;
case NativeMethods.VK_G:
key = Key.G;
break;
case NativeMethods.VK_H:
key = Key.H;
break;
case NativeMethods.VK_I:
key = Key.I;
break;
case NativeMethods.VK_J:
key = Key.J;
break;
case NativeMethods.VK_K:
key = Key.K;
break;
case NativeMethods.VK_L:
key = Key.L;
break;
case NativeMethods.VK_M:
key = Key.M;
break;
case NativeMethods.VK_N:
key = Key.N;
break;
case NativeMethods.VK_O:
key = Key.O;
break;
case NativeMethods.VK_P:
key = Key.P;
break;
case NativeMethods.VK_Q:
key = Key.Q;
break;
case NativeMethods.VK_R:
key = Key.R;
break;
case NativeMethods.VK_S:
key = Key.S;
break;
case NativeMethods.VK_T:
key = Key.T;
break;
case NativeMethods.VK_U:
key = Key.U;
break;
case NativeMethods.VK_V:
key = Key.V;
break;
case NativeMethods.VK_W:
key = Key.W;
break;
case NativeMethods.VK_X:
key = Key.X;
break;
case NativeMethods.VK_Y:
key = Key.Y;
break;
case NativeMethods.VK_Z:
key = Key.Z;
break;
case NativeMethods.VK_LWIN:
key = Key.LWin;
break;
case NativeMethods.VK_RWIN:
key = Key.RWin;
break;
case NativeMethods.VK_APPS:
key = Key.Apps;
break;
case NativeMethods.VK_SLEEP:
key = Key.Sleep;
break;
case NativeMethods.VK_NUMPAD0:
key = Key.NumPad0;
break;
case NativeMethods.VK_NUMPAD1:
key = Key.NumPad1;
break;
case NativeMethods.VK_NUMPAD2:
key = Key.NumPad2;
break;
case NativeMethods.VK_NUMPAD3:
key = Key.NumPad3;
break;
case NativeMethods.VK_NUMPAD4:
key = Key.NumPad4;
break;
case NativeMethods.VK_NUMPAD5:
key = Key.NumPad5;
break;
case NativeMethods.VK_NUMPAD6:
key = Key.NumPad6;
break;
case NativeMethods.VK_NUMPAD7:
key = Key.NumPad7;
break;
case NativeMethods.VK_NUMPAD8:
key = Key.NumPad8;
break;
case NativeMethods.VK_NUMPAD9:
key = Key.NumPad9;
break;
case NativeMethods.VK_MULTIPLY:
key = Key.Multiply;
break;
case NativeMethods.VK_ADD:
key = Key.Add;
break;
case NativeMethods.VK_SEPARATOR:
key = Key.Separator;
break;
case NativeMethods.VK_SUBTRACT:
key = Key.Subtract;
break;
case NativeMethods.VK_DECIMAL:
key = Key.Decimal;
break;
case NativeMethods.VK_DIVIDE:
key = Key.Divide;
break;
case NativeMethods.VK_F1:
key = Key.F1;
break;
case NativeMethods.VK_F2:
key = Key.F2;
break;
case NativeMethods.VK_F3:
key = Key.F3;
break;
case NativeMethods.VK_F4:
key = Key.F4;
break;
case NativeMethods.VK_F5:
key = Key.F5;
break;
case NativeMethods.VK_F6:
key = Key.F6;
break;
case NativeMethods.VK_F7:
key = Key.F7;
break;
case NativeMethods.VK_F8:
key = Key.F8;
break;
case NativeMethods.VK_F9:
key = Key.F9;
break;
case NativeMethods.VK_F10:
key = Key.F10;
break;
case NativeMethods.VK_F11:
key = Key.F11;
break;
case NativeMethods.VK_F12:
key = Key.F12;
break;
case NativeMethods.VK_F13:
key = Key.F13;
break;
case NativeMethods.VK_F14:
key = Key.F14;
break;
case NativeMethods.VK_F15:
key = Key.F15;
break;
case NativeMethods.VK_F16:
key = Key.F16;
break;
case NativeMethods.VK_F17:
key = Key.F17;
break;
case NativeMethods.VK_F18:
key = Key.F18;
break;
case NativeMethods.VK_F19:
key = Key.F19;
break;
case NativeMethods.VK_F20:
key = Key.F20;
break;
case NativeMethods.VK_F21:
key = Key.F21;
break;
case NativeMethods.VK_F22:
key = Key.F22;
break;
case NativeMethods.VK_F23:
key = Key.F23;
break;
case NativeMethods.VK_F24:
key = Key.F24;
break;
case NativeMethods.VK_NUMLOCK:
key = Key.NumLock;
break;
case NativeMethods.VK_SCROLL:
key = Key.Scroll;
break;
case NativeMethods.VK_SHIFT:
case NativeMethods.VK_LSHIFT:
key = Key.LeftShift;
break;
case NativeMethods.VK_RSHIFT:
key = Key.RightShift;
break;
case NativeMethods.VK_CONTROL:
case NativeMethods.VK_LCONTROL:
key = Key.LeftCtrl;
break;
case NativeMethods.VK_RCONTROL:
key = Key.RightCtrl;
break;
case NativeMethods.VK_MENU:
case NativeMethods.VK_LMENU:
key = Key.LeftAlt;
break;
case NativeMethods.VK_RMENU:
key = Key.RightAlt;
break;
case NativeMethods.VK_BROWSER_BACK:
key = Key.BrowserBack;
break;
case NativeMethods.VK_BROWSER_FORWARD:
key = Key.BrowserForward;
break;
case NativeMethods.VK_BROWSER_REFRESH:
key = Key.BrowserRefresh;
break;
case NativeMethods.VK_BROWSER_STOP:
key = Key.BrowserStop;
break;
case NativeMethods.VK_BROWSER_SEARCH:
key = Key.BrowserSearch;
break;
case NativeMethods.VK_BROWSER_FAVORITES:
key = Key.BrowserFavorites;
break;
case NativeMethods.VK_BROWSER_HOME:
key = Key.BrowserHome;
break;
case NativeMethods.VK_VOLUME_MUTE:
key = Key.VolumeMute;
break;
case NativeMethods.VK_VOLUME_DOWN:
key = Key.VolumeDown;
break;
case NativeMethods.VK_VOLUME_UP:
key = Key.VolumeUp;
break;
case NativeMethods.VK_MEDIA_NEXT_TRACK:
key = Key.MediaNextTrack;
break;
case NativeMethods.VK_MEDIA_PREV_TRACK:
key = Key.MediaPreviousTrack;
break;
case NativeMethods.VK_MEDIA_STOP:
key = Key.MediaStop;
break;
case NativeMethods.VK_MEDIA_PLAY_PAUSE:
key = Key.MediaPlayPause;
break;
case NativeMethods.VK_LAUNCH_MAIL:
key = Key.LaunchMail;
break;
case NativeMethods.VK_LAUNCH_MEDIA_SELECT:
key = Key.SelectMedia;
break;
case NativeMethods.VK_LAUNCH_APP1:
key = Key.LaunchApplication1;
break;
case NativeMethods.VK_LAUNCH_APP2:
key = Key.LaunchApplication2;
break;
case NativeMethods.VK_OEM_1:
key = Key.OemSemicolon;
break;
case NativeMethods.VK_OEM_PLUS:
key = Key.OemPlus;
break;
case NativeMethods.VK_OEM_COMMA:
key = Key.OemComma;
break;
case NativeMethods.VK_OEM_MINUS:
key = Key.OemMinus;
break;
case NativeMethods.VK_OEM_PERIOD:
key = Key.OemPeriod;
break;
case NativeMethods.VK_OEM_2:
key = Key.OemQuestion;
break;
case NativeMethods.VK_OEM_3:
key = Key.OemTilde;
break;
case NativeMethods.VK_C1:
key = Key.AbntC1;
break;
case NativeMethods.VK_C2:
key = Key.AbntC2;
break;
case NativeMethods.VK_OEM_4:
key = Key.OemOpenBrackets;
break;
case NativeMethods.VK_OEM_5:
key = Key.OemPipe;
break;
case NativeMethods.VK_OEM_6:
key = Key.OemCloseBrackets;
break;
case NativeMethods.VK_OEM_7:
key = Key.OemQuotes;
break;
case NativeMethods.VK_OEM_8:
key = Key.Oem8;
break;
case NativeMethods.VK_OEM_102:
key = Key.OemBackslash;
break;
case NativeMethods.VK_PROCESSKEY:
key = Key.ImeProcessed;
break;
case NativeMethods.VK_OEM_ATTN: // VK_DBE_ALPHANUMERIC
key = Key.OemAttn; // DbeAlphanumeric
break;
case NativeMethods.VK_OEM_FINISH: // VK_DBE_KATAKANA
key = Key.OemFinish; // DbeKatakana
break;
case NativeMethods.VK_OEM_COPY: // VK_DBE_HIRAGANA
key = Key.OemCopy; // DbeHiragana
break;
case NativeMethods.VK_OEM_AUTO: // VK_DBE_SBCSCHAR
key = Key.OemAuto; // DbeSbcsChar
break;
case NativeMethods.VK_OEM_ENLW: // VK_DBE_DBCSCHAR
key = Key.OemEnlw; // DbeDbcsChar
break;
case NativeMethods.VK_OEM_BACKTAB: // VK_DBE_ROMAN
key = Key.OemBackTab; // DbeRoman
break;
case NativeMethods.VK_ATTN: // VK_DBE_NOROMAN
key = Key.Attn; // DbeNoRoman
break;
case NativeMethods.VK_CRSEL: // VK_DBE_ENTERWORDREGISTERMODE
key = Key.CrSel; // DbeEnterWordRegisterMode
break;
case NativeMethods.VK_EXSEL: // VK_DBE_ENTERIMECONFIGMODE
key = Key.ExSel; // DbeEnterImeConfigMode
break;
case NativeMethods.VK_EREOF: // VK_DBE_FLUSHSTRING
key = Key.EraseEof; // DbeFlushString
break;
case NativeMethods.VK_PLAY: // VK_DBE_CODEINPUT
key = Key.Play; // DbeCodeInput
break;
case NativeMethods.VK_ZOOM: // VK_DBE_NOCODEINPUT
key = Key.Zoom; // DbeNoCodeInput
break;
case NativeMethods.VK_NONAME: // VK_DBE_DETERMINESTRING
key = Key.NoName; // DbeDetermineString
break;
case NativeMethods.VK_PA1: // VK_DBE_ENTERDLGCONVERSIONMODE
key = Key.Pa1; // DbeEnterDlgConversionMode
break;
case NativeMethods.VK_OEM_CLEAR:
key = Key.OemClear;
break;
default:
key = Key.None;
break;
}
return key;
}
/// <summary>
/// Convert our Key enum into a Win32 VirtualKey.
/// </summary>
public static int VirtualKeyFromKey(Key key)
{
int virtualKey = 0;
switch(key)
{
case Key.Cancel:
virtualKey = NativeMethods.VK_CANCEL;
break;
case Key.Back:
virtualKey = NativeMethods.VK_BACK;
break;
case Key.Tab:
virtualKey = NativeMethods.VK_TAB;
break;
case Key.Clear:
virtualKey = NativeMethods.VK_CLEAR;
break;
case Key.Return:
virtualKey = NativeMethods.VK_RETURN;
break;
case Key.Pause:
virtualKey = NativeMethods.VK_PAUSE;
break;
case Key.Capital:
virtualKey = NativeMethods.VK_CAPITAL;
break;
case Key.KanaMode:
virtualKey = NativeMethods.VK_KANA;
break;
case Key.JunjaMode:
virtualKey = NativeMethods.VK_JUNJA;
break;
case Key.FinalMode:
virtualKey = NativeMethods.VK_FINAL;
break;
case Key.KanjiMode:
virtualKey = NativeMethods.VK_KANJI;
break;
case Key.Escape:
virtualKey = NativeMethods.VK_ESCAPE;
break;
case Key.ImeConvert:
virtualKey = NativeMethods.VK_CONVERT;
break;
case Key.ImeNonConvert:
virtualKey = NativeMethods.VK_NONCONVERT;
break;
case Key.ImeAccept:
virtualKey = NativeMethods.VK_ACCEPT;
break;
case Key.ImeModeChange:
virtualKey = NativeMethods.VK_MODECHANGE;
break;
case Key.Space:
virtualKey = NativeMethods.VK_SPACE;
break;
case Key.Prior:
virtualKey = NativeMethods.VK_PRIOR;
break;
case Key.Next:
virtualKey = NativeMethods.VK_NEXT;
break;
case Key.End:
virtualKey = NativeMethods.VK_END;
break;
case Key.Home:
virtualKey = NativeMethods.VK_HOME;
break;
case Key.Left:
virtualKey = NativeMethods.VK_LEFT;
break;
case Key.Up:
virtualKey = NativeMethods.VK_UP;
break;
case Key.Right:
virtualKey = NativeMethods.VK_RIGHT;
break;
case Key.Down:
virtualKey = NativeMethods.VK_DOWN;
break;
case Key.Select:
virtualKey = NativeMethods.VK_SELECT;
break;
case Key.Print:
virtualKey = NativeMethods.VK_PRINT;
break;
case Key.Execute:
virtualKey = NativeMethods.VK_EXECUTE;
break;
case Key.Snapshot:
virtualKey = NativeMethods.VK_SNAPSHOT;
break;
case Key.Insert:
virtualKey = NativeMethods.VK_INSERT;
break;
case Key.Delete:
virtualKey = NativeMethods.VK_DELETE;
break;
case Key.Help:
virtualKey = NativeMethods.VK_HELP;
break;
case Key.D0:
virtualKey = NativeMethods.VK_0;
break;
case Key.D1:
virtualKey = NativeMethods.VK_1;
break;
case Key.D2:
virtualKey = NativeMethods.VK_2;
break;
case Key.D3:
virtualKey = NativeMethods.VK_3;
break;
case Key.D4:
virtualKey = NativeMethods.VK_4;
break;
case Key.D5:
virtualKey = NativeMethods.VK_5;
break;
case Key.D6:
virtualKey = NativeMethods.VK_6;
break;
case Key.D7:
virtualKey = NativeMethods.VK_7;
break;
case Key.D8:
virtualKey = NativeMethods.VK_8;
break;
case Key.D9:
virtualKey = NativeMethods.VK_9;
break;
case Key.A:
virtualKey = NativeMethods.VK_A;
break;
case Key.B:
virtualKey = NativeMethods.VK_B;
break;
case Key.C:
virtualKey = NativeMethods.VK_C;
break;
case Key.D:
virtualKey = NativeMethods.VK_D;
break;
case Key.E:
virtualKey = NativeMethods.VK_E;
break;
case Key.F:
virtualKey = NativeMethods.VK_F;
break;
case Key.G:
virtualKey = NativeMethods.VK_G;
break;
case Key.H:
virtualKey = NativeMethods.VK_H;
break;
case Key.I:
virtualKey = NativeMethods.VK_I;
break;
case Key.J:
virtualKey = NativeMethods.VK_J;
break;
case Key.K:
virtualKey = NativeMethods.VK_K;
break;
case Key.L:
virtualKey = NativeMethods.VK_L;
break;
case Key.M:
virtualKey = NativeMethods.VK_M;
break;
case Key.N:
virtualKey = NativeMethods.VK_N;
break;
case Key.O:
virtualKey = NativeMethods.VK_O;
break;
case Key.P:
virtualKey = NativeMethods.VK_P;
break;
case Key.Q:
virtualKey = NativeMethods.VK_Q;
break;
case Key.R:
virtualKey = NativeMethods.VK_R;
break;
case Key.S:
virtualKey = NativeMethods.VK_S;
break;
case Key.T:
virtualKey = NativeMethods.VK_T;
break;
case Key.U:
virtualKey = NativeMethods.VK_U;
break;
case Key.V:
virtualKey = NativeMethods.VK_V;
break;
case Key.W:
virtualKey = NativeMethods.VK_W;
break;
case Key.X:
virtualKey = NativeMethods.VK_X;
break;
case Key.Y:
virtualKey = NativeMethods.VK_Y;
break;
case Key.Z:
virtualKey = NativeMethods.VK_Z;
break;
case Key.LWin:
virtualKey = NativeMethods.VK_LWIN;
break;
case Key.RWin:
virtualKey = NativeMethods.VK_RWIN;
break;
case Key.Apps:
virtualKey = NativeMethods.VK_APPS;
break;
case Key.Sleep:
virtualKey = NativeMethods.VK_SLEEP;
break;
case Key.NumPad0:
virtualKey = NativeMethods.VK_NUMPAD0;
break;
case Key.NumPad1:
virtualKey = NativeMethods.VK_NUMPAD1;
break;
case Key.NumPad2:
virtualKey = NativeMethods.VK_NUMPAD2;
break;
case Key.NumPad3:
virtualKey = NativeMethods.VK_NUMPAD3;
break;
case Key.NumPad4:
virtualKey = NativeMethods.VK_NUMPAD4;
break;
case Key.NumPad5:
virtualKey = NativeMethods.VK_NUMPAD5;
break;
case Key.NumPad6:
virtualKey = NativeMethods.VK_NUMPAD6;
break;
case Key.NumPad7:
virtualKey = NativeMethods.VK_NUMPAD7;
break;
case Key.NumPad8:
virtualKey = NativeMethods.VK_NUMPAD8;
break;
case Key.NumPad9:
virtualKey = NativeMethods.VK_NUMPAD9;
break;
case Key.Multiply:
virtualKey = NativeMethods.VK_MULTIPLY;
break;
case Key.Add:
virtualKey = NativeMethods.VK_ADD;
break;
case Key.Separator:
virtualKey = NativeMethods.VK_SEPARATOR;
break;
case Key.Subtract:
virtualKey = NativeMethods.VK_SUBTRACT;
break;
case Key.Decimal:
virtualKey = NativeMethods.VK_DECIMAL;
break;
case Key.Divide:
virtualKey = NativeMethods.VK_DIVIDE;
break;
case Key.F1:
virtualKey = NativeMethods.VK_F1;
break;
case Key.F2:
virtualKey = NativeMethods.VK_F2;
break;
case Key.F3:
virtualKey = NativeMethods.VK_F3;
break;
case Key.F4:
virtualKey = NativeMethods.VK_F4;
break;
case Key.F5:
virtualKey = NativeMethods.VK_F5;
break;
case Key.F6:
virtualKey = NativeMethods.VK_F6;
break;
case Key.F7:
virtualKey = NativeMethods.VK_F7;
break;
case Key.F8:
virtualKey = NativeMethods.VK_F8;
break;
case Key.F9:
virtualKey = NativeMethods.VK_F9;
break;
case Key.F10:
virtualKey = NativeMethods.VK_F10;
break;
case Key.F11:
virtualKey = NativeMethods.VK_F11;
break;
case Key.F12:
virtualKey = NativeMethods.VK_F12;
break;
case Key.F13:
virtualKey = NativeMethods.VK_F13;
break;
case Key.F14:
virtualKey = NativeMethods.VK_F14;
break;
case Key.F15:
virtualKey = NativeMethods.VK_F15;
break;
case Key.F16:
virtualKey = NativeMethods.VK_F16;
break;
case Key.F17:
virtualKey = NativeMethods.VK_F17;
break;
case Key.F18:
virtualKey = NativeMethods.VK_F18;
break;
case Key.F19:
virtualKey = NativeMethods.VK_F19;
break;
case Key.F20:
virtualKey = NativeMethods.VK_F20;
break;
case Key.F21:
virtualKey = NativeMethods.VK_F21;
break;
case Key.F22:
virtualKey = NativeMethods.VK_F22;
break;
case Key.F23:
virtualKey = NativeMethods.VK_F23;
break;
case Key.F24:
virtualKey = NativeMethods.VK_F24;
break;
case Key.NumLock:
virtualKey = NativeMethods.VK_NUMLOCK;
break;
case Key.Scroll:
virtualKey = NativeMethods.VK_SCROLL;
break;
case Key.LeftShift:
virtualKey = NativeMethods.VK_LSHIFT;
break;
case Key.RightShift:
virtualKey = NativeMethods.VK_RSHIFT;
break;
case Key.LeftCtrl:
virtualKey = NativeMethods.VK_LCONTROL;
break;
case Key.RightCtrl:
virtualKey = NativeMethods.VK_RCONTROL;
break;
case Key.LeftAlt:
virtualKey = NativeMethods.VK_LMENU;
break;
case Key.RightAlt:
virtualKey = NativeMethods.VK_RMENU;
break;
case Key.BrowserBack:
virtualKey = NativeMethods.VK_BROWSER_BACK;
break;
case Key.BrowserForward:
virtualKey = NativeMethods.VK_BROWSER_FORWARD;
break;
case Key.BrowserRefresh:
virtualKey = NativeMethods.VK_BROWSER_REFRESH;
break;
case Key.BrowserStop:
virtualKey = NativeMethods.VK_BROWSER_STOP;
break;
case Key.BrowserSearch:
virtualKey = NativeMethods.VK_BROWSER_SEARCH;
break;
case Key.BrowserFavorites:
virtualKey = NativeMethods.VK_BROWSER_FAVORITES;
break;
case Key.BrowserHome:
virtualKey = NativeMethods.VK_BROWSER_HOME;
break;
case Key.VolumeMute:
virtualKey = NativeMethods.VK_VOLUME_MUTE;
break;
case Key.VolumeDown:
virtualKey = NativeMethods.VK_VOLUME_DOWN;
break;
case Key.VolumeUp:
virtualKey = NativeMethods.VK_VOLUME_UP;
break;
case Key.MediaNextTrack:
virtualKey = NativeMethods.VK_MEDIA_NEXT_TRACK;
break;
case Key.MediaPreviousTrack:
virtualKey = NativeMethods.VK_MEDIA_PREV_TRACK;
break;
case Key.MediaStop:
virtualKey = NativeMethods.VK_MEDIA_STOP;
break;
case Key.MediaPlayPause:
virtualKey = NativeMethods.VK_MEDIA_PLAY_PAUSE;
break;
case Key.LaunchMail:
virtualKey = NativeMethods.VK_LAUNCH_MAIL;
break;
case Key.SelectMedia:
virtualKey = NativeMethods.VK_LAUNCH_MEDIA_SELECT;
break;
case Key.LaunchApplication1:
virtualKey = NativeMethods.VK_LAUNCH_APP1;
break;
case Key.LaunchApplication2:
virtualKey = NativeMethods.VK_LAUNCH_APP2;
break;
case Key.OemSemicolon:
virtualKey = NativeMethods.VK_OEM_1;
break;
case Key.OemPlus:
virtualKey = NativeMethods.VK_OEM_PLUS;
break;
case Key.OemComma:
virtualKey = NativeMethods.VK_OEM_COMMA;
break;
case Key.OemMinus:
virtualKey = NativeMethods.VK_OEM_MINUS;
break;
case Key.OemPeriod:
virtualKey = NativeMethods.VK_OEM_PERIOD;
break;
case Key.OemQuestion:
virtualKey = NativeMethods.VK_OEM_2;
break;
case Key.OemTilde:
virtualKey = NativeMethods.VK_OEM_3;
break;
case Key.AbntC1:
virtualKey = NativeMethods.VK_C1;
break;
case Key.AbntC2:
virtualKey = NativeMethods.VK_C2;
break;
case Key.OemOpenBrackets:
virtualKey = NativeMethods.VK_OEM_4;
break;
case Key.OemPipe:
virtualKey = NativeMethods.VK_OEM_5;
break;
case Key.OemCloseBrackets:
virtualKey = NativeMethods.VK_OEM_6;
break;
case Key.OemQuotes:
virtualKey = NativeMethods.VK_OEM_7;
break;
case Key.Oem8:
virtualKey = NativeMethods.VK_OEM_8;
break;
case Key.OemBackslash:
virtualKey = NativeMethods.VK_OEM_102;
break;
case Key.ImeProcessed:
virtualKey = NativeMethods.VK_PROCESSKEY;
break;
case Key.OemAttn: // DbeAlphanumeric
virtualKey = NativeMethods.VK_OEM_ATTN; // VK_DBE_ALPHANUMERIC
break;
case Key.OemFinish: // DbeKatakana
virtualKey = NativeMethods.VK_OEM_FINISH; // VK_DBE_KATAKANA
break;
case Key.OemCopy: // DbeHiragana
virtualKey = NativeMethods.VK_OEM_COPY; // VK_DBE_HIRAGANA
break;
case Key.OemAuto: // DbeSbcsChar
virtualKey = NativeMethods.VK_OEM_AUTO; // VK_DBE_SBCSCHAR
break;
case Key.OemEnlw: // DbeDbcsChar
virtualKey = NativeMethods.VK_OEM_ENLW; // VK_DBE_DBCSCHAR
break;
case Key.OemBackTab: // DbeRoman
virtualKey = NativeMethods.VK_OEM_BACKTAB; // VK_DBE_ROMAN
break;
case Key.Attn: // DbeNoRoman
virtualKey = NativeMethods.VK_ATTN; // VK_DBE_NOROMAN
break;
case Key.CrSel: // DbeEnterWordRegisterMode
virtualKey = NativeMethods.VK_CRSEL; // VK_DBE_ENTERWORDREGISTERMODE
break;
case Key.ExSel: // EnterImeConfigureMode
virtualKey = NativeMethods.VK_EXSEL; // VK_DBE_ENTERIMECONFIGMODE
break;
case Key.EraseEof: // DbeFlushString
virtualKey = NativeMethods.VK_EREOF; // VK_DBE_FLUSHSTRING
break;
case Key.Play: // DbeCodeInput
virtualKey = NativeMethods.VK_PLAY; // VK_DBE_CODEINPUT
break;
case Key.Zoom: // DbeNoCodeInput
virtualKey = NativeMethods.VK_ZOOM; // VK_DBE_NOCODEINPUT
break;
case Key.NoName: // DbeDetermineString
virtualKey = NativeMethods.VK_NONAME; // VK_DBE_DETERMINESTRING
break;
case Key.Pa1: // DbeEnterDlgConversionMode
virtualKey = NativeMethods.VK_PA1; // VK_ENTERDLGCONVERSIONMODE
break;
case Key.OemClear:
virtualKey = NativeMethods.VK_OEM_CLEAR;
break;
case Key.DeadCharProcessed: //This is usused. It's just here for completeness.
virtualKey = 0; //There is no Win32 VKey for this.
break;
default:
virtualKey = 0;
break;
}
return virtualKey;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using MessageStream2;
using DarkMultiPlayerCommon;
using UnityEngine;
namespace DarkMultiPlayer
{
public class FlagSyncer
{
//Singleton
private static FlagSyncer singleton;
//Public
public bool workerEnabled;
public bool flagChangeEvent;
public bool syncComplete;
//Private
private string flagPath;
private Dictionary<string, FlagInfo> serverFlags = new Dictionary<string, FlagInfo>();
private Queue<FlagRespondMessage> newFlags = new Queue<FlagRespondMessage>();
public FlagSyncer()
{
flagPath = Path.Combine(Path.Combine(Path.Combine(KSPUtil.ApplicationRootPath, "GameData"), "DarkMultiPlayer"), "Flags");
}
public static FlagSyncer fetch
{
get
{
return singleton;
}
}
public void SendFlagList()
{
string[] dmpFlags = Directory.GetFiles(flagPath);
string[] dmpSha = new string[dmpFlags.Length];
for (int i=0; i < dmpFlags.Length; i++)
{
dmpSha[i] = Common.CalculateSHA256Hash(dmpFlags[i]);
dmpFlags[i] = Path.GetFileName(dmpFlags[i]);
}
using (MessageWriter mw = new MessageWriter())
{
mw.Write<int>((int)FlagMessageType.LIST);
mw.Write<string>(Settings.fetch.playerName);
mw.Write<string[]>(dmpFlags);
mw.Write<string[]>(dmpSha);
NetworkWorker.fetch.SendFlagMessage(mw.GetMessageBytes());
}
}
public void HandleMessage(byte[] messageData)
{
using (MessageReader mr = new MessageReader(messageData))
{
FlagMessageType messageType = (FlagMessageType)mr.Read<int>();
switch (messageType)
{
case FlagMessageType.LIST:
{
//List code
string[] serverFlagFiles = mr.Read<string[]>();
string[] serverFlagOwners = mr.Read<string[]>();
string[] serverFlagShaSums = mr.Read<string[]>();
for (int i = 0; i < serverFlagFiles.Length; i++)
{
FlagInfo fi = new FlagInfo();
fi.owner = serverFlagOwners[i];
fi.shaSum = serverFlagShaSums[i];
serverFlags[Path.GetFileNameWithoutExtension(serverFlagFiles[i])] = fi;
}
syncComplete = true;
//Check if we need to upload the flag
flagChangeEvent = true;
}
break;
case FlagMessageType.FLAG_DATA:
{
FlagRespondMessage frm = new FlagRespondMessage();
frm.flagInfo.owner = mr.Read<string>();
frm.flagName = mr.Read<string>();
frm.flagData = mr.Read<byte[]>();
frm.flagInfo.shaSum = Common.CalculateSHA256Hash(frm.flagData);
newFlags.Enqueue(frm);
}
break;
case FlagMessageType.DELETE_FILE:
{
string flagName = mr.Read<string>();
string flagFile = Path.Combine(flagPath, flagName);
if (File.Exists(flagFile))
{
try
{
if (File.Exists(flagFile))
{
DarkLog.Debug("Deleting flag " + flagFile);
File.Delete(flagFile);
}
}
catch (Exception e)
{
DarkLog.Debug("Error deleting flag " + flagFile + ", exception: " + e);
}
}
}
break;
}
}
}
private void Update()
{
if (workerEnabled && syncComplete && (HighLogic.CurrentGame != null ? HighLogic.CurrentGame.flagURL != null : false))
{
if (flagChangeEvent)
{
flagChangeEvent = false;
HandleFlagChangeEvent();
}
while (newFlags.Count > 0)
{
HandleFlagRespondMessage(newFlags.Dequeue());
}
}
}
private void HandleFlagChangeEvent()
{
string flagURL = HighLogic.CurrentGame.flagURL;
if (!flagURL.ToLower().StartsWith("darkmultiplayer/flags/"))
{
//If it's not a DMP flag don't sync it.
return;
}
string flagName = flagURL.Substring("DarkMultiPlayer/Flags/".Length);
if (serverFlags.ContainsKey(flagName) ? serverFlags[flagName].owner != Settings.fetch.playerName : false)
{
//If the flag is owned by someone else don't sync it
return;
}
string flagFile = "";
string[] flagFiles = Directory.GetFiles(flagPath, "*", SearchOption.TopDirectoryOnly);
foreach (string possibleMatch in flagFiles)
{
if (flagName.ToLower() == Path.GetFileNameWithoutExtension(possibleMatch).ToLower())
{
flagFile = possibleMatch;
}
}
//Sanity check to make sure we found the file
if (flagFile != "" ? File.Exists(flagFile) : false)
{
string shaSum = Common.CalculateSHA256Hash(flagFile);
if (serverFlags.ContainsKey(flagName) ? serverFlags[flagName].shaSum == shaSum : false)
{
//Don't send the flag when the SHA sum already matches
return;
}
DarkLog.Debug("Uploading " + Path.GetFileName(flagFile));
using (MessageWriter mw = new MessageWriter())
{
mw.Write<int>((int)FlagMessageType.UPLOAD_FILE);
mw.Write<string>(Settings.fetch.playerName);
mw.Write<string>(Path.GetFileName(flagFile));
mw.Write<byte[]>(File.ReadAllBytes(flagFile));
NetworkWorker.fetch.SendFlagMessage(mw.GetMessageBytes());
}
FlagInfo fi = new FlagInfo();
fi.owner = Settings.fetch.playerName;
fi.shaSum = Common.CalculateSHA256Hash(flagFile);
serverFlags[flagName] = fi;
}
}
private void HandleFlagRespondMessage(FlagRespondMessage flagRespondMessage)
{
serverFlags[flagRespondMessage.flagName] = flagRespondMessage.flagInfo;
string flagFile = Path.Combine(flagPath, flagRespondMessage.flagName);
Texture2D flagTexture = new Texture2D(4, 4);
if (flagTexture.LoadImage(flagRespondMessage.flagData))
{
flagTexture.name = "DarkMultiPlayer/Flags/" + Path.GetFileNameWithoutExtension(flagRespondMessage.flagName);
File.WriteAllBytes(flagFile, flagRespondMessage.flagData);
GameDatabase.TextureInfo ti = new GameDatabase.TextureInfo(flagTexture, false, true, false);
ti.name = flagTexture.name;
bool containsTexture = false;
foreach (GameDatabase.TextureInfo databaseTi in GameDatabase.Instance.databaseTexture)
{
if (databaseTi.name == ti.name)
{
containsTexture = true;
}
}
if (!containsTexture)
{
GameDatabase.Instance.databaseTexture.Add(ti);
}
else
{
GameDatabase.Instance.ReplaceTexture(ti.name, ti);
}
DarkLog.Debug("Loaded " + flagTexture.name);
}
else
{
DarkLog.Debug("Failed to load flag " + flagRespondMessage.flagName);
}
}
public static void Reset()
{
lock (Client.eventLock)
{
if (singleton != null)
{
singleton.workerEnabled = false;
Client.updateEvent.Remove(singleton.Update);
}
singleton = new FlagSyncer();
Client.updateEvent.Add(singleton.Update);
}
}
}
public class FlagRespondMessage
{
public string flagName;
public byte[] flagData;
public FlagInfo flagInfo = new FlagInfo();
}
public class FlagInfo
{
public string shaSum;
public string owner;
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Threading;
#if CLR2
namespace Microsoft.Scripting.Ast.Compiler {
#else
namespace System.Linq.Expressions.Compiler {
#endif
#if CLR2 || SILVERLIGHT
using ILGenerator = OffsetTrackingILGenerator;
#endif
/// <summary>
/// LambdaCompiler is responsible for compiling individual lambda (LambdaExpression). The complete tree may
/// contain multiple lambdas, the Compiler class is reponsible for compiling the whole tree, individual
/// lambdas are then compiled by the LambdaCompiler.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
internal sealed partial class LambdaCompiler {
private delegate void WriteBack();
// Information on the entire lambda tree currently being compiled
private readonly AnalyzedTree _tree;
private readonly ILGenerator _ilg;
// The TypeBuilder backing this method, if any
private readonly TypeBuilder _typeBuilder;
private readonly MethodInfo _method;
// Currently active LabelTargets and their mapping to IL labels
private LabelScopeInfo _labelBlock = new LabelScopeInfo(null, LabelScopeKind.Lambda);
// Mapping of labels used for "long" jumps (jumping out and into blocks)
private readonly Dictionary<LabelTarget, LabelInfo> _labelInfo = new Dictionary<LabelTarget, LabelInfo>();
// The currently active variable scope
private CompilerScope _scope;
// The lambda we are compiling
private readonly LambdaExpression _lambda;
// True if the method's first argument is of type Closure
private readonly bool _hasClosureArgument;
// True if we want to emitting debug symbols
private bool EmitDebugSymbols { get { return _tree.DebugInfoGenerator != null; } }
// Runtime constants bound to the delegate
private readonly BoundConstants _boundConstants;
// Free list of locals, so we reuse them rather than creating new ones
private readonly KeyedQueue<Type, LocalBuilder> _freeLocals = new KeyedQueue<Type, LocalBuilder>();
/// <summary>
/// The value is true if a clearance was emitted and no new sequence point
/// has been emitted since that.
/// </summary>
bool _sequencePointCleared;
/// <summary>
/// Creates a lambda compiler that will compile to a dynamic method
/// </summary>
private LambdaCompiler(AnalyzedTree tree, LambdaExpression lambda) {
Type[] parameterTypes = GetParameterTypes(lambda).AddFirst(typeof(Closure));
#if SILVERLIGHT && CLR2
var method = new DynamicMethod(lambda.Name ?? "lambda_method", lambda.ReturnType, parameterTypes);
#else
var method = new DynamicMethod(lambda.Name ?? "lambda_method", lambda.ReturnType, parameterTypes, true);
#endif
_tree = tree;
_lambda = lambda;
_method = method;
#if CLR2 || SILVERLIGHT
_ilg = new OffsetTrackingILGenerator(method.GetILGenerator());
#else
// In a Win8 immersive process user code is not allowed to access non-W8P framework APIs through
// reflection or RefEmit. Framework code, however, is given an exemption.
// This is to make sure that user code cannot access non-W8P framework APIs via ExpressionTree.
method.ProfileAPICheck = true;
_ilg = method.GetILGenerator();
#endif
_hasClosureArgument = true;
// These are populated by AnalyzeTree/VariableBinder
_scope = tree.Scopes[lambda];
_boundConstants = tree.Constants[lambda];
InitializeMethod();
}
/// <summary>
/// Creates a lambda compiler that will compile into the provided Methodbuilder
/// </summary>
private LambdaCompiler(AnalyzedTree tree, LambdaExpression lambda, MethodBuilder method) {
_hasClosureArgument = tree.Scopes[lambda].NeedsClosure;
Type[] paramTypes = GetParameterTypes(lambda);
if (_hasClosureArgument) {
paramTypes = paramTypes.AddFirst(typeof(Closure));
}
method.SetReturnType(lambda.ReturnType);
method.SetParameters(paramTypes);
var paramNames = lambda.Parameters.Map(p => p.Name);
// parameters are index from 1, with closure argument we need to skip the first arg
int startIndex = _hasClosureArgument ? 2 : 1;
for (int i = 0; i < paramNames.Length; i++) {
method.DefineParameter(i + startIndex, ParameterAttributes.None, paramNames[i]);
}
_tree = tree;
_lambda = lambda;
_typeBuilder = (TypeBuilder)method.DeclaringType;
_method = method;
#if CLR2 || SILVERLIGHT
_ilg = new OffsetTrackingILGenerator(method.GetILGenerator());
#else
_ilg = method.GetILGenerator();
#endif
// These are populated by AnalyzeTree/VariableBinder
_scope = tree.Scopes[lambda];
_boundConstants = tree.Constants[lambda];
InitializeMethod();
}
/// <summary>
/// Creates a lambda compiler for an inlined lambda
/// </summary>
private LambdaCompiler(LambdaCompiler parent, LambdaExpression lambda) {
_tree = parent._tree;
_lambda = lambda;
_method = parent._method;
_ilg = parent._ilg;
_hasClosureArgument = parent._hasClosureArgument;
_typeBuilder = parent._typeBuilder;
_scope = _tree.Scopes[lambda];
_boundConstants = parent._boundConstants;
}
private void InitializeMethod() {
// See if we can find a return label, so we can emit better IL
AddReturnLabel(_lambda);
_boundConstants.EmitCacheConstants(this);
}
public override string ToString() {
return _method.ToString();
}
internal ILGenerator IL {
get { return _ilg; }
}
internal ReadOnlyCollection<ParameterExpression> Parameters {
get { return _lambda.Parameters; }
}
internal bool CanEmitBoundConstants {
get { return _method is DynamicMethod; }
}
#region Compiler entry points
/// <summary>
/// Compiler entry point
/// </summary>
/// <param name="lambda">LambdaExpression to compile.</param>
/// <param name="debugInfoGenerator">Debug info generator.</param>
/// <returns>The compiled delegate.</returns>
internal static Delegate Compile(LambdaExpression lambda, DebugInfoGenerator debugInfoGenerator) {
// 1. Bind lambda
AnalyzedTree tree = AnalyzeLambda(ref lambda);
tree.DebugInfoGenerator = debugInfoGenerator;
// 2. Create lambda compiler
LambdaCompiler c = new LambdaCompiler(tree, lambda);
// 3. Emit
c.EmitLambdaBody();
// 4. Return the delegate.
return c.CreateDelegate();
}
/// <summary>
/// Mutates the MethodBuilder parameter, filling in IL, parameters,
/// and return type.
///
/// (probably shouldn't be modifying parameters/return type...)
/// </summary>
internal static void Compile(LambdaExpression lambda, MethodBuilder method, DebugInfoGenerator debugInfoGenerator) {
// 1. Bind lambda
AnalyzedTree tree = AnalyzeLambda(ref lambda);
tree.DebugInfoGenerator = debugInfoGenerator;
// 2. Create lambda compiler
LambdaCompiler c = new LambdaCompiler(tree, lambda, method);
// 3. Emit
c.EmitLambdaBody();
}
#endregion
private static AnalyzedTree AnalyzeLambda(ref LambdaExpression lambda) {
// Spill the stack for any exception handling blocks or other
// constructs which require entering with an empty stack
lambda = StackSpiller.AnalyzeLambda(lambda);
// Bind any variable references in this lambda
return VariableBinder.Bind(lambda);
}
internal LocalBuilder GetLocal(Type type) {
Debug.Assert(type != null);
LocalBuilder local;
if (_freeLocals.TryDequeue(type, out local)) {
Debug.Assert(type == local.LocalType);
return local;
}
return _ilg.DeclareLocal(type);
}
internal void FreeLocal(LocalBuilder local) {
if (local != null) {
_freeLocals.Enqueue(local.LocalType, local);
}
}
internal LocalBuilder GetNamedLocal(Type type, ParameterExpression variable) {
Debug.Assert(type != null && variable != null);
LocalBuilder lb = _ilg.DeclareLocal(type);
if (EmitDebugSymbols && variable.Name != null) {
_tree.DebugInfoGenerator.SetLocalName(lb, variable.Name);
}
return lb;
}
/// <summary>
/// Gets the argument slot corresponding to the parameter at the given
/// index. Assumes that the method takes a certain number of prefix
/// arguments, followed by the real parameters stored in Parameters
/// </summary>
internal int GetLambdaArgument(int index) {
return index + (_hasClosureArgument ? 1 : 0) + (_method.IsStatic ? 0 : 1);
}
/// <summary>
/// Returns the index-th argument. This method provides access to the actual arguments
/// defined on the lambda itself, and excludes the possible 0-th closure argument.
/// </summary>
internal void EmitLambdaArgument(int index) {
_ilg.EmitLoadArg(GetLambdaArgument(index));
}
internal void EmitClosureArgument() {
Debug.Assert(_hasClosureArgument, "must have a Closure argument");
Debug.Assert(_method.IsStatic, "must be a static method");
_ilg.EmitLoadArg(0);
}
private Delegate CreateDelegate() {
Debug.Assert(_method is DynamicMethod);
return _method.CreateDelegate(_lambda.Type, new Closure(_boundConstants.ToArray(), null));
}
private FieldBuilder CreateStaticField(string name, Type type) {
// We are emitting into someone else's type. We don't want name
// conflicts, so choose a long name that is unlikely to confict.
// Naming scheme chosen here is similar to what the C# compiler
// uses.
return _typeBuilder.DefineField("<ExpressionCompilerImplementationDetails>{" + Interlocked.Increment(ref _Counter) + "}" + name, type, FieldAttributes.Static | FieldAttributes.Private);
}
/// <summary>
/// Creates an unitialized field suitible for private implementation details
/// Works with DynamicMethods or TypeBuilders.
/// </summary>
private MemberExpression CreateLazyInitializedField<T>(string name) {
if (_method is DynamicMethod) {
return Expression.Field(Expression.Constant(new StrongBox<T>(default(T))), "Value");
} else {
return Expression.Field(null, CreateStaticField(name, typeof(T)));
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.Suppression;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.ErrorLogger;
using Microsoft.CodeAnalysis.Extensions;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeFixes
{
public class CodeFixServiceTests
{
[Fact]
public async Task TestGetFirstDiagnosticWithFixAsync()
{
var diagnosticService = new TestDiagnosticAnalyzerService(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap());
var fixers = CreateFixers();
var code = @"
a
";
using (var workspace = await CSharpWorkspaceFactory.CreateWorkspaceFromFileAsync(code))
{
var logger = SpecializedCollections.SingletonEnumerable(new Lazy<IErrorLoggerService>(() => workspace.Services.GetService<IErrorLoggerService>()));
var fixService = new CodeFixService(
diagnosticService, logger, fixers, SpecializedCollections.EmptyEnumerable<Lazy<ISuppressionFixProvider, CodeChangeProviderMetadata>>());
var incrementalAnalyzer = (IIncrementalAnalyzerProvider)diagnosticService;
// register diagnostic engine to solution crawler
var analyzer = incrementalAnalyzer.CreateIncrementalAnalyzer(workspace);
var reference = new MockAnalyzerReference();
var project = workspace.CurrentSolution.Projects.Single().AddAnalyzerReference(reference);
var document = project.Documents.Single();
var unused = await fixService.GetFirstDiagnosticWithFixAsync(document, TextSpan.FromBounds(0, 0), considerSuppressionFixes: false, cancellationToken: CancellationToken.None);
var fixer1 = fixers.Single().Value as MockFixer;
var fixer2 = reference.Fixer as MockFixer;
// check to make sure both of them are called.
Assert.True(fixer1.Called);
Assert.True(fixer2.Called);
}
}
[Fact]
public async Task TestGetCodeFixWithExceptionInRegisterMethod()
{
await GetFirstDiagnosticWithFixAsync(new ErrorCases.ExceptionInRegisterMethod());
await GetAddedFixesAsync(new ErrorCases.ExceptionInRegisterMethod());
}
[Fact]
public async Task TestGetCodeFixWithExceptionInRegisterMethodAsync()
{
await GetFirstDiagnosticWithFixAsync(new ErrorCases.ExceptionInRegisterMethodAsync());
await GetAddedFixesAsync(new ErrorCases.ExceptionInRegisterMethodAsync());
}
[Fact]
public async Task TestGetCodeFixWithExceptionInFixableDiagnosticIds()
{
await GetDefaultFixesAsync(new ErrorCases.ExceptionInFixableDiagnosticIds());
await GetAddedFixesAsync(new ErrorCases.ExceptionInFixableDiagnosticIds());
}
[Fact]
public async Task TestGetCodeFixWithExceptionInFixableDiagnosticIds2()
{
await GetDefaultFixesAsync(new ErrorCases.ExceptionInFixableDiagnosticIds2());
await GetAddedFixesAsync(new ErrorCases.ExceptionInFixableDiagnosticIds2());
}
[Fact]
public async Task TestGetCodeFixWithExceptionInGetFixAllProvider()
{
await GetAddedFixesAsync(new ErrorCases.ExceptionInGetFixAllProvider());
}
public async Task GetDefaultFixesAsync(CodeFixProvider codefix)
{
var tuple = await ServiceSetupAsync(codefix);
using (var workspace = tuple.Item1)
{
Document document;
EditorLayerExtensionManager.ExtensionManager extensionManager;
GetDocumentAndExtensionManager(tuple.Item2, workspace, out document, out extensionManager);
var fixes = await tuple.Item3.GetFixesAsync(document, TextSpan.FromBounds(0, 0), includeSuppressionFixes: true, cancellationToken: CancellationToken.None);
Assert.True(((TestErrorLogger)tuple.Item4).Messages.Count == 1);
string message;
Assert.True(((TestErrorLogger)tuple.Item4).Messages.TryGetValue(codefix.GetType().Name, out message));
}
}
public async Task GetAddedFixesAsync(CodeFixProvider codefix)
{
var tuple = await ServiceSetupAsync(codefix);
using (var workspace = tuple.Item1)
{
Document document;
EditorLayerExtensionManager.ExtensionManager extensionManager;
GetDocumentAndExtensionManager(tuple.Item2, workspace, out document, out extensionManager);
var incrementalAnalyzer = (IIncrementalAnalyzerProvider)tuple.Item2;
var analyzer = incrementalAnalyzer.CreateIncrementalAnalyzer(workspace);
var reference = new MockAnalyzerReference(codefix);
var project = workspace.CurrentSolution.Projects.Single().AddAnalyzerReference(reference);
document = project.Documents.Single();
var fixes = await tuple.Item3.GetFixesAsync(document, TextSpan.FromBounds(0, 0), includeSuppressionFixes: true, cancellationToken: CancellationToken.None);
Assert.True(extensionManager.IsDisabled(codefix));
Assert.False(extensionManager.IsIgnored(codefix));
}
}
public async Task GetFirstDiagnosticWithFixAsync(CodeFixProvider codefix)
{
var tuple = await ServiceSetupAsync(codefix);
using (var workspace = tuple.Item1)
{
Document document;
EditorLayerExtensionManager.ExtensionManager extensionManager;
GetDocumentAndExtensionManager(tuple.Item2, workspace, out document, out extensionManager);
var unused = await tuple.Item3.GetFirstDiagnosticWithFixAsync(document, TextSpan.FromBounds(0, 0), considerSuppressionFixes: false, cancellationToken: CancellationToken.None);
Assert.True(extensionManager.IsDisabled(codefix));
Assert.False(extensionManager.IsIgnored(codefix));
}
}
private static async Task<Tuple<TestWorkspace, TestDiagnosticAnalyzerService, CodeFixService, IErrorLoggerService>> ServiceSetupAsync(CodeFixProvider codefix)
{
var diagnosticService = new TestDiagnosticAnalyzerService(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap());
var fixers = SpecializedCollections.SingletonEnumerable(
new Lazy<CodeFixProvider, CodeChangeProviderMetadata>(
() => codefix,
new CodeChangeProviderMetadata("Test", languages: LanguageNames.CSharp)));
var code = @"class Program { }";
var workspace = await CSharpWorkspaceFactory.CreateWorkspaceFromFileAsync(code);
var logger = SpecializedCollections.SingletonEnumerable(new Lazy<IErrorLoggerService>(() => new TestErrorLogger()));
var errorLogger = logger.First().Value;
var fixService = new CodeFixService(
diagnosticService, logger, fixers, SpecializedCollections.EmptyEnumerable<Lazy<ISuppressionFixProvider, CodeChangeProviderMetadata>>());
return Tuple.Create(workspace, diagnosticService, fixService, errorLogger);
}
private static void GetDocumentAndExtensionManager(TestDiagnosticAnalyzerService diagnosticService, TestWorkspace workspace, out Document document, out EditorLayerExtensionManager.ExtensionManager extensionManager)
{
var incrementalAnalyzer = (IIncrementalAnalyzerProvider)diagnosticService;
// register diagnostic engine to solution crawler
var analyzer = incrementalAnalyzer.CreateIncrementalAnalyzer(workspace);
var reference = new MockAnalyzerReference();
var project = workspace.CurrentSolution.Projects.Single().AddAnalyzerReference(reference);
document = project.Documents.Single();
extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>() as EditorLayerExtensionManager.ExtensionManager;
}
private IEnumerable<Lazy<CodeFixProvider, CodeChangeProviderMetadata>> CreateFixers()
{
return SpecializedCollections.SingletonEnumerable(
new Lazy<CodeFixProvider, CodeChangeProviderMetadata>(() => new MockFixer(), new CodeChangeProviderMetadata("Test", languages: LanguageNames.CSharp)));
}
internal class MockFixer : CodeFixProvider
{
public const string Id = "MyDiagnostic";
public bool Called = false;
public sealed override ImmutableArray<string> FixableDiagnosticIds
{
get { return ImmutableArray.Create(Id); }
}
public sealed override Task RegisterCodeFixesAsync(CodeFixContext context)
{
Called = true;
return SpecializedTasks.EmptyTask;
}
}
private class MockAnalyzerReference : AnalyzerReference, ICodeFixProviderFactory
{
public readonly CodeFixProvider Fixer;
public readonly MockDiagnosticAnalyzer Analyzer = new MockDiagnosticAnalyzer();
public MockAnalyzerReference()
{
Fixer = new MockFixer();
}
public MockAnalyzerReference(CodeFixProvider codeFix)
{
Fixer = codeFix;
}
public override string Display
{
get
{
return "MockAnalyzerReference";
}
}
public override string FullPath
{
get
{
return string.Empty;
}
}
public override object Id
{
get
{
return "MockAnalyzerReference";
}
}
public override ImmutableArray<DiagnosticAnalyzer> GetAnalyzers(string language)
{
return ImmutableArray.Create<DiagnosticAnalyzer>(Analyzer);
}
public override ImmutableArray<DiagnosticAnalyzer> GetAnalyzersForAllLanguages()
{
return ImmutableArray<DiagnosticAnalyzer>.Empty;
}
public ImmutableArray<CodeFixProvider> GetFixers()
{
return ImmutableArray.Create<CodeFixProvider>(Fixer);
}
public class MockDiagnosticAnalyzer : DiagnosticAnalyzer
{
private DiagnosticDescriptor _descriptor = new DiagnosticDescriptor(MockFixer.Id, "MockDiagnostic", "MockDiagnostic", "InternalCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(_descriptor);
}
}
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxTreeAction(c =>
{
c.ReportDiagnostic(Diagnostic.Create(_descriptor, c.Tree.GetLocation(TextSpan.FromBounds(0, 0))));
});
}
}
}
internal class TestErrorLogger : IErrorLoggerService
{
public Dictionary<string, string> Messages = new Dictionary<string, string>();
public void LogException(object source, Exception exception)
{
Messages.Add(source.GetType().Name, ToLogFormat(exception));
}
public bool TryLogException(object source, Exception exception)
{
try
{
Messages.Add(source.GetType().Name, ToLogFormat(exception));
return true;
}
catch (Exception)
{
return false;
}
}
private static string ToLogFormat(Exception exception)
{
return exception.Message + Environment.NewLine + exception.StackTrace;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
namespace IxMilia.Dxf.Generator
{
[Generator]
public class ObjectGenerator : GeneratorBase, ISourceGenerator
{
private XElement _xml;
private string _xmlns;
private IEnumerable<XElement> _objects;
public const string ObjectNamespace = "IxMilia.Dxf.Objects";
public void Initialize(GeneratorInitializationContext context)
{
}
public void Execute(GeneratorExecutionContext context)
{
var specText = context.AdditionalFiles.Single(f => Path.GetFileName(f.Path) == "ObjectsSpec.xml").GetText().ToString();
_xml = XDocument.Parse(specText).Root;
_xmlns = _xml.Name.NamespaceName;
_objects = _xml.Elements(XName.Get("Object", _xmlns)).Where(x => x.Attribute("Name").Value != "DxfObject");
OutputDxfObjectType(context);
OutputDxfObject(context);
OutputDxfObjects(context);
}
private void OutputDxfObjectType(GeneratorExecutionContext context)
{
CreateNewFile(ObjectNamespace, "System", "System.Collections.Generic", "System.Linq", "IxMilia.Dxf.Collections");
IncreaseIndent();
AppendLine("public enum DxfObjectType");
AppendLine("{");
IncreaseIndent();
var enumNames = _objects.Select(o => ObjectType(o)).Distinct().OrderBy(o => o);
var enumStr = string.Join($",{Environment.NewLine} ", enumNames);
AppendLine(enumStr);
DecreaseIndent();
AppendLine("}");
DecreaseIndent();
FinishFile();
WriteFile(context, "DxfObjectTypeGenerated.cs");
}
private void OutputDxfObject(GeneratorExecutionContext context)
{
var baseObject = _xml.Elements(XName.Get("Object", _xmlns)).Where(x => Name(x) == "DxfObject").Single();
CreateNewFile(ObjectNamespace, "System", "System.Collections.Generic", "System.Linq", "IxMilia.Dxf.Collections");
IncreaseIndent();
AppendLine("/// <summary>");
AppendLine("/// DxfObject class");
AppendLine("/// </summary>");
AppendLine("public partial class DxfObject : IDxfItemInternal");
AppendLine("{");
IncreaseIndent();
AppendLine("DxfHandle IDxfItemInternal.Handle { get; set; }");
AppendLine("DxfHandle IDxfItemInternal.OwnerHandle { get; set; }");
AppendLine("public IDxfItem Owner { get; private set;}");
AppendLine();
AppendLine("void IDxfItemInternal.SetOwner(IDxfItem owner)");
AppendLine("{");
AppendLine(" Owner = owner;");
AppendLine("}");
AppendLine();
AppendLine("IEnumerable<DxfPointer> IDxfItemInternal.GetPointers()");
AppendLine("{");
AppendLine(" yield break;");
AppendLine("}");
AppendLine();
AppendLine("IEnumerable<IDxfItemInternal> IDxfItemInternal.GetChildItems()");
AppendLine("{");
AppendLine(" return ((IDxfItemInternal)this).GetPointers().Select(p => (IDxfItemInternal)p.Item);");
AppendLine("}");
//
// ObjectTypeString
//
AppendLine();
AppendLine("public string ObjectTypeString");
AppendLine("{");
AppendLine(" get");
AppendLine(" {");
AppendLine(" switch (ObjectType)");
AppendLine(" {");
foreach (var obj in _objects)
{
var typeString = TypeString(obj);
var commaIndex = typeString.IndexOf(',');
if (commaIndex >= 0)
{
typeString = typeString.Substring(0, commaIndex);
}
if (!string.IsNullOrEmpty(typeString))
{
AppendLine($" case DxfObjectType.{ObjectType(obj)}:");
AppendLine($" return \"{typeString}\";");
}
}
AppendLine(" default:");
AppendLine(" throw new NotImplementedException();");
AppendLine(" }");
AppendLine(" }");
AppendLine("}");
//
// Copy constructor
//
AppendLine();
AppendLine("protected DxfObject(DxfObject other)");
AppendLine(" : this()");
AppendLine("{");
AppendLine("}");
//
// Initialize
//
AppendLine();
AppendLine("protected virtual void Initialize()");
AppendLine("{");
AppendLine("}");
//
// AddValuePairs
//
AppendLine();
AppendLine("protected virtual void AddValuePairs(List<DxfCodePair> pairs, DxfAcadVersion version, bool outputHandles, bool writeXData)");
AppendLine("{");
AppendLine(" pairs.Add(new DxfCodePair(0, ObjectTypeString));");
foreach (var line in GetWriteCommands(baseObject))
{
if (string.IsNullOrWhiteSpace(line))
{
AppendLine();
}
else
{
AppendLine(" " + line);
}
}
AppendLine("}");
//
// TrySetPair
//
AppendLine();
AppendLine("internal virtual bool TrySetPair(DxfCodePair pair)");
AppendLine("{");
IncreaseIndent();
AppendLine("switch (pair.Code)");
AppendLine("{");
IncreaseIndent();
AppendLine("case 5:");
AppendLine(" ((IDxfItemInternal)this).Handle = HandleString(pair.StringValue);");
AppendLine(" break;");
AppendLine("case 330:");
AppendLine(" ((IDxfItemInternal)this).OwnerHandle = HandleString(pair.StringValue);");
AppendLine(" break;");
foreach (var propertyGroup in GetProperties(baseObject).Where(p => !ProtectedSet(p)).GroupBy(p => Code(p)).OrderBy(p => p.Key))
{
var code = propertyGroup.Key;
var property = propertyGroup.Single();
var name = Name(property);
var codeType = DxfCodePair.ExpectedType(code);
var codeTypeValue = TypeToString(codeType);
var assignCode = AllowMultiples(property)
? string.Format("this.{0}.Add(", Name(property))
: string.Format("this.{0} = ", Name(property));
var assignSuffix = AllowMultiples(property)
? ")"
: "";
var readConverter = ReadConverter(property);
AppendLine($"case {code}:");
AppendLine($" {assignCode}{string.Format(readConverter, $"pair.{codeTypeValue}")}{assignSuffix};");
AppendLine(" break;");
}
AppendLine("default:");
AppendLine(" return false;");
DecreaseIndent();
AppendLine("}"); // end switch
AppendLine();
AppendLine("return true;");
DecreaseIndent();
AppendLine("}"); // end method
//
// FromBuffer
//
AppendLine();
AppendLine("internal static DxfObject FromBuffer(DxfCodePairBufferReader buffer)");
AppendLine("{");
IncreaseIndent();
AppendLine("var first = buffer.Peek();");
AppendLine("buffer.Advance();");
AppendLine("DxfObject obj;");
AppendLine("switch (first.StringValue)");
AppendLine("{");
IncreaseIndent();
foreach (var obj in _objects)
{
var typeString = TypeString(obj);
if (!string.IsNullOrEmpty(typeString))
{
AppendLine($"case \"{typeString}\":");
AppendLine($" obj = new {Name(obj)}();");
AppendLine(" break;");
}
}
AppendLine("default:");
AppendLine(" SwallowObject(buffer);");
AppendLine(" obj = null;");
AppendLine(" break;");
DecreaseIndent();
AppendLine("}"); // end switch
AppendLine();
AppendLine("if (obj != null)");
AppendLine("{");
AppendLine(" obj = obj.PopulateFromBuffer(buffer);");
AppendLine("}");
AppendLine();
AppendLine("return obj;");
DecreaseIndent();
AppendLine("}"); // end method
DecreaseIndent();
AppendLine("}"); // end class
DecreaseIndent();
FinishFile();
WriteFile(context, "DxfObjectGenerated.cs");
}
private void OutputDxfObjects(GeneratorExecutionContext context)
{
foreach (var obj in _objects)
{
var className = Name(obj);
CreateNewFile(ObjectNamespace, "System", "System.Collections.Generic", "System.Diagnostics", "System.Linq", "IxMilia.Dxf.Collections", "IxMilia.Dxf.Entities");
IncreaseIndent();
OutputSingleDxfObject(obj);
DecreaseIndent();
FinishFile();
WriteFile(context, className + "Generated.cs");
}
}
private void OutputSingleDxfObject(XElement obj)
{
AppendLine("/// <summary>");
AppendLine($"/// {Name(obj)} class");
AppendLine("/// </summary>");
var baseClass = BaseClass(obj, "DxfObject");
if (GetPointers(obj).Any())
{
baseClass += ", IDxfItemInternal";
}
AppendLine($"{Accessibility(obj)} partial class {Name(obj)} : {baseClass}");
AppendLine("{");
IncreaseIndent();
AppendLine($"public override DxfObjectType ObjectType {{ get {{ return DxfObjectType.{ObjectType(obj)}; }} }}");
AppendMinAndMaxVersions(obj);
AppendPointers(obj);
AppendProperties(obj);
AppendFlags(obj);
AppendDefaultConstructor(obj);
AppendParameterizedConstructors(obj);
AppendCopyConstructor(obj);
AppendInitializeMethod(obj);
AppendAddValuePairsMethod(obj);
//
// TrySetPair
//
if (GetPropertiesAndPointers(obj).Any() && GenerateReaderFunction(obj))
{
// handle codes with multiple values (but only positive codes (negative codes mean special handling))
var multiCodeProperties = GetProperties(obj)
.Where(p => !ProtectedSet(p))
.GroupBy(p => Code(p))
.Where(p => p.Key > 0 && p.Count() > 1)
.OrderBy(p => p.Key);
if (multiCodeProperties.Any())
{
AppendLine();
AppendLine("// This object has vales that share codes between properties and these counters are used to know which property to");
AppendLine("// assign to in TrySetPair() below.");
}
foreach (var propertyGroup in multiCodeProperties)
{
AppendLine($"private int _code_{propertyGroup.Key}_index = 0; // shared by properties {string.Join(", ", propertyGroup.Select(p => Name(p)))}");
}
}
AppendTrySetPairMethod(obj);
DecreaseIndent();
AppendLine("}"); // end class
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Security;
using System.Security.Permissions;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Hosting;
using Microsoft.Win32.SafeHandles;
namespace Yaws
{
class Request : SimpleWorkerRequest
{
static char[] badPathChars = new char[] { '%', '>', '<', ':', '\\' };
static string[] defaultFileNames = new string[] { "default.aspx", "default.htm", "default.html" };
static string[] restrictedDirs = new string[] {
"/bin",
"/app_browsers",
"/app_code",
"/app_data",
"/app_localresources",
"/app_globalresources",
"/app_webreferences" };
const int MaxChunkLength = 64 * 1024;
Server _server;
Host _host;
Connection _connection;
// security permission to Assert remoting calls to _connection
IStackWalk _connectionPermission = new PermissionSet(PermissionState.Unrestricted);
// raw request data
const int maxHeaderBytes = 32 * 1024;
byte[] _headerBytes;
int _startHeadersOffset;
int _endHeadersOffset;
List<ByteString> _headerByteStrings;
// parsed request data
bool _isClientScriptPath;
string _verb;
string _url;
string _prot;
string _path;
string _filePath;
string _pathInfo;
string _pathTranslated;
string _queryString;
byte[] _queryStringBytes;
int _contentLength;
int _preloadedContentLength;
byte[] _preloadedContent;
string _allRawHeaders;
string[][] _unknownRequestHeaders;
string[] _knownRequestHeaders;
bool _specialCaseStaticFileHeaders;
// cached response
bool _headersSent;
int _responseStatus;
StringBuilder _responseHeadersBuilder;
List<byte[]> _responseBodyBytes;
public Request(Server server, Host host, Connection connection)
: base(String.Empty, String.Empty, null)
{
_server = server;
_host = host;
_connection = connection;
}
public void Process()
{
// read the request
if (!TryParseRequest())
{
return;
}
// 100 response to POST
if (_verb == "POST" && _contentLength > 0 && _preloadedContentLength < _contentLength)
{
_connection.Write100Continue();
}
// special case for client script
if (_isClientScriptPath)
{
_connection.WriteEntireResponseFromFile(_host.PhysicalClientScriptPath + _path.Substring(_host.NormalizedClientScriptPath.Length), false);
return;
}
// deny access to code, bin, etc.
if (IsRequestForRestrictedDirectory())
{
_connection.WriteErrorAndClose(403);
return;
}
// special case for directory listing
if (ProcessDirectoryListingRequest())
{
return;
}
PrepareResponse();
// Hand the processing over to HttpRuntime
HttpRuntime.ProcessRequest(this);
}
void Reset()
{
_headerBytes = null;
_startHeadersOffset = 0;
_endHeadersOffset = 0;
_headerByteStrings = null;
_isClientScriptPath = false;
_verb = null;
_url = null;
_prot = null;
_path = null;
_filePath = null;
_pathInfo = null;
_pathTranslated = null;
_queryString = null;
_queryStringBytes = null;
_contentLength = 0;
_preloadedContentLength = 0;
_preloadedContent = null;
_allRawHeaders = null;
_unknownRequestHeaders = null;
_knownRequestHeaders = null;
_specialCaseStaticFileHeaders = false;
}
bool TryParseRequest()
{
Reset();
ReadAllHeaders();
if (_headerBytes == null || _endHeadersOffset < 0 ||
_headerByteStrings == null || _headerByteStrings.Count == 0)
{
_connection.WriteErrorAndClose(400);
return false;
}
ParseRequestLine();
// Check for bad path
if (IsBadPath())
{
_connection.WriteErrorAndClose(400);
return false;
}
// Check if the path is not well formed or is not for the current app
if (!_host.IsVirtualPathInApp(_path, out _isClientScriptPath))
{
_connection.WriteErrorAndClose(404);
return false;
}
ParseHeaders();
ParsePostedContent();
return true;
}
bool TryReadAllHeaders()
{
// read the first packet (up to 32K)
byte[] headerBytes = _connection.ReadRequestBytes(maxHeaderBytes);
if (headerBytes == null || headerBytes.Length == 0)
return false;
if (_headerBytes != null)
{
// previous partial read
int len = headerBytes.Length + _headerBytes.Length;
if (len > maxHeaderBytes)
return false;
byte[] bytes = new byte[len];
Buffer.BlockCopy(_headerBytes, 0, bytes, 0, _headerBytes.Length);
Buffer.BlockCopy(headerBytes, 0, bytes, _headerBytes.Length, headerBytes.Length);
_headerBytes = bytes;
}
else
{
_headerBytes = headerBytes;
}
// start parsing
_startHeadersOffset = -1;
_endHeadersOffset = -1;
_headerByteStrings = new List<ByteString>();
// find the end of headers
ByteParser parser = new ByteParser(_headerBytes);
for (; ; )
{
ByteString line = parser.ReadLine();
if (line == null)
{
break;
}
if (_startHeadersOffset < 0)
{
_startHeadersOffset = parser.CurrentOffset;
}
if (line.IsEmpty)
{
_endHeadersOffset = parser.CurrentOffset;
break;
}
_headerByteStrings.Add(line);
}
return true;
}
void ReadAllHeaders()
{
_headerBytes = null;
do
{
if (!TryReadAllHeaders())
{
// something bad happened
break;
}
}
while (_endHeadersOffset < 0); // found \r\n\r\n
}
void ParseRequestLine()
{
ByteString requestLine = _headerByteStrings[0];
ByteString[] elems = requestLine.Split(' ');
if (elems == null || elems.Length < 2 || elems.Length > 3)
{
_connection.WriteErrorAndClose(400);
return;
}
_verb = elems[0].GetString();
ByteString urlBytes = elems[1];
_url = urlBytes.GetString();
if (elems.Length == 3)
{
_prot = elems[2].GetString();
}
else
{
_prot = "HTTP/1.0";
}
// query string
int iqs = urlBytes.IndexOf('?');
if (iqs > 0)
{
_queryStringBytes = urlBytes.Substring(iqs + 1).GetBytes();
}
else
{
_queryStringBytes = new byte[0];
}
iqs = _url.IndexOf('?');
if (iqs > 0)
{
_path = _url.Substring(0, iqs);
_queryString = _url.Substring(iqs + 1);
}
else
{
_path = _url;
_queryStringBytes = new byte[0];
}
// url-decode path
if (_path.IndexOf('%') >= 0)
{
_path = HttpUtility.UrlDecode(_path, Encoding.UTF8);
iqs = _url.IndexOf('?');
if (iqs >= 0)
{
_url = _path + _url.Substring(iqs);
}
else
{
_url = _path;
}
}
// path info
int lastDot = _path.LastIndexOf('.');
int lastSlh = _path.LastIndexOf('/');
if (lastDot >= 0 && lastSlh >= 0 && lastDot < lastSlh)
{
int ipi = _path.IndexOf('/', lastDot);
_filePath = _path.Substring(0, ipi);
_pathInfo = _path.Substring(ipi);
}
else
{
_filePath = _path;
_pathInfo = String.Empty;
}
_pathTranslated = MapPath(_filePath);
}
bool IsBadPath()
{
if (_path.IndexOfAny(badPathChars) >= 0)
{
return true;
}
if (CultureInfo.InvariantCulture.CompareInfo.IndexOf(_path, "..", CompareOptions.Ordinal) >= 0)
{
return true;
}
if (CultureInfo.InvariantCulture.CompareInfo.IndexOf(_path, "//", CompareOptions.Ordinal) >= 0)
{
return true;
}
return false;
}
void ParseHeaders()
{
_knownRequestHeaders = new string[RequestHeaderMaximum];
// construct unknown headers as array list of name1,value1,...
var headers = new List<string>();
for (int i = 1; i < _headerByteStrings.Count; i++)
{
string s = _headerByteStrings[i].GetString();
int c = s.IndexOf(':');
if (c >= 0)
{
string name = s.Substring(0, c).Trim();
string value = s.Substring(c + 1).Trim();
// remember
int knownIndex = GetKnownRequestHeaderIndex(name);
if (knownIndex >= 0)
{
_knownRequestHeaders[knownIndex] = value;
}
else
{
headers.Add(name);
headers.Add(value);
}
}
}
// copy to array unknown headers
int n = headers.Count / 2;
_unknownRequestHeaders = new string[n][];
int j = 0;
for (int i = 0; i < n; i++)
{
_unknownRequestHeaders[i] = new string[2];
_unknownRequestHeaders[i][0] = headers[j++];
_unknownRequestHeaders[i][1] = headers[j++];
}
// remember all raw headers as one string
if (_headerByteStrings.Count > 1)
{
_allRawHeaders = Encoding.UTF8.GetString(_headerBytes, _startHeadersOffset, _endHeadersOffset - _startHeadersOffset);
}
else
{
_allRawHeaders = String.Empty;
}
}
void ParsePostedContent()
{
_contentLength = 0;
_preloadedContentLength = 0;
string contentLengthValue = _knownRequestHeaders[HttpWorkerRequest.HeaderContentLength];
if (contentLengthValue != null)
{
try
{
_contentLength = Int32.Parse(contentLengthValue, CultureInfo.InvariantCulture);
}
catch
{
}
}
if (_headerBytes.Length > _endHeadersOffset)
{
_preloadedContentLength = _headerBytes.Length - _endHeadersOffset;
if (_preloadedContentLength > _contentLength)
{
_preloadedContentLength = _contentLength; // don't read more than the content-length
}
if (_preloadedContentLength > 0)
{
_preloadedContent = new byte[_preloadedContentLength];
Buffer.BlockCopy(_headerBytes, _endHeadersOffset, _preloadedContent, 0, _preloadedContentLength);
}
}
}
void SkipAllPostedContent()
{
if (_contentLength > 0 && _preloadedContentLength < _contentLength)
{
int bytesRemaining = (_contentLength - _preloadedContentLength);
while (bytesRemaining > 0)
{
byte[] bytes = _connection.ReadRequestBytes(bytesRemaining);
if (bytes == null || bytes.Length == 0)
{
return;
}
bytesRemaining -= bytes.Length;
}
}
}
bool IsRequestForRestrictedDirectory()
{
String p = CultureInfo.InvariantCulture.TextInfo.ToLower(_path);
if (_host.VirtualPath != "/")
{
p = p.Substring(_host.VirtualPath.Length);
}
foreach (String dir in restrictedDirs)
{
if (p.StartsWith(dir, StringComparison.Ordinal))
{
if (p.Length == dir.Length || p[dir.Length] == '/')
{
return true;
}
}
}
return false;
}
bool ProcessDirectoryListingRequest()
{
if (_verb != "GET")
{
return false;
}
String dirPathTranslated = _pathTranslated;
if (_pathInfo.Length > 0)
{
// directory path can never have pathInfo
dirPathTranslated = MapPath(_path);
}
if (!Directory.Exists(dirPathTranslated))
{
return false;
}
// have to redirect /foo to /foo/ to allow relative links to work
if (!_path.EndsWith("/", StringComparison.Ordinal))
{
string newPath = _path + "/";
string location = "Location: " + UrlEncodeRedirect(newPath) + "\r\n";
string body = "<html><head><title>Object moved</title></head><body>\r\n" +
"<h2>Object moved to <a href='" + newPath + "'>here</a>.</h2>\r\n" +
"</body></html>\r\n";
_connection.WriteEntireResponseFromString(302, location, body, false);
return true;
}
// check for the default file
foreach (string filename in defaultFileNames)
{
string defaultFilePath = dirPathTranslated + "\\" + filename;
if (File.Exists(defaultFilePath))
{
// pretend the request is for the default file path
_path += filename;
_filePath = _path;
_url = (_queryString != null) ? (_path + "?" + _queryString) : _path;
_pathTranslated = defaultFilePath;
return false; // go through normal processing
}
}
// get all files and subdirs
FileSystemInfo[] infos = null;
try
{
infos = (new DirectoryInfo(dirPathTranslated)).GetFileSystemInfos();
}
catch
{
}
// determine if parent is appropriate
string parentPath = null;
if (_path.Length > 1)
{
int i = _path.LastIndexOf('/', _path.Length - 2);
parentPath = (i > 0) ? _path.Substring(0, i) : "/";
if (!_host.IsVirtualPathInApp(parentPath))
{
parentPath = null;
}
}
_connection.WriteEntireResponseFromString(200, "Content-type: text/html; charset=utf-8\r\n",
Messages.FormatDirectoryListing(_path, parentPath, infos),
false);
return true;
}
static char[] IntToHex = new char[16] {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
static string UrlEncodeRedirect(string path)
{
// this method mimics the logic in HttpResponse.Redirect (which relies on internal methods)
// count non-ascii characters
byte[] bytes = Encoding.UTF8.GetBytes(path);
int count = bytes.Length;
int countNonAscii = 0;
for (int i = 0; i < count; i++)
{
if ((bytes[i] & 0x80) != 0)
{
countNonAscii++;
}
}
// encode all non-ascii characters using UTF-8 %XX
if (countNonAscii > 0)
{
// expand not 'safe' characters into %XX, spaces to +s
byte[] expandedBytes = new byte[count + countNonAscii * 2];
int pos = 0;
for (int i = 0; i < count; i++)
{
byte b = bytes[i];
if ((b & 0x80) == 0)
{
expandedBytes[pos++] = b;
}
else
{
expandedBytes[pos++] = (byte)'%';
expandedBytes[pos++] = (byte)IntToHex[(b >> 4) & 0xf];
expandedBytes[pos++] = (byte)IntToHex[b & 0xf];
}
}
path = Encoding.ASCII.GetString(expandedBytes);
}
// encode spaces into %20
if (path.IndexOf(' ') >= 0)
{
path = path.Replace(" ", "%20");
}
return path;
}
void PrepareResponse()
{
_headersSent = false;
_responseStatus = 200;
_responseHeadersBuilder = new StringBuilder();
_responseBodyBytes = new List<byte[]>();
}
///////////////////////////////////////////////////////////////////////////////////////////////
// Implementation of HttpWorkerRequest
public override string GetUriPath()
{
return _path;
}
public override string GetQueryString()
{
return _queryString;
}
public override byte[] GetQueryStringRawBytes()
{
return _queryStringBytes;
}
public override string GetRawUrl()
{
return _url;
}
public override string GetHttpVerbName()
{
return _verb;
}
public override string GetHttpVersion()
{
return _prot;
}
public override string GetRemoteAddress()
{
_connectionPermission.Assert();
return _connection.RemoteIP;
}
public override int GetRemotePort()
{
return 0;
}
public override string GetLocalAddress()
{
_connectionPermission.Assert();
return _connection.LocalIP;
}
public override string GetServerName()
{
string localAddress = GetLocalAddress();
if (localAddress.Equals("127.0.0.1"))
{
return "localhost";
}
return localAddress;
}
public override int GetLocalPort()
{
return _host.Port;
}
public override string GetFilePath()
{
return _filePath;
}
public override string GetFilePathTranslated()
{
return _pathTranslated;
}
public override string GetPathInfo()
{
return _pathInfo;
}
public override string GetAppPath()
{
return _host.VirtualPath;
}
public override string GetAppPathTranslated()
{
return _host.PhysicalPath;
}
public override byte[] GetPreloadedEntityBody()
{
return _preloadedContent;
}
public override bool IsEntireEntityBodyIsPreloaded()
{
return (_contentLength == _preloadedContentLength);
}
public override int ReadEntityBody(byte[] buffer, int size)
{
int bytesRead = 0;
_connectionPermission.Assert();
byte[] bytes = _connection.ReadRequestBytes(size);
if (bytes != null && bytes.Length > 0)
{
bytesRead = bytes.Length;
Buffer.BlockCopy(bytes, 0, buffer, 0, bytesRead);
}
return bytesRead;
}
public override string GetKnownRequestHeader(int index)
{
return _knownRequestHeaders[index];
}
public override string GetUnknownRequestHeader(string name)
{
int n = _unknownRequestHeaders.Length;
for (int i = 0; i < n; i++)
{
if (string.Compare(name, _unknownRequestHeaders[i][0], StringComparison.OrdinalIgnoreCase) == 0)
{
return _unknownRequestHeaders[i][1];
}
}
return null;
}
public override string[][] GetUnknownRequestHeaders()
{
return _unknownRequestHeaders;
}
public override string GetServerVariable(string name)
{
string s = String.Empty;
switch (name)
{
case "ALL_RAW":
s = _allRawHeaders;
break;
case "SERVER_PROTOCOL":
s = _prot;
break;
case "SERVER_SOFTWARE":
s = "Yaws/" + Messages.VersionString;
break;
}
return s;
}
public override string MapPath(string path)
{
string mappedPath = String.Empty;
bool isClientScriptPath = false;
if (path == null || path.Length == 0 || path.Equals("/"))
{
// asking for the site root
if (_host.VirtualPath == "/")
{
// app at the site root
mappedPath = _host.PhysicalPath;
}
else
{
// unknown site root - don't point to app root to avoid double config inclusion
mappedPath = Environment.SystemDirectory;
}
}
else if (_host.IsVirtualPathAppPath(path))
{
// application path
mappedPath = _host.PhysicalPath;
}
else if (_host.IsVirtualPathInApp(path, out isClientScriptPath))
{
if (isClientScriptPath)
{
mappedPath = _host.PhysicalClientScriptPath + path.Substring(_host.NormalizedClientScriptPath.Length);
}
else
{
// inside app but not the app path itself
mappedPath = _host.PhysicalPath + path.Substring(_host.NormalizedVirtualPath.Length);
}
}
else
{
// outside of app -- make relative to app path
if (path.StartsWith("/", StringComparison.Ordinal))
{
mappedPath = _host.PhysicalPath + path.Substring(1);
}
else
{
mappedPath = _host.PhysicalPath + path;
}
}
mappedPath = mappedPath.Replace('/', '\\');
if (mappedPath.EndsWith("\\", StringComparison.Ordinal) && !mappedPath.EndsWith(":\\", StringComparison.Ordinal))
{
mappedPath = mappedPath.Substring(0, mappedPath.Length - 1);
}
return mappedPath;
}
public override void SendStatus(int statusCode, string statusDescription)
{
_responseStatus = statusCode;
}
public override void SendKnownResponseHeader(int index, string value)
{
if (_headersSent)
{
return;
}
switch (index)
{
case HttpWorkerRequest.HeaderServer:
case HttpWorkerRequest.HeaderDate:
case HttpWorkerRequest.HeaderConnection:
// ignore these
return;
case HttpWorkerRequest.HeaderAcceptRanges:
if (value == "bytes")
{
// use this header to detect when we're processing a static file
_specialCaseStaticFileHeaders = true;
return;
}
break;
case HttpWorkerRequest.HeaderExpires:
case HttpWorkerRequest.HeaderLastModified:
if (_specialCaseStaticFileHeaders)
{
// NOTE: Ignore these for static files. These are generated
// by the StaticFileHandler, but they shouldn't be.
return;
}
break;
}
_responseHeadersBuilder.Append(GetKnownResponseHeaderName(index));
_responseHeadersBuilder.Append(": ");
_responseHeadersBuilder.Append(value);
_responseHeadersBuilder.Append("\r\n");
}
public override void SendUnknownResponseHeader(string name, string value)
{
if (_headersSent)
return;
_responseHeadersBuilder.Append(name);
_responseHeadersBuilder.Append(": ");
_responseHeadersBuilder.Append(value);
_responseHeadersBuilder.Append("\r\n");
}
public override void SendCalculatedContentLength(int contentLength)
{
if (!_headersSent)
{
_responseHeadersBuilder.Append("Content-Length: ");
_responseHeadersBuilder.Append(contentLength.ToString(CultureInfo.InvariantCulture));
_responseHeadersBuilder.Append("\r\n");
}
}
public override bool HeadersSent()
{
return _headersSent;
}
public override bool IsClientConnected()
{
_connectionPermission.Assert();
return _connection.Connected;
}
public override void CloseConnection()
{
_connectionPermission.Assert();
_connection.Close();
}
public override void SendResponseFromMemory(byte[] data, int length)
{
if (length > 0)
{
byte[] bytes = new byte[length];
Buffer.BlockCopy(data, 0, bytes, 0, length);
_responseBodyBytes.Add(bytes);
}
}
public override void SendResponseFromFile(string filename, long offset, long length)
{
if (length == 0)
{
return;
}
FileStream f = null;
try
{
f = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
SendResponseFromFileStream(f, offset, length);
}
finally
{
if (f != null)
{
f.Close();
}
}
}
public override void SendResponseFromFile(IntPtr handle, long offset, long length)
{
if (length == 0)
{
return;
}
FileStream f = null;
try
{
SafeFileHandle sfh = new SafeFileHandle(handle, false);
f = new FileStream(sfh, FileAccess.Read);
SendResponseFromFileStream(f, offset, length);
}
finally
{
if (f != null)
{
f.Close();
f = null;
}
}
}
void SendResponseFromFileStream(FileStream f, long offset, long length)
{
long fileSize = f.Length;
if (length == -1)
{
length = fileSize - offset;
}
if (length == 0 || offset < 0 || length > fileSize - offset)
{
return;
}
if (offset > 0)
{
f.Seek(offset, SeekOrigin.Begin);
}
if (length <= MaxChunkLength)
{
byte[] fileBytes = new byte[(int)length];
int bytesRead = f.Read(fileBytes, 0, (int)length);
SendResponseFromMemory(fileBytes, bytesRead);
}
else
{
byte[] chunk = new byte[MaxChunkLength];
int bytesRemaining = (int)length;
while (bytesRemaining > 0)
{
int bytesToRead = (bytesRemaining < MaxChunkLength) ? bytesRemaining : MaxChunkLength;
int bytesRead = f.Read(chunk, 0, bytesToRead);
SendResponseFromMemory(chunk, bytesRead);
bytesRemaining -= bytesRead;
// flush to release keep memory
if ((bytesRemaining > 0) && (bytesRead > 0))
{
FlushResponse(false);
}
}
}
}
public override void FlushResponse(bool finalFlush)
{
_connectionPermission.Assert();
if (!_headersSent)
{
_connection.WriteHeaders(_responseStatus, _responseHeadersBuilder.ToString());
_headersSent = true;
}
for (int i = 0; i < _responseBodyBytes.Count; i++)
{
byte[] bytes = _responseBodyBytes[i];
_connection.WriteBody(bytes, 0, bytes.Length);
}
_responseBodyBytes = new List<byte[]>();
if (finalFlush)
{
_connection.Close();
}
}
public override void EndOfRequest()
{
Connection conn = _connection;
if (conn != null)
{
_connection = null;
_server.OnRequestEnd(conn);
}
}
}
}
| |
namespace VisionObjectTrack
{
using AVFoundation;
using CoreFoundation;
using CoreGraphics;
using Foundation;
using Photos;
using System;
using UIKit;
public partial class AssetsViewController : UICollectionViewController
{
private const string ShowTrackingViewSegueIdentifier = "ShowTrackingView";
private PHFetchResult assets;
public AssetsViewController(IntPtr handle) : base(handle) { }
public override void ViewDidLoad()
{
base.ViewDidLoad();
PHPhotoLibrary.RequestAuthorization((status) =>
{
if (status == PHAuthorizationStatus.Authorized)
{
DispatchQueue.MainQueue.DispatchAsync(() => this.LoadAssetsFromLibrary());
}
});
}
public override void ViewDidLayoutSubviews()
{
base.ViewDidLayoutSubviews();
this.RecalculateItemSize();
}
public override bool PrefersStatusBarHidden()
{
return true;
}
private void LoadAssetsFromLibrary()
{
var assetsOptions = new PHFetchOptions();
// include all source types
assetsOptions.IncludeAssetSourceTypes = PHAssetSourceType.CloudShared | PHAssetSourceType.UserLibrary | PHAssetSourceType.iTunesSynced;
// show most recent first
assetsOptions.SortDescriptors = new NSSortDescriptor[] { new NSSortDescriptor("modificationDate", false) };
// fecth videos
this.assets = PHAsset.FetchAssets(PHAssetMediaType.Video, assetsOptions);
// setup collection view
this.RecalculateItemSize();
this.CollectionView?.ReloadData();
}
private void RecalculateItemSize()
{
if (this.CollectionView != null)
{
if (this.CollectionView.CollectionViewLayout is UICollectionViewFlowLayout layout)
{
var desiredItemCount = this.TraitCollection.HorizontalSizeClass == UIUserInterfaceSizeClass.Compact ? 4 : 6;
var availableSize = this.CollectionView.Bounds.Width;
var insets = layout.SectionInset;
availableSize -= (insets.Left + insets.Right);
availableSize -= layout.MinimumInteritemSpacing * (desiredItemCount - 1f);
var itemSize = Math.Floor(availableSize / desiredItemCount);
if (layout.ItemSize.Width != itemSize)
{
layout.ItemSize = new CGSize(itemSize, itemSize);
layout.InvalidateLayout();
}
}
}
}
private PHAsset Asset(string identifier)
{
PHAsset foundAsset = null;
this.assets.Enumerate((NSObject element, nuint index, out bool stop) =>
{
if (element is PHAsset asset && asset?.LocalIdentifier == identifier)
{
foundAsset = asset;
stop = true;
}
else
{
stop = false;
}
});
return foundAsset;
}
#region Navigation
public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender)
{
if (segue.Identifier == ShowTrackingViewSegueIdentifier)
{
if (sender is AVAsset avAsset)
{
if (segue.DestinationViewController is TrackingViewController trackingController)
{
trackingController.VideoAsset = avAsset;
}
else
{
throw new Exception("Unexpected destination view controller type");
}
}
else
{
throw new Exception("Unexpected sender type");
}
}
}
#endregion
#region UICollectionViewDataSource
public override nint NumberOfSections(UICollectionView collectionView)
{
return 1;
}
public override nint GetItemsCount(UICollectionView collectionView, nint section)
{
return this.assets?.Count ?? 0;
}
public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath)
{
UICollectionViewCell result = null;
if (this.assets?[indexPath.Item] is PHAsset asset)
{
var genericCell = collectionView.DequeueReusableCell(AssetsCell.Identifier, indexPath);
if (genericCell is AssetsCell cell)
{
cell.RepresentedAssetIdentifier = asset.LocalIdentifier;
var imageManager = new PHImageManager();
var options = new PHImageRequestOptions
{
NetworkAccessAllowed = true,
ResizeMode = PHImageRequestOptionsResizeMode.Fast,
DeliveryMode = PHImageRequestOptionsDeliveryMode.Opportunistic,
};
imageManager.RequestImageForAsset(asset, cell.Bounds.Size, PHImageContentMode.AspectFill, options, (image, _) =>
{
if (asset.LocalIdentifier == cell.RepresentedAssetIdentifier)
{
cell.ImageView.Image = image;
}
});
result = cell;
}
else
{
result = genericCell as UICollectionViewCell;
}
}
else
{
throw new Exception($"Failed to find asset at index {indexPath.Item}");
}
return result;
}
#endregion
#region UICollectionViewDelegate
public override void ItemSelected(UICollectionView collectionView, NSIndexPath indexPath)
{
if (collectionView.CellForItem(indexPath) is AssetsCell cell)
{
var assetId = cell.RepresentedAssetIdentifier;
var asset = this.Asset(assetId);
if (asset == null)
{
throw new Exception($"Failed to find asset with identifier {assetId}");
}
var imageManager = PHImageManager.DefaultManager;
var videoOptions = new PHVideoRequestOptions
{
NetworkAccessAllowed = true,
DeliveryMode = PHVideoRequestOptionsDeliveryMode.HighQualityFormat
};
imageManager.RequestAvAsset(asset, videoOptions, (avAsset, _, __) =>
{
if (avAsset != null)
{
DispatchQueue.MainQueue.DispatchAsync(() =>
{
this.PerformSegue(ShowTrackingViewSegueIdentifier, avAsset);
});
}
});
}
else
{
throw new Exception($"Failed to find cell as index path {indexPath}");
}
}
#endregion
}
}
| |
using System;
using System.Text.RegularExpressions;
using FluentAssertions.Execution;
#if !OLD_MSTEST
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif
namespace FluentAssertions.Specs
{
[TestClass]
public class AssertionScopeSpecs
{
[TestMethod]
public void When_disposed_it_should_throw_any_failures()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var scope = new AssertionScope();
AssertionScope.Current.FailWith("Failure1");
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = scope.Dispose;
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
try
{
act();
}
catch (Exception exception)
{
Assert.IsTrue(exception.Message.StartsWith("Failure1"));
}
}
[TestMethod]
public void When_multiple_scopes_are_nested_it_should_throw_all_failures_from_the_outer_scope()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var scope = new AssertionScope();
AssertionScope.Current.FailWith("Failure1");
using (var nestedScope = new AssertionScope())
{
nestedScope.FailWith("Failure2");
using (var deeplyNestedScope = new AssertionScope())
{
deeplyNestedScope.FailWith("Failure3");
}
}
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = scope.Dispose;
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
try
{
act();
}
catch (Exception exception)
{
Assert.IsTrue(exception.Message.Contains("Failure1"));
Assert.IsTrue(exception.Message.Contains("Failure2"));
Assert.IsTrue(exception.Message.Contains("Failure3"));
}
}
[TestMethod]
public void When_a_nested_scope_is_discarded_its_failures_should_also_be_discarded()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var scope = new AssertionScope();
AssertionScope.Current.FailWith("Failure1");
using (var nestedScope = new AssertionScope())
{
nestedScope.FailWith("Failure2");
using (var deeplyNestedScope = new AssertionScope())
{
deeplyNestedScope.FailWith("Failure3");
deeplyNestedScope.Discard();
}
}
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = scope.Dispose;
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
try
{
act();
}
catch (Exception exception)
{
Assert.IsTrue(exception.Message.Contains("Failure1"));
Assert.IsTrue(exception.Message.Contains("Failure2"));
Assert.IsFalse(exception.Message.Contains("Failure3"));
}
}
[TestMethod]
public void When_the_same_failure_is_handled_twice_or_more_it_should_still_report_it_once()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var scope = new AssertionScope();
AssertionScope.Current.FailWith("Failure");
AssertionScope.Current.FailWith("Failure");
using (var nestedScope = new AssertionScope())
{
nestedScope.FailWith("Failure");
nestedScope.FailWith("Failure");
}
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = scope.Dispose;
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
try
{
act();
}
catch (Exception exception)
{
int matches = new Regex(".*Failure.*").Matches(exception.Message).Count;
Assert.AreEqual(4, matches);
}
}
[TestMethod]
public void When_an_assertion_fails_in_a_named_scope_it_should_use_the_name_as_the_assertion_context()
{
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () =>
{
using (new AssertionScope("foo"))
{
new[] {1, 2, 3}.Should().Equal(3, 2, 1);
}
};
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected foo to be equal to*");
}
[TestMethod]
public void When_an_assertion_fails_in_a_scope_with_braces_it_should_use_the_name_as_the_assertion_context()
{
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () =>
{
using (new AssertionScope("{}"))
{
default(Array).Should().Equal(3, 2, 1);
}
};
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected {} to be equal to*");
}
[TestMethod]
public void When_parentheses_are_used_in_the_because_arguments_it_should_render_them_correctly()
{
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => 1.Should().Be(2, "can't use these in becauseArgs: {0} {1}", "{", "}");
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("*because can't use these in becauseArgs: { }*");
}
[TestMethod]
public void When_parentheses_are_used_in_literal_values_it_should_render_them_correctly()
{
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => "{foo}".Should().Be("{bar}");
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected string to be \"{bar}\", but \"{foo}\" differs near*");
}
}
}
| |
using System;
using UnityEngine;
namespace InControl
{
public class InputDevice
{
public static readonly InputDevice Null = new InputDevice( "NullInputDevice" );
internal int SortOrder = int.MaxValue;
public string Name { get; protected set; }
public string Meta { get; protected set; }
public ulong LastChangeTick { get; protected set; }
public InputControl[] Controls { get; protected set; }
public TwoAxisInputControl LeftStick { get; protected set; }
public TwoAxisInputControl RightStick { get; protected set; }
public TwoAxisInputControl DPad { get; protected set; }
public InputDevice( string name )
{
Name = name;
Meta = "";
LastChangeTick = 0;
const int numInputControlTypes = (int) InputControlType.Count + 1;
Controls = new InputControl[numInputControlTypes];
LeftStick = new TwoAxisInputControl();
RightStick = new TwoAxisInputControl();
DPad = new TwoAxisInputControl();
}
public InputControl GetControl( InputControlType inputControlType )
{
var control = Controls[ (int) inputControlType ];
return control ?? InputControl.Null;
}
// Warning: this is not efficient. Don't use it unless you have to, m'kay?
public static InputControlType GetInputControlTypeByName( string inputControlName )
{
return (InputControlType) Enum.Parse( typeof(InputControlType), inputControlName );
}
// Warning: this is not efficient. Don't use it unless you have to, m'kay?
public InputControl GetControlByName( string inputControlName )
{
var inputControlType = GetInputControlTypeByName( inputControlName );
return GetControl( inputControlType );
}
public InputControl AddControl( InputControlType inputControlType, string handle )
{
var inputControl = new InputControl( handle, inputControlType );
Controls[ (int) inputControlType ] = inputControl;
return inputControl;
}
public void UpdateWithState( InputControlType inputControlType, bool state, ulong updateTick )
{
GetControl( inputControlType ).UpdateWithState( state, updateTick );
}
public void UpdateWithValue( InputControlType inputControlType, float value, ulong updateTick )
{
GetControl( inputControlType ).UpdateWithValue( value, updateTick );
}
public void PreUpdate( ulong updateTick, float deltaTime )
{
int controlCount = Controls.GetLength( 0 );
for (int i = 0; i < controlCount; i++)
{
var control = Controls[i];
if (control != null)
{
control.PreUpdate( updateTick );
}
}
}
public virtual void Update( ulong updateTick, float deltaTime )
{
// Implemented by subclasses.
}
public void PostUpdate( ulong updateTick, float deltaTime )
{
// Apply post-processing to controls.
int controlCount = Controls.GetLength( 0 );
for (int i = 0; i < controlCount; i++)
{
var control = Controls[i];
if (control != null)
{
if (control.RawValue.HasValue)
{
control.UpdateWithValue( control.RawValue.Value, updateTick );
}
else
if (control.PreValue.HasValue)
{
control.UpdateWithValue( ProcessAnalogControlValue( control, deltaTime ), updateTick );
}
control.PostUpdate( updateTick );
if (control.HasChanged)
{
LastChangeTick = updateTick;
}
}
}
// Update two-axis controls.
LeftStick.Update( LeftStickX, LeftStickY, updateTick );
RightStick.Update( RightStickX, RightStickY, updateTick );
var dpv = DPadVector;
DPad.Update( dpv.x, dpv.y, updateTick );
}
float ProcessAnalogControlValue( InputControl control, float deltaTime )
{
var analogValue = control.PreValue.Value;
var obverseTarget = control.Obverse;
if (obverseTarget.HasValue)
{
var obverseControl = GetControl( obverseTarget.Value );
if (obverseControl.PreValue.HasValue)
{
analogValue = ApplyCircularDeadZone( analogValue, obverseControl.PreValue.Value, control.LowerDeadZone, control.UpperDeadZone );
}
else
{
analogValue = ApplyDeadZone( analogValue, control.LowerDeadZone, control.UpperDeadZone );
}
}
else
{
analogValue = ApplyDeadZone( analogValue, control.LowerDeadZone, control.UpperDeadZone );
}
return ApplySmoothing( analogValue, control.LastValue, deltaTime, control.Sensitivity );
}
float ApplyDeadZone( float value, float lowerDeadZone, float upperDeadZone )
{
return Mathf.InverseLerp( lowerDeadZone, upperDeadZone, Mathf.Abs( value ) ) * Mathf.Sign( value );
}
float ApplyCircularDeadZone( float axisValue1, float axisValue2, float lowerDeadZone, float upperDeadZone )
{
var axisVector = new Vector2( axisValue1, axisValue2 );
var magnitude = Mathf.InverseLerp( lowerDeadZone, upperDeadZone, axisVector.magnitude );
return (axisVector.normalized * magnitude).x;
}
float ApplySmoothing( float thisValue, float lastValue, float deltaTime, float sensitivity )
{
// 1.0f and above is instant (no smoothing).
if (Mathf.Approximately( sensitivity, 1.0f ))
{
return thisValue;
}
// Apply sensitivity (how quickly the value adapts to changes).
var maxDelta = deltaTime * sensitivity * 100.0f;
// Snap to zero when changing direction quickly.
if (Mathf.Sign( lastValue ) != Mathf.Sign( thisValue ))
{
lastValue = 0.0f;
}
return Mathf.MoveTowards( lastValue, thisValue, maxDelta );
}
Vector2 DPadVector
{
get
{
var x = DPadLeft.State ? -DPadLeft.Value : DPadRight.Value;
var t = DPadUp.State ? DPadUp.Value : -DPadDown.Value;
var y = InputManager.InvertYAxis ? -t : t;
return new Vector2( x, y ).normalized;
}
}
public bool LastChangedAfter( InputDevice otherDevice )
{
return LastChangeTick > otherDevice.LastChangeTick;
}
public virtual void Vibrate( float leftMotor, float rightMotor )
{
}
public void Vibrate( float intensity )
{
Vibrate( intensity, intensity );
}
public virtual bool IsSupportedOnThisPlatform
{
get { return true; }
}
public virtual bool IsKnown
{
get { return true; }
}
public bool MenuWasPressed
{
get
{
return GetControl( InputControlType.Back ).WasPressed ||
GetControl( InputControlType.Start ).WasPressed ||
GetControl( InputControlType.Select ).WasPressed ||
GetControl( InputControlType.System ).WasPressed ||
GetControl( InputControlType.Pause ).WasPressed ||
GetControl( InputControlType.Menu ).WasPressed;
}
}
public InputControl AnyButton
{
get
{
int controlCount = Controls.GetLength( 0 );
for (int i = 0; i < controlCount; i++)
{
var control = Controls[i];
if (control != null && control.IsButton && control.IsPressed)
{
return control;
}
}
return InputControl.Null;
}
}
public InputControl LeftStickX { get { return GetControl( InputControlType.LeftStickX ); } }
public InputControl LeftStickY { get { return GetControl( InputControlType.LeftStickY ); } }
public InputControl RightStickX { get { return GetControl( InputControlType.RightStickX ); } }
public InputControl RightStickY { get { return GetControl( InputControlType.RightStickY ); } }
public InputControl DPadUp { get { return GetControl( InputControlType.DPadUp ); } }
public InputControl DPadDown { get { return GetControl( InputControlType.DPadDown ); } }
public InputControl DPadLeft { get { return GetControl( InputControlType.DPadLeft ); } }
public InputControl DPadRight { get { return GetControl( InputControlType.DPadRight ); } }
public InputControl Action1 { get { return GetControl( InputControlType.Action1 ); } }
public InputControl Action2 { get { return GetControl( InputControlType.Action2 ); } }
public InputControl Action3 { get { return GetControl( InputControlType.Action3 ); } }
public InputControl Action4 { get { return GetControl( InputControlType.Action4 ); } }
public InputControl LeftTrigger { get { return GetControl( InputControlType.LeftTrigger ); } }
public InputControl RightTrigger { get { return GetControl( InputControlType.RightTrigger ); } }
public InputControl LeftBumper { get { return GetControl( InputControlType.LeftBumper ); } }
public InputControl RightBumper { get { return GetControl( InputControlType.RightBumper ); } }
public InputControl LeftStickButton { get { return GetControl( InputControlType.LeftStickButton ); } }
public InputControl RightStickButton { get { return GetControl( InputControlType.RightStickButton ); } }
public float DPadX
{
get
{
return DPad.X;
}
}
public float DPadY
{
get
{
return DPad.Y;
}
}
public TwoAxisInputControl Direction
{
get
{
return DPad.UpdateTick > LeftStick.UpdateTick ? DPad : LeftStick;
}
}
}
}
| |
namespace VeloEventsManager.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
using System.Linq;
using Microsoft.AspNet.Identity;
using VeloEventsManager.Common;
using VeloEventsManager.Data;
using VeloEventsManager.Models;
public sealed class Configuration : DbMigrationsConfiguration<VeloEventsManagerDbContext>
{
private Random random;
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
}
protected override void Seed(VeloEventsManagerDbContext context)
{
this.SeedRoles(context);
context = new VeloEventsManagerDbContext();
this.SeedUsers(context);
context = new VeloEventsManagerDbContext();
this.SeedBikes(context);
context = new VeloEventsManagerDbContext();
this.SeedPoints(context);
context = new VeloEventsManagerDbContext();
this.SeedRoutes(context);
context = new VeloEventsManagerDbContext();
this.SeedEvents(context);
context = new VeloEventsManagerDbContext();
this.SeedEventDays(context);
}
private void SeedEvents(VeloEventsManagerDbContext context)
{
if (context.Events.Any())
{
return;
}
var creator = context.Users.FirstOrDefault(x => x.UserName == "admin@admin.com");
var users = context.Users.ToList();
random = new Random();
for (int i = 0; i < 20; i++)
{
var startDay = DateTime.Now.AddDays(i);
var endDay = DateTime.Now.AddDays(i + 10);
var trip = new Event()
{
Name = $"Test event name {i}",
Description = $"Test event description {i}",
StartDate = startDay,
EndDate = endDay,
PriceInLeva = i + 100,
TotalDistance = i + 500,
Creator = creator
};
trip.Participants.Add(creator);
for (int j = 0; j < 20 + i; j++)
{
var participant = users[random.Next(0, users.Count)];
trip.Participants.Add(participant);
}
context.Events.Add(trip);
}
context.SaveChanges();
}
private void SeedEventDays(VeloEventsManagerDbContext context)
{
if (context.EventDays.Any())
{
return;
}
var routes = context.Routes.ToList();
var trips = context.Events.ToList();
random = new Random();
for (int i = 0; i < 100; i++)
{
var date = DateTime.Now.AddDays(i);
var startTime = DateTime.Now.AddDays(i).AddHours(i);
var endTime = DateTime.Now.AddDays(i).AddHours(i + 5);
var mainRoute = routes[random.Next(0, routes.Count)];
var trip = trips[random.Next(0, trips.Count)];
var eventDay = new EventDay()
{
Description = $"Test description: Day {i % 10}. Long day...",
Date = date,
StartTime = startTime,
EndTime = endTime,
MainRoute = mainRoute,
Event = trip
};
// some optional routes
if (i % 2 == 0)
{
for (int j = 0; j < 3; j++)
{
var currentOptionalRoute = routes[random.Next(0, routes.Count)];
eventDay.OptionalRoutes.Add(currentOptionalRoute);
}
}
context.EventDays.Add(eventDay);
}
context.SaveChanges();
}
private void SeedRoutes(VeloEventsManagerDbContext context)
{
if (context.Routes.Any())
{
return;
}
var points = context.Points.ToList();
random = new Random();
for (int i = 0; i < 100; i++)
{
var startPoint = points[random.Next(0, points.Count)];
var endPoint = points[random.Next(0, points.Count)];
var route = new Route()
{
Name = $"route_{i}",
StartPoint = startPoint,
EndPoint = endPoint,
AscentInMeters = i + 1,
DescentInMeters = i + 1,
LengthInMeters = i + 1,
Difficulty = i + 1
};
context.Routes.Add(route);
}
context.SaveChanges();
var usersCount = context.Users.Count();
var routesCount = context.Routes.Count();
for (int i = 0; i < usersCount; i++)
{
var user = context.Users.OrderBy(x => x.Id).Skip(i).Take(1).First();
for (int j = 0; j < random.Next(1,5); j++)
{
var randomIndex = random.Next(1, routesCount);
var route = context.Routes.FirstOrDefault(x => x.Id == randomIndex);
if (user.Routes.Contains(route) || route.User != null)
{
continue;
}
route.User = user;
}
}
context.SaveChanges();
}
private void SeedPoints(VeloEventsManagerDbContext context)
{
if (context.Points.Any())
{
return;
}
for (int i = 0; i < 1000; i++)
{
var point = new Point()
{
Elevation = i / 100,
Lattitude = 42 + i * 0.001,
Longitude = 23 + i * 0.001,
};
context.Points.Add(point);
}
context.SaveChanges();
}
private void SeedBikes(VeloEventsManagerDbContext context)
{
if (context.Bikes.Any())
{
return;
}
var users = context.Users.ToList();
for (int i = 0; i < users.Count; i++)
{
var currentUser = users[i];
var bike = new Bike()
{
Owner = currentUser,
SpecificInformation = $"Specific Information for bike {i}",
Height = i + 1,
Length = i + 1,
Weight = i + 1,
Width = i + 1
};
context.Bikes.Add(bike);
}
context.SaveChanges();
}
private void SeedRoles(VeloEventsManagerDbContext context)
{
if (!context.AppRoles.Any())
{
context.AppRoles.Add(new AppRole("admin"));
context.AppRoles.Add(new AppRole("user"));
context.SaveChanges();
}
}
private void SeedUsers(VeloEventsManagerDbContext context)
{
if (context.Users.Any())
{
return;
}
var admin = new User()
{
UserName = "a",
PasswordHash = new PasswordHasher().HashPassword("1"),
SecurityStamp = Guid.NewGuid().ToString()
};
var roles = context.AppRoles.ToList();
admin.AppRoles.Add(roles[0]);
context.Users.AddOrUpdate(admin);
var languages = VeloEventsManager.Common.Constants.Languages;
var skills = VeloEventsManager.Common.Constants.Skills;
random = new Random();
for (int i = 0; i < 100; i++)
{
var user = new User()
{
Email = $"user{i}@test.bg",
UserName = $"u{i}",
PasswordHash = new PasswordHasher().HashPassword($"{1}"),
SecurityStamp = Guid.NewGuid().ToString()
};
for (int j = 0; j < 2; j++)
{
var lang = languages[random.Next(0, languages.Length)];
var skill = skills[random.Next(0, skills.Length)];
user.Languages.Add(lang);
user.Skills.Add(skill);
}
user.AppRoles.Add(roles[1]);
context.Users.Add(user);
}
context.SaveChanges();
}
}
}
| |
#region Header
// Revit API .NET Labs
//
// Copyright (C) 2007-2021 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software
// for any purpose and without fee is hereby granted, provided
// that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
#endregion // Header
#region Namespaces
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Linq;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Architecture;
using Autodesk.Revit.UI;
// Galaxy Alpha: todo: report and resolve this, this should not be required: 'RE: ambiguous BoundarySegmentArrayArray'
//using BoundarySegmentArrayArray = Autodesk.Revit.DB.Architecture.BoundarySegmentArrayArray;
//using BoundarySegmentArray = Autodesk.Revit.DB.Architecture.BoundarySegmentArray;
//using BoundarySegment = Autodesk.Revit.DB.Architecture.BoundarySegment;
// Galaxy Beta 1: Error 1 'BoundarySegment' is an ambiguous reference between 'Autodesk.Revit.DB.BoundarySegment' and 'Autodesk.Revit.DB.Architecture.BoundarySegment' C:\a\lib\revit\2012\adn\src\rac\labs\cs\Labs5.cs 299 23 LabsCs
//using BoundarySegmentArrayArray = Autodesk.Revit.DB.BoundarySegmentArrayArray;
//using BoundarySegmentArray = Autodesk.Revit.DB.Arch.BoundarySegmentArray;
using BoundarySegment = Autodesk.Revit.DB.BoundarySegment;
#endregion // Namespaces
namespace XtraCs
{
#region Lab5_1_GroupsAndGroupTypes
/// <summary>
/// List all groups and group types in the model.
/// </summary>
[Transaction( TransactionMode.ReadOnly )]
public class Lab5_1_GroupsAndGroupTypes : IExternalCommand
{
const string _groupTypeModel = "Model Group"; // BEWARE: In the browser, it says only "Model"
const string _groupsTypeModel = "Model Groups";
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements )
{
UIApplication app = commandData.Application;
Document doc = app.ActiveUIDocument.Document;
List<string> a = new List<string>();
// list groups:
FilteredElementCollector collector;
collector = new FilteredElementCollector( doc );
collector.OfClass( typeof( Group ) );
foreach( Group g in collector )
{
a.Add( "Id=" + g.Id.IntegerValue.ToString() + "; Type=" + g.GroupType.Name );
}
LabUtils.InfoMsg( "{0} group{1} in the document{2}", a );
// list groups types:
BuiltInParameter bic = BuiltInParameter.SYMBOL_FAMILY_NAME_PARAM;
a.Clear();
collector = new FilteredElementCollector( doc );
collector.OfClass( typeof( GroupType ) );
foreach( GroupType g in collector )
{
// determine the GroupType system family
// (cf. Labs3 for standard symbols):
Parameter p = g.get_Parameter( bic );
string famName = ( null == p ) ? "?" : p.AsString();
a.Add( "Name=" + g.Name + "; Id=" + g.Id.IntegerValue.ToString() + "; Family=" + famName );
}
LabUtils.InfoMsg( "{0} group type{1} in the document{2}", a );
// typically, only "Model" types will be needed.
// create a filter by creating a provider and an evaluator.
// we can reuse the collector we already set up for group
// types, and just add another criteria to check to it:
a.Clear();
#region Failed attempts
/*
* this returns zero elements:
*
ParameterValueProvider provider
= new ParameterValueProvider( new ElementId( ( int ) bic ) );
FilterStringRuleEvaluator evaluator
= new FilterStringEquals();
string ruleString = _groupTypeModel;
bool caseSensitive = true;
FilterRule rule = new FilterStringRule( provider, evaluator, ruleString, caseSensitive );
// Create an ElementParameter filter:
ElementParameterFilter filter = new ElementParameterFilter( rule );
// Apply the filter to the elements in the active collector:
collector.WherePasses( filter ).ToElements();
*/
/*
* this returns false:
*
if( doc.Settings.Categories.Contains( _groupsTypeModel ) )
{
Category cat = doc.Settings.Categories.get_Item( _groupsTypeModel );
foreach( GroupType g in collector )
{
a.Add( "Name=" + g.Name + "; Id=" + g.Id.IntegerValue.ToString() );
}
}
*/
#endregion // Failed attempts
collector.OfCategory( BuiltInCategory.OST_IOSModelGroups );
foreach( GroupType g in collector )
{
a.Add( "Name=" + g.Name + "; Id=" + g.Id.IntegerValue.ToString() );
}
LabUtils.InfoMsg( "{0} *model* group type{1} in the document{2}", a );
return Result.Failed;
}
}
#endregion // Lab5_1_GroupsAndGroupTypes
#region Lab5_2_SwapGroupTypes
/// <summary>
/// Swap group types for selected groups.
/// </summary>
[Transaction( TransactionMode.Manual )]
public class Lab5_2_SwapGroupTypes : IExternalCommand
{
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements )
{
UIApplication app = commandData.Application;
UIDocument uidoc = app.ActiveUIDocument;
Document doc = uidoc.Document;
// Get all Group Types of Model Family:
FilteredElementCollector modelGroupTypes
= new FilteredElementCollector( doc );
modelGroupTypes.OfClass( typeof( GroupType ) );
modelGroupTypes.OfCategory( BuiltInCategory.OST_IOSModelGroups );
if( 0 == modelGroupTypes.Count() )
{
message = "No model group types found in model.";
return Result.Failed;
}
FilteredElementCollector groups;
groups = new FilteredElementCollector( doc );
groups.OfClass( typeof( Group ) );
foreach( Group g in groups )
{
// Offer simple message box to swap the type
// (one-by-one, stop if user confirms the change)
foreach( GroupType gt in modelGroupTypes )
{
string msg = "Swap OLD Type=" + g.GroupType.Name
+ " with NEW Type=" + gt.Name
+ " for Group Id=" + g.Id.IntegerValue.ToString() + "?";
TaskDialogResult r = LabUtils.QuestionCancelMsg( msg );
switch( r )
{
case TaskDialogResult.Yes:
using( Transaction tx = new Transaction( doc ) )
{
tx.Start( "Swap Group Type" );
g.GroupType = gt;
tx.Commit();
}
LabUtils.InfoMsg( "Group type successfully swapped." );
return Result.Succeeded;
case TaskDialogResult.Cancel:
LabUtils.InfoMsg( "Command cancelled." );
return Result.Cancelled;
// else continue...
}
}
}
/*
//
// cannot modify group members after creation:
//
Element e = null;
ElementArray els = new ElementArray();
els.Append( e );
Group g = new Group();
g.Members = els; // Property or indexer 'Autodesk.Revit.Elements.Group.Members' cannot be assigned to -- it is read only
Element e2 = null;
els.Append( e2 );
g.Members = els;
*/
return Result.Succeeded;
}
}
#endregion // Lab5_2_SwapGroupTypes
#region Lab5_3_Rooms
/// <summary>
/// List room boundaries.
/// </summary>
[Transaction( TransactionMode.ReadOnly )]
public class Lab5_3_Rooms : IExternalCommand
{
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements )
{
UIApplication app = commandData.Application;
Document doc = app.ActiveUIDocument.Document;
FilteredElementCollector rooms
= new FilteredElementCollector( doc );
//
// this is one way of obtaining rooms ... but see below for a better solution:
//
//rooms.OfClass( typeof( Room ) ); // Input type is of an element type that exists in the API, but not in Revit's native object model. Try using Autodesk.Revit.DB.Enclosure instead, and then postprocessing the results to find the elements of interest.
//rooms.OfClass( typeof( Enclosure ) ); // this works but returns all Enclosure elements
RoomFilter filter = new RoomFilter();
rooms.WherePasses( filter );
if( 0 == rooms.Count() )
{
LabUtils.InfoMsg( "There are no rooms in this model." );
}
else
{
List<string> a = new List<string>();
/*
foreach( Enclosure e in rooms ) // todo: remove this
{
Room room = e as Room; // todo: remove this
if( null != room ) // todo: remove this
{
*/
foreach( Room room in rooms )
{
string roomName = room.Name;
string roomNumber = room.Number;
string s = "Room Id=" + room.Id.IntegerValue.ToString()
+ " Name=" + roomName + " Number=" + roomNumber + "\n";
// Loop all boundaries of this room
//BoundarySegmentArrayArray boundaries = room.Boundary; // 2011
IList<IList<BoundarySegment>> boundaries // 2012
= room.GetBoundarySegments( // 2012
new SpatialElementBoundaryOptions() ); // 2012; passing in a null value throws an exception
// Check to ensure room has boundary
if( null != boundaries )
{
int iB = 0;
//foreach( BoundarySegmentArray boundary in boundaries ) // 2011
foreach( IList<BoundarySegment> boundary in boundaries ) // 2012
{
++iB;
s += " Boundary " + iB + ":\n";
int iSeg = 0;
foreach( BoundarySegment segment in boundary )
{
++iSeg;
// Segment's curve
Curve crv = segment.GetCurve();
if( crv is Line )
{
Line line = crv as Line;
XYZ ptS = line.GetEndPoint( 0 );
XYZ ptE = line.GetEndPoint( 1 );
s += " Segment " + iSeg + " is a LINE: "
+ LabUtils.PointString( ptS ) + " ; "
+ LabUtils.PointString( ptE ) + "\n";
}
else if( crv is Arc )
{
Arc arc = crv as Arc;
XYZ ptS = arc.GetEndPoint( 0 );
XYZ ptE = arc.GetEndPoint( 1 );
double r = arc.Radius;
s += " Segment " + iSeg + " is an ARC:"
+ LabUtils.PointString( ptS ) + " ; "
+ LabUtils.PointString( ptE ) + " ; R="
+ LabUtils.RealString( r ) + "\n";
}
}
}
a.Add( s );
}
LabUtils.InfoMsg( "{0} room{1} in the model{2}", a );
}
}
return Result.Failed;
}
}
#endregion // Lab5_3_Rooms
}
| |
/*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
using Ds3.Models;
using System;
using System.Net;
namespace Ds3.Calls
{
public class GetTapeDrivesSpectraS3Request : Ds3Request
{
private bool? _lastPage;
public bool? LastPage
{
get { return _lastPage; }
set { WithLastPage(value); }
}
private int? _pageLength;
public int? PageLength
{
get { return _pageLength; }
set { WithPageLength(value); }
}
private int? _pageOffset;
public int? PageOffset
{
get { return _pageOffset; }
set { WithPageOffset(value); }
}
private string _pageStartMarker;
public string PageStartMarker
{
get { return _pageStartMarker; }
set { WithPageStartMarker(value); }
}
private string _partitionId;
public string PartitionId
{
get { return _partitionId; }
set { WithPartitionId(value); }
}
private ReservedTaskType? _reservedTaskType;
public ReservedTaskType? ReservedTaskType
{
get { return _reservedTaskType; }
set { WithReservedTaskType(value); }
}
private string _serialNumber;
public string SerialNumber
{
get { return _serialNumber; }
set { WithSerialNumber(value); }
}
private TapeDriveState? _state;
public TapeDriveState? State
{
get { return _state; }
set { WithState(value); }
}
private TapeDriveType? _type;
public TapeDriveType? Type
{
get { return _type; }
set { WithType(value); }
}
public GetTapeDrivesSpectraS3Request WithLastPage(bool? lastPage)
{
this._lastPage = lastPage;
if (lastPage != null)
{
this.QueryParams.Add("last_page", lastPage.ToString());
}
else
{
this.QueryParams.Remove("last_page");
}
return this;
}
public GetTapeDrivesSpectraS3Request WithPageLength(int? pageLength)
{
this._pageLength = pageLength;
if (pageLength != null)
{
this.QueryParams.Add("page_length", pageLength.ToString());
}
else
{
this.QueryParams.Remove("page_length");
}
return this;
}
public GetTapeDrivesSpectraS3Request WithPageOffset(int? pageOffset)
{
this._pageOffset = pageOffset;
if (pageOffset != null)
{
this.QueryParams.Add("page_offset", pageOffset.ToString());
}
else
{
this.QueryParams.Remove("page_offset");
}
return this;
}
public GetTapeDrivesSpectraS3Request WithPageStartMarker(Guid? pageStartMarker)
{
this._pageStartMarker = pageStartMarker.ToString();
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker.ToString());
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetTapeDrivesSpectraS3Request WithPageStartMarker(string pageStartMarker)
{
this._pageStartMarker = pageStartMarker;
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker);
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetTapeDrivesSpectraS3Request WithPartitionId(Guid? partitionId)
{
this._partitionId = partitionId.ToString();
if (partitionId != null)
{
this.QueryParams.Add("partition_id", partitionId.ToString());
}
else
{
this.QueryParams.Remove("partition_id");
}
return this;
}
public GetTapeDrivesSpectraS3Request WithPartitionId(string partitionId)
{
this._partitionId = partitionId;
if (partitionId != null)
{
this.QueryParams.Add("partition_id", partitionId);
}
else
{
this.QueryParams.Remove("partition_id");
}
return this;
}
public GetTapeDrivesSpectraS3Request WithReservedTaskType(ReservedTaskType? reservedTaskType)
{
this._reservedTaskType = reservedTaskType;
if (reservedTaskType != null)
{
this.QueryParams.Add("reserved_task_type", reservedTaskType.ToString());
}
else
{
this.QueryParams.Remove("reserved_task_type");
}
return this;
}
public GetTapeDrivesSpectraS3Request WithSerialNumber(string serialNumber)
{
this._serialNumber = serialNumber;
if (serialNumber != null)
{
this.QueryParams.Add("serial_number", serialNumber);
}
else
{
this.QueryParams.Remove("serial_number");
}
return this;
}
public GetTapeDrivesSpectraS3Request WithState(TapeDriveState? state)
{
this._state = state;
if (state != null)
{
this.QueryParams.Add("state", state.ToString());
}
else
{
this.QueryParams.Remove("state");
}
return this;
}
public GetTapeDrivesSpectraS3Request WithType(TapeDriveType? type)
{
this._type = type;
if (type != null)
{
this.QueryParams.Add("type", type.ToString());
}
else
{
this.QueryParams.Remove("type");
}
return this;
}
public GetTapeDrivesSpectraS3Request()
{
}
internal override HttpVerb Verb
{
get
{
return HttpVerb.GET;
}
}
internal override string Path
{
get
{
return "/_rest_/tape_drive";
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Dispatcher
{
using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.Diagnostics;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Diagnostics.Application;
using System.Threading;
using System.Transactions;
using System.Xml;
using SessionIdleManager = System.ServiceModel.Channels.ServiceChannel.SessionIdleManager;
class ChannelHandler
{
public static readonly TimeSpan CloseAfterFaultTimeout = TimeSpan.FromSeconds(10);
public const string MessageBufferPropertyName = "_RequestMessageBuffer_";
readonly IChannelBinder binder;
readonly DuplexChannelBinder duplexBinder;
readonly ServiceHostBase host;
readonly bool incrementedActivityCountInConstructor;
readonly bool isCallback;
readonly ListenerHandler listener;
readonly ServiceThrottle throttle;
readonly bool wasChannelThrottled;
readonly SessionIdleManager idleManager;
readonly bool sendAsynchronously;
static AsyncCallback onAsyncReplyComplete = Fx.ThunkCallback(new AsyncCallback(ChannelHandler.OnAsyncReplyComplete));
static AsyncCallback onAsyncReceiveComplete = Fx.ThunkCallback(new AsyncCallback(ChannelHandler.OnAsyncReceiveComplete));
static Action<object> onContinueAsyncReceive = new Action<object>(ChannelHandler.OnContinueAsyncReceive);
static Action<object> onStartSyncMessagePump = new Action<object>(ChannelHandler.OnStartSyncMessagePump);
static Action<object> onStartAsyncMessagePump = new Action<object>(ChannelHandler.OnStartAsyncMessagePump);
static Action<object> onStartSingleTransactedBatch = new Action<object>(ChannelHandler.OnStartSingleTransactedBatch);
static Action<object> openAndEnsurePump = new Action<object>(ChannelHandler.OpenAndEnsurePump);
RequestInfo requestInfo;
ServiceChannel channel;
bool doneReceiving;
bool hasRegisterBeenCalled;
bool hasSession;
int isPumpAcquired;
bool isChannelTerminated;
bool isConcurrent;
bool isManualAddressing;
MessageVersion messageVersion;
ErrorHandlingReceiver receiver;
bool receiveSynchronously;
bool receiveWithTransaction;
RequestContext replied;
RequestContext requestWaitingForThrottle;
WrappedTransaction acceptTransaction;
ServiceThrottle instanceContextThrottle;
SharedTransactedBatchContext sharedTransactedBatchContext;
TransactedBatchContext transactedBatchContext;
bool isMainTransactedBatchHandler;
EventTraceActivity eventTraceActivity;
SessionOpenNotification sessionOpenNotification;
bool needToCreateSessionOpenNotificationMessage;
bool shouldRejectMessageWithOnOpenActionHeader;
internal ChannelHandler(MessageVersion messageVersion, IChannelBinder binder, ServiceChannel channel)
{
ClientRuntime clientRuntime = channel.ClientRuntime;
this.messageVersion = messageVersion;
this.isManualAddressing = clientRuntime.ManualAddressing;
this.binder = binder;
this.channel = channel;
this.isConcurrent = true;
this.duplexBinder = binder as DuplexChannelBinder;
this.hasSession = binder.HasSession;
this.isCallback = true;
DispatchRuntime dispatchRuntime = clientRuntime.DispatchRuntime;
if (dispatchRuntime == null)
{
this.receiver = new ErrorHandlingReceiver(binder, null);
}
else
{
this.receiver = new ErrorHandlingReceiver(binder, dispatchRuntime.ChannelDispatcher);
}
this.requestInfo = new RequestInfo(this);
}
internal ChannelHandler(MessageVersion messageVersion, IChannelBinder binder, ServiceThrottle throttle,
ListenerHandler listener, bool wasChannelThrottled, WrappedTransaction acceptTransaction, SessionIdleManager idleManager)
{
ChannelDispatcher channelDispatcher = listener.ChannelDispatcher;
this.messageVersion = messageVersion;
this.isManualAddressing = channelDispatcher.ManualAddressing;
this.binder = binder;
this.throttle = throttle;
this.listener = listener;
this.wasChannelThrottled = wasChannelThrottled;
this.host = listener.Host;
this.receiveSynchronously = channelDispatcher.ReceiveSynchronously;
this.sendAsynchronously = channelDispatcher.SendAsynchronously;
this.duplexBinder = binder as DuplexChannelBinder;
this.hasSession = binder.HasSession;
this.isConcurrent = ConcurrencyBehavior.IsConcurrent(channelDispatcher, this.hasSession);
if (channelDispatcher.MaxPendingReceives > 1)
{
// We need to preserve order if the ChannelHandler is not concurrent.
this.binder = new MultipleReceiveBinder(
this.binder,
channelDispatcher.MaxPendingReceives,
!this.isConcurrent);
}
if (channelDispatcher.BufferedReceiveEnabled)
{
this.binder = new BufferedReceiveBinder(this.binder);
}
this.receiver = new ErrorHandlingReceiver(this.binder, channelDispatcher);
this.idleManager = idleManager;
Fx.Assert((this.idleManager != null) == (this.binder.HasSession && this.listener.ChannelDispatcher.DefaultCommunicationTimeouts.ReceiveTimeout != TimeSpan.MaxValue), "idle manager is present only when there is a session with a finite receive timeout");
if (channelDispatcher.IsTransactedReceive && !channelDispatcher.ReceiveContextEnabled)
{
receiveSynchronously = true;
receiveWithTransaction = true;
if (channelDispatcher.MaxTransactedBatchSize > 0)
{
int maxConcurrentBatches = 1;
if (null != throttle && throttle.MaxConcurrentCalls > 1)
{
maxConcurrentBatches = throttle.MaxConcurrentCalls;
foreach (EndpointDispatcher endpointDispatcher in channelDispatcher.Endpoints)
{
if (ConcurrencyMode.Multiple != endpointDispatcher.DispatchRuntime.ConcurrencyMode)
{
maxConcurrentBatches = 1;
break;
}
}
}
this.sharedTransactedBatchContext = new SharedTransactedBatchContext(this, channelDispatcher, maxConcurrentBatches);
this.isMainTransactedBatchHandler = true;
this.throttle = null;
}
}
else if (channelDispatcher.IsTransactedReceive && channelDispatcher.ReceiveContextEnabled && channelDispatcher.MaxTransactedBatchSize > 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.IncompatibleBehaviors)));
}
if (this.binder.HasSession)
{
this.sessionOpenNotification = this.binder.Channel.GetProperty<SessionOpenNotification>();
this.needToCreateSessionOpenNotificationMessage = this.sessionOpenNotification != null && this.sessionOpenNotification.IsEnabled;
}
this.acceptTransaction = acceptTransaction;
this.requestInfo = new RequestInfo(this);
if (this.listener.State == CommunicationState.Opened)
{
this.listener.ChannelDispatcher.Channels.IncrementActivityCount();
this.incrementedActivityCountInConstructor = true;
}
}
internal ChannelHandler(ChannelHandler handler, TransactedBatchContext context)
{
this.messageVersion = handler.messageVersion;
this.isManualAddressing = handler.isManualAddressing;
this.binder = handler.binder;
this.listener = handler.listener;
this.wasChannelThrottled = handler.wasChannelThrottled;
this.host = handler.host;
this.receiveSynchronously = true;
this.receiveWithTransaction = true;
this.duplexBinder = handler.duplexBinder;
this.hasSession = handler.hasSession;
this.isConcurrent = handler.isConcurrent;
this.receiver = handler.receiver;
this.sharedTransactedBatchContext = context.Shared;
this.transactedBatchContext = context;
this.requestInfo = new RequestInfo(this);
this.sendAsynchronously = handler.sendAsynchronously;
this.sessionOpenNotification = handler.sessionOpenNotification;
this.needToCreateSessionOpenNotificationMessage = handler.needToCreateSessionOpenNotificationMessage;
this.shouldRejectMessageWithOnOpenActionHeader = handler.shouldRejectMessageWithOnOpenActionHeader;
}
internal IChannelBinder Binder
{
get { return this.binder; }
}
internal ServiceChannel Channel
{
get { return this.channel; }
}
internal bool HasRegisterBeenCalled
{
get { return this.hasRegisterBeenCalled; }
}
internal InstanceContext InstanceContext
{
get { return (this.channel != null) ? this.channel.InstanceContext : null; }
}
internal ServiceThrottle InstanceContextServiceThrottle
{
get
{
return this.instanceContextThrottle;
}
set
{
this.instanceContextThrottle = value;
}
}
bool IsOpen
{
get { return this.binder.Channel.State == CommunicationState.Opened; }
}
EndpointAddress LocalAddress
{
get
{
if (this.binder != null)
{
IInputChannel input = this.binder.Channel as IInputChannel;
if (input != null)
{
return input.LocalAddress;
}
IReplyChannel reply = this.binder.Channel as IReplyChannel;
if (reply != null)
{
return reply.LocalAddress;
}
}
return null;
}
}
object ThisLock
{
get { return this; }
}
EventTraceActivity EventTraceActivity
{
get
{
if (this.eventTraceActivity == null)
{
this.eventTraceActivity = new EventTraceActivity();
}
return this.eventTraceActivity;
}
}
internal static void Register(ChannelHandler handler)
{
handler.Register();
}
internal static void Register(ChannelHandler handler, RequestContext request)
{
BufferedReceiveBinder bufferedBinder = handler.Binder as BufferedReceiveBinder;
Fx.Assert(bufferedBinder != null, "ChannelHandler.Binder is not a BufferedReceiveBinder");
bufferedBinder.InjectRequest(request);
handler.Register();
}
void Register()
{
this.hasRegisterBeenCalled = true;
if (this.binder.Channel.State == CommunicationState.Created)
{
ActionItem.Schedule(openAndEnsurePump, this);
}
else
{
this.EnsurePump();
}
}
void AsyncMessagePump()
{
IAsyncResult result = this.BeginTryReceive();
if ((result != null) && result.CompletedSynchronously)
{
this.AsyncMessagePump(result);
}
}
void AsyncMessagePump(IAsyncResult result)
{
if (TD.ChannelReceiveStopIsEnabled())
{
TD.ChannelReceiveStop(this.EventTraceActivity, this.GetHashCode());
}
for (;;)
{
RequestContext request;
while (!this.EndTryReceive(result, out request))
{
result = this.BeginTryReceive();
if ((result == null) || !result.CompletedSynchronously)
{
return;
}
}
if (!HandleRequest(request, null))
{
break;
}
if (!TryAcquirePump())
{
break;
}
result = this.BeginTryReceive();
if (result == null || !result.CompletedSynchronously)
{
break;
}
}
}
IAsyncResult BeginTryReceive()
{
this.requestInfo.Cleanup();
if (TD.ChannelReceiveStartIsEnabled())
{
TD.ChannelReceiveStart(this.EventTraceActivity, this.GetHashCode());
}
this.shouldRejectMessageWithOnOpenActionHeader = !this.needToCreateSessionOpenNotificationMessage;
if (this.needToCreateSessionOpenNotificationMessage)
{
return new CompletedAsyncResult(ChannelHandler.onAsyncReceiveComplete, this);
}
return this.receiver.BeginTryReceive(TimeSpan.MaxValue, ChannelHandler.onAsyncReceiveComplete, this);
}
bool DispatchAndReleasePump(RequestContext request, bool cleanThread, OperationContext currentOperationContext)
{
ServiceChannel channel = this.requestInfo.Channel;
EndpointDispatcher endpoint = this.requestInfo.Endpoint;
bool releasedPump = false;
try
{
DispatchRuntime dispatchBehavior = this.requestInfo.DispatchRuntime;
if (channel == null || dispatchBehavior == null)
{
Fx.Assert("System.ServiceModel.Dispatcher.ChannelHandler.Dispatch(): (channel == null || dispatchBehavior == null)");
return true;
}
MessageBuffer buffer = null;
Message message;
EventTraceActivity eventTraceActivity = TraceDispatchMessageStart(request.RequestMessage);
AspNetEnvironment.Current.PrepareMessageForDispatch(request.RequestMessage);
if (dispatchBehavior.PreserveMessage)
{
object previousBuffer = null;
if (request.RequestMessage.Properties.TryGetValue(MessageBufferPropertyName, out previousBuffer))
{
buffer = (MessageBuffer)previousBuffer;
message = buffer.CreateMessage();
}
else
{
//
buffer = request.RequestMessage.CreateBufferedCopy(int.MaxValue);
message = buffer.CreateMessage();
}
}
else
{
message = request.RequestMessage;
}
DispatchOperationRuntime operation = dispatchBehavior.GetOperation(ref message);
if (operation == null)
{
Fx.Assert("ChannelHandler.Dispatch (operation == null)");
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "No DispatchOperationRuntime found to process message.")));
}
if (this.shouldRejectMessageWithOnOpenActionHeader && message.Headers.Action == OperationDescription.SessionOpenedAction)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxNoEndpointMatchingAddressForConnectionOpeningMessage, message.Headers.Action, "Open")));
}
if (MessageLogger.LoggingEnabled)
{
MessageLogger.LogMessage(ref message, (operation.IsOneWay ? MessageLoggingSource.ServiceLevelReceiveDatagram : MessageLoggingSource.ServiceLevelReceiveRequest) | MessageLoggingSource.LastChance);
}
if (operation.IsTerminating && this.hasSession)
{
this.isChannelTerminated = true;
}
bool hasOperationContextBeenSet;
if (currentOperationContext != null)
{
hasOperationContextBeenSet = true;
currentOperationContext.ReInit(request, message, channel);
}
else
{
hasOperationContextBeenSet = false;
currentOperationContext = new OperationContext(request, message, channel, this.host);
}
if (dispatchBehavior.PreserveMessage)
{
currentOperationContext.IncomingMessageProperties.Add(MessageBufferPropertyName, buffer);
}
if (currentOperationContext.EndpointDispatcher == null && this.listener != null)
{
currentOperationContext.EndpointDispatcher = endpoint;
}
MessageRpc rpc = new MessageRpc(request, message, operation, channel, this.host,
this, cleanThread, currentOperationContext, this.requestInfo.ExistingInstanceContext, eventTraceActivity);
TraceUtility.MessageFlowAtMessageReceived(message, currentOperationContext, eventTraceActivity, true);
rpc.TransactedBatchContext = this.transactedBatchContext;
// passing responsibility for call throttle to MessageRpc
// (MessageRpc implicitly owns this throttle once it's created)
this.requestInfo.ChannelHandlerOwnsCallThrottle = false;
// explicitly passing responsibility for instance throttle to MessageRpc
rpc.MessageRpcOwnsInstanceContextThrottle = this.requestInfo.ChannelHandlerOwnsInstanceContextThrottle;
this.requestInfo.ChannelHandlerOwnsInstanceContextThrottle = false;
// These need to happen before Dispatch but after accessing any ChannelHandler
// state, because we go multi-threaded after this until we reacquire pump mutex.
this.ReleasePump();
releasedPump = true;
return operation.Parent.Dispatch(ref rpc, hasOperationContextBeenSet);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
return this.HandleError(e, request, channel);
}
finally
{
if (!releasedPump)
{
this.ReleasePump();
}
}
}
internal void DispatchDone()
{
if (this.throttle != null)
{
this.throttle.DeactivateCall();
}
}
RequestContext GetSessionOpenNotificationRequestContext()
{
Fx.Assert(this.sessionOpenNotification != null, "this.sessionOpenNotification should not be null.");
Message message = Message.CreateMessage(this.Binder.Channel.GetProperty<MessageVersion>(), OperationDescription.SessionOpenedAction);
Fx.Assert(this.LocalAddress != null, "this.LocalAddress should not be null.");
message.Headers.To = this.LocalAddress.Uri;
this.sessionOpenNotification.UpdateMessageProperties(message.Properties);
return this.Binder.CreateRequestContext(message);
}
bool EndTryReceive(IAsyncResult result, out RequestContext requestContext)
{
bool valid;
if (this.needToCreateSessionOpenNotificationMessage)
{
this.needToCreateSessionOpenNotificationMessage = false;
Fx.Assert(result is CompletedAsyncResult, "result must be CompletedAsyncResult");
CompletedAsyncResult.End(result);
requestContext = this.GetSessionOpenNotificationRequestContext();
valid = true;
}
else
{
valid = this.receiver.EndTryReceive(result, out requestContext);
}
if (valid)
{
this.HandleReceiveComplete(requestContext);
}
return valid;
}
void EnsureChannelAndEndpoint(RequestContext request)
{
this.requestInfo.Channel = this.channel;
if (this.requestInfo.Channel == null)
{
bool addressMatched;
if (this.hasSession)
{
this.requestInfo.Channel = this.GetSessionChannel(request.RequestMessage, out this.requestInfo.Endpoint, out addressMatched);
}
else
{
this.requestInfo.Channel = this.GetDatagramChannel(request.RequestMessage, out this.requestInfo.Endpoint, out addressMatched);
}
if (this.requestInfo.Channel == null)
{
this.host.RaiseUnknownMessageReceived(request.RequestMessage);
if (addressMatched)
{
this.ReplyContractFilterDidNotMatch(request);
}
else
{
this.ReplyAddressFilterDidNotMatch(request);
}
}
}
else
{
this.requestInfo.Endpoint = this.requestInfo.Channel.EndpointDispatcher;
//For sessionful contracts, the InstanceContext throttle is not copied over to the channel
//as we create the channel before acquiring the lock
if (this.InstanceContextServiceThrottle != null && this.requestInfo.Channel.InstanceContextServiceThrottle == null)
{
this.requestInfo.Channel.InstanceContextServiceThrottle = this.InstanceContextServiceThrottle;
}
}
this.requestInfo.EndpointLookupDone = true;
if (this.requestInfo.Channel == null)
{
// SFx drops a message here
TraceUtility.TraceDroppedMessage(request.RequestMessage, this.requestInfo.Endpoint);
request.Close();
return;
}
if (this.requestInfo.Channel.HasSession || this.isCallback)
{
this.requestInfo.DispatchRuntime = this.requestInfo.Channel.DispatchRuntime;
}
else
{
this.requestInfo.DispatchRuntime = this.requestInfo.Endpoint.DispatchRuntime;
}
}
void EnsurePump()
{
if (null == this.sharedTransactedBatchContext || this.isMainTransactedBatchHandler)
{
if (TryAcquirePump())
{
if (this.receiveSynchronously)
{
ActionItem.Schedule(ChannelHandler.onStartSyncMessagePump, this);
}
else
{
if (Thread.CurrentThread.IsThreadPoolThread)
{
IAsyncResult result = this.BeginTryReceive();
if ((result != null) && result.CompletedSynchronously)
{
ActionItem.Schedule(ChannelHandler.onContinueAsyncReceive, result);
}
}
else
{
// Since this is not a threadpool thread, we don't know if this thread will exit
// while the IO is still pending (which would cancel the IO), so we have to get
// over to a threadpool thread which we know will not exit while there is pending IO.
ActionItem.Schedule(ChannelHandler.onStartAsyncMessagePump, this);
}
}
}
}
else
{
ActionItem.Schedule(ChannelHandler.onStartSingleTransactedBatch, this);
}
}
ServiceChannel GetDatagramChannel(Message message, out EndpointDispatcher endpoint, out bool addressMatched)
{
addressMatched = false;
endpoint = this.GetEndpointDispatcher(message, out addressMatched);
if (endpoint == null)
{
return null;
}
if (endpoint.DatagramChannel == null)
{
lock (this.listener.ThisLock)
{
if (endpoint.DatagramChannel == null)
{
endpoint.DatagramChannel = new ServiceChannel(this.binder, endpoint, this.listener.ChannelDispatcher, this.idleManager);
this.InitializeServiceChannel(endpoint.DatagramChannel);
}
}
}
return endpoint.DatagramChannel;
}
EndpointDispatcher GetEndpointDispatcher(Message message, out bool addressMatched)
{
return this.listener.Endpoints.Lookup(message, out addressMatched);
}
ServiceChannel GetSessionChannel(Message message, out EndpointDispatcher endpoint, out bool addressMatched)
{
addressMatched = false;
if (this.channel == null)
{
lock (this.ThisLock)
{
if (this.channel == null)
{
endpoint = this.GetEndpointDispatcher(message, out addressMatched);
if (endpoint != null)
{
this.channel = new ServiceChannel(this.binder, endpoint, this.listener.ChannelDispatcher, this.idleManager);
this.InitializeServiceChannel(this.channel);
}
}
}
}
if (this.channel == null)
{
endpoint = null;
}
else
{
endpoint = this.channel.EndpointDispatcher;
}
return this.channel;
}
void InitializeServiceChannel(ServiceChannel channel)
{
if (this.wasChannelThrottled)
{
// TFS#500703, when the idle timeout was hit, the constructor of ServiceChannel will abort itself directly. So
// the session throttle will not be released and thus lead to a service unavailablity.
// Note that if the channel is already aborted, the next line "channel.ServiceThrottle = this.throttle;" will throw an exception,
// so we are not going to do any more work inside this method.
// Ideally we should do a thorough refactoring work for this throttling issue. However, it's too risky as a QFE. We should consider
// this in a whole release.
// Note that the "wasChannelThrottled" boolean will only be true if we aquired the session throttle. So we don't have to check HasSession
// again here.
if (channel.Aborted && this.throttle != null)
{
// This line will release the "session" throttle.
this.throttle.DeactivateChannel();
}
channel.ServiceThrottle = this.throttle;
}
if (this.InstanceContextServiceThrottle != null)
{
channel.InstanceContextServiceThrottle = this.InstanceContextServiceThrottle;
}
ClientRuntime clientRuntime = channel.ClientRuntime;
if (clientRuntime != null)
{
Type contractType = clientRuntime.ContractClientType;
Type callbackType = clientRuntime.CallbackClientType;
if (contractType != null)
{
channel.Proxy = ServiceChannelFactory.CreateProxy(contractType, callbackType, MessageDirection.Output, channel);
}
}
if (this.listener != null)
{
this.listener.ChannelDispatcher.InitializeChannel((IClientChannel)channel.Proxy);
}
((IChannel)channel).Open();
}
void ProvideFault(Exception e, ref ErrorHandlerFaultInfo faultInfo)
{
if (this.listener != null)
{
this.listener.ChannelDispatcher.ProvideFault(e, this.requestInfo.Channel == null ? this.binder.Channel.GetProperty<FaultConverter>() : this.requestInfo.Channel.GetProperty<FaultConverter>(), ref faultInfo);
}
else if (this.channel != null)
{
DispatchRuntime dispatchBehavior = this.channel.ClientRuntime.CallbackDispatchRuntime;
dispatchBehavior.ChannelDispatcher.ProvideFault(e, this.channel.GetProperty<FaultConverter>(), ref faultInfo);
}
}
internal bool HandleError(Exception e)
{
ErrorHandlerFaultInfo dummy = new ErrorHandlerFaultInfo();
return this.HandleError(e, ref dummy);
}
bool HandleError(Exception e, ref ErrorHandlerFaultInfo faultInfo)
{
if (e == null)
{
Fx.Assert(SR.GetString(SR.GetString(SR.SFxNonExceptionThrown)));
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.GetString(SR.SFxNonExceptionThrown))));
}
if (this.listener != null)
{
return listener.ChannelDispatcher.HandleError(e, ref faultInfo);
}
else if (this.channel != null)
{
return this.channel.ClientRuntime.CallbackDispatchRuntime.ChannelDispatcher.HandleError(e, ref faultInfo);
}
else
{
return false;
}
}
bool HandleError(Exception e, RequestContext request, ServiceChannel channel)
{
ErrorHandlerFaultInfo faultInfo = new ErrorHandlerFaultInfo(this.messageVersion.Addressing.DefaultFaultAction);
bool replied, replySentAsync;
ProvideFaultAndReplyFailure(request, e, ref faultInfo, out replied, out replySentAsync);
if (!replySentAsync)
{
return this.HandleErrorContinuation(e, request, channel, ref faultInfo, replied);
}
else
{
return false;
}
}
bool HandleErrorContinuation(Exception e, RequestContext request, ServiceChannel channel, ref ErrorHandlerFaultInfo faultInfo, bool replied)
{
if (replied)
{
try
{
request.Close();
}
catch (Exception e1)
{
if (Fx.IsFatal(e1))
{
throw;
}
this.HandleError(e1);
}
}
else
{
request.Abort();
}
if (!this.HandleError(e, ref faultInfo) && this.hasSession)
{
if (channel != null)
{
if (replied)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(CloseAfterFaultTimeout);
try
{
channel.Close(timeoutHelper.RemainingTime());
}
catch (Exception e2)
{
if (Fx.IsFatal(e2))
{
throw;
}
this.HandleError(e2);
}
try
{
this.binder.CloseAfterFault(timeoutHelper.RemainingTime());
}
catch (Exception e3)
{
if (Fx.IsFatal(e3))
{
throw;
}
this.HandleError(e3);
}
}
else
{
channel.Abort();
this.binder.Abort();
}
}
else
{
if (replied)
{
try
{
this.binder.CloseAfterFault(CloseAfterFaultTimeout);
}
catch (Exception e4)
{
if (Fx.IsFatal(e4))
{
throw;
}
this.HandleError(e4);
}
}
else
{
this.binder.Abort();
}
}
}
return true;
}
void HandleReceiveComplete(RequestContext context)
{
try
{
if (this.channel != null)
{
this.channel.HandleReceiveComplete(context);
}
else
{
if (context == null && this.hasSession)
{
bool close;
lock (this.ThisLock)
{
close = !this.doneReceiving;
this.doneReceiving = true;
}
if (close)
{
this.receiver.Close();
if (this.idleManager != null)
{
this.idleManager.CancelTimer();
}
ServiceThrottle throttle = this.throttle;
if (throttle != null)
{
throttle.DeactivateChannel();
}
}
}
}
}
finally
{
if ((context == null) && this.incrementedActivityCountInConstructor)
{
this.listener.ChannelDispatcher.Channels.DecrementActivityCount();
}
}
}
bool HandleRequest(RequestContext request, OperationContext currentOperationContext)
{
if (request == null)
{
// channel EOF, stop receiving
return false;
}
ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? TraceUtility.ExtractActivity(request) : null;
using (ServiceModelActivity.BoundOperation(activity))
{
if (this.HandleRequestAsReply(request))
{
this.ReleasePump();
return true;
}
if (this.isChannelTerminated)
{
this.ReleasePump();
this.ReplyChannelTerminated(request);
return true;
}
if (this.requestInfo.RequestContext != null)
{
Fx.Assert("ChannelHandler.HandleRequest: this.requestInfo.RequestContext != null");
}
this.requestInfo.RequestContext = request;
if (!this.TryAcquireCallThrottle(request))
{
// this.ThrottleAcquiredForCall will be called to continue
return false;
}
// NOTE: from here on down, ensure that this code is the same as ThrottleAcquiredForCall (see 55460)
if (this.requestInfo.ChannelHandlerOwnsCallThrottle)
{
Fx.Assert("ChannelHandler.HandleRequest: this.requestInfo.ChannelHandlerOwnsCallThrottle");
}
this.requestInfo.ChannelHandlerOwnsCallThrottle = true;
if (!this.TryRetrievingInstanceContext(request))
{
//Would have replied and close the request.
return true;
}
this.requestInfo.Channel.CompletedIOOperation();
//Only acquire InstanceContext throttle if one doesnt already exist.
if (!this.TryAcquireThrottle(request, (this.requestInfo.ExistingInstanceContext == null)))
{
// this.ThrottleAcquired will be called to continue
return false;
}
if (this.requestInfo.ChannelHandlerOwnsInstanceContextThrottle)
{
Fx.Assert("ChannelHandler.HandleRequest: this.requestInfo.ChannelHandlerOwnsInstanceContextThrottle");
}
this.requestInfo.ChannelHandlerOwnsInstanceContextThrottle = (this.requestInfo.ExistingInstanceContext == null);
if (!this.DispatchAndReleasePump(request, true, currentOperationContext))
{
// this.DispatchDone will be called to continue
return false;
}
}
return true;
}
bool HandleRequestAsReply(RequestContext request)
{
if (this.duplexBinder != null)
{
if (this.duplexBinder.HandleRequestAsReply(request.RequestMessage))
{
return true;
}
}
return false;
}
static void OnStartAsyncMessagePump(object state)
{
((ChannelHandler)state).AsyncMessagePump();
}
static void OnStartSyncMessagePump(object state)
{
ChannelHandler handler = state as ChannelHandler;
if (TD.ChannelReceiveStopIsEnabled())
{
TD.ChannelReceiveStop(handler.EventTraceActivity, state.GetHashCode());
}
if (handler.receiveWithTransaction)
{
handler.SyncTransactionalMessagePump();
}
else
{
handler.SyncMessagePump();
}
}
static void OnStartSingleTransactedBatch(object state)
{
ChannelHandler handler = state as ChannelHandler;
handler.TransactedBatchLoop();
}
static void OnAsyncReceiveComplete(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
((ChannelHandler)result.AsyncState).AsyncMessagePump(result);
}
}
static void OnContinueAsyncReceive(object state)
{
IAsyncResult result = (IAsyncResult)state;
((ChannelHandler)result.AsyncState).AsyncMessagePump(result);
}
static void OpenAndEnsurePump(object state)
{
((ChannelHandler)state).OpenAndEnsurePump();
}
void OpenAndEnsurePump()
{
Exception exception = null;
try
{
this.binder.Channel.Open();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
exception = e;
}
if (exception != null)
{
if (DiagnosticUtility.ShouldTraceWarning)
{
TraceUtility.TraceEvent(System.Diagnostics.TraceEventType.Warning,
TraceCode.FailedToOpenIncomingChannel,
SR.GetString(SR.TraceCodeFailedToOpenIncomingChannel));
}
SessionIdleManager idleManager = this.idleManager;
if (idleManager != null)
{
idleManager.CancelTimer();
}
if ((this.throttle != null) && this.hasSession)
{
this.throttle.DeactivateChannel();
}
bool errorHandled = this.HandleError(exception);
if (this.incrementedActivityCountInConstructor)
{
this.listener.ChannelDispatcher.Channels.DecrementActivityCount();
}
if (!errorHandled)
{
this.binder.Channel.Abort();
}
}
else
{
this.EnsurePump();
}
}
bool TryReceive(TimeSpan timeout, out RequestContext requestContext)
{
this.shouldRejectMessageWithOnOpenActionHeader = !this.needToCreateSessionOpenNotificationMessage;
bool valid;
if (this.needToCreateSessionOpenNotificationMessage)
{
this.needToCreateSessionOpenNotificationMessage = false;
requestContext = this.GetSessionOpenNotificationRequestContext();
valid = true;
}
else
{
valid = this.receiver.TryReceive(timeout, out requestContext);
}
if (valid)
{
this.HandleReceiveComplete(requestContext);
}
return valid;
}
void ReplyAddressFilterDidNotMatch(RequestContext request)
{
FaultCode code = FaultCode.CreateSenderFaultCode(AddressingStrings.DestinationUnreachable,
this.messageVersion.Addressing.Namespace);
string reason = SR.GetString(SR.SFxNoEndpointMatchingAddress, request.RequestMessage.Headers.To);
ReplyFailure(request, code, reason);
}
void ReplyContractFilterDidNotMatch(RequestContext request)
{
// By default, the contract filter is just a filter over the set of initiating actions in
// the contract, so we do error messages accordingly
AddressingVersion addressingVersion = this.messageVersion.Addressing;
if (addressingVersion != AddressingVersion.None && request.RequestMessage.Headers.Action == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new MessageHeaderException(
SR.GetString(SR.SFxMissingActionHeader, addressingVersion.Namespace), AddressingStrings.Action, addressingVersion.Namespace));
}
else
{
// some of this code is duplicated in DispatchRuntime.UnhandledActionInvoker
// ideally both places would use FaultConverter and ActionNotSupportedException
FaultCode code = FaultCode.CreateSenderFaultCode(AddressingStrings.ActionNotSupported,
this.messageVersion.Addressing.Namespace);
string reason = SR.GetString(SR.SFxNoEndpointMatchingContract, request.RequestMessage.Headers.Action);
ReplyFailure(request, code, reason, this.messageVersion.Addressing.FaultAction);
}
}
void ReplyChannelTerminated(RequestContext request)
{
FaultCode code = FaultCode.CreateSenderFaultCode(FaultCodeConstants.Codes.SessionTerminated,
FaultCodeConstants.Namespaces.NetDispatch);
string reason = SR.GetString(SR.SFxChannelTerminated0);
string action = FaultCodeConstants.Actions.NetDispatcher;
Message fault = Message.CreateMessage(this.messageVersion, code, reason, action);
ReplyFailure(request, fault, action, reason, code);
}
void ReplyFailure(RequestContext request, FaultCode code, string reason)
{
string action = this.messageVersion.Addressing.DefaultFaultAction;
ReplyFailure(request, code, reason, action);
}
void ReplyFailure(RequestContext request, FaultCode code, string reason, string action)
{
Message fault = Message.CreateMessage(this.messageVersion, code, reason, action);
ReplyFailure(request, fault, action, reason, code);
}
void ReplyFailure(RequestContext request, Message fault, string action, string reason, FaultCode code)
{
FaultException exception = new FaultException(reason, code);
ErrorBehavior.ThrowAndCatch(exception);
ErrorHandlerFaultInfo faultInfo = new ErrorHandlerFaultInfo(action);
faultInfo.Fault = fault;
bool replied, replySentAsync;
ProvideFaultAndReplyFailure(request, exception, ref faultInfo, out replied, out replySentAsync);
this.HandleError(exception, ref faultInfo);
}
void ProvideFaultAndReplyFailure(RequestContext request, Exception exception, ref ErrorHandlerFaultInfo faultInfo, out bool replied, out bool replySentAsync)
{
replied = false;
replySentAsync = false;
bool requestMessageIsFault = false;
try
{
requestMessageIsFault = request.RequestMessage.IsFault;
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
// ---- it
}
bool enableFaults = false;
if (this.listener != null)
{
enableFaults = this.listener.ChannelDispatcher.EnableFaults;
}
else if (this.channel != null && this.channel.IsClient)
{
enableFaults = this.channel.ClientRuntime.EnableFaults;
}
if ((!requestMessageIsFault) && enableFaults)
{
this.ProvideFault(exception, ref faultInfo);
if (faultInfo.Fault != null)
{
Message reply = faultInfo.Fault;
try
{
try
{
if (this.PrepareReply(request, reply))
{
if (this.sendAsynchronously)
{
var state = new ContinuationState { ChannelHandler = this, Channel = channel, Exception = exception, FaultInfo = faultInfo, Request = request, Reply = reply };
var result = request.BeginReply(reply, ChannelHandler.onAsyncReplyComplete, state);
if (result.CompletedSynchronously)
{
ChannelHandler.AsyncReplyComplete(result, state);
replied = true;
}
else
{
replySentAsync = true;
}
}
else
{
request.Reply(reply);
replied = true;
}
}
}
finally
{
if (!replySentAsync)
{
reply.Close();
}
}
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
this.HandleError(e);
}
}
}
}
/// <summary>
/// Prepares a reply that can either be sent asynchronously or synchronously depending on the value of
/// sendAsynchronously
/// </summary>
/// <param name="request">The request context to prepare</param>
/// <param name="reply">The reply to prepare</param>
/// <returns>True if channel is open and prepared reply should be sent; otherwise false.</returns>
bool PrepareReply(RequestContext request, Message reply)
{
// Ensure we only reply once (we may hit the same error multiple times)
if (this.replied == request)
{
return false;
}
this.replied = request;
bool canSendReply = true;
Message requestMessage = null;
try
{
requestMessage = request.RequestMessage;
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
// ---- it
}
if (!object.ReferenceEquals(requestMessage, null))
{
UniqueId requestID = null;
try
{
requestID = requestMessage.Headers.MessageId;
}
catch (MessageHeaderException)
{
// ---- it - we don't need to correlate the reply if the MessageId header is bad
}
if (!object.ReferenceEquals(requestID, null) && !this.isManualAddressing)
{
System.ServiceModel.Channels.RequestReplyCorrelator.PrepareReply(reply, requestID);
}
if (!this.hasSession && !this.isManualAddressing)
{
try
{
canSendReply = System.ServiceModel.Channels.RequestReplyCorrelator.AddressReply(reply, requestMessage);
}
catch (MessageHeaderException)
{
// ---- it - we don't need to address the reply if the FaultTo header is bad
}
}
}
// ObjectDisposeException can happen
// if the channel is closed in a different
// thread. 99% this check will avoid false
// exceptions.
return this.IsOpen && canSendReply;
}
static void AsyncReplyComplete(IAsyncResult result, ContinuationState state)
{
try
{
state.Request.EndReply(result);
}
catch (Exception e)
{
DiagnosticUtility.TraceHandledException(e, System.Diagnostics.TraceEventType.Error);
if (Fx.IsFatal(e))
{
throw;
}
state.ChannelHandler.HandleError(e);
}
try
{
state.Reply.Close();
}
catch (Exception e)
{
DiagnosticUtility.TraceHandledException(e, System.Diagnostics.TraceEventType.Error);
if (Fx.IsFatal(e))
{
throw;
}
state.ChannelHandler.HandleError(e);
}
try
{
state.ChannelHandler.HandleErrorContinuation(state.Exception, state.Request, state.Channel, ref state.FaultInfo, true);
}
catch (Exception e)
{
DiagnosticUtility.TraceHandledException(e, System.Diagnostics.TraceEventType.Error);
if (Fx.IsFatal(e))
{
throw;
}
state.ChannelHandler.HandleError(e);
}
state.ChannelHandler.EnsurePump();
}
static void OnAsyncReplyComplete(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
try
{
var state = (ContinuationState)result.AsyncState;
ChannelHandler.AsyncReplyComplete(result, state);
}
catch (Exception e)
{
DiagnosticUtility.TraceHandledException(e, System.Diagnostics.TraceEventType.Error);
if (Fx.IsFatal(e))
{
throw;
}
}
}
void ReleasePump()
{
if (this.isConcurrent)
{
Interlocked.Exchange(ref this.isPumpAcquired, 0);
}
}
void SyncMessagePump()
{
OperationContext existingOperationContext = OperationContext.Current;
try
{
OperationContext currentOperationContext = new OperationContext(this.host);
OperationContext.Current = currentOperationContext;
for (;;)
{
RequestContext request;
this.requestInfo.Cleanup();
while (!TryReceive(TimeSpan.MaxValue, out request))
{
}
if (!HandleRequest(request, currentOperationContext))
{
break;
}
if (!TryAcquirePump())
{
break;
}
currentOperationContext.Recycle();
}
}
finally
{
OperationContext.Current = existingOperationContext;
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
void SyncTransactionalMessagePump()
{
for (;;)
{
bool completedSynchronously;
if (null == sharedTransactedBatchContext)
{
completedSynchronously = TransactedLoop();
}
else
{
completedSynchronously = TransactedBatchLoop();
}
if (!completedSynchronously)
{
return;
}
}
}
bool TransactedLoop()
{
try
{
this.receiver.WaitForMessage();
}
catch (Exception ex)
{
if (Fx.IsFatal(ex))
{
throw;
}
if (!this.HandleError(ex))
{
throw;
}
}
RequestContext request;
Transaction tx = CreateOrGetAttachedTransaction();
OperationContext existingOperationContext = OperationContext.Current;
try
{
OperationContext currentOperationContext = new OperationContext(this.host);
OperationContext.Current = currentOperationContext;
for (;;)
{
this.requestInfo.Cleanup();
bool received = TryTransactionalReceive(tx, out request);
if (!received)
{
return IsOpen;
}
if (null == request)
{
return false;
}
TransactionMessageProperty.Set(tx, request.RequestMessage);
if (!HandleRequest(request, currentOperationContext))
{
return false;
}
if (!TryAcquirePump())
{
return false;
}
tx = CreateOrGetAttachedTransaction();
currentOperationContext.Recycle();
}
}
finally
{
OperationContext.Current = existingOperationContext;
}
}
bool TransactedBatchLoop()
{
if (null != this.transactedBatchContext)
{
if (this.transactedBatchContext.InDispatch)
{
this.transactedBatchContext.ForceRollback();
this.transactedBatchContext.InDispatch = false;
}
if (!this.transactedBatchContext.IsActive)
{
if (!this.isMainTransactedBatchHandler)
{
return false;
}
this.transactedBatchContext = null;
}
}
if (null == this.transactedBatchContext)
{
try
{
this.receiver.WaitForMessage();
}
catch (Exception ex)
{
if (Fx.IsFatal(ex))
{
throw;
}
if (!this.HandleError(ex))
{
throw;
}
}
this.transactedBatchContext = this.sharedTransactedBatchContext.CreateTransactedBatchContext();
}
OperationContext existingOperationContext = OperationContext.Current;
try
{
OperationContext currentOperationContext = new OperationContext(this.host);
OperationContext.Current = currentOperationContext;
RequestContext request;
while (this.transactedBatchContext.IsActive)
{
this.requestInfo.Cleanup();
bool valid = TryTransactionalReceive(this.transactedBatchContext.Transaction, out request);
if (!valid)
{
if (this.IsOpen)
{
this.transactedBatchContext.ForceCommit();
return true;
}
else
{
this.transactedBatchContext.ForceRollback();
return false;
}
}
if (null == request)
{
this.transactedBatchContext.ForceRollback();
return false;
}
TransactionMessageProperty.Set(this.transactedBatchContext.Transaction, request.RequestMessage);
this.transactedBatchContext.InDispatch = true;
if (!HandleRequest(request, currentOperationContext))
{
return false;
}
if (this.transactedBatchContext.InDispatch)
{
this.transactedBatchContext.ForceRollback();
this.transactedBatchContext.InDispatch = false;
return true;
}
if (!TryAcquirePump())
{
Fx.Assert("System.ServiceModel.Dispatcher.ChannelHandler.TransactedBatchLoop(): (TryAcquiredPump returned false)");
return false;
}
currentOperationContext.Recycle();
}
}
finally
{
OperationContext.Current = existingOperationContext;
}
return true;
}
Transaction CreateOrGetAttachedTransaction()
{
if (null != this.acceptTransaction)
{
lock (ThisLock)
{
if (null != this.acceptTransaction)
{
Transaction tx = this.acceptTransaction.Transaction;
this.acceptTransaction = null;
return tx;
}
}
}
if (null != this.InstanceContext && this.InstanceContext.HasTransaction)
{
return InstanceContext.Transaction.Attached;
}
else
{
return TransactionBehavior.CreateTransaction(
this.listener.ChannelDispatcher.TransactionIsolationLevel,
TransactionBehavior.NormalizeTimeout(this.listener.ChannelDispatcher.TransactionTimeout));
}
}
// calls receive on the channel; returns false if no message during the "short timeout"
bool TryTransactionalReceive(Transaction tx, out RequestContext request)
{
request = null;
bool received = false;
try
{
using (TransactionScope scope = new TransactionScope(tx))
{
if (null != this.sharedTransactedBatchContext)
{
lock (this.sharedTransactedBatchContext.ReceiveLock)
{
if (this.transactedBatchContext.AboutToExpire)
{
return false;
}
received = this.receiver.TryReceive(TimeSpan.Zero, out request);
}
}
else
{
TimeSpan receiveTimeout = TimeoutHelper.Min(this.listener.ChannelDispatcher.TransactionTimeout, this.listener.ChannelDispatcher.DefaultCommunicationTimeouts.ReceiveTimeout);
received = this.receiver.TryReceive(TransactionBehavior.NormalizeTimeout(receiveTimeout), out request);
}
scope.Complete();
}
if (received)
{
this.HandleReceiveComplete(request);
}
}
catch (ObjectDisposedException ex) // thrown from the transaction
{
this.HandleError(ex);
request = null;
return false;
}
catch (TransactionException ex)
{
this.HandleError(ex);
request = null;
return false;
}
catch (Exception ex)
{
if (Fx.IsFatal(ex))
{
throw;
}
if (!this.HandleError(ex))
{
throw;
}
}
return received;
}
// This callback always occurs async and always on a dirty thread
internal void ThrottleAcquiredForCall()
{
RequestContext request = this.requestWaitingForThrottle;
this.requestWaitingForThrottle = null;
if (this.requestInfo.ChannelHandlerOwnsCallThrottle)
{
Fx.Assert("ChannelHandler.ThrottleAcquiredForCall: this.requestInfo.ChannelHandlerOwnsCallThrottle");
}
this.requestInfo.ChannelHandlerOwnsCallThrottle = true;
if (!this.TryRetrievingInstanceContext(request))
{
//Should reply/close request and also close the pump
this.EnsurePump();
return;
}
this.requestInfo.Channel.CompletedIOOperation();
if (this.TryAcquireThrottle(request, (this.requestInfo.ExistingInstanceContext == null)))
{
if (this.requestInfo.ChannelHandlerOwnsInstanceContextThrottle)
{
Fx.Assert("ChannelHandler.ThrottleAcquiredForCall: this.requestInfo.ChannelHandlerOwnsInstanceContextThrottle");
}
this.requestInfo.ChannelHandlerOwnsInstanceContextThrottle = (this.requestInfo.ExistingInstanceContext == null);
if (this.DispatchAndReleasePump(request, false, null))
{
this.EnsurePump();
}
}
}
bool TryRetrievingInstanceContext(RequestContext request)
{
try
{
return TryRetrievingInstanceContextCore(request);
}
catch (Exception ex)
{
if (Fx.IsFatal(ex))
{
throw;
}
DiagnosticUtility.TraceHandledException(ex, TraceEventType.Error);
try
{
request.Close();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
request.Abort();
}
return false;
}
}
//Return: False denotes failure, Caller should discard the request.
// : True denotes operation is sucessful.
bool TryRetrievingInstanceContextCore(RequestContext request)
{
bool releasePump = true;
try
{
if (!this.requestInfo.EndpointLookupDone)
{
this.EnsureChannelAndEndpoint(request);
}
if (this.requestInfo.Channel == null)
{
return false;
}
if (this.requestInfo.DispatchRuntime != null)
{
IContextChannel transparentProxy = this.requestInfo.Channel.Proxy as IContextChannel;
try
{
this.requestInfo.ExistingInstanceContext = this.requestInfo.DispatchRuntime.InstanceContextProvider.GetExistingInstanceContext(request.RequestMessage, transparentProxy);
releasePump = false;
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
this.requestInfo.Channel = null;
this.HandleError(e, request, channel);
return false;
}
}
else
{
// This can happen if we are pumping for an async client,
// and we receive a bogus reply. In that case, there is no
// DispatchRuntime, because we are only expecting replies.
//
// One possible fix for this would be in DuplexChannelBinder
// to drop all messages with a RelatesTo that do not match a
// pending request.
//
// However, that would not fix:
// (a) we could get a valid request message with a
// RelatesTo that we should try to process.
// (b) we could get a reply message that does not have
// a RelatesTo.
//
// So we do the null check here.
//
// SFx drops a message here
TraceUtility.TraceDroppedMessage(request.RequestMessage, this.requestInfo.Endpoint);
request.Close();
return false;
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
this.HandleError(e, request, channel);
return false;
}
finally
{
if (releasePump)
{
this.ReleasePump();
}
}
return true;
}
// This callback always occurs async and always on a dirty thread
internal void ThrottleAcquired()
{
RequestContext request = this.requestWaitingForThrottle;
this.requestWaitingForThrottle = null;
if (this.requestInfo.ChannelHandlerOwnsInstanceContextThrottle)
{
Fx.Assert("ChannelHandler.ThrottleAcquired: this.requestInfo.ChannelHandlerOwnsInstanceContextThrottle");
}
this.requestInfo.ChannelHandlerOwnsInstanceContextThrottle = (this.requestInfo.ExistingInstanceContext == null);
if (this.DispatchAndReleasePump(request, false, null))
{
this.EnsurePump();
}
}
bool TryAcquireThrottle(RequestContext request, bool acquireInstanceContextThrottle)
{
ServiceThrottle throttle = this.throttle;
if ((throttle != null) && (throttle.IsActive))
{
this.requestWaitingForThrottle = request;
if (throttle.AcquireInstanceContextAndDynamic(this, acquireInstanceContextThrottle))
{
this.requestWaitingForThrottle = null;
return true;
}
else
{
return false;
}
}
else
{
return true;
}
}
bool TryAcquireCallThrottle(RequestContext request)
{
ServiceThrottle throttle = this.throttle;
if ((throttle != null) && (throttle.IsActive))
{
this.requestWaitingForThrottle = request;
if (throttle.AcquireCall(this))
{
this.requestWaitingForThrottle = null;
return true;
}
else
{
return false;
}
}
else
{
return true;
}
}
bool TryAcquirePump()
{
if (this.isConcurrent)
{
return Interlocked.CompareExchange(ref this.isPumpAcquired, 1, 0) == 0;
}
return true;
}
struct RequestInfo
{
public EndpointDispatcher Endpoint;
public InstanceContext ExistingInstanceContext;
public ServiceChannel Channel;
public bool EndpointLookupDone;
public DispatchRuntime DispatchRuntime;
public RequestContext RequestContext;
public ChannelHandler ChannelHandler;
public bool ChannelHandlerOwnsCallThrottle; // if true, we are responsible for call throttle
public bool ChannelHandlerOwnsInstanceContextThrottle; // if true, we are responsible for instance/dynamic throttle
public RequestInfo(ChannelHandler channelHandler)
{
this.Endpoint = null;
this.ExistingInstanceContext = null;
this.Channel = null;
this.EndpointLookupDone = false;
this.DispatchRuntime = null;
this.RequestContext = null;
this.ChannelHandler = channelHandler;
this.ChannelHandlerOwnsCallThrottle = false;
this.ChannelHandlerOwnsInstanceContextThrottle = false;
}
public void Cleanup()
{
if (this.ChannelHandlerOwnsInstanceContextThrottle)
{
this.ChannelHandler.throttle.DeactivateInstanceContext();
this.ChannelHandlerOwnsInstanceContextThrottle = false;
}
this.Endpoint = null;
this.ExistingInstanceContext = null;
this.Channel = null;
this.EndpointLookupDone = false;
this.RequestContext = null;
if (this.ChannelHandlerOwnsCallThrottle)
{
this.ChannelHandler.DispatchDone();
this.ChannelHandlerOwnsCallThrottle = false;
}
}
}
EventTraceActivity TraceDispatchMessageStart(Message message)
{
if (FxTrace.Trace.IsEnd2EndActivityTracingEnabled && message != null)
{
EventTraceActivity eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message);
if (TD.DispatchMessageStartIsEnabled())
{
TD.DispatchMessageStart(eventTraceActivity);
}
return eventTraceActivity;
}
return null;
}
/// <summary>
/// Data structure used to carry state for asynchronous replies
/// </summary>
struct ContinuationState
{
public ChannelHandler ChannelHandler;
public Exception Exception;
public RequestContext Request;
public Message Reply;
public ServiceChannel Channel;
public ErrorHandlerFaultInfo FaultInfo;
}
}
}
| |
// 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.Globalization;
using System.IO;
using System.Net.Cache;
using System.Net.Sockets;
using System.Security;
using System.Runtime.ExceptionServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net
{
internal enum FtpOperation
{
DownloadFile = 0,
ListDirectory = 1,
ListDirectoryDetails = 2,
UploadFile = 3,
UploadFileUnique = 4,
AppendFile = 5,
DeleteFile = 6,
GetDateTimestamp = 7,
GetFileSize = 8,
Rename = 9,
MakeDirectory = 10,
RemoveDirectory = 11,
PrintWorkingDirectory = 12,
Other = 13,
}
[Flags]
internal enum FtpMethodFlags
{
None = 0x0,
IsDownload = 0x1,
IsUpload = 0x2,
TakesParameter = 0x4,
MayTakeParameter = 0x8,
DoesNotTakeParameter = 0x10,
ParameterIsDirectory = 0x20,
ShouldParseForResponseUri = 0x40,
HasHttpCommand = 0x80,
MustChangeWorkingDirectoryToPath = 0x100
}
internal class FtpMethodInfo
{
internal string Method;
internal FtpOperation Operation;
internal FtpMethodFlags Flags;
internal string HttpCommand;
internal FtpMethodInfo(string method,
FtpOperation operation,
FtpMethodFlags flags,
string httpCommand)
{
Method = method;
Operation = operation;
Flags = flags;
HttpCommand = httpCommand;
}
internal bool HasFlag(FtpMethodFlags flags)
{
return (Flags & flags) != 0;
}
internal bool IsCommandOnly
{
get { return (Flags & (FtpMethodFlags.IsDownload | FtpMethodFlags.IsUpload)) == 0; }
}
internal bool IsUpload
{
get { return (Flags & FtpMethodFlags.IsUpload) != 0; }
}
internal bool IsDownload
{
get { return (Flags & FtpMethodFlags.IsDownload) != 0; }
}
/// <summary>
/// <para>True if we should attempt to get a response uri
/// out of a server response</para>
/// </summary>
internal bool ShouldParseForResponseUri
{
get { return (Flags & FtpMethodFlags.ShouldParseForResponseUri) != 0; }
}
internal static FtpMethodInfo GetMethodInfo(string method)
{
method = method.ToUpper(CultureInfo.InvariantCulture);
foreach (FtpMethodInfo methodInfo in s_knownMethodInfo)
if (method == methodInfo.Method)
return methodInfo;
// We don't support generic methods
throw new ArgumentException(SR.net_ftp_unsupported_method, nameof(method));
}
private static readonly FtpMethodInfo[] s_knownMethodInfo =
{
new FtpMethodInfo(WebRequestMethods.Ftp.DownloadFile,
FtpOperation.DownloadFile,
FtpMethodFlags.IsDownload
| FtpMethodFlags.HasHttpCommand
| FtpMethodFlags.TakesParameter,
"GET"),
new FtpMethodInfo(WebRequestMethods.Ftp.ListDirectory,
FtpOperation.ListDirectory,
FtpMethodFlags.IsDownload
| FtpMethodFlags.MustChangeWorkingDirectoryToPath
| FtpMethodFlags.HasHttpCommand
| FtpMethodFlags.MayTakeParameter,
"GET"),
new FtpMethodInfo(WebRequestMethods.Ftp.ListDirectoryDetails,
FtpOperation.ListDirectoryDetails,
FtpMethodFlags.IsDownload
| FtpMethodFlags.MustChangeWorkingDirectoryToPath
| FtpMethodFlags.HasHttpCommand
| FtpMethodFlags.MayTakeParameter,
"GET"),
new FtpMethodInfo(WebRequestMethods.Ftp.UploadFile,
FtpOperation.UploadFile,
FtpMethodFlags.IsUpload
| FtpMethodFlags.TakesParameter,
null),
new FtpMethodInfo(WebRequestMethods.Ftp.UploadFileWithUniqueName,
FtpOperation.UploadFileUnique,
FtpMethodFlags.IsUpload
| FtpMethodFlags.MustChangeWorkingDirectoryToPath
| FtpMethodFlags.DoesNotTakeParameter
| FtpMethodFlags.ShouldParseForResponseUri,
null),
new FtpMethodInfo(WebRequestMethods.Ftp.AppendFile,
FtpOperation.AppendFile,
FtpMethodFlags.IsUpload
| FtpMethodFlags.TakesParameter,
null),
new FtpMethodInfo(WebRequestMethods.Ftp.DeleteFile,
FtpOperation.DeleteFile,
FtpMethodFlags.TakesParameter,
null),
new FtpMethodInfo(WebRequestMethods.Ftp.GetDateTimestamp,
FtpOperation.GetDateTimestamp,
FtpMethodFlags.TakesParameter,
null),
new FtpMethodInfo(WebRequestMethods.Ftp.GetFileSize,
FtpOperation.GetFileSize,
FtpMethodFlags.TakesParameter,
null),
new FtpMethodInfo(WebRequestMethods.Ftp.Rename,
FtpOperation.Rename,
FtpMethodFlags.TakesParameter,
null),
new FtpMethodInfo(WebRequestMethods.Ftp.MakeDirectory,
FtpOperation.MakeDirectory,
FtpMethodFlags.TakesParameter
| FtpMethodFlags.ParameterIsDirectory,
null),
new FtpMethodInfo(WebRequestMethods.Ftp.RemoveDirectory,
FtpOperation.RemoveDirectory,
FtpMethodFlags.TakesParameter
| FtpMethodFlags.ParameterIsDirectory,
null),
new FtpMethodInfo(WebRequestMethods.Ftp.PrintWorkingDirectory,
FtpOperation.PrintWorkingDirectory,
FtpMethodFlags.DoesNotTakeParameter,
null)
};
}
/// <summary>
/// The FtpWebRequest class implements a basic FTP client interface.
/// </summary>
public sealed class FtpWebRequest : WebRequest
{
private object _syncObject;
private ICredentials _authInfo;
private readonly Uri _uri;
private FtpMethodInfo _methodInfo;
private string _renameTo = null;
private bool _getRequestStreamStarted;
private bool _getResponseStarted;
private DateTime _startTime;
private int _timeout = s_DefaultTimeout;
private int _remainingTimeout;
private long _contentLength = 0;
private long _contentOffset = 0;
private X509CertificateCollection _clientCertificates;
private bool _passive = true;
private bool _binary = true;
private string _connectionGroupName;
private ServicePoint _servicePoint;
private bool _async;
private bool _aborted;
private bool _timedOut;
private Exception _exception;
private TimerThread.Queue _timerQueue = s_DefaultTimerQueue;
private readonly TimerThread.Callback _timerCallback;
private bool _enableSsl;
private FtpControlStream _connection;
private Stream _stream;
private RequestStage _requestStage;
private bool _onceFailed;
private WebHeaderCollection _ftpRequestHeaders;
private FtpWebResponse _ftpWebResponse;
private int _readWriteTimeout = 5 * 60 * 1000; // 5 minutes.
private ContextAwareResult _writeAsyncResult;
private LazyAsyncResult _readAsyncResult;
private LazyAsyncResult _requestCompleteAsyncResult;
private static readonly NetworkCredential s_defaultFtpNetworkCredential = new NetworkCredential("anonymous", "anonymous@", string.Empty);
private const int s_DefaultTimeout = 100000; // 100 seconds
private static readonly TimerThread.Queue s_DefaultTimerQueue = TimerThread.GetOrCreateQueue(s_DefaultTimeout);
// Used by FtpControlStream
internal FtpMethodInfo MethodInfo
{
get
{
return _methodInfo;
}
}
public static new RequestCachePolicy DefaultCachePolicy
{
get
{
return WebRequest.DefaultCachePolicy;
}
set
{
// We don't support caching, so ignore attempts to set this property.
}
}
/// <summary>
/// <para>
/// Selects FTP command to use. WebRequestMethods.Ftp.DownloadFile is default.
/// Not allowed to be changed once request is started.
/// </para>
/// </summary>
public override string Method
{
get
{
return _methodInfo.Method;
}
set
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException(SR.net_ftp_invalid_method_name, nameof(value));
}
if (InUse)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
try
{
_methodInfo = FtpMethodInfo.GetMethodInfo(value);
}
catch (ArgumentException)
{
throw new ArgumentException(SR.net_ftp_unsupported_method, nameof(value));
}
}
}
/// <summary>
/// <para>
/// Sets the target name for the WebRequestMethods.Ftp.Rename command.
/// Not allowed to be changed once request is started.
/// </para>
/// </summary>
public string RenameTo
{
get
{
return _renameTo;
}
set
{
if (InUse)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException(SR.net_ftp_invalid_renameto, nameof(value));
}
_renameTo = value;
}
}
/// <summary>
/// <para>Used for clear text authentication with FTP server</para>
/// </summary>
public override ICredentials Credentials
{
get
{
return _authInfo;
}
set
{
if (InUse)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (value == CredentialCache.DefaultNetworkCredentials)
{
throw new ArgumentException(SR.net_ftp_no_defaultcreds, nameof(value));
}
_authInfo = value;
}
}
/// <summary>
/// <para>Gets the Uri used to make the request</para>
/// </summary>
public override Uri RequestUri
{
get
{
return _uri;
}
}
/// <summary>
/// <para>Timeout of the blocking calls such as GetResponse and GetRequestStream (default 100 secs)</para>
/// </summary>
public override int Timeout
{
get
{
return _timeout;
}
set
{
if (InUse)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
if (value < 0 && value != System.Threading.Timeout.Infinite)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_ge_zero);
}
if (_timeout != value)
{
_timeout = value;
_timerQueue = null;
}
}
}
internal int RemainingTimeout
{
get
{
return _remainingTimeout;
}
}
/// <summary>
/// <para>Used to control the Timeout when calling Stream.Read and Stream.Write.
/// Applies to Streams returned from GetResponse().GetResponseStream() and GetRequestStream().
/// Default is 5 mins.
/// </para>
/// </summary>
public int ReadWriteTimeout
{
get
{
return _readWriteTimeout;
}
set
{
if (_getResponseStarted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
if (value <= 0 && value != System.Threading.Timeout.Infinite)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_gt_zero);
}
_readWriteTimeout = value;
}
}
/// <summary>
/// <para>Used to specify what offset we will read at</para>
/// </summary>
public long ContentOffset
{
get
{
return _contentOffset;
}
set
{
if (InUse)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_contentOffset = value;
}
}
/// <summary>
/// <para>Gets or sets the data size of to-be uploaded data</para>
/// </summary>
public override long ContentLength
{
get
{
return _contentLength;
}
set
{
_contentLength = value;
}
}
public override IWebProxy Proxy
{
get
{
return null;
}
set
{
if (InUse)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
// Ignore, since we do not support proxied requests.
}
}
public override string ConnectionGroupName
{
get
{
return _connectionGroupName;
}
set
{
if (InUse)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
_connectionGroupName = value;
}
}
public ServicePoint ServicePoint
{
get
{
if (_servicePoint == null)
{
_servicePoint = ServicePointManager.FindServicePoint(_uri);
}
return _servicePoint;
}
}
internal bool Aborted
{
get
{
return _aborted;
}
}
internal FtpWebRequest(Uri uri)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, uri);
if ((object)uri.Scheme != (object)Uri.UriSchemeFtp)
throw new ArgumentOutOfRangeException(nameof(uri));
_timerCallback = new TimerThread.Callback(TimerCallback);
_syncObject = new object();
NetworkCredential networkCredential = null;
_uri = uri;
_methodInfo = FtpMethodInfo.GetMethodInfo(WebRequestMethods.Ftp.DownloadFile);
if (_uri.UserInfo != null && _uri.UserInfo.Length != 0)
{
string userInfo = _uri.UserInfo;
string username = userInfo;
string password = "";
int index = userInfo.IndexOf(':');
if (index != -1)
{
username = Uri.UnescapeDataString(userInfo.Substring(0, index));
index++; // skip ':'
password = Uri.UnescapeDataString(userInfo.Substring(index, userInfo.Length - index));
}
networkCredential = new NetworkCredential(username, password);
}
if (networkCredential == null)
{
networkCredential = s_defaultFtpNetworkCredential;
}
_authInfo = networkCredential;
}
//
// Used to query for the Response of an FTP request
//
public override WebResponse GetResponse()
{
if (NetEventSource.IsEnabled)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Method: {_methodInfo.Method}");
}
try
{
CheckError();
if (_ftpWebResponse != null)
{
return _ftpWebResponse;
}
if (_getResponseStarted)
{
throw new InvalidOperationException(SR.net_repcall);
}
_getResponseStarted = true;
_startTime = DateTime.UtcNow;
_remainingTimeout = Timeout;
if (Timeout != System.Threading.Timeout.Infinite)
{
_remainingTimeout = Timeout - (int)((DateTime.UtcNow - _startTime).TotalMilliseconds);
if (_remainingTimeout <= 0)
{
throw ExceptionHelper.TimeoutException;
}
}
RequestStage prev = FinishRequestStage(RequestStage.RequestStarted);
if (prev >= RequestStage.RequestStarted)
{
if (prev < RequestStage.ReadReady)
{
lock (_syncObject)
{
if (_requestStage < RequestStage.ReadReady)
_readAsyncResult = new LazyAsyncResult(null, null, null);
}
// GetRequeststream or BeginGetRequestStream has not finished yet
if (_readAsyncResult != null)
_readAsyncResult.InternalWaitForCompletion();
CheckError();
}
}
else
{
SubmitRequest(false);
if (_methodInfo.IsUpload)
FinishRequestStage(RequestStage.WriteReady);
else
FinishRequestStage(RequestStage.ReadReady);
CheckError();
EnsureFtpWebResponse(null);
}
}
catch (Exception exception)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception);
// if _exception == null, we are about to throw an exception to the user
// and we haven't saved the exception, which also means we haven't dealt
// with it. So just release the connection and log this for investigation.
if (_exception == null)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception);
SetException(exception);
FinishRequestStage(RequestStage.CheckForError);
}
throw;
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, _ftpWebResponse);
}
return _ftpWebResponse;
}
/// <summary>
/// <para>Used to query for the Response of an FTP request [async version]</para>
/// </summary>
public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(this);
NetEventSource.Info(this, $"Method: {_methodInfo.Method}");
}
ContextAwareResult asyncResult;
try
{
if (_ftpWebResponse != null)
{
asyncResult = new ContextAwareResult(this, state, callback);
asyncResult.InvokeCallback(_ftpWebResponse);
return asyncResult;
}
if (_getResponseStarted)
{
throw new InvalidOperationException(SR.net_repcall);
}
_getResponseStarted = true;
CheckError();
RequestStage prev = FinishRequestStage(RequestStage.RequestStarted);
asyncResult = new ContextAwareResult(true, true, this, state, callback);
_readAsyncResult = asyncResult;
if (prev >= RequestStage.RequestStarted)
{
// To make sure the context is flowed
asyncResult.StartPostingAsyncOp();
asyncResult.FinishPostingAsyncOp();
if (prev >= RequestStage.ReadReady)
asyncResult = null;
else
{
lock (_syncObject)
{
if (_requestStage >= RequestStage.ReadReady)
asyncResult = null; ;
}
}
if (asyncResult == null)
{
// need to complete it now
asyncResult = (ContextAwareResult)_readAsyncResult;
if (!asyncResult.InternalPeekCompleted)
asyncResult.InvokeCallback();
}
}
else
{
// Do internal processing in this handler to optimize context flowing.
lock (asyncResult.StartPostingAsyncOp())
{
SubmitRequest(true);
asyncResult.FinishPostingAsyncOp();
}
FinishRequestStage(RequestStage.CheckForError);
}
}
catch (Exception exception)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception);
throw;
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
return asyncResult;
}
/// <summary>
/// <para>Returns result of query for the Response of an FTP request [async version]</para>
/// </summary>
public override WebResponse EndGetResponse(IAsyncResult asyncResult)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
try
{
// parameter validation
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
LazyAsyncResult castedAsyncResult = asyncResult as LazyAsyncResult;
if (castedAsyncResult == null)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
if (castedAsyncResult.EndCalled)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndGetResponse"));
}
castedAsyncResult.InternalWaitForCompletion();
castedAsyncResult.EndCalled = true;
CheckError();
}
catch (Exception exception)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception);
throw;
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
return _ftpWebResponse;
}
/// <summary>
/// <para>Used to query for the Request stream of an FTP Request</para>
/// </summary>
public override Stream GetRequestStream()
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(this);
NetEventSource.Info(this, $"Method: {_methodInfo.Method}");
}
try
{
if (_getRequestStreamStarted)
{
throw new InvalidOperationException(SR.net_repcall);
}
_getRequestStreamStarted = true;
if (!_methodInfo.IsUpload)
{
throw new ProtocolViolationException(SR.net_nouploadonget);
}
CheckError();
_startTime = DateTime.UtcNow;
_remainingTimeout = Timeout;
if (Timeout != System.Threading.Timeout.Infinite)
{
_remainingTimeout = Timeout - (int)((DateTime.UtcNow - _startTime).TotalMilliseconds);
if (_remainingTimeout <= 0)
{
throw ExceptionHelper.TimeoutException;
}
}
FinishRequestStage(RequestStage.RequestStarted);
SubmitRequest(false);
FinishRequestStage(RequestStage.WriteReady);
CheckError();
if (_stream.CanTimeout)
{
_stream.WriteTimeout = ReadWriteTimeout;
_stream.ReadTimeout = ReadWriteTimeout;
}
}
catch (Exception exception)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception);
throw;
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
return _stream;
}
/// <summary>
/// <para>Used to query for the Request stream of an FTP Request [async version]</para>
/// </summary>
public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(this);
NetEventSource.Info(this, $"Method: {_methodInfo.Method}");
}
ContextAwareResult asyncResult = null;
try
{
if (_getRequestStreamStarted)
{
throw new InvalidOperationException(SR.net_repcall);
}
_getRequestStreamStarted = true;
if (!_methodInfo.IsUpload)
{
throw new ProtocolViolationException(SR.net_nouploadonget);
}
CheckError();
FinishRequestStage(RequestStage.RequestStarted);
asyncResult = new ContextAwareResult(true, true, this, state, callback);
lock (asyncResult.StartPostingAsyncOp())
{
_writeAsyncResult = asyncResult;
SubmitRequest(true);
asyncResult.FinishPostingAsyncOp();
FinishRequestStage(RequestStage.CheckForError);
}
}
catch (Exception exception)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception);
throw;
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
return asyncResult;
}
public override Stream EndGetRequestStream(IAsyncResult asyncResult)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
Stream requestStream = null;
try
{
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
LazyAsyncResult castedAsyncResult = asyncResult as LazyAsyncResult;
if (castedAsyncResult == null)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
if (castedAsyncResult.EndCalled)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndGetResponse"));
}
castedAsyncResult.InternalWaitForCompletion();
castedAsyncResult.EndCalled = true;
CheckError();
requestStream = _stream;
castedAsyncResult.EndCalled = true;
if (requestStream.CanTimeout)
{
requestStream.WriteTimeout = ReadWriteTimeout;
requestStream.ReadTimeout = ReadWriteTimeout;
}
}
catch (Exception exception)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception);
throw;
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
return requestStream;
}
//
// NOTE1: The caller must synchronize access to SubmitRequest(), only one call is allowed for a particular request.
// NOTE2: This method eats all exceptions so the caller must rethrow them.
//
private void SubmitRequest(bool isAsync)
{
try
{
_async = isAsync;
//
// FYI: Will do 2 attempts max as per AttemptedRecovery
//
Stream stream;
while (true)
{
FtpControlStream connection = _connection;
if (connection == null)
{
if (isAsync)
{
CreateConnectionAsync();
return;
}
connection = CreateConnection();
_connection = connection;
}
if (!isAsync)
{
if (Timeout != System.Threading.Timeout.Infinite)
{
_remainingTimeout = Timeout - (int)((DateTime.UtcNow - _startTime).TotalMilliseconds);
if (_remainingTimeout <= 0)
{
throw ExceptionHelper.TimeoutException;
}
}
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Request being submitted");
connection.SetSocketTimeoutOption(RemainingTimeout);
try
{
stream = TimedSubmitRequestHelper(isAsync);
}
catch (Exception e)
{
if (AttemptedRecovery(e))
{
if (!isAsync)
{
if (Timeout != System.Threading.Timeout.Infinite)
{
_remainingTimeout = Timeout - (int)((DateTime.UtcNow - _startTime).TotalMilliseconds);
if (_remainingTimeout <= 0)
{
throw;
}
}
}
continue;
}
throw;
}
// no retry needed
break;
}
}
catch (WebException webException)
{
// If this was a timeout, throw a timeout exception
IOException ioEx = webException.InnerException as IOException;
if (ioEx != null)
{
SocketException sEx = ioEx.InnerException as SocketException;
if (sEx != null)
{
if (sEx.SocketErrorCode == SocketError.TimedOut)
{
SetException(ExceptionDispatchInfo.SetCurrentStackTrace(new WebException(SR.net_timeout, WebExceptionStatus.Timeout)));
}
}
}
SetException(webException);
}
catch (Exception exception)
{
SetException(exception);
}
}
private Exception TranslateConnectException(Exception e)
{
SocketException se = e as SocketException;
if (se != null)
{
if (se.SocketErrorCode == SocketError.HostNotFound)
{
return new WebException(SR.net_webstatus_NameResolutionFailure, WebExceptionStatus.NameResolutionFailure);
}
else
{
return new WebException(SR.net_webstatus_ConnectFailure, WebExceptionStatus.ConnectFailure);
}
}
// Wasn't a socket error, so leave as is
return e;
}
private async void CreateConnectionAsync()
{
string hostname = _uri.Host;
int port = _uri.Port;
TcpClient client = new TcpClient();
object result;
try
{
await client.ConnectAsync(hostname, port).ConfigureAwait(false);
result = new FtpControlStream(client);
}
catch (Exception e)
{
result = TranslateConnectException(e);
}
AsyncRequestCallback(result);
}
private FtpControlStream CreateConnection()
{
string hostname = _uri.Host;
int port = _uri.Port;
TcpClient client = new TcpClient();
try
{
client.Connect(hostname, port);
}
catch (Exception e)
{
throw TranslateConnectException(e);
}
return new FtpControlStream(client);
}
private Stream TimedSubmitRequestHelper(bool isAsync)
{
if (isAsync)
{
// non-null in the case of re-submit (recovery)
if (_requestCompleteAsyncResult == null)
_requestCompleteAsyncResult = new LazyAsyncResult(null, null, null);
return _connection.SubmitRequest(this, true, true);
}
Stream stream = null;
bool timedOut = false;
TimerThread.Timer timer = TimerQueue.CreateTimer(_timerCallback, null);
try
{
stream = _connection.SubmitRequest(this, false, true);
}
catch (Exception exception)
{
if (!(exception is SocketException || exception is ObjectDisposedException) || !timer.HasExpired)
{
timer.Cancel();
throw;
}
timedOut = true;
}
if (timedOut || !timer.Cancel())
{
_timedOut = true;
throw ExceptionHelper.TimeoutException;
}
if (stream != null)
{
lock (_syncObject)
{
if (_aborted)
{
((ICloseEx)stream).CloseEx(CloseExState.Abort | CloseExState.Silent);
CheckError(); //must throw
throw new InternalException(); //consider replacing this on Assert
}
_stream = stream;
}
}
return stream;
}
/// <summary>
/// <para>Because this is called from the timer thread, neither it nor any methods it calls can call user code.</para>
/// </summary>
private void TimerCallback(TimerThread.Timer timer, int timeNoticed, object context)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this);
FtpControlStream connection = _connection;
if (connection != null)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "aborting connection");
connection.AbortConnect();
}
}
private TimerThread.Queue TimerQueue
{
get
{
if (_timerQueue == null)
{
_timerQueue = TimerThread.GetOrCreateQueue(RemainingTimeout);
}
return _timerQueue;
}
}
/// <summary>
/// <para>Returns true if we should restart the request after an error</para>
/// </summary>
private bool AttemptedRecovery(Exception e)
{
if (e is OutOfMemoryException
|| _onceFailed
|| _aborted
|| _timedOut
|| _connection == null
|| !_connection.RecoverableFailure)
{
return false;
}
_onceFailed = true;
lock (_syncObject)
{
if (_connection != null)
{
_connection.CloseSocket();
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Releasing connection: {_connection}");
_connection = null;
}
else
{
return false;
}
}
return true;
}
/// <summary>
/// <para>Updates and sets our exception to be thrown</para>
/// </summary>
private void SetException(Exception exception)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this);
if (exception is OutOfMemoryException)
{
_exception = exception;
throw exception;
}
FtpControlStream connection = _connection;
if (_exception == null)
{
if (exception is WebException)
{
EnsureFtpWebResponse(exception);
_exception = new WebException(exception.Message, null, ((WebException)exception).Status, _ftpWebResponse);
}
else if (exception is AuthenticationException || exception is SecurityException)
{
_exception = exception;
}
else if (connection != null && connection.StatusCode != FtpStatusCode.Undefined)
{
EnsureFtpWebResponse(exception);
_exception = new WebException(SR.Format(SR.net_ftp_servererror, connection.StatusLine), exception, WebExceptionStatus.ProtocolError, _ftpWebResponse);
}
else
{
_exception = new WebException(exception.Message, exception);
}
if (connection != null && _ftpWebResponse != null)
_ftpWebResponse.UpdateStatus(connection.StatusCode, connection.StatusLine, connection.ExitMessage);
}
}
/// <summary>
/// <para>Opposite of SetException, rethrows the exception</para>
/// </summary>
private void CheckError()
{
if (_exception != null)
{
ExceptionDispatchInfo.Throw(_exception);
}
}
internal void RequestCallback(object obj)
{
if (_async)
AsyncRequestCallback(obj);
else
SyncRequestCallback(obj);
}
//
// Only executed for Sync requests when the pipline is completed
//
private void SyncRequestCallback(object obj)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, obj);
RequestStage stageMode = RequestStage.CheckForError;
try
{
bool completedRequest = obj == null;
Exception exception = obj as Exception;
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"exp:{exception} completedRequest:{completedRequest}");
if (exception != null)
{
SetException(exception);
}
else if (!completedRequest)
{
throw new InternalException();
}
else
{
FtpControlStream connection = _connection;
if (connection != null)
{
EnsureFtpWebResponse(null);
// This to update response status and exit message if any.
// Note that status 221 "Service closing control connection" is always suppressed.
_ftpWebResponse.UpdateStatus(connection.StatusCode, connection.StatusLine, connection.ExitMessage);
}
stageMode = RequestStage.ReleaseConnection;
}
}
catch (Exception exception)
{
SetException(exception);
}
finally
{
FinishRequestStage(stageMode);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
CheckError(); //will throw on error
}
}
//
// Only executed for Async requests
//
private void AsyncRequestCallback(object obj)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, obj);
RequestStage stageMode = RequestStage.CheckForError;
try
{
FtpControlStream connection;
connection = obj as FtpControlStream;
FtpDataStream stream = obj as FtpDataStream;
Exception exception = obj as Exception;
bool completedRequest = (obj == null);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"stream:{stream} conn:{connection} exp:{exception} completedRequest:{completedRequest}");
while (true)
{
if (exception != null)
{
if (AttemptedRecovery(exception))
{
connection = CreateConnection();
if (connection == null)
return;
exception = null;
}
if (exception != null)
{
SetException(exception);
break;
}
}
if (connection != null)
{
lock (_syncObject)
{
if (_aborted)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Releasing connect:{connection}");
connection.CloseSocket();
break;
}
_connection = connection;
if (NetEventSource.IsEnabled) NetEventSource.Associate(this, _connection);
}
try
{
stream = (FtpDataStream)TimedSubmitRequestHelper(true);
}
catch (Exception e)
{
exception = e;
continue;
}
return;
}
else if (stream != null)
{
lock (_syncObject)
{
if (_aborted)
{
((ICloseEx)stream).CloseEx(CloseExState.Abort | CloseExState.Silent);
break;
}
_stream = stream;
}
stream.SetSocketTimeoutOption(Timeout);
EnsureFtpWebResponse(null);
stageMode = stream.CanRead ? RequestStage.ReadReady : RequestStage.WriteReady;
}
else if (completedRequest)
{
connection = _connection;
if (connection != null)
{
EnsureFtpWebResponse(null);
// This to update response status and exit message if any.
// Note that the status 221 "Service closing control connection" is always suppressed.
_ftpWebResponse.UpdateStatus(connection.StatusCode, connection.StatusLine, connection.ExitMessage);
}
stageMode = RequestStage.ReleaseConnection;
}
else
{
throw new InternalException();
}
break;
}
}
catch (Exception exception)
{
SetException(exception);
}
finally
{
FinishRequestStage(stageMode);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
}
private enum RequestStage
{
CheckForError = 0, // Do nothing except if there is an error then auto promote to ReleaseConnection
RequestStarted, // Mark this request as started
WriteReady, // First half is done, i.e. either writer or response stream. This is always assumed unless Started or CheckForError
ReadReady, // Second half is done, i.e. the read stream can be accesses.
ReleaseConnection // Release the control connection (request is read i.e. done-done)
}
//
// Returns a previous stage
//
private RequestStage FinishRequestStage(RequestStage stage)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"state:{stage}");
if (_exception != null)
stage = RequestStage.ReleaseConnection;
RequestStage prev;
LazyAsyncResult writeResult;
LazyAsyncResult readResult;
FtpControlStream connection;
lock (_syncObject)
{
prev = _requestStage;
if (stage == RequestStage.CheckForError)
return prev;
if (prev == RequestStage.ReleaseConnection &&
stage == RequestStage.ReleaseConnection)
{
return RequestStage.ReleaseConnection;
}
if (stage > prev)
_requestStage = stage;
if (stage <= RequestStage.RequestStarted)
return prev;
writeResult = _writeAsyncResult;
readResult = _readAsyncResult;
connection = _connection;
if (stage == RequestStage.ReleaseConnection)
{
if (_exception == null &&
!_aborted &&
prev != RequestStage.ReadReady &&
_methodInfo.IsDownload &&
!_ftpWebResponse.IsFromCache)
{
return prev;
}
_connection = null;
}
}
try
{
// First check to see on releasing the connection
if ((stage == RequestStage.ReleaseConnection ||
prev == RequestStage.ReleaseConnection)
&& connection != null)
{
try
{
if (_exception != null)
{
connection.Abort(_exception);
}
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Releasing connection: {connection}");
connection.CloseSocket();
if (_async)
if (_requestCompleteAsyncResult != null)
_requestCompleteAsyncResult.InvokeCallback();
}
}
return prev;
}
finally
{
try
{
// In any case we want to signal the writer if came here
if (stage >= RequestStage.WriteReady)
{
// If writeResult == null and this is an upload request, it means
// that the user has called GetResponse() without calling
// GetRequestStream() first. So they are not interested in a
// stream. Therefore we close the stream so that the
// request/pipeline can continue
if (_methodInfo.IsUpload && !_getRequestStreamStarted)
{
if (_stream != null)
_stream.Close();
}
else if (writeResult != null && !writeResult.InternalPeekCompleted)
writeResult.InvokeCallback();
}
}
finally
{
// The response is ready either with or without a stream
if (stage >= RequestStage.ReadReady && readResult != null && !readResult.InternalPeekCompleted)
readResult.InvokeCallback();
}
}
}
/// <summary>
/// <para>Aborts underlying connection to FTP server (command & data)</para>
/// </summary>
public override void Abort()
{
if (_aborted)
return;
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
try
{
Stream stream;
FtpControlStream connection;
lock (_syncObject)
{
if (_requestStage >= RequestStage.ReleaseConnection)
return;
_aborted = true;
stream = _stream;
connection = _connection;
_exception = ExceptionHelper.RequestAbortedException;
}
if (stream != null)
{
if (!(stream is ICloseEx))
{
NetEventSource.Fail(this, "The _stream member is not CloseEx hence the risk of connection been orphaned.");
}
((ICloseEx)stream).CloseEx(CloseExState.Abort | CloseExState.Silent);
}
if (connection != null)
connection.Abort(ExceptionHelper.RequestAbortedException);
}
catch (Exception exception)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception);
throw;
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
}
public bool KeepAlive
{
get
{
return true;
}
set
{
if (InUse)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
// We don't support connection pooling, so just silently ignore this.
}
}
public override RequestCachePolicy CachePolicy
{
get
{
return FtpWebRequest.DefaultCachePolicy;
}
set
{
if (InUse)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
// We don't support caching, so just silently ignore this.
}
}
/// <summary>
/// <para>True by default, false allows transmission using text mode</para>
/// </summary>
public bool UseBinary
{
get
{
return _binary;
}
set
{
if (InUse)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
_binary = value;
}
}
public bool UsePassive
{
get
{
return _passive;
}
set
{
if (InUse)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
_passive = value;
}
}
public X509CertificateCollection ClientCertificates
{
get
{
return LazyInitializer.EnsureInitialized(ref _clientCertificates, ref _syncObject, () => new X509CertificateCollection());
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_clientCertificates = value;
}
}
/// <summary>
/// <para>Set to true if we need SSL</para>
/// </summary>
public bool EnableSsl
{
get
{
return _enableSsl;
}
set
{
if (InUse)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
_enableSsl = value;
}
}
public override WebHeaderCollection Headers
{
get
{
if (_ftpRequestHeaders == null)
{
_ftpRequestHeaders = new WebHeaderCollection();
}
return _ftpRequestHeaders;
}
set
{
_ftpRequestHeaders = value;
}
}
// NOT SUPPORTED method
public override string ContentType
{
get
{
throw ExceptionHelper.PropertyNotSupportedException;
}
set
{
throw ExceptionHelper.PropertyNotSupportedException;
}
}
// NOT SUPPORTED method
public override bool UseDefaultCredentials
{
get
{
throw ExceptionHelper.PropertyNotSupportedException;
}
set
{
throw ExceptionHelper.PropertyNotSupportedException;
}
}
// NOT SUPPORTED method
public override bool PreAuthenticate
{
get
{
throw ExceptionHelper.PropertyNotSupportedException;
}
set
{
throw ExceptionHelper.PropertyNotSupportedException;
}
}
/// <summary>
/// <para>True if a request has been submitted (ie already active)</para>
/// </summary>
private bool InUse
{
get
{
if (_getRequestStreamStarted || _getResponseStarted)
{
return true;
}
else
{
return false;
}
}
}
/// <summary>
/// <para>Creates an FTP WebResponse based off the responseStream and our active Connection</para>
/// </summary>
private void EnsureFtpWebResponse(Exception exception)
{
if (_ftpWebResponse == null || (_ftpWebResponse.GetResponseStream() is FtpWebResponse.EmptyStream && _stream != null))
{
lock (_syncObject)
{
if (_ftpWebResponse == null || (_ftpWebResponse.GetResponseStream() is FtpWebResponse.EmptyStream && _stream != null))
{
Stream responseStream = _stream;
if (_methodInfo.IsUpload)
{
responseStream = null;
}
if (_stream != null && _stream.CanRead && _stream.CanTimeout)
{
_stream.ReadTimeout = ReadWriteTimeout;
_stream.WriteTimeout = ReadWriteTimeout;
}
FtpControlStream connection = _connection;
long contentLength = connection != null ? connection.ContentLength : -1;
if (responseStream == null)
{
// If the last command was SIZE, we set the ContentLength on
// the FtpControlStream to be the size of the file returned in the
// response. We should propagate that file size to the response so
// users can access it. This also maintains the compatibility with
// HTTP when returning size instead of content.
if (contentLength < 0)
contentLength = 0;
}
if (_ftpWebResponse != null)
{
_ftpWebResponse.SetResponseStream(responseStream);
}
else
{
if (connection != null)
_ftpWebResponse = new FtpWebResponse(responseStream, contentLength, connection.ResponseUri, connection.StatusCode, connection.StatusLine, connection.LastModified, connection.BannerMessage, connection.WelcomeMessage, connection.ExitMessage);
else
_ftpWebResponse = new FtpWebResponse(responseStream, -1, _uri, FtpStatusCode.Undefined, null, DateTime.Now, null, null, null);
}
}
}
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Returns {_ftpWebResponse} with stream {_ftpWebResponse._responseStream}");
return;
}
internal void DataStreamClosed(CloseExState closeState)
{
if ((closeState & CloseExState.Abort) == 0)
{
if (!_async)
{
if (_connection != null)
_connection.CheckContinuePipeline();
}
else
{
_requestCompleteAsyncResult.InternalWaitForCompletion();
CheckError();
}
}
else
{
FtpControlStream connection = _connection;
if (connection != null)
connection.Abort(ExceptionHelper.RequestAbortedException);
}
}
} // class FtpWebRequest
//
// Class used by the WebRequest.Create factory to create FTP requests
//
internal class FtpWebRequestCreator : IWebRequestCreate
{
internal FtpWebRequestCreator()
{
}
public WebRequest Create(Uri uri)
{
return new FtpWebRequest(uri);
}
} // class FtpWebRequestCreator
} // namespace System.Net
| |
//
// UnityOSC - Open Sound Control interface for the Unity3d game engine
//
// Copyright (c) 2012 Jorge Garcia Martin
// Last edit: Gerard Llorach 2nd August 2017
//
// 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.
//
// Inspired by http://www.unifycommunity.com/wiki/index.php?title=AManagerClass
using System;
using System.Net;
using System.Collections.Generic;
using UnityEngine;
using UnityOSC;
/// <summary>
/// Models a log of a server composed by an OSCServer, a List of OSCPacket and a List of
/// strings that represent the current messages in the log.
/// </summary>
public struct ServerLog
{
public OSCServer server;
public List<OSCPacket> packets;
public List<string> log;
}
/// <summary>
/// Models a log of a client composed by an OSCClient, a List of OSCMessage and a List of
/// strings that represent the current messages in the log.
/// </summary>
public struct ClientLog
{
public OSCClient client;
public List<OSCMessage> messages;
public List<string> log;
}
/// <summary>
/// Handles all the OSC servers and clients of the current Unity game/application.
/// Tracks incoming and outgoing messages.
/// </summary>
public class OSCHandler : MonoBehaviour
{
#region Singleton Constructors
static OSCHandler()
{
}
OSCHandler()
{
}
public static OSCHandler Instance
{
get
{
if (_instance == null)
{
_instance = new GameObject ("OSCHandler").AddComponent<OSCHandler>();
}
return _instance;
}
}
#endregion
#region Member Variables
private static OSCHandler _instance = null;
private Dictionary<string, ClientLog> _clients = new Dictionary<string, ClientLog>();
private Dictionary<string, ServerLog> _servers = new Dictionary<string, ServerLog>();
public List<OSCPacket> packets = new List<OSCPacket>();
private const int _loglength = 100;
#endregion
/// <summary>
/// Initializes the OSC Handler.
/// Here you can create the OSC servers and clientes.
/// </summary>
public void Init()
{
//Initialize OSC clients (transmitters)
//Example:
//CreateClient("SuperCollider", IPAddress.Parse("127.0.0.1"), 5555);
//Initialize OSC servers (listeners)
//Example:
//CreateServer("AndroidPhone", 6666);
}
#region Properties
public Dictionary<string, ClientLog> Clients
{
get
{
return _clients;
}
}
public Dictionary<string, ServerLog> Servers
{
get
{
return _servers;
}
}
#endregion
#region Methods
/// <summary>
/// Ensure that the instance is destroyed when the game is stopped in the Unity editor
/// Close all the OSC clients and servers
/// </summary>
void OnApplicationQuit()
{
foreach(KeyValuePair<string,ClientLog> pair in _clients)
{
pair.Value.client.Close();
}
foreach(KeyValuePair<string,ServerLog> pair in _servers)
{
pair.Value.server.Close();
}
_instance = null;
}
/// <summary>
/// Creates an OSC Client (sends OSC messages) given an outgoing port and address.
/// </summary>
/// <param name="clientId">
/// A <see cref="System.String"/>
/// </param>
/// <param name="destination">
/// A <see cref="IPAddress"/>
/// </param>
/// <param name="port">
/// A <see cref="System.Int32"/>
/// </param>
public void CreateClient(string clientId, IPAddress destination, int port)
{
ClientLog clientitem = new ClientLog();
clientitem.client = new OSCClient(destination, port);
clientitem.log = new List<string>();
clientitem.messages = new List<OSCMessage>();
_clients.Add(clientId, clientitem);
// Send test message
string testaddress = "/test/alive/";
OSCMessage message = new OSCMessage(testaddress, destination.ToString());
message.Append(port); message.Append("OK");
_clients[clientId].log.Add(String.Concat(DateTime.UtcNow.ToString(),".",
FormatMilliseconds(DateTime.Now.Millisecond), " : ",
testaddress," ", DataToString(message.Data)));
_clients[clientId].messages.Add(message);
_clients[clientId].client.Send(message);
}
/// <summary>
/// Creates an OSC Server (listens to upcoming OSC messages) given an incoming port.
/// </summary>
/// <param name="serverId">
/// A <see cref="System.String"/>
/// </param>
/// <param name="port">
/// A <see cref="System.Int32"/>
/// </param>
public OSCServer CreateServer(string serverId, int port)
{
OSCServer server = new OSCServer(port);
server.PacketReceivedEvent += OnPacketReceived;
ServerLog serveritem = new ServerLog();
serveritem.server = server;
serveritem.log = new List<string>();
serveritem.packets = new List<OSCPacket>();
_servers.Add(serverId, serveritem);
return server;
}
/// <summary>
/// Callback when a message is received. It stores the messages in a list of the oscControl
void OnPacketReceived(OSCServer server, OSCPacket packet)
{
// Remember origin
packet.server = server;
// Limit buffer
if (packets.Count > _loglength)
{
packets.RemoveRange(0, packets.Count - _loglength);
}
// Add to OSCPackets list
packets.Add(packet);
}
/// <summary>
/// Sends an OSC message to a specified client, given its clientId (defined at the OSC client construction),
/// OSC address and a single value. Also updates the client log.
/// </summary>
/// <param name="clientId">
/// A <see cref="System.String"/>
/// </param>
/// <param name="address">
/// A <see cref="System.String"/>
/// </param>
/// <param name="value">
/// A <see cref="T"/>
/// </param>
public void SendMessageToClient<T>(string clientId, string address, T value)
{
List<object> temp = new List<object>();
temp.Add(value);
SendMessageToClient(clientId, address, temp);
}
/// <summary>
/// Sends an OSC message to a specified client, given its clientId (defined at the OSC client construction),
/// OSC address and a list of values. Also updates the client log.
/// </summary>
/// <param name="clientId">
/// A <see cref="System.String"/>
/// </param>
/// <param name="address">
/// A <see cref="System.String"/>
/// </param>
/// <param name="values">
/// A <see cref="List<T>"/>
/// </param>
public void SendMessageToClient<T>(string clientId, string address, List<T> values)
{
if(_clients.ContainsKey(clientId))
{
OSCMessage message = new OSCMessage(address);
foreach(T msgvalue in values)
{
message.Append(msgvalue);
}
if(_clients[clientId].log.Count < _loglength)
{
_clients[clientId].log.Add(String.Concat(DateTime.UtcNow.ToString(),".",
FormatMilliseconds(DateTime.Now.Millisecond),
" : ", address, " ", DataToString(message.Data)));
_clients[clientId].messages.Add(message);
}
else
{
_clients[clientId].log.RemoveAt(0);
_clients[clientId].messages.RemoveAt(0);
_clients[clientId].log.Add(String.Concat(DateTime.UtcNow.ToString(),".",
FormatMilliseconds(DateTime.Now.Millisecond),
" : ", address, " ", DataToString(message.Data)));
_clients[clientId].messages.Add(message);
}
_clients[clientId].client.Send(message);
}
else
{
Debug.LogError(string.Format("Can't send OSC messages to {0}. Client doesn't exist.", clientId));
}
}
/// <summary>
/// Updates clients and servers logs.
/// NOTE: Only used by the editor helper script (OSCHelper.cs), could be removed
/// </summary>
public void UpdateLogs()
{
foreach(KeyValuePair<string,ServerLog> pair in _servers)
{
if(_servers[pair.Key].server.LastReceivedPacket != null)
{
//Initialization for the first packet received
if(_servers[pair.Key].log.Count == 0)
{
_servers[pair.Key].packets.Add(_servers[pair.Key].server.LastReceivedPacket);
_servers[pair.Key].log.Add(String.Concat(DateTime.UtcNow.ToString(), ".",
FormatMilliseconds(DateTime.Now.Millisecond)," : ",
_servers[pair.Key].server.LastReceivedPacket.Address," ",
DataToString(_servers[pair.Key].server.LastReceivedPacket.Data)));
break;
}
if(_servers[pair.Key].server.LastReceivedPacket.TimeStamp
!= _servers[pair.Key].packets[_servers[pair.Key].packets.Count - 1].TimeStamp)
{
if(_servers[pair.Key].log.Count > _loglength - 1)
{
_servers[pair.Key].log.RemoveAt(0);
_servers[pair.Key].packets.RemoveAt(0);
}
_servers[pair.Key].packets.Add(_servers[pair.Key].server.LastReceivedPacket);
_servers[pair.Key].log.Add(String.Concat(DateTime.UtcNow.ToString(), ".",
FormatMilliseconds(DateTime.Now.Millisecond)," : ",
_servers[pair.Key].server.LastReceivedPacket.Address," ",
DataToString(_servers[pair.Key].server.LastReceivedPacket.Data)));
}
}
}
}
/// <summary>
/// Converts a collection of object values to a concatenated string.
/// </summary>
/// <param name="data">
/// A <see cref="List<System.Object>"/>
/// </param>
/// <returns>
/// A <see cref="System.String"/>
/// </returns>
private string DataToString(List<object> data)
{
string buffer = "";
for(int i = 0; i < data.Count; i++)
{
buffer += data[i].ToString() + " ";
}
buffer += "\n";
return buffer;
}
/// <summary>
/// Formats a milliseconds number to a 000 format. E.g. given 50, it outputs 050. Given 5, it outputs 005
/// </summary>
/// <param name="milliseconds">
/// A <see cref="System.Int32"/>
/// </param>
/// <returns>
/// A <see cref="System.String"/>
/// </returns>
private string FormatMilliseconds(int milliseconds)
{
if(milliseconds < 100)
{
if(milliseconds < 10)
return String.Concat("00",milliseconds.ToString());
return String.Concat("0",milliseconds.ToString());
}
return milliseconds.ToString();
}
#endregion
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.Metadata;
using Pomelo.EntityFrameworkCore.MySql.Internal;
using Microsoft.EntityFrameworkCore.Storage;
namespace Pomelo.EntityFrameworkCore.MySql.Storage.Internal
{
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public class MySqlTypeMappingSource : RelationalTypeMappingSource
{
private readonly RelationalTypeMapping _sqlVariant
= new MySqlSqlVariantTypeMapping("sql_variant");
private readonly FloatTypeMapping _real
= new MySqlFloatTypeMapping("real");
private readonly ByteTypeMapping _byte
= new MySqlByteTypeMapping("tinyint", DbType.Byte);
private readonly ShortTypeMapping _short
= new MySqlShortTypeMapping("smallint", DbType.Int16);
private readonly LongTypeMapping _long
= new MySqlLongTypeMapping("bigint", DbType.Int64);
private readonly MySqlByteArrayTypeMapping _rowversion
= new MySqlByteArrayTypeMapping(
"rowversion",
size: 8,
comparer: new ValueComparer<byte[]>(
(v1, v2) => StructuralComparisons.StructuralEqualityComparer.Equals(v1, v2),
v => StructuralComparisons.StructuralEqualityComparer.GetHashCode(v),
v => v == null ? null : v.ToArray()),
storeTypePostfix: StoreTypePostfix.None);
private readonly IntTypeMapping _int
= new IntTypeMapping("int", DbType.Int32);
private readonly BoolTypeMapping _bool
= new BoolTypeMapping("bit");
private readonly MySqlStringTypeMapping _fixedLengthUnicodeString
= new MySqlStringTypeMapping(unicode: true, fixedLength: true);
private readonly MySqlStringTypeMapping _variableLengthUnicodeString
= new MySqlStringTypeMapping(unicode: true);
private readonly MySqlStringTypeMapping _variableLengthMaxUnicodeString
= new MySqlStringTypeMapping("nvarchar(max)", unicode: true, storeTypePostfix: StoreTypePostfix.None);
private readonly MySqlStringTypeMapping _fixedLengthAnsiString
= new MySqlStringTypeMapping(fixedLength: true);
private readonly MySqlStringTypeMapping _variableLengthAnsiString
= new MySqlStringTypeMapping();
private readonly MySqlStringTypeMapping _variableLengthMaxAnsiString
= new MySqlStringTypeMapping("varchar(max)", storeTypePostfix: StoreTypePostfix.None);
private readonly MySqlByteArrayTypeMapping _variableLengthBinary
= new MySqlByteArrayTypeMapping();
private readonly MySqlByteArrayTypeMapping _variableLengthMaxBinary
= new MySqlByteArrayTypeMapping("varbinary(max)", storeTypePostfix: StoreTypePostfix.None);
private readonly MySqlByteArrayTypeMapping _fixedLengthBinary
= new MySqlByteArrayTypeMapping(fixedLength: true);
private readonly MySqlDateTimeTypeMapping _date
= new MySqlDateTimeTypeMapping("date", DbType.Date);
private readonly MySqlDateTimeTypeMapping _datetime
= new MySqlDateTimeTypeMapping("datetime", DbType.DateTime);
private readonly MySqlDateTimeTypeMapping _datetime2
= new MySqlDateTimeTypeMapping("datetime2", DbType.DateTime2);
private readonly DoubleTypeMapping _double
= new MySqlDoubleTypeMapping("float");
private readonly MySqlDateTimeOffsetTypeMapping _datetimeoffset
= new MySqlDateTimeOffsetTypeMapping("datetimeoffset");
private readonly GuidTypeMapping _uniqueidentifier
= new GuidTypeMapping("uniqueidentifier", DbType.Guid);
private readonly DecimalTypeMapping _decimal
= new MySqlDecimalTypeMapping("decimal(18, 2)", precision: 18, scale: 2, storeTypePostfix: StoreTypePostfix.PrecisionAndScale);
private readonly DecimalTypeMapping _money
= new MySqlDecimalTypeMapping("money");
private readonly TimeSpanTypeMapping _time
= new MySqlTimeSpanTypeMapping("time");
private readonly MySqlStringTypeMapping _xml
= new MySqlStringTypeMapping("xml", unicode: true, storeTypePostfix: StoreTypePostfix.None);
private readonly Dictionary<Type, RelationalTypeMapping> _clrTypeMappings;
private readonly Dictionary<string, RelationalTypeMapping> _storeTypeMappings;
// These are disallowed only if specified without any kind of length specified in parenthesis.
private readonly HashSet<string> _disallowedMappings
= new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"binary",
"binary varying",
"varbinary",
"char",
"character",
"char varying",
"character varying",
"varchar",
"national char",
"national character",
"nchar",
"national char varying",
"national character varying",
"nvarchar"
};
private readonly IReadOnlyDictionary<string, Func<Type, RelationalTypeMapping>> _namedClrMappings
= new Dictionary<string, Func<Type, RelationalTypeMapping>>(StringComparer.Ordinal)
{
{
"Microsoft.MySql.Types.SqlHierarchyId",
t => MySqlUdtTypeMapping.CreateSqlHierarchyIdMapping(t)
},
{
"Microsoft.MySql.Types.SqlGeography",
t => MySqlUdtTypeMapping.CreateSqlSpatialMapping(t, "geography")
},
{
"Microsoft.MySql.Types.SqlGeometry",
t => MySqlUdtTypeMapping.CreateSqlSpatialMapping(t, "geometry")
}
};
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public MySqlTypeMappingSource(
[NotNull] TypeMappingSourceDependencies dependencies,
[NotNull] RelationalTypeMappingSourceDependencies relationalDependencies)
: base(dependencies, relationalDependencies)
{
_clrTypeMappings
= new Dictionary<Type, RelationalTypeMapping>
{
{ typeof(int), _int },
{ typeof(long), _long },
{ typeof(DateTime), _datetime2 },
{ typeof(Guid), _uniqueidentifier },
{ typeof(bool), _bool },
{ typeof(byte), _byte },
{ typeof(double), _double },
{ typeof(DateTimeOffset), _datetimeoffset },
{ typeof(short), _short },
{ typeof(float), _real },
{ typeof(decimal), _decimal },
{ typeof(TimeSpan), _time }
};
_storeTypeMappings
= new Dictionary<string, RelationalTypeMapping>(StringComparer.OrdinalIgnoreCase)
{
{ "bigint", _long },
{ "binary varying", _variableLengthBinary },
{ "binary", _fixedLengthBinary },
{ "bit", _bool },
{ "char varying", _variableLengthAnsiString },
{ "char", _fixedLengthAnsiString },
{ "character varying", _variableLengthAnsiString },
{ "character", _fixedLengthAnsiString },
{ "date", _date },
{ "datetime", _datetime },
{ "datetime2", _datetime2 },
{ "datetimeoffset", _datetimeoffset },
{ "dec", _decimal },
{ "decimal", _decimal },
{ "double precision", _double },
{ "float", _double },
{ "image", _variableLengthBinary },
{ "int", _int },
{ "money", _money },
{ "national char varying", _variableLengthUnicodeString },
{ "national character varying", _variableLengthUnicodeString },
{ "national character", _fixedLengthUnicodeString },
{ "nchar", _fixedLengthUnicodeString },
{ "ntext", _variableLengthUnicodeString },
{ "numeric", _decimal },
{ "nvarchar", _variableLengthUnicodeString },
{ "nvarchar(max)", _variableLengthMaxUnicodeString },
{ "real", _real },
{ "rowversion", _rowversion },
{ "smalldatetime", _datetime },
{ "smallint", _short },
{ "smallmoney", _money },
{ "sql_variant", _sqlVariant },
{ "text", _variableLengthAnsiString },
{ "time", _time },
{ "timestamp", _rowversion },
{ "tinyint", _byte },
{ "uniqueidentifier", _uniqueidentifier },
{ "varbinary", _variableLengthBinary },
{ "varbinary(max)", _variableLengthMaxBinary },
{ "varchar", _variableLengthAnsiString },
{ "varchar(max)", _variableLengthMaxAnsiString },
{ "xml", _xml }
};
}
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
protected override void ValidateMapping(CoreTypeMapping mapping, IProperty property)
{
var relationalMapping = mapping as RelationalTypeMapping;
if (_disallowedMappings.Contains(relationalMapping?.StoreType))
{
if (property == null)
{
throw new ArgumentException(MySqlStrings.UnqualifiedDataType(relationalMapping.StoreType));
}
throw new ArgumentException(MySqlStrings.UnqualifiedDataTypeOnProperty(relationalMapping.StoreType, property.Name));
}
}
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
protected override RelationalTypeMapping FindMapping(in RelationalTypeMappingInfo mappingInfo)
=> FindRawMapping(mappingInfo)?.Clone(mappingInfo)
?? base.FindMapping(mappingInfo);
private RelationalTypeMapping FindRawMapping(RelationalTypeMappingInfo mappingInfo)
{
var clrType = mappingInfo.ClrType;
var storeTypeName = mappingInfo.StoreTypeName;
var storeTypeNameBase = mappingInfo.StoreTypeNameBase;
if (storeTypeName != null)
{
if (clrType == typeof(float)
&& mappingInfo.Size != null
&& mappingInfo.Size <= 24
&& (storeTypeNameBase.Equals("float", StringComparison.OrdinalIgnoreCase)
|| storeTypeNameBase.Equals("double precision", StringComparison.OrdinalIgnoreCase)))
{
return _real;
}
if (_storeTypeMappings.TryGetValue(storeTypeName, out var mapping)
|| _storeTypeMappings.TryGetValue(storeTypeNameBase, out mapping))
{
return clrType == null
|| mapping.ClrType == clrType
? mapping
: null;
}
}
if (clrType != null)
{
if (_clrTypeMappings.TryGetValue(clrType, out var mapping))
{
return mapping;
}
if (_namedClrMappings.TryGetValue(clrType.FullName, out var mappingFunc))
{
return mappingFunc(clrType);
}
if (clrType == typeof(string))
{
var isAnsi = mappingInfo.IsUnicode == false;
var isFixedLength = mappingInfo.IsFixedLength == true;
var maxSize = isAnsi ? 8000 : 4000;
var size = mappingInfo.Size ?? (mappingInfo.IsKeyOrIndex ? (int?)(isAnsi ? 900 : 450) : null);
if (size > maxSize)
{
size = isFixedLength ? maxSize : (int?)null;
}
return size == null
? isAnsi ? _variableLengthMaxAnsiString : _variableLengthMaxUnicodeString
: new MySqlStringTypeMapping(
unicode: !isAnsi,
size: size,
fixedLength: isFixedLength);
}
if (clrType == typeof(byte[]))
{
if (mappingInfo.IsRowVersion == true)
{
return _rowversion;
}
var isFixedLength = mappingInfo.IsFixedLength == true;
var size = mappingInfo.Size ?? (mappingInfo.IsKeyOrIndex ? (int?)900 : null);
if (size > 8000)
{
size = isFixedLength ? 8000 : (int?)null;
}
return size == null
? _variableLengthMaxBinary
: new MySqlByteArrayTypeMapping(size: size, fixedLength: isFixedLength);
}
}
return null;
}
}
}
| |
#region Licence
/****************************************************************************
Copyright 1999-2015 Vincent J. Jacquet. All rights reserved.
Permission is granted to anyone to use this software for any purpose on
any computer system, and to alter it and redistribute it, subject
to the following restrictions:
1. The author is not responsible for the consequences of use of this
software, no matter how awful, even if they arise from flaws in it.
2. The origin of this software must not be misrepresented, either by
explicit claim or by omission. Since few users ever read sources,
credits must appear in the documentation.
3. Altered versions must be plainly marked as such, and must not be
misrepresented as being the original software. Since few users
ever read sources, credits must appear in the documentation.
4. This notice may not be removed or altered.
****************************************************************************/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using WmcSoft.Units.Properties;
namespace WmcSoft.Units
{
/// <summary>
/// Converts a quantity in a source unit to a quantity in a target unit.
/// </summary>
public static class UnitConverter
{
#region Fields
static object syncRoot = new Object();
static IDictionary<Unit, Hashtable> unitConversions;
static UnitConverter()
{
unitConversions = new Dictionary<Unit, Hashtable>();
}
#endregion
public delegate decimal ConvertCallback(decimal value);
public static bool RegisterConversion(UnitConversion conversion)
{
return RegisterConversion(conversion, true);
}
static bool Register(Unit source, Unit target, ConvertCallback convert, bool throwOnDuplicates)
{
Hashtable table;
if (!unitConversions.TryGetValue(source, out table)) {
table = new Hashtable();
table[target] = convert;
unitConversions[source] = table;
return true;
} else if (!table.ContainsKey(target)) {
table[target] = convert;
return true;
} else if (throwOnDuplicates) {
throw new ArgumentException(string.Format(Resources.DuplicateConversionException, source, target));
}
return false;
}
internal static bool RegisterConversion(UnitConversion conversion, bool throwOnDuplicate)
{
lock (syncRoot) {
if (unitConversions == null) {
unitConversions = new Dictionary<Unit, Hashtable>();
}
bool registered = Register(conversion.Source, conversion.Target, new ConvertCallback(conversion.Convert), throwOnDuplicate);
registered |= Register(conversion.Target, conversion.Source, new ConvertCallback(conversion.ConvertBack), throwOnDuplicate);
return registered;
}
}
public static bool RegisterUnit(ScaledUnit scaledUnit)
{
if (!unitConversions.ContainsKey(scaledUnit)) {
var factor = 1m;
var source = scaledUnit;
while (scaledUnit != null) {
factor *= scaledUnit.ScaleFactor;
RegisterConversion(new LinearConversion(source, scaledUnit.Reference, factor), false);
scaledUnit = scaledUnit.Reference as ScaledUnit;
}
return true;
}
return false;
}
public static bool RegisterUnit(Unit unit)
{
if (!unitConversions.ContainsKey(unit)) {
//if (scaledUnit != null) {
// RegisterConversion(new ExtrapolatedConversion(scaledUnit), false);
//}
bool registered = false;
foreach (object attribute in unit.GetType().GetCustomAttributes(true)) {
var conversion = attribute as UnitConversionAttribute;
if (conversion != null) {
registered |= RegisterConversion(conversion.UnitConversion);
}
}
return registered;
}
return false;
}
public static Quantity Convert(Quantity quantity, Unit target)
{
if (quantity.Metric == target)
return quantity;
var source = quantity.Metric as Unit;
if (source == null)
throw new ArgumentException(Resources.NotAUnitException, "quantity");
RegisterUnit(source);
RegisterUnit(target);
Hashtable table;
if (unitConversions.TryGetValue(source, out table)) {
var callback = table[target] as ConvertCallback;
if (callback != null) {
return new Quantity(callback(quantity.Amount), target);
}
}
throw new NotSupportedException();
}
/// <summary>
/// Converts a quantity to a quantity of the target Unit.
/// </summary>
/// <param name="quantity">The quantity.</param>
/// <param name="target">The target unit.</param>
/// <returns>The converted quantity.</returns>
public static Quantity ConvertTo(this Quantity quantity, Unit target)
{
return Convert(quantity, target);
}
/// <summary>
/// Converts a quantity to a quantity of the target Unit.
/// </summary>
/// <typeparam name="U">The target unit type.</typeparam>
/// <param name="quantity">The quantity.</param>
/// <returns>The converted quantity.</returns>
public static Quantity<U> ConvertTo<U>(this Quantity quantity) where U : Unit, new()
{
var result = Convert(quantity, new U());
return new Quantity<U>(result.Amount);
}
/// <summary>
/// Creates a reciprocal unit conversion.
/// </summary>
/// <param name="conversion">The unit conversion.</param>
/// <returns>The reciprocal unit conversion.</returns>
/// <remarks>This function guarantee that <code>Reciprocal(Reciprocal(conversion)) == conversion</code>.</remarks>
public static UnitConversion Reciprocal(this UnitConversion conversion)
{
if (conversion == null)
throw new ArgumentNullException("conversion");
var reciprocal = conversion as ReciprocalUnitConversion;
if (reciprocal == null)
return new ReciprocalUnitConversion(conversion);
return reciprocal.BaseUnitConversion;
}
static UnitConversion DoCompose(LinearConversion x, LinearConversion y)
{
return new LinearConversion(x.Source, y.Target, x.ConversionFactor * y.ConversionFactor);
}
static UnitConversion DoCompose(UnitConversion x, UnitConversion y)
{
return new CompositeConversion(x, y);
}
static UnitConversion DoCompose(CompositeConversion x, UnitConversion y)
{
return new CompositeConversion(x, y);
}
static UnitConversion DoCompose(UnitConversion x, CompositeConversion y)
{
return new CompositeConversion(x, y);
}
static UnitConversion DoCompose(CompositeConversion x, CompositeConversion y)
{
return new CompositeConversion(x, y);
}
public static UnitConversion Compose(UnitConversion x, UnitConversion y)
{
if (x.Target != y.Source) throw new ArgumentException(string.Format(Resources.InvalidUnitConversionPath, x.Target, y.Source));
if (x.Source == y.Target)
return new IdentityConversion(x.Source);
// performs double dispatch
var factory = typeof(UnitConverter).GetMethod("DoCompose", BindingFlags.Static | BindingFlags.NonPublic, Type.DefaultBinder, new[] { x.GetType(), y.GetType() }, new ParameterModifier[0]);
if (factory != null)
return (UnitConversion)factory.Invoke(null, new[] { x, y });
throw new InvalidOperationException();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.