context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// <copyright file=SceneManager.cs
// <copyright>
// Copyright (c) 2016, University of Stuttgart
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the Software),
// to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
// <license>MIT License</license>
// <main contributors>
// Markus Funk, Thomas Kosch, Sven Mayer
// </main contributors>
// <co-contributors>
// Paul Brombosch, Mai El-Komy, Juana Heusler,
// Matthias Hoppe, Robert Konrad, Alexander Martin
// </co-contributors>
// <patent information>
// We are aware that this software implements patterns and ideas,
// which might be protected by patents in your country.
// Example patents in Germany are:
// Patent reference number: DE 103 20 557.8
// Patent reference number: DE 10 2013 220 107.9
// Please make sure when using this software not to violate any existing patents in your country.
// </patent information>
// <date> 11/2/2016 12:25:58 PM</date>
using HciLab.motionEAP.InterfacesAndDataModel;
using HciLab.Utilities;
using motionEAPAdmin.Backend;
using motionEAPAdmin.Backend.AssembleyZones;
using motionEAPAdmin.Backend.Boxes;
using motionEAPAdmin.ContentProviders;
using motionEAPAdmin.Scene;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Windows.Forms;
using System.Windows.Media;
namespace motionEAPAdmin
{
public class SceneManager : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// the Scene that belongs to the current working step
/// </summary>
private Scene.Scene m_CurrentScene;
/// <summary>
/// the Scene that is responsible for the temprorary items
/// </summary>
private Scene.Scene m_TemporaryScene;
/// <summary>
/// the Scene that is responsible for the temprorary items and box feedback
/// </summary>
private Scene.Scene m_TemporaryBoxScene;
private Scene.Scene m_TemporaryAssemblyZoneScene;
private Scene.Scene m_TemporaryObjectsScene;
private Scene.Scene m_TemporaryStatsScene;
private Scene.Scene m_TemporaryDebugScene;
private Scene.Scene m_TemporaryObjectsTextScene;
private Scene.Scene m_TemporaryFeedbackScene;
private Scene.Scene m_TemporaryWaitingScene;
private bool m_DisableObjectScenes = false;
private bool m_DisplayTempFeedback = false;
private SceneItem m_DemoRect;
private static SceneManager m_Instance;
public static SceneManager Instance
{
get
{
if (m_Instance == null)
m_Instance = new SceneManager();
return m_Instance;
}
}
/// <summary>
/// constructor
/// </summary>
private SceneManager()
{
m_CurrentScene = new Scene.Scene();
m_TemporaryScene = new Scene.Scene();
m_TemporaryBoxScene = new Scene.Scene();
m_TemporaryAssemblyZoneScene = new Scene.Scene();
m_TemporaryObjectsScene = new Scene.Scene();
m_TemporaryStatsScene = new Scene.Scene();
m_TemporaryDebugScene = new Scene.Scene();
m_TemporaryObjectsTextScene = new Scene.Scene();
m_TemporaryFeedbackScene = new Scene.Scene();
m_TemporaryWaitingScene = new Scene.Scene();
NotificationManager.Init();
}
/// <summary>
/// this method initializes the content that is to be drawn by the scene.
/// This content is static FOR NOW! This has to be dynamically at some point
/// </summary>
///
///
public void initContent()
{
if (SettingsManager.Instance.Settings.SettingsTable.ShowDemoAnimation)
{
//m_DemoRect = new DemoRectScene(m_CurrentScene);
m_DemoRect = new SceneRect(150, 150, 150, 150, Color.FromRgb(255, 0, 0));
m_CurrentScene.Add(m_DemoRect);
}
}
private void NotifyPropertyChanged(string Obj)
{
if (PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(Obj));
}
}
/// <summary>
/// This method displays a given SceneItem temporarily on top of the
/// current Scene. This can be used for information that does not
/// belog to the fixed Scene belonging to each step of a workflow.
///
/// USE THIS TO DISPLAY SCENEITEMS TEMPORARILY e.g. for selection
/// </summary>
///
///
public void temporarylyDisplaySceneItem(SceneItem pItem)
{
m_TemporaryScene.Add(pItem);
}
/// <summary>
/// This method removes the SceneItem with the id pId from the
/// temporaryly displayed Scene.
///
/// USE THIS TO DELETE TEMP-SCENEITEMS
/// </summary>
/// <param name="pId">id of the to be deleted sceneItem</param>
///
///
public void removeTemporarylyDisplayedSceneItem(int pId)
{
SceneItem toRemoveItem = m_TemporaryScene.Items.GetBySceneObjId(pId);
m_TemporaryScene.Remove(toRemoveItem);
}
public void Update()
{
NotificationManager.Update();
}
public void SaveSceneToFile()
{
// check if scnes dir exists
if (!Directory.Exists(ProjectConstants.SCENES_DIR))
{
// if not create it
Directory.CreateDirectory(ProjectConstants.SCENES_DIR);
}
System.Windows.Forms.SaveFileDialog dlg = new System.Windows.Forms.SaveFileDialog();
dlg.InitialDirectory = Directory.GetCurrentDirectory() + "\\" + ProjectConstants.SCENES_DIR;
dlg.Filter = "scene files (*.scene)|*.scene";
if (dlg.ShowDialog() != DialogResult.OK)
return;
string filename = dlg.FileName;
if (!filename.EndsWith(ProjectConstants.SCENE_FILE_ENDING))
{
filename = filename + ProjectConstants.SCENE_FILE_ENDING;
}
UtilitiesIO.SaveObjectToJson(CurrentScene, filename);
}
public void LoadScene()
{
CurrentScene = LoadSceneFromFile();
}
public Scene.Scene LoadSceneFromFile()
{
System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog();
dlg.InitialDirectory = Directory.GetCurrentDirectory() + "\\" + ProjectConstants.SCENES_DIR;
dlg.Filter = "scene files (*.scene)|*.scene";
dlg.FilterIndex = 2;
dlg.RestoreDirectory = true;
if (dlg.ShowDialog() != DialogResult.OK)
return null;
Scene.Scene ret = null;
bool isOkay = UtilitiesIO.GetObjectFromJson(ref ret, dlg.FileName);
if (!isOkay)
return null;
return ret;
}
/// <summary>
/// All scenes that have to be displayed at the moment
/// </summary>
/// <returns></returns>
public List<Scene.Scene> getAllScenes()
{
List<Scene.Scene> ret = new List<Scene.Scene>();
if (m_CurrentScene != null)
{
ret.Add(m_CurrentScene);
}
if (SettingsManager.Instance.Settings.AssemblyZoneVisualFeedbackProject && StateManager.Instance.State != AllEnums.State.WORKFLOW_PLAYING && StateManager.Instance.State != AllEnums.State.EDIT)
ret.Add(AssemblyZoneManager.Instance.drawProjectorUI());
if (SettingsManager.Instance.Settings.BoxesVisualFeedbackProject && StateManager.Instance.State != AllEnums.State.WORKFLOW_PLAYING && StateManager.Instance.State != AllEnums.State.EDIT)
ret.Add(BoxManager.Instance.drawProjectorUI());
if (StateManager.Instance.State == AllEnums.State.WORKFLOW_PLAYING && StateManager.Instance.State != AllEnums.State.EDIT)
{
ret.Add(BoxManager.Instance.drawErrorFeedback());
}
if (!m_DisableObjectScenes)
{
ret.Add(m_TemporaryObjectsScene);
ret.Add(m_TemporaryObjectsTextScene);
}
if (m_DisplayTempFeedback)
{
ret.Add(m_TemporaryFeedbackScene);
}
ret.Add(m_TemporaryWaitingScene);
ret.Add(m_TemporaryStatsScene);
ret.Add(m_TemporaryDebugScene);
return ret;
}
#region Getter / Setter
public bool DisableObjectScenes
{
get
{
return m_DisableObjectScenes;
}
set
{
m_DisableObjectScenes = value;
NotifyPropertyChanged("DisableObjectScenes");
}
}
public bool DisplayTempFeedback
{
get
{
return m_DisplayTempFeedback;
}
set
{
m_DisplayTempFeedback = value;
NotifyPropertyChanged("DisplayTempFeedback");
}
}
public Scene.Scene CurrentScene
{
get
{
return m_CurrentScene;
}
set
{
// do stuff with old scene
m_CurrentScene.setShown(false);
// do stuff with new scene
m_CurrentScene = value;
m_CurrentScene.setShown(true);
NotifyPropertyChanged("CurrentScene");
}
}
public Scene.Scene TemporaryScene
{
get
{
return m_TemporaryScene;
}
set
{
m_TemporaryScene = value;
NotifyPropertyChanged("TemporaryScene");
}
}
public Scene.Scene TemporaryBoxScene
{
get
{
return m_TemporaryBoxScene;
}
set
{
m_TemporaryBoxScene = value;
NotifyPropertyChanged("TemporaryBoxScene");
}
}
public Scene.Scene TemporaryObjectsScene
{
get
{
return m_TemporaryObjectsScene;
}
set
{
m_TemporaryObjectsScene = value;
NotifyPropertyChanged("TemporaryObjectsScene");
}
}
public Scene.Scene TemporaryObjectsTextScene
{
get
{
return m_TemporaryObjectsTextScene;
}
set
{
m_TemporaryObjectsTextScene = value;
NotifyPropertyChanged("TemporaryObjectsTextScene");
}
}
public Scene.Scene TemporaryAssemblyZoneScene
{
get
{
return m_TemporaryAssemblyZoneScene;
}
set
{
m_TemporaryAssemblyZoneScene = value;
NotifyPropertyChanged("TemporaryAssemblyZoneScene");
}
}
public Scene.Scene TemporaryFeedbackScene
{
get
{
return m_TemporaryFeedbackScene;
}
set
{
m_TemporaryFeedbackScene = value;
NotifyPropertyChanged("TemporaryFeedbackScene");
}
}
public Scene.Scene TemporaryStatsScene
{
get
{
return m_TemporaryStatsScene;
}
set
{
m_TemporaryStatsScene = value;
NotifyPropertyChanged("TemporaryStatsScene");
}
}
public Scene.Scene TemporaryDebugScene
{
get
{
return m_TemporaryDebugScene;
}
set
{
m_TemporaryDebugScene = value;
NotifyPropertyChanged("TemporaryDebugScene");
}
}
public Scene.Scene TemporaryWaitingScene
{
get { return m_TemporaryWaitingScene; }
set
{
m_TemporaryWaitingScene = value;
NotifyPropertyChanged("TemporaryWaitingScene");
}
}
#endregion
}
}
| |
/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Security;
using SearchOption = System.IO.SearchOption;
namespace Alphaleonis.Win32.Filesystem
{
public static partial class Directory
{
/// <summary>[AlphaFS] Returns an enumerable collection of file names in a specified <paramref name="path"/>.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the files in the directory specified by <paramref name="path"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
[SecurityCritical]
public static IEnumerable<string> EnumerateFilesTransacted(KernelTransaction transaction, string path)
{
return EnumerateFileSystemEntryInfosCore<string>(false, transaction, path, Path.WildcardStarMatchAll, null, null, null, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file instances that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the files in the directory specified by <paramref name="path"/> and that match the <paramref name="searchPattern"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
[SecurityCritical]
[Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")]
public static IEnumerable<string> EnumerateFilesTransacted(KernelTransaction transaction, string path, string searchPattern)
{
return EnumerateFileSystemEntryInfosCore<string>(false, transaction, path, searchPattern, null, null, null, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file instances instances that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>, and optionally searches subdirectories.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the files in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/> and <paramref name="searchOption"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
/// <param name="searchOption">
/// One of the <see cref="SearchOption"/> enumeration values that specifies whether the <paramref name="searchOption"/>
/// should include only the current directory or should include all subdirectories.
/// </param>
[SecurityCritical]
[Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")]
public static IEnumerable<string> EnumerateFilesTransacted(KernelTransaction transaction, string path, string searchPattern, SearchOption searchOption)
{
return EnumerateFileSystemEntryInfosCore<string>(false, transaction, path, searchPattern, searchOption, null, null, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file names in a specified <paramref name="path"/>.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the files in the directory specified by <paramref name="path"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
public static IEnumerable<string> EnumerateFilesTransacted(KernelTransaction transaction, string path, PathFormat pathFormat)
{
return EnumerateFileSystemEntryInfosCore<string>(false, transaction, path, Path.WildcardStarMatchAll, null, null, null, pathFormat);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file instances that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the files in the directory specified by <paramref name="path"/> and that match the <paramref name="searchPattern"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
[Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")]
public static IEnumerable<string> EnumerateFilesTransacted(KernelTransaction transaction, string path, string searchPattern, PathFormat pathFormat)
{
return EnumerateFileSystemEntryInfosCore<string>(false, transaction, path, searchPattern, null, null, null, pathFormat);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file instances instances that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>, and optionally searches subdirectories.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the files in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/> and <paramref name="searchOption"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
/// <param name="searchOption">
/// One of the <see cref="SearchOption"/> enumeration values that specifies whether the <paramref name="searchOption"/>
/// should include only the current directory or should include all subdirectories.
/// </param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
[Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")]
public static IEnumerable<string> EnumerateFilesTransacted(KernelTransaction transaction, string path, string searchPattern, SearchOption searchOption, PathFormat pathFormat)
{
return EnumerateFileSystemEntryInfosCore<string>(false, transaction, path, searchPattern, searchOption, null, null, pathFormat);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file names in a specified <paramref name="path"/>.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the files in the directory specified by <paramref name="path"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
[SecurityCritical]
public static IEnumerable<string> EnumerateFilesTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options)
{
return EnumerateFileSystemEntryInfosCore<string>(false, transaction, path, Path.WildcardStarMatchAll, null, options, null, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file names in a specified <paramref name="path"/>.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the files in the directory specified by <paramref name="path"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
public static IEnumerable<string> EnumerateFilesTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options, PathFormat pathFormat)
{
return EnumerateFileSystemEntryInfosCore<string>(false, transaction, path, Path.WildcardStarMatchAll, null, options, null, pathFormat);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file instances that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the files in the directory specified by <paramref name="path"/> and that match the <paramref name="searchPattern"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
[SecurityCritical]
[Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")]
public static IEnumerable<string> EnumerateFilesTransacted(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationOptions options)
{
return EnumerateFileSystemEntryInfosCore<string>(false, transaction, path, searchPattern, null, options, null, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file instances that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the files in the directory specified by <paramref name="path"/> and that match the <paramref name="searchPattern"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
[Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")]
public static IEnumerable<string> EnumerateFilesTransacted(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationOptions options, PathFormat pathFormat)
{
return EnumerateFileSystemEntryInfosCore<string>(false, transaction, path, searchPattern, null, options, null, pathFormat);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file names in a specified <paramref name="path"/>.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the files in the directory specified by <paramref name="path"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
/// <param name="filters">The specification of custom filters to be used in the process.</param>
[SecurityCritical]
public static IEnumerable<string> EnumerateFilesTransacted(KernelTransaction transaction, string path, DirectoryEnumerationFilters filters)
{
return EnumerateFileSystemEntryInfosCore<string>(false, transaction, path, Path.WildcardStarMatchAll, null, null, filters, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file names in a specified <paramref name="path"/>.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the files in the directory specified by <paramref name="path"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
/// <param name="filters">The specification of custom filters to be used in the process.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
public static IEnumerable<string> EnumerateFilesTransacted(KernelTransaction transaction, string path, DirectoryEnumerationFilters filters, PathFormat pathFormat)
{
return EnumerateFileSystemEntryInfosCore<string>(false, transaction, path, Path.WildcardStarMatchAll, null, null, filters, pathFormat);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file names in a specified <paramref name="path"/>.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the files in the directory specified by <paramref name="path"/> and that match the <paramref name="searchPattern"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
/// <param name="filters">The specification of custom filters to be used in the process.</param>
[SecurityCritical]
[Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")]
public static IEnumerable<string> EnumerateFilesTransacted(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationFilters filters)
{
return EnumerateFileSystemEntryInfosCore<string>(false, transaction, path, searchPattern, null, null, filters, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file names in a specified <paramref name="path"/>.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the files in the directory specified by <paramref name="path"/> and that match the <paramref name="searchPattern"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
/// <param name="filters">The specification of custom filters to be used in the process.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
[Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")]
public static IEnumerable<string> EnumerateFilesTransacted(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationFilters filters, PathFormat pathFormat)
{
return EnumerateFileSystemEntryInfosCore<string>(false, transaction, path, searchPattern, null, null, filters, pathFormat);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file names in a specified <paramref name="path"/>.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the files in the directory specified by <paramref name="path"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
/// <param name="filters">The specification of custom filters to be used in the process.</param>
[SecurityCritical]
public static IEnumerable<string> EnumerateFilesTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters)
{
return EnumerateFileSystemEntryInfosCore<string>(false, transaction, path, Path.WildcardStarMatchAll, null, options, filters, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file names in a specified <paramref name="path"/>.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the files in the directory specified by <paramref name="path"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
/// <param name="filters">The specification of custom filters to be used in the process.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
public static IEnumerable<string> EnumerateFilesTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters, PathFormat pathFormat)
{
return EnumerateFileSystemEntryInfosCore<string>(false, transaction, path, Path.WildcardStarMatchAll, null, options, filters, pathFormat);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file names in a specified <paramref name="path"/>.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the files in the directory specified by <paramref name="path"/> and that match the <paramref name="searchPattern"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
/// <param name="filters">The specification of custom filters to be used in the process.</param>
[SecurityCritical]
[Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")]
public static IEnumerable<string> EnumerateFilesTransacted(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters)
{
return EnumerateFileSystemEntryInfosCore<string>(false, transaction, path, searchPattern, null, options, filters, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file names in a specified <paramref name="path"/>.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the files in the directory specified by <paramref name="path"/> and that match the <paramref name="searchPattern"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
/// <param name="filters">The specification of custom filters to be used in the process.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
[Obsolete("Argument searchPattern is obsolete. The DirectoryEnumerationFilters argument provides better filter criteria.")]
public static IEnumerable<string> EnumerateFilesTransacted(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationOptions options, DirectoryEnumerationFilters filters, PathFormat pathFormat)
{
return EnumerateFileSystemEntryInfosCore<string>(false, transaction, path, searchPattern, null, options, filters, pathFormat);
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Utilities;
using System.Globalization;
namespace Newtonsoft.Json.Linq
{
/// <summary>
/// Represents a JSON constructor.
/// </summary>
public class JConstructor : JContainer
{
private string _name;
private IList<JToken> _values = new List<JToken>();
/// <summary>
/// Gets the container's children tokens.
/// </summary>
/// <value>The container's children tokens.</value>
protected override IList<JToken> ChildrenTokens
{
get { return _values; }
}
/// <summary>
/// Gets or sets the name of this constructor.
/// </summary>
/// <value>The constructor name.</value>
public string Name
{
get { return _name; }
set { _name = value; }
}
/// <summary>
/// Gets the node type for this <see cref="JToken"/>.
/// </summary>
/// <value>The type.</value>
public override JTokenType Type
{
get { return JTokenType.Constructor; }
}
/// <summary>
/// Initializes a new instance of the <see cref="JConstructor"/> class.
/// </summary>
public JConstructor()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JConstructor"/> class from another <see cref="JConstructor"/> object.
/// </summary>
/// <param name="other">A <see cref="JConstructor"/> object to copy from.</param>
public JConstructor(JConstructor other)
: base(other)
{
_name = other.Name;
}
/// <summary>
/// Initializes a new instance of the <see cref="JConstructor"/> class with the specified name and content.
/// </summary>
/// <param name="name">The constructor name.</param>
/// <param name="content">The contents of the constructor.</param>
public JConstructor(string name, params object[] content)
: this(name, (object)content)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JConstructor"/> class with the specified name and content.
/// </summary>
/// <param name="name">The constructor name.</param>
/// <param name="content">The contents of the constructor.</param>
public JConstructor(string name, object content)
: this(name)
{
Add(content);
}
/// <summary>
/// Initializes a new instance of the <see cref="JConstructor"/> class with the specified name.
/// </summary>
/// <param name="name">The constructor name.</param>
public JConstructor(string name)
{
ValidationUtils.ArgumentNotNullOrEmpty(name, "name");
_name = name;
}
internal override bool DeepEquals(JToken node)
{
JConstructor c = node as JConstructor;
return (c != null && _name == c.Name && ContentsEqual(c));
}
internal override JToken CloneToken()
{
return new JConstructor(this);
}
/// <summary>
/// Writes this token to a <see cref="JsonWriter"/>.
/// </summary>
/// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
/// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param>
public override void WriteTo(JsonWriter writer, params JsonConverter[] converters)
{
writer.WriteStartConstructor(_name);
foreach (JToken token in Children())
{
token.WriteTo(writer, converters);
}
writer.WriteEndConstructor();
}
/// <summary>
/// Gets the <see cref="JToken"/> with the specified key.
/// </summary>
/// <value>The <see cref="JToken"/> with the specified key.</value>
public override JToken this[object key]
{
get
{
ValidationUtils.ArgumentNotNull(key, "o");
if (!(key is int))
throw new ArgumentException("Accessed JConstructor values with invalid key value: {0}. Argument position index expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key)));
return GetItem((int)key);
}
set
{
ValidationUtils.ArgumentNotNull(key, "o");
if (!(key is int))
throw new ArgumentException("Set JConstructor values with invalid key value: {0}. Argument position index expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key)));
SetItem((int)key, value);
}
}
internal override int GetDeepHashCode()
{
return _name.GetHashCode() ^ ContentsHashCode();
}
/// <summary>
/// Loads an <see cref="JConstructor"/> from a <see cref="JsonReader"/>.
/// </summary>
/// <param name="reader">A <see cref="JsonReader"/> that will be read for the content of the <see cref="JConstructor"/>.</param>
/// <returns>A <see cref="JConstructor"/> that contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns>
public static new JConstructor Load(JsonReader reader)
{
if (reader.TokenType == JsonToken.None)
{
if (!reader.Read())
throw new Exception("Error reading JConstructor from JsonReader.");
}
if (reader.TokenType != JsonToken.StartConstructor)
throw new Exception("Error reading JConstructor from JsonReader. Current JsonReader item is not a constructor: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
JConstructor c = new JConstructor((string)reader.Value);
c.SetLineInfo(reader as IJsonLineInfo);
c.ReadTokenFrom(reader);
return c;
}
}
}
| |
//
// HTTPTracker.cs
//
// Authors:
// Eric Butler eric@extremeboredom.net
// Alan McGovern alan.mcgovern@gmail.com
//
// Copyright (C) 2007 Eric Butler
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace OctoTorrent.Client.Tracker
{
using System;
using System.Collections.Generic;
using BEncoding;
using System.Text.RegularExpressions;
using System.Net;
using Common;
using System.IO;
public class HTTPTracker : Tracker
{
private static readonly Random Random = new Random();
private static readonly TimeSpan RequestTimeout = TimeSpan.FromSeconds(10);
private readonly Uri _scrapeUrl;
private string _trackerId;
public string Key { get; private set; }
public Uri ScrapeUri
{
get { return _scrapeUrl; }
}
public HTTPTracker(Uri announceUrl)
: base(announceUrl)
{
CanAnnounce = true;
var index = announceUrl.OriginalString.LastIndexOf('/');
var part = (index + 9 <= announceUrl.OriginalString.Length) ? announceUrl.OriginalString.Substring(index + 1, 8) : "";
if (part.Equals("announce", StringComparison.OrdinalIgnoreCase))
{
CanScrape = true;
var r = new Regex("announce");
_scrapeUrl = new Uri(r.Replace(announceUrl.OriginalString, "scrape", 1, index));
}
var passwordKey = new byte[8];
lock (Random)
Random.NextBytes(passwordKey);
Key = UriHelper.UrlEncode(passwordKey);
}
public override void Announce(AnnounceParameters parameters, object state)
{
try
{
var announceString = CreateAnnounceString(parameters);
var request = (HttpWebRequest) WebRequest.Create(announceString);
request.UserAgent = VersionInfo.ClientVersion;
request.Proxy = new WebProxy(); // If i don't do this, i can't run the webrequest. It's wierd.
RaiseBeforeAnnounce();
BeginRequest(request, AnnounceReceived, new[] { request, state });
}
catch (Exception ex)
{
Status = TrackerState.Offline;
FailureMessage = ("Could not initiate announce request: " + ex.Message);
RaiseAnnounceComplete(new AnnounceResponseEventArgs(this, state, false));
}
}
private void BeginRequest(WebRequest request, AsyncCallback callback, object state)
{
var result = request.BeginGetResponse(callback, state);
ClientEngine.MainLoop.QueueTimeout(RequestTimeout, () =>
{
if (!result.IsCompleted)
request.Abort();
return false;
});
}
void AnnounceReceived(IAsyncResult result)
{
FailureMessage = string.Empty;
WarningMessage = string.Empty;
var stateOb = (object[])result.AsyncState;
var request = (WebRequest)stateOb[0];
var state = stateOb[1];
var peers = new List<Peer>();
try
{
var dict = DecodeResponse(request, result);
HandleAnnounce(dict, peers);
Status = TrackerState.Ok;
}
catch (WebException)
{
Status = TrackerState.Offline;
FailureMessage = "The tracker could not be contacted";
}
catch
{
Status = TrackerState.InvalidResponse;
FailureMessage = "The tracker returned an invalid or incomplete response";
}
finally
{
RaiseAnnounceComplete(new AnnounceResponseEventArgs(this, state, string.IsNullOrEmpty(FailureMessage), peers));
}
}
private Uri CreateAnnounceString(AnnounceParameters parameters)
{
var builder = new UriQueryBuilder(Uri);
builder.Add("info_hash", parameters.InfoHash.UrlEncode())
.Add("peer_id", parameters.PeerId)
.Add("port", parameters.Port)
.Add("uploaded", parameters.BytesUploaded)
.Add("downloaded", parameters.BytesDownloaded)
.Add("left", parameters.BytesLeft)
.Add("compact", 1)
.Add("numwant", 100);
if (parameters.SupportsEncryption)
builder.Add("supportcrypto", 1);
if (parameters.RequireEncryption)
builder.Add("requirecrypto", 1);
if (!builder.Contains("key"))
builder.Add("key", Key);
if (!string.IsNullOrEmpty(parameters.Ipaddress))
builder.Add("ip", parameters.Ipaddress);
// If we have not successfully sent the started event to this tier, override the passed in started event
// Otherwise append the event if it is not "none"
//if (!parameters.Id.Tracker.Tier.SentStartedEvent)
//{
// sb.Append("&event=started");
// parameters.Id.Tracker.Tier.SendingStartedEvent = true;
//}
if (parameters.ClientEvent != TorrentEvent.None)
builder.Add("event", parameters.ClientEvent.ToString().ToLower());
if (!string.IsNullOrEmpty(_trackerId))
builder.Add("trackerid", _trackerId);
return builder.ToUri();
}
private BEncodedDictionary DecodeResponse(WebRequest request, IAsyncResult result)
{
var totalRead = 0;
var buffer = new byte[2048];
var response = request.EndGetResponse(result);
using (var dataStream = new MemoryStream(response.ContentLength > 0 ? (int)response.ContentLength : 256))
{
using (var reader = new BinaryReader(response.GetResponseStream()))
{
// If there is a ContentLength, use that to decide how much we read.
int bytesRead;
if (response.ContentLength > 0)
{
while (totalRead < response.ContentLength)
{
bytesRead = reader.Read(buffer, 0, buffer.Length);
dataStream.Write(buffer, 0, bytesRead);
totalRead += bytesRead;
}
}
else // A compact response doesn't always have a content length, so we
{ // just have to keep reading until we think we have everything.
while ((bytesRead = reader.Read(buffer, 0, buffer.Length)) > 0)
dataStream.Write(buffer, 0, bytesRead);
}
}
response.Close();
dataStream.Seek(0, SeekOrigin.Begin);
return (BEncodedDictionary)BEncodedValue.Decode(dataStream);
}
}
public override bool Equals(object obj)
{
var tracker = obj as HTTPTracker;
return tracker != null && (Uri.Equals(tracker.Uri));
// If the announce URL matches, then CanScrape and the scrape URL must match too
}
public override int GetHashCode()
{
return Uri.GetHashCode();
}
void HandleAnnounce(BEncodedDictionary dict, List<Peer> peers)
{
foreach (var keypair in dict)
{
switch (keypair.Key.Text)
{
case ("complete"):
Complete = Convert.ToInt32(keypair.Value.ToString());
break;
case ("incomplete"):
Incomplete = Convert.ToInt32(keypair.Value.ToString());
break;
case ("downloaded"):
Downloaded = Convert.ToInt32(keypair.Value.ToString());
break;
case ("tracker id"):
_trackerId = keypair.Value.ToString();
break;
case ("min interval"):
MinUpdateInterval = TimeSpan.FromSeconds(int.Parse(keypair.Value.ToString()));
break;
case ("interval"):
UpdateInterval = TimeSpan.FromSeconds(int.Parse(keypair.Value.ToString()));
break;
case ("peers"):
if (keypair.Value is BEncodedList) // Non-compact response
peers.AddRange(Peer.Decode((BEncodedList)keypair.Value));
else if (keypair.Value is BEncodedString) // Compact response
peers.AddRange(Peer.Decode((BEncodedString)keypair.Value));
break;
case ("failure reason"):
FailureMessage = keypair.Value.ToString();
break;
case ("warning message"):
WarningMessage = keypair.Value.ToString();
break;
default:
Logger.Log(null, "HttpTracker - Unknown announce tag received: Key {0} Value: {1}", keypair.Key.ToString(), keypair.Value.ToString());
break;
}
}
}
public override void Scrape(ScrapeParameters parameters, object state)
{
try
{
var url = _scrapeUrl.OriginalString;
// If you want to scrape the tracker for *all* torrents, don't append the info_hash.
if (url.IndexOf('?') == -1)
url += "?info_hash=" + parameters.InfoHash.UrlEncode ();
else
url += "&info_hash=" + parameters.InfoHash.UrlEncode ();
var request = (HttpWebRequest)WebRequest.Create(url);
request.UserAgent = VersionInfo.ClientVersion;
BeginRequest(request, ScrapeReceived, new[] { request, state });
}
catch
{
RaiseScrapeComplete(new ScrapeResponseEventArgs(this, state, false));
}
}
void ScrapeReceived(IAsyncResult result)
{
var message = string.Empty;
var stateOb = (object[])result.AsyncState;
var request = (WebRequest)stateOb[0];
var state = stateOb[1];
try
{
var dict = DecodeResponse(request, result);
// FIXME: Log the failure?
if (!dict.ContainsKey("files"))
{
message = "Response contained no data";
return;
}
var files = (BEncodedDictionary)dict["files"];
foreach (var keypair in files)
{
var d = (BEncodedDictionary) keypair.Value;
foreach (var kp in d)
{
switch (kp.Key.ToString())
{
case ("complete"):
Complete = (int)((BEncodedNumber)kp.Value).Number;
break;
case ("downloaded"):
Downloaded = (int)((BEncodedNumber)kp.Value).Number;
break;
case ("incomplete"):
Incomplete = (int)((BEncodedNumber)kp.Value).Number;
break;
default:
Logger.Log(null, "HttpTracker - Unknown scrape tag received: Key {0} Value {1}", kp.Key.ToString(), kp.Value.ToString());
break;
}
}
}
}
catch (WebException)
{
message = "The tracker could not be contacted";
}
catch
{
message = "The tracker returned an invalid or incomplete response";
}
finally
{
RaiseScrapeComplete(new ScrapeResponseEventArgs(this, state, string.IsNullOrEmpty(message)));
}
}
public override string ToString()
{
return Uri.ToString();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using ConsoleToolkit.ApplicationStyles.Internals;
using ConsoleToolkit.Exceptions;
namespace ConsoleToolkit.CommandLineInterpretation
{
/// <summary>
/// The configuration for a command. This may be the unnamed command (i.e. the command line parameters for an application that does not support commands)
/// or a named "sub-command" of a program that supports that paradigm.
/// </summary>
/// <typeparam name="T">The type that will be populated with the command parameters extracted from the command line.</typeparam>
public class CommandConfig<T> : BaseCommandConfig, IOptionContainer<CommandConfig<T>> where T :class
{
private readonly Func<string, T> _initialiser;
private IContext _currentContext;
private Func<T, IList<string>, bool> _validator;
public CommandConfig(Func<T> initialiser) : this(s => initialiser())
{
}
public CommandConfig(Func<string, T> initialiser)
{
_initialiser = initialiser;
_currentContext = this;
}
/// <summary>
/// Add a positional parameter.
/// </summary>
/// <typeparam name="T1">The data type of the paramter value.</typeparam>
/// <param name="parameterName">The name of the parameter</param>
/// <param name="positionalInitialiser">An expression that sets the value of the parameter in the command type.</param>
public CommandConfig<T> Positional<T1>(string parameterName, Action<T, T1> positionalInitialiser)
{
var commandPositional = new CommandPositional<T, T1>(parameterName, positionalInitialiser);
Positionals.Add(commandPositional);
_currentContext = commandPositional;
return this;
}
/// <summary>
/// Add a positional parameter.
/// </summary>
/// <typeparam name="T1">The data type of the paramter value.</typeparam>
/// <param name="parameterName">The name of the parameter</param>
/// <param name="positionalVariableIdentifier">An expression that returns the property in the command type that should receive the value.</param>
public CommandConfig<T> Positional<T1>(string parameterName, Expression<Func<T, T1>> positionalVariableIdentifier)
{
var commandPositional = ConfigGenerator.PositionalFromExpression(parameterName, positionalVariableIdentifier);
Positionals.Add(commandPositional);
_currentContext = commandPositional;
return this;
}
/// <summary>
/// Add a positional parameter.
/// </summary>
/// <param name="parameterName">The name of the parameter</param>
public CommandConfig<T> Positional(string parameterName)
{
var commandPositional = ConfigGenerator.PositionalByName<T>(parameterName);
Positionals.Add(commandPositional);
_currentContext = commandPositional;
return this;
}
public CommandConfig<T> DefaultValue(string value)
{
if (ContextIsPositional())
{
var positional = (_currentContext as BasePositional);
if (positional != null)
{
positional.DefaultValue = value;
positional.IsOptional = true;
return this;
}
}
throw new DefaultValueMayOnlyBeSpecifiedForPositionalParameters(_currentContext);
}
/// <summary>
/// Specifies the simplest possible option type - there are no parameters, the option is simply present.
/// However, some parsing conventions allow for a boolean to be specified allowing a false to be supplied.
/// In order to support this, the option must accept a boolean and apply it appropriately.
/// </summary>
/// <param name="optionName">The name of the option.</param>
/// <param name="optionInitialiser">The lambda that applies the option to the command parameters type. Note that this must accept a boolean.</param>
/// <returns>The command config.</returns>
public CommandConfig<T> Option(string optionName, Action<T, bool> optionInitialiser)
{
var commandOption = new CommandOption<Action<T, bool>>(optionName, optionInitialiser, false) { IsBoolean = true};
Options.Add(commandOption);
_currentContext = commandOption;
return this;
}
/// <summary>
/// Specifies the simplest possible option type - there are no parameters, the option is simply present.
/// However, some parsing conventions allow for a boolean to be specified allowing a false to be supplied.
/// In order to support this, the option must accept a boolean and apply it appropriately.
/// </summary>
/// <param name="optionName">The name of the option.</param>
/// <param name="optionVariableIndicator">The expression that identifies the boolean that should be set in the command type.</param>
/// <returns>The command config.</returns>
public CommandConfig<T> Option(string optionName, Expression<Func<T, bool>> optionVariableIndicator)
{
var commandOption = ConfigGenerator.OptionFromExpression(typeof(T), optionName, optionVariableIndicator, true, false);
Options.Add(commandOption);
_currentContext = commandOption;
return this;
}
/// <summary>
/// Specifies an option taking a single parameter. The property related to the option is identified using a Linq expression.
/// </summary>
/// <param name="optionName">The name of the option.</param>
/// <param name="optionVariableIndicator">The expression that identifies the member that should be set in the command type. The type of the member determines the data type of the option.</param>
/// <returns>The command config.</returns>
public CommandConfig<T> Option<TParam>(string optionName, Expression<Func<T, TParam>> optionVariableIndicator)
{
var commandOption = ConfigGenerator.OptionFromExpression(typeof(T), optionName, optionVariableIndicator, false, false);
Options.Add(commandOption);
_currentContext = commandOption;
return this;
}
/// <summary>
/// Specifies an option taking a single parameter. The option is set using a caller supplied lambda expression.
/// </summary>
/// <typeparam name="T1">The parameter.</typeparam>
/// <param name="optionName">The name of the option.</param>
/// <param name="optionInitialiser">The action that will be invoked when the option's parameters have been converted.</param>
/// <returns>The command config.</returns>
public CommandConfig<T> Option<T1>(string optionName, Action<T, T1> optionInitialiser)
{
var commandOption = new CommandOption<Action<T, T1>>(optionName, optionInitialiser, false);
Options.Add(commandOption);
_currentContext = commandOption;
return this;
}
/// <summary>
/// Specifies an option taking a single parameter. The property related to the option is identified automatically using the option name.
/// </summary>
/// <param name="optionName">The name of the option.</param>
/// <returns>The command config.</returns>
public CommandConfig<T> Option(string optionName)
{
var commandOption = ConfigGenerator.OptionByName(typeof(T), optionName, false);
Options.Add(commandOption);
_currentContext = commandOption;
return this;
}
/// <summary>
/// Specifies an option taking a two parameters.
/// </summary>
/// <typeparam name="T1">The first parameter.</typeparam>
/// <typeparam name="T2">The second parameter.</typeparam>
/// <param name="optionName">The name of the option.</param>
/// <param name="optionInitialiser">The action that will be invoked when the option's parameters have been converted.</param>
/// <returns>The command config.</returns>
public CommandConfig<T> Option<T1, T2>(string optionName, Action<T, T1, T2> optionInitialiser)
{
var commandOption = new CommandOption<Action<T, T1, T2>>(optionName, optionInitialiser, false);
Options.Add(commandOption);
_currentContext = commandOption;
return this;
}
/// <summary>
/// Specifies an option taking a two parameters.
/// </summary>
/// <typeparam name="T1">The first parameter.</typeparam>
/// <typeparam name="T2">The second parameter.</typeparam>
/// <typeparam name="T3">The third parameter.</typeparam>
/// <param name="optionName">The name of the option.</param>
/// <param name="optionInitialiser">The action that will be invoked when the option's parameters have been converted.</param>
/// <returns>The command config.</returns>
public CommandConfig<T> Option<T1, T2, T3>(string optionName, Action<T, T1, T2, T3> optionInitialiser)
{
var commandOption = new CommandOption<Action<T, T1, T2, T3>>(optionName, optionInitialiser, false);
Options.Add(commandOption);
_currentContext = commandOption;
return this;
}
/// <summary>
/// Short circuit the parsing process. This allows options to be specified that bypass the usual validation of
/// missing parameters. Options that display help text are a good example of where this could be useful.
/// </summary>
public CommandConfig<T> ShortCircuitOption()
{
if (_currentContext is BaseOption)
{
(_currentContext as BaseOption).IsShortCircuit = true;
return this;
}
if (ContextIsPositional())
throw new ShortCircuitInvalidOnPositionalParameter(_currentContext);
throw new ShortCircuitInvalid();
}
/// <summary>
/// Allow this option or parameter to be specified multiple times.
/// </summary>
public CommandConfig<T> AllowMultiple()
{
if (_currentContext is BaseOption)
{
(_currentContext as BaseOption).AllowMultiple = true;
return this;
}
if (_currentContext is BasePositional)
{
(_currentContext as BasePositional).AllowMultiple = true;
return this;
}
throw new AllowMultipleInvalid();
}
internal override object Create(string commandName)
{
return _initialiser(commandName);
}
internal override bool Validate(object command, IList<string> messages)
{
if (_validator == null || command == null) return true;
if (command is T)
return _validator(command as T, messages);
messages.Add(String.Format("Internal error: Command type received was {0}, but {1} was expected.", command.GetType(), typeof (T)));
return false;
}
/// <summary>
/// Use this method to provide descriptive text. The description is context sensitive and will be applied to the command,
/// option or parameter that is currently being configured. Therefore, you must specify the appropriate description before
/// configuring more detail.
/// </summary>
/// <param name="text">The descriptive test.</param>
/// <returns>The command config.</returns>
public CommandConfig<T> Description(string text)
{
if (_currentContext != null)
_currentContext.Description = text;
return this;
}
/// <summary>
/// Use this method to add a keyword to the command. Keywords are words that precede the actual command. For example, "config add ..."
/// where the command is "add" and the keyword is "config". This allows applications to support sets of commands related by the same
/// keyword. e.g.:
/// <para/>
/// <list type = "table" >
/// <item>
/// <description>config update ...</description>
/// </item>
/// <item>
/// <description>config add ...</description>
/// </item>
/// <item>
/// <description>config delete ...</description>
/// </item>
/// <item>
/// <description>user add ...</description>
/// </item>
/// <item>
/// <description>user update ...</description>
/// </item>
/// <item>
/// <description>user delete ...</description>
/// </item>
/// </list>
/// Here, two keywords have been used - "config" and "user", each of which has been associated with commands. In all, six commands
/// have been defined - there is no mechanism to share commands between prefixes i.e. "config add" is a different command to "user add"
/// and they <i>cannot</i> be implemented by the same command.
/// </summary>
public CommandConfig<T> Keyword(string keyword, string helpText = null)
{
if (!ReferenceEquals(_currentContext, this))
{
throw new KeywordCanOnlyBeSpecifiedOnCommand();
}
var tokens = CommandLineTokeniser.Tokenise(keyword).ToList();
foreach (var token in tokens)
Keywords.Add(token);
KeywordsDocs.Add(new KeywordsDesc(helpText, Keywords.ToList()));
return this;
}
/// <summary>
/// Supply a validation routine for the command or parameters. This will be called with the populated command instance and
/// a list into which error messages and warnings may be inserted. The validator should return true if the command is valid,
/// or false if an error is found. If any messages are placed in the list, they are assyumed to be warnings if true is
/// returned, or errors if false is returned.
///
/// Error messages returned by the validator will be printed to the error writer, warnings will be printed to the console.
/// </summary>
/// <param name="validationFunction"></param>
public void Validator(Func<T, IList<string>, bool> validationFunction)
{
_validator = validationFunction;
}
/// <summary>
/// Supply an alternative name for the option. All of the alias names and the primary option name will refer to the same option.
/// This feature can be used to supply a short name for an option with a long name. This is common in Gnu command line applications.
/// </summary>
/// <param name="alias">The alternative name for the option.</param>
public CommandConfig<T> Alias(string alias)
{
if (_currentContext is BaseOption)
{
var existingNames = Options.SelectMany(o => new [] { o.Name }.Concat(o.Aliases));
(_currentContext as BaseOption).Alias(alias, existingNames);
return this;
}
throw new AliasNotSupported();
}
/// <summary>
/// Allow the command in an interactive session, but do not allow the command from command line parameters. If you do not specify this option or <see cref="NonInteractive"/>
/// the command will be valid in both interactive sessions and from command line parameters.
/// </summary>
public CommandConfig<T> Interactive()
{
ValidInInteractiveContext = true;
ValidInNonInteractiveContext = false;
return this;
}
/// <summary>
/// Allow the command from command line parameters, but do not allow the command in an interactive session. If you do not specify this option or <see cref="Interactive"/>
/// the command will be valid in both interactive sessions and from command line parameters.
/// </summary>
public CommandConfig<T> NonInteractive()
{
ValidInInteractiveContext = false;
ValidInNonInteractiveContext = true;
return this;
}
private bool ContextIsPositional()
{
return Positionals.Contains(_currentContext);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// OrderablePartitioner.cs
//
//
//
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
namespace System.Collections.Concurrent
{
/// <summary>
/// Represents a particular manner of splitting an orderable data source into multiple partitions.
/// </summary>
/// <typeparam name="TSource">Type of the elements in the collection.</typeparam>
/// <remarks>
/// <para>
/// Each element in each partition has an integer index associated with it, which determines the relative
/// order of that element against elements in other partitions.
/// </para>
/// <para>
/// Inheritors of <see cref="OrderablePartitioner{TSource}"/> must adhere to the following rules:
/// <ol>
/// <li>All indices must be unique, such that there may not be duplicate indices. If all indices are not
/// unique, the output ordering may be scrambled.</li>
/// <li>All indices must be non-negative. If any indices are negative, consumers of the implementation
/// may throw exceptions.</li>
/// <li><see cref="GetPartitions"/> and <see cref="GetOrderablePartitions"/> should throw a
/// <see cref="T:System.ArgumentOutOfRangeException"/> if the requested partition count is less than or
/// equal to zero.</li>
/// <li><see cref="GetPartitions"/> and <see cref="GetOrderablePartitions"/> should always return a number
/// of enumerables equal to the requested partition count. If the partitioner runs out of data and cannot
/// create as many partitions as requested, an empty enumerator should be returned for each of the
/// remaining partitions. If this rule is not followed, consumers of the implementation may throw a <see
/// cref="T:System.InvalidOperationException"/>.</li>
/// <li><see cref="GetPartitions"/>, <see cref="GetOrderablePartitions"/>,
/// <see cref="GetDynamicPartitions"/>, and <see cref="GetOrderableDynamicPartitions"/>
/// should never return null. If null is returned, a consumer of the implementation may throw a
/// <see cref="T:System.InvalidOperationException"/>.</li>
/// <li><see cref="GetPartitions"/>, <see cref="GetOrderablePartitions"/>,
/// <see cref="GetDynamicPartitions"/>, and <see cref="GetOrderableDynamicPartitions"/>
/// should always return partitions that can fully and uniquely enumerate the input data source. All of
/// the data and only the data contained in the input source should be enumerated, with no duplication
/// that was not already in the input, unless specifically required by the particular partitioner's
/// design. If this is not followed, the output ordering may be scrambled.</li>
/// <li>If <see cref="KeysOrderedInEachPartition"/> returns true, each partition must return elements
/// with increasing key indices.</li>
/// <li>If <see cref="KeysOrderedAcrossPartitions"/> returns true, all the keys in partition numbered N
/// must be larger than all the keys in partition numbered N-1.</li>
/// <li>If <see cref="KeysNormalized"/> returns true, all indices must be monotonically increasing from
/// 0, though not necessarily within a single partition.</li>
/// </ol>
/// </para>
/// </remarks>
public abstract class OrderablePartitioner<TSource> : Partitioner<TSource>
{
/// <summary>
/// Initializes a new instance of the <see cref="OrderablePartitioner{TSource}"/> class with the
/// specified constraints on the index keys.
/// </summary>
/// <param name="keysOrderedInEachPartition">
/// Indicates whether the elements in each partition are yielded in the order of
/// increasing keys.
/// </param>
/// <param name="keysOrderedAcrossPartitions">
/// Indicates whether elements in an earlier partition always come before
/// elements in a later partition. If true, each element in partition 0 has a smaller order key than
/// any element in partition 1, each element in partition 1 has a smaller order key than any element
/// in partition 2, and so on.
/// </param>
/// <param name="keysNormalized">
/// Indicates whether keys are normalized. If true, all order keys are distinct
/// integers in the range [0 .. numberOfElements-1]. If false, order keys must still be distinct, but
/// only their relative order is considered, not their absolute values.
/// </param>
protected OrderablePartitioner(bool keysOrderedInEachPartition, bool keysOrderedAcrossPartitions, bool keysNormalized)
{
KeysOrderedInEachPartition = keysOrderedInEachPartition;
KeysOrderedAcrossPartitions = keysOrderedAcrossPartitions;
KeysNormalized = keysNormalized;
}
/// <summary>
/// Partitions the underlying collection into the specified number of orderable partitions.
/// </summary>
/// <remarks>
/// Each partition is represented as an enumerator over key-value pairs.
/// The value of the pair is the element itself, and the key is an integer which determines
/// the relative ordering of this element against other elements in the data source.
/// </remarks>
/// <param name="partitionCount">The number of partitions to create.</param>
/// <returns>A list containing <paramref name="partitionCount"/> enumerators.</returns>
public abstract IList<IEnumerator<KeyValuePair<long, TSource>>> GetOrderablePartitions(int partitionCount);
/// <summary>
/// Creates an object that can partition the underlying collection into a variable number of
/// partitions.
/// </summary>
/// <remarks>
/// <para>
/// The returned object implements the <see
/// cref="T:System.Collections.Generic.IEnumerable{TSource}"/> interface. Calling <see
/// cref="System.Collections.Generic.IEnumerable{TSource}.GetEnumerator">GetEnumerator</see> on the
/// object creates another partition over the sequence.
/// </para>
/// <para>
/// Each partition is represented as an enumerator over key-value pairs. The value in the pair is the element
/// itself, and the key is an integer which determines the relative ordering of this element against
/// other elements.
/// </para>
/// <para>
/// The <see cref="GetOrderableDynamicPartitions"/> method is only supported if the <see
/// cref="System.Collections.Concurrent.Partitioner{TSource}.SupportsDynamicPartitions">SupportsDynamicPartitions</see>
/// property returns true.
/// </para>
/// </remarks>
/// <returns>An object that can create partitions over the underlying data source.</returns>
/// <exception cref="NotSupportedException">Dynamic partitioning is not supported by this
/// partitioner.</exception>
public virtual IEnumerable<KeyValuePair<long, TSource>> GetOrderableDynamicPartitions()
{
throw new NotSupportedException(SR.Partitioner_DynamicPartitionsNotSupported);
}
/// <summary>
/// Gets whether elements in each partition are yielded in the order of increasing keys.
/// </summary>
public bool KeysOrderedInEachPartition { get; private set; }
/// <summary>
/// Gets whether elements in an earlier partition always come before elements in a later partition.
/// </summary>
/// <remarks>
/// If <see cref="KeysOrderedAcrossPartitions"/> returns true, each element in partition 0 has a
/// smaller order key than any element in partition 1, each element in partition 1 has a smaller
/// order key than any element in partition 2, and so on.
/// </remarks>
public bool KeysOrderedAcrossPartitions { get; private set; }
/// <summary>
/// Gets whether order keys are normalized.
/// </summary>
/// <remarks>
/// If <see cref="KeysNormalized"/> returns true, all order keys are distinct integers in the range
/// [0 .. numberOfElements-1]. If the property returns false, order keys must still be distinct, but
/// only their relative order is considered, not their absolute values.
/// </remarks>
public bool KeysNormalized { get; private set; }
/// <summary>
/// Partitions the underlying collection into the given number of ordered partitions.
/// </summary>
/// <remarks>
/// The default implementation provides the same behavior as <see cref="GetOrderablePartitions"/> except
/// that the returned set of partitions does not provide the keys for the elements.
/// </remarks>
/// <param name="partitionCount">The number of partitions to create.</param>
/// <returns>A list containing <paramref name="partitionCount"/> enumerators.</returns>
public override IList<IEnumerator<TSource>> GetPartitions(int partitionCount)
{
IList<IEnumerator<KeyValuePair<long, TSource>>> orderablePartitions = GetOrderablePartitions(partitionCount);
if (orderablePartitions.Count != partitionCount)
{
throw new InvalidOperationException("OrderablePartitioner_GetPartitions_WrongNumberOfPartitions");
}
IEnumerator<TSource>[] partitions = new IEnumerator<TSource>[partitionCount];
for (int i = 0; i < partitionCount; i++)
{
partitions[i] = new EnumeratorDropIndices(orderablePartitions[i]);
}
return partitions;
}
/// <summary>
/// Creates an object that can partition the underlying collection into a variable number of
/// partitions.
/// </summary>
/// <remarks>
/// <para>
/// The returned object implements the <see
/// cref="T:System.Collections.Generic.IEnumerable{TSource}"/> interface. Calling <see
/// cref="System.Collections.Generic.IEnumerable{TSource}.GetEnumerator">GetEnumerator</see> on the
/// object creates another partition over the sequence.
/// </para>
/// <para>
/// The default implementation provides the same behavior as <see cref="GetOrderableDynamicPartitions"/> except
/// that the returned set of partitions does not provide the keys for the elements.
/// </para>
/// <para>
/// The <see cref="GetDynamicPartitions"/> method is only supported if the <see
/// cref="System.Collections.Concurrent.Partitioner{TSource}.SupportsDynamicPartitions"/>
/// property returns true.
/// </para>
/// </remarks>
/// <returns>An object that can create partitions over the underlying data source.</returns>
/// <exception cref="NotSupportedException">Dynamic partitioning is not supported by this
/// partitioner.</exception>
public override IEnumerable<TSource> GetDynamicPartitions()
{
IEnumerable<KeyValuePair<long, TSource>> orderablePartitions = GetOrderableDynamicPartitions();
return new EnumerableDropIndices(orderablePartitions);
}
/// <summary>
/// Converts an enumerable over key-value pairs to an enumerable over values.
/// </summary>
private class EnumerableDropIndices : IEnumerable<TSource>, IDisposable
{
private readonly IEnumerable<KeyValuePair<long, TSource>> _source;
public EnumerableDropIndices(IEnumerable<KeyValuePair<long, TSource>> source)
{
_source = source;
}
public IEnumerator<TSource> GetEnumerator()
{
return new EnumeratorDropIndices(_source.GetEnumerator());
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((EnumerableDropIndices)this).GetEnumerator();
}
public void Dispose()
{
IDisposable d = _source as IDisposable;
if (d != null)
{
d.Dispose();
}
}
}
private class EnumeratorDropIndices : IEnumerator<TSource>
{
private readonly IEnumerator<KeyValuePair<long, TSource>> _source;
public EnumeratorDropIndices(IEnumerator<KeyValuePair<long, TSource>> source)
{
_source = source;
}
public bool MoveNext()
{
return _source.MoveNext();
}
public TSource Current
{
get
{
return _source.Current.Value;
}
}
Object IEnumerator.Current
{
get
{
return ((EnumeratorDropIndices)this).Current;
}
}
public void Dispose()
{
_source.Dispose();
}
public void Reset()
{
_source.Reset();
}
}
}
}
| |
//
// Encog(tm) Core v3.2 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Collections.Generic;
using System.IO;
namespace Encog.App.Generate.Program
{
/// <summary>
/// A node that holds a program.
/// </summary>
public class EncogProgramNode : EncogTreeNode
{
/// <summary>
/// The argements to the program.
/// </summary>
private readonly IList<EncogProgramArg> args = new List<EncogProgramArg>();
/// <summary>
/// The name od this node.
/// </summary>
private readonly String name;
/// <summary>
/// The type of node that this is.
/// </summary>
private readonly NodeType type;
/// <summary>
/// Construct the program node.
/// </summary>
/// <param name="theProgram">THe program.</param>
/// <param name="theParent">The parent.</param>
/// <param name="theNodeType">The node type.</param>
/// <param name="theName">The name of the node.</param>
public EncogProgramNode(EncogGenProgram theProgram,
EncogTreeNode theParent, NodeType theNodeType,
String theName)
: base(theProgram, theParent)
{
type = theNodeType;
name = theName;
}
/// <summary>
/// The args.
/// </summary>
public IList<EncogProgramArg> Args
{
get { return args; }
}
/// <summary>
/// The name.
/// </summary>
public String Name
{
get { return name; }
}
/// <summary>
/// The type.
/// </summary>
public NodeType Type
{
get { return type; }
}
/// <summary>
/// Add a double argument.
/// </summary>
/// <param name="argValue">The argument value.</param>
public void AddArg(double argValue)
{
var arg = new EncogProgramArg(argValue);
args.Add(arg);
}
/// <summary>
/// Add an int argument.
/// </summary>
/// <param name="argValue">The argument value.</param>
public void AddArg(int argValue)
{
var arg = new EncogProgramArg(argValue);
args.Add(arg);
}
/// <summary>
/// Add an object argument.
/// </summary>
/// <param name="argValue">The argument value.</param>
public void AddArg(Object argValue)
{
var arg = new EncogProgramArg(argValue);
args.Add(arg);
}
/// <summary>
/// Add a string argument.
/// </summary>
/// <param name="argValue">The argument value.</param>
public void AddArg(string argValue)
{
var arg = new EncogProgramArg(argValue);
args.Add(arg);
}
/// <summary>
/// Create an array.
/// </summary>
/// <param name="name">THe name of the array.</param>
/// <param name="a">The value to init the array to.</param>
/// <returns>The newly creatred array.</returns>
public EncogProgramNode CreateArray(string name, double[] a)
{
var node = new EncogProgramNode(Program, this,
NodeType.InitArray, name);
node.AddArg(a);
Children.Add(node);
return node;
}
/// <summary>
/// Create a function.
/// </summary>
/// <param name="theName">The name of the function.</param>
/// <returns>The newly created function.</returns>
public EncogProgramNode CreateFunction(string theName)
{
var node = new EncogProgramNode(Program, this,
NodeType.StaticFunction, theName);
Children.Add(node);
return node;
}
/// <summary>
/// Create a function call.
/// </summary>
/// <param name="funct">The function to call.</param>
/// <param name="returnType">The type returned.</param>
/// <param name="returnVariable">The value to assigne the function call to.</param>
/// <returns>The newly created function call.</returns>
public EncogProgramNode CreateFunctionCall(EncogProgramNode funct,
String returnType, String returnVariable)
{
var node = new EncogProgramNode(Program, this,
NodeType.FunctionCall, funct.Name);
node.AddArg(returnType);
node.AddArg(returnVariable);
Children.Add(node);
return node;
}
/// <summary>
/// Create a function call.
/// </summary>
/// <param name="name">The name of the function to call.</param>
/// <param name="returnType">The return type.</param>
/// <param name="returnVariable">The variable to assign the function to.</param>
/// <returns>The newly created function call.</returns>
public EncogProgramNode CreateFunctionCall(string name,
string returnType, string returnVariable)
{
var node = new EncogProgramNode(Program, this,
NodeType.FunctionCall, name);
node.AddArg(returnType);
node.AddArg(returnVariable);
Children.Add(node);
return node;
}
/// <summary>
/// Create a new main function.
/// </summary>
/// <returns>The newly created main function.</returns>
public EncogProgramNode CreateMainFunction()
{
var node = new EncogProgramNode(Program, this,
NodeType.MainFunction, null);
Children.Add(node);
return node;
}
/// <summary>
/// Create a new network function.
/// </summary>
/// <param name="name">The name of the network function.</param>
/// <param name="method">The method to call.</param>
/// <returns>The newly created network function.</returns>
public EncogProgramNode CreateNetworkFunction(string name,
FileInfo method)
{
var node = new EncogProgramNode(Program, this,
NodeType.CreateNetwork, name);
node.AddArg(method);
Children.Add(node);
return node;
}
/// <summary>
/// Define a const.
/// </summary>
/// <param name="type">The type of const.</param>
/// <param name="name">The name of the const.</param>
/// <param name="value">The value of the const.</param>
public void DefineConst(EncogArgType type, string name,
string value)
{
var node = new EncogProgramNode(Program, this,
NodeType.Const, name);
node.AddArg(value);
node.AddArg(type.ToString());
Children.Add(node);
}
/// <summary>
/// Embed training data.
/// </summary>
/// <param name="data">The training data to embed.</param>
/// <returns>The newly created embeded training data.</returns>
public EncogProgramNode EmbedTraining(FileInfo data)
{
var node = new EncogProgramNode(Program, this,
NodeType.EmbedTraining, "");
node.AddArg(data);
Children.Add(node);
return node;
}
/// <summary>
/// Load the training data.
/// </summary>
/// <param name="data">The data.</param>
/// <returns>The newly created data load.</returns>
public EncogProgramNode GenerateLoadTraining(FileInfo data)
{
var node = new EncogProgramNode(Program, this,
NodeType.LoadTraining, "");
node.AddArg(data);
Children.Add(node);
return node;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Dispatcher;
using System.Threading.Tasks;
namespace System.ServiceModel.Channels
{
internal abstract class ServiceChannelFactory : ChannelFactoryBase
{
private string _bindingName;
private List<IChannel> _channelsList;
private ClientRuntime _clientRuntime;
private RequestReplyCorrelator _requestReplyCorrelator = new RequestReplyCorrelator();
private IDefaultCommunicationTimeouts _timeouts;
private MessageVersion _messageVersion;
public ServiceChannelFactory(ClientRuntime clientRuntime, Binding binding)
: base()
{
if (clientRuntime == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("clientRuntime");
}
_bindingName = binding.Name;
_channelsList = new List<IChannel>();
_clientRuntime = clientRuntime;
_timeouts = new DefaultCommunicationTimeouts(binding);
_messageVersion = binding.MessageVersion;
}
public ClientRuntime ClientRuntime
{
get
{
this.ThrowIfDisposed();
return _clientRuntime;
}
}
internal RequestReplyCorrelator RequestReplyCorrelator
{
get
{
ThrowIfDisposed();
return _requestReplyCorrelator;
}
}
protected override TimeSpan DefaultCloseTimeout
{
get { return _timeouts.CloseTimeout; }
}
protected override TimeSpan DefaultReceiveTimeout
{
get { return _timeouts.ReceiveTimeout; }
}
protected override TimeSpan DefaultOpenTimeout
{
get { return _timeouts.OpenTimeout; }
}
protected override TimeSpan DefaultSendTimeout
{
get { return _timeouts.SendTimeout; }
}
public MessageVersion MessageVersion
{
get { return _messageVersion; }
}
// special overload for security only
public static ServiceChannelFactory BuildChannelFactory(ChannelBuilder channelBuilder, ClientRuntime clientRuntime)
{
if (channelBuilder.CanBuildChannelFactory<IDuplexChannel>())
{
return new ServiceChannelFactoryOverDuplex(channelBuilder.BuildChannelFactory<IDuplexChannel>(), clientRuntime,
channelBuilder.Binding);
}
else if (channelBuilder.CanBuildChannelFactory<IDuplexSessionChannel>())
{
return new ServiceChannelFactoryOverDuplexSession(channelBuilder.BuildChannelFactory<IDuplexSessionChannel>(), clientRuntime, channelBuilder.Binding, false);
}
else
{
return new ServiceChannelFactoryOverRequestSession(channelBuilder.BuildChannelFactory<IRequestSessionChannel>(), clientRuntime, channelBuilder.Binding, false);
}
}
public static ServiceChannelFactory BuildChannelFactory(ServiceEndpoint serviceEndpoint)
{
return BuildChannelFactory(serviceEndpoint, false);
}
public static ServiceChannelFactory BuildChannelFactory(ServiceEndpoint serviceEndpoint, bool useActiveAutoClose)
{
if (serviceEndpoint == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serviceEndpoint");
}
serviceEndpoint.EnsureInvariants();
serviceEndpoint.ValidateForClient();
ChannelRequirements requirements;
ContractDescription contractDescription = serviceEndpoint.Contract;
ChannelRequirements.ComputeContractRequirements(contractDescription, out requirements);
BindingParameterCollection parameters;
ClientRuntime clientRuntime = DispatcherBuilder.BuildProxyBehavior(serviceEndpoint, out parameters);
Binding binding = serviceEndpoint.Binding;
Type[] requiredChannels = ChannelRequirements.ComputeRequiredChannels(ref requirements);
CustomBinding customBinding = new CustomBinding(binding);
BindingContext context = new BindingContext(customBinding, parameters);
customBinding = new CustomBinding(context.RemainingBindingElements);
customBinding.CopyTimeouts(serviceEndpoint.Binding);
foreach (Type type in requiredChannels)
{
if (type == typeof(IOutputChannel) && customBinding.CanBuildChannelFactory<IOutputChannel>(parameters))
{
return new ServiceChannelFactoryOverOutput(customBinding.BuildChannelFactory<IOutputChannel>(parameters), clientRuntime, binding);
}
if (type == typeof(IRequestChannel) && customBinding.CanBuildChannelFactory<IRequestChannel>(parameters))
{
return new ServiceChannelFactoryOverRequest(customBinding.BuildChannelFactory<IRequestChannel>(parameters), clientRuntime, binding);
}
if (type == typeof(IDuplexChannel) && customBinding.CanBuildChannelFactory<IDuplexChannel>(parameters))
{
if (requirements.usesReply &&
binding.CreateBindingElements().Find<TransportBindingElement>().ManualAddressing)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.CantCreateChannelWithManualAddressing));
}
return new ServiceChannelFactoryOverDuplex(customBinding.BuildChannelFactory<IDuplexChannel>(parameters), clientRuntime, binding);
}
if (type == typeof(IOutputSessionChannel) && customBinding.CanBuildChannelFactory<IOutputSessionChannel>(parameters))
{
return new ServiceChannelFactoryOverOutputSession(customBinding.BuildChannelFactory<IOutputSessionChannel>(parameters), clientRuntime, binding, false);
}
if (type == typeof(IRequestSessionChannel) && customBinding.CanBuildChannelFactory<IRequestSessionChannel>(parameters))
{
return new ServiceChannelFactoryOverRequestSession(customBinding.BuildChannelFactory<IRequestSessionChannel>(parameters), clientRuntime, binding, false);
}
if (type == typeof(IDuplexSessionChannel) && customBinding.CanBuildChannelFactory<IDuplexSessionChannel>(parameters))
{
if (requirements.usesReply &&
binding.CreateBindingElements().Find<TransportBindingElement>().ManualAddressing)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.CantCreateChannelWithManualAddressing));
}
return new ServiceChannelFactoryOverDuplexSession(customBinding.BuildChannelFactory<IDuplexSessionChannel>(parameters), clientRuntime, binding, useActiveAutoClose);
}
}
foreach (Type type in requiredChannels)
{
// For SessionMode.Allowed or SessionMode.NotAllowed we will accept session-ful variants as well
if (type == typeof(IOutputChannel) && customBinding.CanBuildChannelFactory<IOutputSessionChannel>(parameters))
{
return new ServiceChannelFactoryOverOutputSession(customBinding.BuildChannelFactory<IOutputSessionChannel>(parameters), clientRuntime, binding, true);
}
if (type == typeof(IRequestChannel) && customBinding.CanBuildChannelFactory<IRequestSessionChannel>(parameters))
{
return new ServiceChannelFactoryOverRequestSession(customBinding.BuildChannelFactory<IRequestSessionChannel>(parameters), clientRuntime, binding, true);
}
// and for SessionMode.Required, it is possible that the InstanceContextProvider is handling the session management, so
// accept datagram variants if that is the case
if (type == typeof(IRequestSessionChannel) && customBinding.CanBuildChannelFactory<IRequestChannel>(parameters)
&& customBinding.GetProperty<IContextSessionProvider>(parameters) != null)
{
return new ServiceChannelFactoryOverRequest(customBinding.BuildChannelFactory<IRequestChannel>(parameters), clientRuntime, binding);
}
}
// we put a lot of work into creating a good error message, as this is a common case
Dictionary<Type, byte> supportedChannels = new Dictionary<Type, byte>();
if (customBinding.CanBuildChannelFactory<IOutputChannel>(parameters))
{
supportedChannels.Add(typeof(IOutputChannel), 0);
}
if (customBinding.CanBuildChannelFactory<IRequestChannel>(parameters))
{
supportedChannels.Add(typeof(IRequestChannel), 0);
}
if (customBinding.CanBuildChannelFactory<IDuplexChannel>(parameters))
{
supportedChannels.Add(typeof(IDuplexChannel), 0);
}
if (customBinding.CanBuildChannelFactory<IOutputSessionChannel>(parameters))
{
supportedChannels.Add(typeof(IOutputSessionChannel), 0);
}
if (customBinding.CanBuildChannelFactory<IRequestSessionChannel>(parameters))
{
supportedChannels.Add(typeof(IRequestSessionChannel), 0);
}
if (customBinding.CanBuildChannelFactory<IDuplexSessionChannel>(parameters))
{
supportedChannels.Add(typeof(IDuplexSessionChannel), 0);
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ChannelRequirements.CantCreateChannelException(
supportedChannels.Keys, requiredChannels, binding.Name));
}
protected override void OnAbort()
{
IChannel channel = null;
lock (ThisLock)
{
channel = (_channelsList.Count > 0) ? _channelsList[_channelsList.Count - 1] : null;
}
while (channel != null)
{
channel.Abort();
lock (ThisLock)
{
_channelsList.Remove(channel);
channel = (_channelsList.Count > 0) ? _channelsList[_channelsList.Count - 1] : null;
}
}
}
protected override void OnClose(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
while (true)
{
int count;
IChannel channel;
lock (ThisLock)
{
count = _channelsList.Count;
if (count == 0)
return;
channel = _channelsList[0];
}
channel.Close(timeoutHelper.RemainingTime());
}
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
List<ICommunicationObject> objectList;
lock (ThisLock)
{
objectList = new List<ICommunicationObject>();
for (int index = 0; index < _channelsList.Count; index++)
objectList.Add(_channelsList[index]);
}
return new CloseCollectionAsyncResult(timeout, callback, state, objectList);
}
protected override void OnEndClose(IAsyncResult result)
{
CloseCollectionAsyncResult.End(result);
}
protected internal override Task OnCloseAsync(TimeSpan timeout)
{
return OnCloseAsyncInternal(timeout);
}
protected override void OnOpened()
{
base.OnOpened();
_clientRuntime.LockDownProperties();
}
public void ChannelCreated(IChannel channel)
{
lock (ThisLock)
{
ThrowIfDisposed();
_channelsList.Add(channel);
}
}
public void ChannelDisposed(IChannel channel)
{
lock (ThisLock)
{
_channelsList.Remove(channel);
}
}
public virtual ServiceChannel CreateServiceChannel(EndpointAddress address, Uri via)
{
IChannelBinder binder = this.CreateInnerChannelBinder(address, via);
ServiceChannel serviceChannel = new ServiceChannel(this, binder);
if (binder is DuplexChannelBinder)
{
DuplexChannelBinder duplexChannelBinder = binder as DuplexChannelBinder;
duplexChannelBinder.ChannelHandler = new ChannelHandler(_messageVersion, binder, serviceChannel);
duplexChannelBinder.DefaultCloseTimeout = this.DefaultCloseTimeout;
duplexChannelBinder.DefaultSendTimeout = this.DefaultSendTimeout;
duplexChannelBinder.IdentityVerifier = _clientRuntime.IdentityVerifier;
}
return serviceChannel;
}
public TChannel CreateChannel<TChannel>(EndpointAddress address)
{
return this.CreateChannel<TChannel>(address, null);
}
public TChannel CreateChannel<TChannel>(EndpointAddress address, Uri via)
{
if (via == null)
{
via = this.ClientRuntime.Via;
if (via == null)
{
via = address.Uri;
}
}
ServiceChannel serviceChannel = this.CreateServiceChannel(address, via);
serviceChannel.Proxy = CreateProxy<TChannel>(MessageDirection.Input, serviceChannel);
IClientChannel clientChannel = serviceChannel.Proxy as IClientChannel;
if (clientChannel == null)
{
clientChannel = serviceChannel;
}
serviceChannel.ClientRuntime.GetRuntime().InitializeChannel(clientChannel);
OperationContext current = OperationContext.Current;
if ((current != null) && (current.InstanceContext != null))
{
current.InstanceContext.WmiChannels.Add((IChannel)serviceChannel.Proxy);
}
return (TChannel)serviceChannel.Proxy;
}
public abstract bool CanCreateChannel<TChannel>();
internal static object CreateProxy(Type interfaceType, Type proxiedType, MessageDirection direction, ServiceChannel serviceChannel)
{
throw ExceptionHelper.PlatformNotSupported();
}
internal static object CreateProxy<TChannel>(MessageDirection direction, ServiceChannel serviceChannel)
{
if (!typeof(TChannel).IsInterface())
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxChannelFactoryTypeMustBeInterface));
}
return ServiceChannelProxy.CreateProxy<TChannel>(direction, serviceChannel);
}
internal static ServiceChannel GetServiceChannel(object transparentProxy)
{
IChannelBaseProxy cb = transparentProxy as IChannelBaseProxy;
if (cb != null)
return cb.GetServiceChannel();
ServiceChannelProxy proxy = transparentProxy as ServiceChannelProxy;
if (proxy != null)
return proxy.GetServiceChannel();
else
return null;
}
private async Task OnCloseAsyncInternal(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
while (true)
{
int count;
IChannel channel;
lock (ThisLock)
{
count = _channelsList.Count;
if (count == 0)
return;
channel = _channelsList[0];
}
IAsyncCommunicationObject asyncChannel = channel as IAsyncCommunicationObject;
if (asyncChannel != null)
{
await asyncChannel.CloseAsync(timeoutHelper.RemainingTime());
}
else
{
await Task.Factory.FromAsync(channel.BeginClose, channel.EndClose, TaskCreationOptions.None);
}
}
}
protected abstract IChannelBinder CreateInnerChannelBinder(EndpointAddress address, Uri via);
internal abstract class TypedServiceChannelFactory<TChannel> : ServiceChannelFactory
where TChannel : class, IChannel
{
private IChannelFactory<TChannel> _innerChannelFactory;
protected TypedServiceChannelFactory(IChannelFactory<TChannel> innerChannelFactory,
ClientRuntime clientRuntime, Binding binding)
: base(clientRuntime, binding)
{
_innerChannelFactory = innerChannelFactory;
}
protected IChannelFactory<TChannel> InnerChannelFactory
{
get { return _innerChannelFactory; }
}
protected override void OnAbort()
{
base.OnAbort();
_innerChannelFactory.Abort();
}
protected override void OnOpen(TimeSpan timeout)
{
_innerChannelFactory.Open(timeout);
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return _innerChannelFactory.BeginOpen(timeout, callback, state);
}
protected override void OnEndOpen(IAsyncResult result)
{
_innerChannelFactory.EndOpen(result);
}
protected override void OnClose(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
base.OnClose(timeoutHelper.RemainingTime());
_innerChannelFactory.Close(timeoutHelper.RemainingTime());
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return new ChainedAsyncResult(timeout, callback, state, base.OnBeginClose, base.OnEndClose,
_innerChannelFactory.BeginClose, _innerChannelFactory.EndClose);
}
protected override void OnEndClose(IAsyncResult result)
{
ChainedAsyncResult.End(result);
}
protected internal override Task OnCloseAsync(TimeSpan timeout)
{
return OnCloseAsyncInternal(timeout);
}
protected internal override Task OnOpenAsync(TimeSpan timeout)
{
this.OnOpen(timeout);
return TaskHelpers.CompletedTask();
}
public override T GetProperty<T>()
{
if (typeof(T) == typeof(TypedServiceChannelFactory<TChannel>))
{
return (T)(object)this;
}
T baseProperty = base.GetProperty<T>();
if (baseProperty != null)
{
return baseProperty;
}
return _innerChannelFactory.GetProperty<T>();
}
private new async Task OnCloseAsyncInternal(TimeSpan timeout)
{
await base.OnCloseAsync(timeout);
IAsyncChannelFactory asyncChannelFactory = _innerChannelFactory as IAsyncChannelFactory;
if (asyncChannelFactory != null)
{
await asyncChannelFactory.CloseAsync(timeout);
}
else
{
await Task.Factory.FromAsync(_innerChannelFactory.BeginClose, _innerChannelFactory.EndClose, TaskCreationOptions.None);
}
}
}
private class ServiceChannelFactoryOverOutput : TypedServiceChannelFactory<IOutputChannel>
{
public ServiceChannelFactoryOverOutput(IChannelFactory<IOutputChannel> innerChannelFactory, ClientRuntime clientRuntime, Binding binding)
: base(innerChannelFactory, clientRuntime, binding)
{
}
protected override IChannelBinder CreateInnerChannelBinder(EndpointAddress to, Uri via)
{
return new OutputChannelBinder(this.InnerChannelFactory.CreateChannel(to, via));
}
public override bool CanCreateChannel<TChannel>()
{
return (typeof(TChannel) == typeof(IOutputChannel)
|| typeof(TChannel) == typeof(IRequestChannel));
}
}
private class ServiceChannelFactoryOverDuplex : TypedServiceChannelFactory<IDuplexChannel>
{
public ServiceChannelFactoryOverDuplex(IChannelFactory<IDuplexChannel> innerChannelFactory, ClientRuntime clientRuntime, Binding binding)
: base(innerChannelFactory, clientRuntime, binding)
{
}
protected override IChannelBinder CreateInnerChannelBinder(EndpointAddress to, Uri via)
{
return new DuplexChannelBinder(this.InnerChannelFactory.CreateChannel(to, via), this.RequestReplyCorrelator);
}
public override bool CanCreateChannel<TChannel>()
{
return (typeof(TChannel) == typeof(IOutputChannel)
|| typeof(TChannel) == typeof(IRequestChannel)
|| typeof(TChannel) == typeof(IDuplexChannel));
}
}
private class ServiceChannelFactoryOverRequest : TypedServiceChannelFactory<IRequestChannel>
{
public ServiceChannelFactoryOverRequest(IChannelFactory<IRequestChannel> innerChannelFactory, ClientRuntime clientRuntime, Binding binding)
: base(innerChannelFactory, clientRuntime, binding)
{
}
protected override IChannelBinder CreateInnerChannelBinder(EndpointAddress to, Uri via)
{
return new RequestChannelBinder(this.InnerChannelFactory.CreateChannel(to, via));
}
public override bool CanCreateChannel<TChannel>()
{
return (typeof(TChannel) == typeof(IOutputChannel)
|| typeof(TChannel) == typeof(IRequestChannel));
}
}
internal class ServiceChannelFactoryOverOutputSession : TypedServiceChannelFactory<IOutputSessionChannel>
{
private bool _datagramAdapter;
public ServiceChannelFactoryOverOutputSession(IChannelFactory<IOutputSessionChannel> innerChannelFactory, ClientRuntime clientRuntime, Binding binding, bool datagramAdapter)
: base(innerChannelFactory, clientRuntime, binding)
{
_datagramAdapter = datagramAdapter;
}
protected override IChannelBinder CreateInnerChannelBinder(EndpointAddress to, Uri via)
{
IOutputChannel channel;
{
channel = this.InnerChannelFactory.CreateChannel(to, via);
}
return new OutputChannelBinder(channel);
}
public override bool CanCreateChannel<TChannel>()
{
return (typeof(TChannel) == typeof(IOutputChannel)
|| typeof(TChannel) == typeof(IOutputSessionChannel)
|| typeof(TChannel) == typeof(IRequestChannel)
|| typeof(TChannel) == typeof(IRequestSessionChannel));
}
}
internal class ServiceChannelFactoryOverDuplexSession : TypedServiceChannelFactory<IDuplexSessionChannel>
{
private bool _useActiveAutoClose;
public ServiceChannelFactoryOverDuplexSession(IChannelFactory<IDuplexSessionChannel> innerChannelFactory, ClientRuntime clientRuntime, Binding binding, bool useActiveAutoClose)
: base(innerChannelFactory, clientRuntime, binding)
{
_useActiveAutoClose = useActiveAutoClose;
}
protected override IChannelBinder CreateInnerChannelBinder(EndpointAddress to, Uri via)
{
return new DuplexChannelBinder(this.InnerChannelFactory.CreateChannel(to, via), this.RequestReplyCorrelator, _useActiveAutoClose);
}
public override bool CanCreateChannel<TChannel>()
{
return (typeof(TChannel) == typeof(IOutputChannel)
|| typeof(TChannel) == typeof(IRequestChannel)
|| typeof(TChannel) == typeof(IDuplexChannel)
|| typeof(TChannel) == typeof(IOutputSessionChannel)
|| typeof(TChannel) == typeof(IRequestSessionChannel)
|| typeof(TChannel) == typeof(IDuplexSessionChannel));
}
}
internal class ServiceChannelFactoryOverRequestSession : TypedServiceChannelFactory<IRequestSessionChannel>
{
private bool _datagramAdapter = false;
public ServiceChannelFactoryOverRequestSession(IChannelFactory<IRequestSessionChannel> innerChannelFactory, ClientRuntime clientRuntime, Binding binding, bool datagramAdapter)
: base(innerChannelFactory, clientRuntime, binding)
{
_datagramAdapter = datagramAdapter;
}
protected override IChannelBinder CreateInnerChannelBinder(EndpointAddress to, Uri via)
{
IRequestChannel channel;
{
channel = this.InnerChannelFactory.CreateChannel(to, via);
}
return new RequestChannelBinder(channel);
}
public override bool CanCreateChannel<TChannel>()
{
return (typeof(TChannel) == typeof(IOutputChannel)
|| typeof(TChannel) == typeof(IOutputSessionChannel)
|| typeof(TChannel) == typeof(IRequestChannel)
|| typeof(TChannel) == typeof(IRequestSessionChannel));
}
}
internal class DefaultCommunicationTimeouts : IDefaultCommunicationTimeouts
{
private TimeSpan _closeTimeout;
private TimeSpan _openTimeout;
private TimeSpan _receiveTimeout;
private TimeSpan _sendTimeout;
public DefaultCommunicationTimeouts(IDefaultCommunicationTimeouts timeouts)
{
_closeTimeout = timeouts.CloseTimeout;
_openTimeout = timeouts.OpenTimeout;
_receiveTimeout = timeouts.ReceiveTimeout;
_sendTimeout = timeouts.SendTimeout;
}
public TimeSpan CloseTimeout
{
get { return _closeTimeout; }
}
public TimeSpan OpenTimeout
{
get { return _openTimeout; }
}
public TimeSpan ReceiveTimeout
{
get { return _receiveTimeout; }
}
public TimeSpan SendTimeout
{
get { return _sendTimeout; }
}
}
}
}
| |
using System;
using System.IO;
using Common;
using Fairweather.Service;
namespace Sage_Int
{
public class Company_Settings_Old : Settings_Old
{
readonly int ix;
public Company_Settings_Old(D d)
: this(d, Record_Type.Undefined) {
}
public Company_Settings_Old(D d, Record_Type mode)
: base(d) {
if (mode == 0)
return;
this.ix = SIT_Engine.Get_Mode_Index(mode);
}
protected bool? String_Flag(string key) {
var str = String(key);
if (str.IsNullOrEmpty())
return null;
if (str[0] == '1')
return true;
if (ix >= str.Length)
return false;
if (str[ix] == '1')
return true;
return false;
}
// removeme 0788c1c9-a6a2-4e85-ab99-91ad0b75d7b6
Lazy<Pair<bool>> Documents_Grouping_Auto_Relative = new Lazy<Pair<bool>>(
() =>
{
var _auto = true;
var _relative = true;
var _file = "invoice_grouping.txt";
if (File.Exists(_file)) {
using (var _sr = new StreamReader(_file)) {
Func<bool, bool> read = __def =>
{
if (_sr.EndOfStream)
return __def;
var __str = _sr.ReadLine().strdef().Trim().ToUpper();
if (__str.IsNullOrEmpty())
return __def;
if (__str.EndsWith("YES"))
return true;
if (__str.EndsWith("NO"))
return false;
return __def;
};
_auto = read(_auto);
_relative = _auto ? read(_relative) : false;
}
}
return new Pair<bool>(_auto, _relative);
});
public bool? Documents_Numbering_Auto {
get {
return Documents_Grouping_Auto_Relative.Value.First;// String_Flag("DOCUMENTS_NUMBERING_AUTO");
}
}
public bool? Documents_Grouping_Relative {
get {
return Documents_Grouping_Auto_Relative.Value.Second;//String_Flag("DOCUMENTS_GROUPING_RELATIVE");
}
}
// C:\Users\Fairweather\Desktop\Generation\sageint_settings.pl
public bool? Has_Headers {
get {
return String_Flag(STR_DYNAMIC_IMPORT_FILE_LAYOUT);
}
}
public bool? Auto_Date {
get {
return String_Flag(STR_NEW_ACCOUNT_AUTO_DATE_ENTRY);
}
}
public bool? Output {
get {
return String_Flag(STR_OUTPUT_SUCCESS_CSV);
}
}
public bool? Overwrite {
get {
return String_Flag(STR_BLANK_FIELDS_OVERWRITE);
}
}
public bool? Group_Transactions_Sales {
get {
return String_Flag(STR_GROUP_TRANSACTIONS_SALES);
}
}
public bool? Group_Transactions_Purchase {
get {
return String_Flag(STR_GROUP_TRANSACTIONS_PURCHASE);
}
}
public bool? Use_Mappings {
get {
return String_Flag(STR_USE_MAPPINGS);
}
}
public bool? Group_Transactions_Any {
get {
return Group_Transactions_Sales == true || Group_Transactions_Purchase == true;
}
}
public bool? Check_Type {
get {
if (String_Flag(STR_CHANGE_BANK_AUDIT_TYPE) == true)
return false;
return String_Flag(STR_CHECK_BANK_AUDIT_TYPE);
}
}
public bool? Change_Type {
get {
if (String_Flag(STR_CHANGE_BANK_AUDIT_TYPE) != true)
return false;
return String_Flag(STR_CHECK_BANK_AUDIT_TYPE);
}
}
public bool? Use_Defaults {
get {
return String_Flag(STR_USE_DEFAULTS);
}
}
public string Sage_Usr {
get {
return String(STR_SAGEUSR_PATH);
}
set {
Set(STR_SAGEUSR_PATH, value);
}
}
public string CurrentPeriod {
get {
return String(STR_CURRENT_PERIOD);
}
set {
Set(STR_CURRENT_PERIOD, value);
}
}
#region ancient, horrible implementation
//public string OutputSuccess {
// get {
// return _settings[current_company]["OUTPUT_SUCCESS_CSV"];
// }
// set {
// _settings[current_company]["OUTPUT_SUCCESS_CSV"] = value;
// b_flag = false;
// for (int i = 0; i < settings_cbs["report"].Length; i++) {
// if (settings_cbs["report"][i] != null) {
// settings_cbs["report"][i].Checked = (value[i] == '1');
// }
// }
// }
//}
//public string GroupTransactionsS {
// get {
// return _settings[current_company]["GROUP_TRANSACTIONS_SALES"];
// }
// set {
// _settings[current_company]["GROUP_TRANSACTIONS_SALES"] = value;
// b_flag = false;
// for (int i = 0; i < settings_cbs["group_sales"].Length; i++) {
// if (settings_cbs["group_sales"][i] != null) {
// settings_cbs["group_sales"][i].Checked = (value[i] == '1');
// }
// }
// }
//}
//public string GroupTransactionsP {
// get {
// return _settings[current_company]["GROUP_TRANSACTIONS_PURCHASE"];
// }
// set {
// _settings[current_company]["GROUP_TRANSACTIONS_PURCHASE"] = value;
// b_flag = false;
// for (int i = 0; i < settings_cbs["group_purchase"].Length; i++) {
// if (settings_cbs["group_purchase"][i] != null) {
// settings_cbs["group_purchase"][i].Checked = (value[i] == '1');
// }
// }
// }
//}
//public string OverrideBlankFields {
// get {
// return _settings[current_company]["BLANK_FIELDS_OVERWRITE"];
// }
// set {
// _settings[current_company]["BLANK_FIELDS_OVERWRITE"] = value;
// b_flag = false;
// for (int i = 0; i < settings_cbs["overr"].Length; i++) {
// if (settings_cbs["overr"][i] != null) {
// settings_cbs["overr"][i].Checked = (value[i] == '1');
// }
// }
// }
//}
//public string AutoDateEntry {
// get {
// return _settings[current_company]["NEW_ACCOUNT_AUTO_DATE_ENTRY"];
// }
// set {
// _settings[current_company]["NEW_ACCOUNT_AUTO_DATE_ENTRY"] = value;
// b_flag = false;
// for (int i = 0; i < settings_cbs["auto_date"].Length; i++) {
// if (settings_cbs["auto_date"][i] != null) {
// settings_cbs["auto_date"][i].Checked = (value[i] == '1');
// }
// }
// }
//}
//public string ExchangeRate {
// get {
// return _settings[current_company]["EXCHANGE_RATE_1_BASE"];
// }
// set {
// _settings[current_company]["EXCHANGE_RATE_1_BASE"] = value;
// b_flag = false;
// for (int i = 0; i < settings_cbs["exchange_rate"].Length; i++) {
// if (settings_cbs["exchange_rate"][i] != null) {
// settings_cbs["exchange_rate"][i].Checked = (value[i] == '1');
// }
// }
// }
//}
//public string GenerateReval {
// get {
// return _settings[current_company]["GENERATE_REVAL"];
// }
// set {
// _settings[current_company]["GENERATE_REVAL"] = value;
// b_flag = false;
// for (int i = 0; i < settings_cbs["reval"].Length; i++) {
// if (settings_cbs["reval"][i] != null) {
// settings_cbs["reval"][i].Checked = (value[i] == '1');
// }
// }
// }
//}
//public string UseDefaults {
// get {
// return "1111111111";
// }
// set {
// _settings[current_company]["USE_DEFAULTS"] = value;
// b_flag = false;
// for (int i = 0; i < settings_cbs["defaults"].Length; i++) {
// if (settings_cbs["defaults"][i] != null) {
// settings_cbs["defaults"][i].Checked = (value[i] == '1');
// }
// }
// }
//}
//public string UseMappings {
// get {
// return _settings[current_company]["USE_MAPPINGS"];
// }
// set {
// _settings[current_company]["USE_MAPPINGS"] = value;
// b_flag = false;
// for (int i = 0; i < settings_cbs["mappings"].Length; i++) {
// if (settings_cbs["mappings"][i] != null) {
// settings_cbs["mappings"][i].Checked = (value[i] == '1');
// }
// }
// }
//}
#endregion
}
}
| |
// ===========================================================
// Copyright (C) 2014-2015 Kendar.org
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following conditions:
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
// OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ===========================================================
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Web;
using System;
using System.Web.WebSockets;
using System.Threading.Tasks;
using System.Globalization;
using System.Web.SessionState;
using System.Web.Configuration;
using System.Web.Caching;
using System.Collections;
using System.Web.Instrumentation;
using System.Web.Profile;
using System.Security.Principal;
using System.Collections.Generic;
using Http.Shared.Contexts;
namespace Http.Contexts
{
public class FromBaseHttpContext : HttpContextBase, IHttpContext
{
public FromBaseHttpContext()
{
RouteParams = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
}
public void ForceRootDir(string rootDir)
{
RootDir = rootDir;
}
public string RootDir { get; private set; }
public IHttpContext RootContext
{
get
{
if (Parent == null) return this;
return Parent.RootContext;
}
}
public Dictionary<string, object> RouteParams { get; set; }
public object SourceObject { get { return _httpContextBase; } }
private static readonly MethodInfo _getInnerCollection;
static FromBaseHttpContext()
{
var innerCollectionProperty = typeof(WebHeaderCollection).GetProperty("InnerCollection", BindingFlags.NonPublic | BindingFlags.Instance);
_getInnerCollection = innerCollectionProperty.GetGetMethod(true);
}
public void ForceHeader(string key, string value)
{
var nameValueCollection = (NameValueCollection)_getInnerCollection.Invoke(_httpContextBase.Request.Headers, new object[] { });
if (!_httpContextBase.Request.Headers.AllKeys.ToArray().Contains(key))
{
nameValueCollection.Add(key, value);
}
else
{
nameValueCollection.Set(key, value);
}
}
private readonly HttpContextBase _httpContextBase;
private FromBaseHttpResponse _response;
private FromBaseHttpRequest _request;
public FromBaseHttpContext(HttpContextBase httpContextBase)
{
if (!(httpContextBase is SimpleHttpContext)) ContextsManager.OnOpen();
_httpContextBase = httpContextBase;
InitializeUnsettable();
}
public IHttpContext Parent
{
get { return null; }
}
public override ISubscriptionToken AddOnRequestCompleted(Action<HttpContextBase> callback)
{
return _httpContextBase.AddOnRequestCompleted(callback);
}
public override void AcceptWebSocketRequest(Func<AspNetWebSocketContext, Task> userFunc)
{
_httpContextBase.AcceptWebSocketRequest(userFunc);
}
public override void AcceptWebSocketRequest(Func<AspNetWebSocketContext, Task> userFunc, AspNetWebSocketOptions options)
{
_httpContextBase.AcceptWebSocketRequest(userFunc, options);
}
public override void AddError(Exception errorInfo)
{
_httpContextBase.AddError(errorInfo);
}
public override void ClearError()
{
_httpContextBase.ClearError();
}
public override ISubscriptionToken DisposeOnPipelineCompleted(IDisposable target)
{
return _httpContextBase.DisposeOnPipelineCompleted(target);
}
public override Object GetGlobalResourceObject(String classKey, String resourceKey)
{
return _httpContextBase.GetGlobalResourceObject(classKey, resourceKey);
}
public override Object GetGlobalResourceObject(String classKey, String resourceKey, CultureInfo culture)
{
return _httpContextBase.GetGlobalResourceObject(classKey, resourceKey, culture);
}
public override Object GetLocalResourceObject(String virtualPath, String resourceKey)
{
return _httpContextBase.GetLocalResourceObject(virtualPath, resourceKey);
}
public override Object GetLocalResourceObject(String virtualPath, String resourceKey, CultureInfo culture)
{
return _httpContextBase.GetLocalResourceObject(virtualPath, resourceKey, culture);
}
public override Object GetSection(String sectionName)
{
return _httpContextBase.GetSection(sectionName);
}
public override void RemapHandler(IHttpHandler handler)
{
_httpContextBase.RemapHandler(handler);
}
public override void RewritePath(String path)
{
_httpContextBase.RewritePath(path);
}
public override void RewritePath(String path, Boolean rebaseClientPath)
{
_httpContextBase.RewritePath(path, rebaseClientPath);
}
public override void RewritePath(String filePath, String pathInfo, String queryString)
{
_httpContextBase.RewritePath(filePath, pathInfo, queryString);
}
public override void RewritePath(String filePath, String pathInfo, String queryString, Boolean setClientFilePath)
{
_httpContextBase.RewritePath(filePath, pathInfo, queryString, setClientFilePath);
}
public override void SetSessionStateBehavior(SessionStateBehavior sessionStateBehavior)
{
_httpContextBase.SetSessionStateBehavior(sessionStateBehavior);
}
public override Object GetService(Type serviceType)
{
return _httpContextBase.GetService(serviceType);
}
public override Exception[] AllErrors { get { return _httpContextBase.AllErrors; } }
public void SetAllErrors(Exception[] val)
{
}
public override Boolean AllowAsyncDuringSyncStages
{
set
{
_httpContextBase.AllowAsyncDuringSyncStages = value;
}
get
{
return _httpContextBase.AllowAsyncDuringSyncStages;
}
}
public override HttpApplicationStateBase Application { get { return _httpContextBase.Application; } }
public void SetApplication(HttpApplicationStateBase val)
{
}
public override HttpApplication ApplicationInstance
{
set
{
_httpContextBase.ApplicationInstance = value;
}
get
{
return _httpContextBase.ApplicationInstance;
}
}
public override AsyncPreloadModeFlags AsyncPreloadMode
{
set
{
_httpContextBase.AsyncPreloadMode = value;
}
get
{
return _httpContextBase.AsyncPreloadMode;
}
}
public override Cache Cache { get { return _httpContextBase.Cache; } }
public void SetCache(Cache val)
{
}
public override IHttpHandler CurrentHandler { get { return _httpContextBase.CurrentHandler; } }
public void SetCurrentHandler(IHttpHandler val)
{
}
public override RequestNotification CurrentNotification { get { return _httpContextBase.CurrentNotification; } }
public void SetCurrentNotification(RequestNotification val)
{
}
public override Exception Error { get { return _httpContextBase.Error; } }
public void SetError(Exception val)
{
}
public override IHttpHandler Handler
{
set
{
_httpContextBase.Handler = value;
}
get
{
return _httpContextBase.Handler;
}
}
public override Boolean IsCustomErrorEnabled { get { return _httpContextBase.IsCustomErrorEnabled; } }
public void SetIsCustomErrorEnabled(Boolean val)
{
}
public override Boolean IsDebuggingEnabled { get { return _httpContextBase.IsDebuggingEnabled; } }
public void SetIsDebuggingEnabled(Boolean val)
{
}
public override Boolean IsPostNotification { get { return _httpContextBase.IsPostNotification; } }
public void SetIsPostNotification(Boolean val)
{
}
public override Boolean IsWebSocketRequest { get { return _httpContextBase.IsWebSocketRequest; } }
public void SetIsWebSocketRequest(Boolean val)
{
}
public override Boolean IsWebSocketRequestUpgrading { get { return _httpContextBase.IsWebSocketRequestUpgrading; } }
public void SetIsWebSocketRequestUpgrading(Boolean val)
{
}
public override IDictionary Items { get { return _httpContextBase.Items; } }
public void SetItems(IDictionary val)
{
}
public override PageInstrumentationService PageInstrumentation { get { return _httpContextBase.PageInstrumentation; } }
public void SetPageInstrumentation(PageInstrumentationService val)
{
}
public override IHttpHandler PreviousHandler { get { return _httpContextBase.PreviousHandler; } }
public void SetPreviousHandler(IHttpHandler val)
{
}
public override ProfileBase Profile { get { return _httpContextBase.Profile; } }
public void SetProfile(ProfileBase val)
{
}
public override HttpRequestBase Request { get { return _httpContextBase.Request; } }
public void SetRequest(HttpRequestBase val)
{
}
public override HttpResponseBase Response { get { return _httpContextBase.Response; } }
public void SetResponse(HttpResponseBase val)
{
}
public override HttpServerUtilityBase Server { get { return _httpContextBase.Server; } }
public void SetServer(HttpServerUtilityBase val)
{
}
public override HttpSessionStateBase Session { get { return _httpContextBase.Session; } }
public void SetSession(HttpSessionStateBase val)
{
}
public override Boolean SkipAuthorization
{
set
{
_httpContextBase.SkipAuthorization = value;
}
get
{
return _httpContextBase.SkipAuthorization;
}
}
public override DateTime Timestamp { get { return _httpContextBase.Timestamp; } }
public void SetTimestamp(DateTime val)
{
}
public override Boolean ThreadAbortOnTimeout
{
set
{
_httpContextBase.ThreadAbortOnTimeout = value;
}
get
{
return _httpContextBase.ThreadAbortOnTimeout;
}
}
public override TraceContext Trace { get { return _httpContextBase.Trace; } }
public void SetTrace(TraceContext val)
{
}
public override IPrincipal User
{
set
{
_httpContextBase.User = value;
}
get
{
return _httpContextBase.User;
}
}
public override String WebSocketNegotiatedProtocol { get { return _httpContextBase.WebSocketNegotiatedProtocol; } }
public void SetWebSocketNegotiatedProtocol(String val)
{
}
public override IList<String> WebSocketRequestedProtocols { get { return _httpContextBase.WebSocketRequestedProtocols; } }
public void SetWebSocketRequestedProtocols(IList<String> val)
{
}
public void InitializeUnsettable()
{
_response = new FromBaseHttpResponse(_httpContextBase.Response);
_request = new FromBaseHttpRequest(_httpContextBase.Request);
_response.ContentEncoding = _request.ContentEncoding;
}
public Task InitializeWebSocket()
{
throw new NotImplementedException();
}
}
}
| |
/*
* 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 IndexReader = Lucene.Net.Index.IndexReader;
namespace Lucene.Net.Search
{
/// <summary>The abstract base class for queries.
/// <p>Instantiable subclasses are:
/// <ul>
/// <li> {@link TermQuery}
/// <li> {@link MultiTermQuery}
/// <li> {@link BooleanQuery}
/// <li> {@link WildcardQuery}
/// <li> {@link PhraseQuery}
/// <li> {@link PrefixQuery}
/// <li> {@link MultiPhraseQuery}
/// <li> {@link FuzzyQuery}
/// <li> {@link RangeQuery}
/// <li> {@link Lucene.Net.Search.Spans.SpanQuery}
/// </ul>
/// <p>A parser for queries is contained in:
/// <ul>
/// <li>{@link Lucene.Net.QueryParsers.QueryParser QueryParser}
/// </ul>
/// </summary>
[Serializable]
public abstract class Query : System.ICloneable
{
private float boost = 1.0f; // query boost factor
/// <summary>Sets the boost for this query clause to <code>b</code>. Documents
/// matching this clause will (in addition to the normal weightings) have
/// their score multiplied by <code>b</code>.
/// </summary>
public virtual void SetBoost(float b)
{
boost = b;
}
/// <summary>Gets the boost for this clause. Documents matching
/// this clause will (in addition to the normal weightings) have their score
/// multiplied by <code>b</code>. The boost is 1.0 by default.
/// </summary>
public virtual float GetBoost()
{
return boost;
}
/// <summary>Prints a query to a string, with <code>field</code> assumed to be the
/// default field and omitted.
/// <p>The representation used is one that is supposed to be readable
/// by {@link Lucene.Net.QueryParsers.QueryParser QueryParser}. However,
/// there are the following limitations:
/// <ul>
/// <li>If the query was created by the parser, the printed
/// representation may not be exactly what was parsed. For example,
/// characters that need to be escaped will be represented without
/// the required backslash.</li>
/// <li>Some of the more complicated queries (e.g. span queries)
/// don't have a representation that can be parsed by QueryParser.</li>
/// </ul>
/// </summary>
public abstract System.String ToString(System.String field);
/// <summary>Prints a query to a string. </summary>
public override System.String ToString()
{
return ToString("");
}
/// <summary>Expert: Constructs an appropriate Weight implementation for this query.
///
/// <p>Only implemented by primitive queries, which re-write to themselves.
/// </summary>
protected internal virtual Weight CreateWeight(Searcher searcher)
{
throw new System.NotSupportedException();
}
/// <summary>Expert: Constructs and initializes a Weight for a top-level query. </summary>
public virtual Weight Weight(Searcher searcher)
{
Query query = searcher.Rewrite(this);
Weight weight = query.CreateWeight(searcher);
float sum = weight.SumOfSquaredWeights();
float norm = GetSimilarity(searcher).QueryNorm(sum);
weight.Normalize(norm);
return weight;
}
/// <summary>Expert: called to re-write queries into primitive queries. For example,
/// a PrefixQuery will be rewritten into a BooleanQuery that consists
/// of TermQuerys.
/// </summary>
public virtual Query Rewrite(IndexReader reader)
{
return this;
}
/// <summary>Expert: called when re-writing queries under MultiSearcher.
///
/// Create a single query suitable for use by all subsearchers (in 1-1
/// correspondence with queries). This is an optimization of the OR of
/// all queries. We handle the common optimization cases of equal
/// queries and overlapping clauses of boolean OR queries (as generated
/// by MultiTermQuery.rewrite() and RangeQuery.rewrite()).
/// Be careful overriding this method as queries[0] determines which
/// method will be called and is not necessarily of the same type as
/// the other queries.
/// </summary>
public virtual Query Combine(Query[] queries)
{
System.Collections.Hashtable uniques = new System.Collections.Hashtable();
for (int i = 0; i < queries.Length; i++)
{
Query query = queries[i];
BooleanClause[] clauses = null;
// check if we can split the query into clauses
bool splittable = (query is BooleanQuery);
if (splittable)
{
BooleanQuery bq = (BooleanQuery) query;
splittable = bq.IsCoordDisabled();
clauses = bq.GetClauses();
for (int j = 0; splittable && j < clauses.Length; j++)
{
splittable = (clauses[j].GetOccur() == BooleanClause.Occur.SHOULD);
}
}
if (splittable)
{
for (int j = 0; j < clauses.Length; j++)
{
Query tmp = clauses[j].GetQuery();
if (uniques.Contains(tmp) == false)
{
uniques.Add(tmp, tmp);
}
}
}
else
{
if (uniques.Contains(query) == false)
{
uniques.Add(query, query);
}
}
}
// optimization: if we have just one query, just return it
if (uniques.Count == 1)
{
System.Collections.IDictionaryEnumerator iter = uniques.GetEnumerator();
iter.MoveNext();
return iter.Value as Query;
}
System.Collections.IDictionaryEnumerator it = uniques.GetEnumerator();
BooleanQuery result = new BooleanQuery(true);
while (it.MoveNext())
{
result.Add((Query) it.Value, BooleanClause.Occur.SHOULD);
}
return result;
}
/// <summary> Expert: adds all terms occuring in this query to the terms set. Only
/// works if this query is in its {@link #rewrite rewritten} form.
///
/// </summary>
/// <throws> UnsupportedOperationException if this query is not yet rewritten </throws>
public virtual void ExtractTerms(System.Collections.Hashtable terms)
{
// needs to be implemented by query subclasses
throw new System.NotSupportedException();
}
/// <summary>Expert: merges the clauses of a set of BooleanQuery's into a single
/// BooleanQuery.
///
/// <p>A utility for use by {@link #Combine(Query[])} implementations.
/// </summary>
public static Query MergeBooleanQueries(Query[] queries)
{
System.Collections.Hashtable allClauses = new System.Collections.Hashtable();
for (int i = 0; i < queries.Length; i++)
{
BooleanClause[] clauses = ((BooleanQuery) queries[i]).GetClauses();
for (int j = 0; j < clauses.Length; j++)
{
allClauses.Add(clauses[j], clauses[j]);
}
}
bool coordDisabled = queries.Length == 0 ? false : ((BooleanQuery) queries[0]).IsCoordDisabled();
BooleanQuery result = new BooleanQuery(coordDisabled);
foreach (BooleanClause booleanClause in allClauses.Keys)
{
result.Add(booleanClause);
}
return result;
}
/// <summary>Expert: Returns the Similarity implementation to be used for this query.
/// Subclasses may override this method to specify their own Similarity
/// implementation, perhaps one that delegates through that of the Searcher.
/// By default the Searcher's Similarity implementation is returned.
/// </summary>
public virtual Similarity GetSimilarity(Searcher searcher)
{
return searcher.GetSimilarity();
}
/// <summary>Returns a clone of this query. </summary>
public virtual object Clone()
{
try
{
return (Query) base.MemberwiseClone();
}
catch (System.Exception e)
{
throw new System.SystemException("Clone not supported: " + e.Message);
}
}
}
}
| |
//
// Copyright (C) 2010 Jackson Harper (jackson@manosdemono.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
namespace Manos.Routing
{
public class ParameterizedActionTarget : IManosTarget
{
private readonly ParameterInfo[] parameters;
private readonly object target;
private ParameterizedAction action;
public ParameterizedActionTarget(object target, MethodInfo method, ParameterizedAction action)
{
if (method == null)
throw new ArgumentNullException("method");
if (action == null)
throw new ArgumentNullException("action");
this.target = target;
Action = action;
parameters = method.GetParameters();
}
public Object Target
{
get { return target; }
}
#region IManosTarget Members
public Delegate Action
{
get { return action; }
set
{
if (value == null)
throw new ArgumentNullException("action");
var pa = value as ParameterizedAction;
if (pa == null)
throw new InvalidOperationException(
"ParameterizedActionTarget Action property can only be set to a ParameterizedAction.");
action = pa;
}
}
public void Invoke(ManosApp app, IManosContext ctx)
{
object[] data;
if (!TryGetDataForParamList(parameters, app, ctx, out data))
{
// TODO: More graceful way of handling this?
ctx.Transaction.Abort(400, "Can not convert parameters to match Action argument list.");
return;
}
action(target, data);
}
#endregion
private ParameterInfo[] GetParamList()
{
MethodInfo method = action.Method;
return method.GetParameters();
}
public static bool TryGetDataForParamList(ParameterInfo[] parameters, ManosApp app, IManosContext ctx,
out object[] data)
{
data = new object[parameters.Length];
int param_start = 1;
data[0] = ctx;
if (typeof (ManosApp).IsAssignableFrom(parameters[1].ParameterType))
{
data[1] = app;
++param_start;
}
for (int i = param_start; i < data.Length; i++)
{
string name = parameters[i].Name;
if (!TryConvertType(ctx, name, parameters[i], out data[i]))
return false;
}
return true;
}
public static bool TryConvertType(IManosContext ctx, string name, ParameterInfo param, out object data)
{
Type dest = param.ParameterType;
if (dest.IsArray)
{
IList<UnsafeString> list = ctx.Request.Data.GetList(name);
if (list != null)
{
Type element = dest.GetElementType();
IList arr = Array.CreateInstance(element, list.Count);
for (int i = 0; i < list.Count; i++)
{
object elem_data;
if (!TryConvertUnsafeString(ctx, element, param, list[i], out elem_data))
{
data = null;
return false;
}
arr[i] = elem_data;
}
data = arr;
return true;
}
}
if (dest.GetInterface("IDictionary") != null)
{
IDictionary<string, UnsafeString> dict = ctx.Request.Data.GetDict(name);
if (dict != null)
{
Type eltype = typeof (UnsafeString);
var dd = (IDictionary) Activator.CreateInstance(dest);
if (dest.IsGenericType)
{
Type[] args = dest.GetGenericArguments();
if (args.Length != 2)
throw new Exception("Generic Dictionaries must contain two generic type arguments.");
if (args[0] != typeof (string))
throw new Exception("Generic Dictionaries must use strings for their keys.");
eltype = args[1]; // ie the TValue in Dictionary<TKey,TValue>
}
foreach (string key in dict.Keys)
{
object elem_data;
if (!TryConvertUnsafeString(ctx, eltype, param, dict[key], out elem_data))
{
data = null;
return false;
}
dd.Add(key, elem_data);
}
data = dd;
return true;
}
}
UnsafeString strd = ctx.Request.Data.Get(name);
return TryConvertUnsafeString(ctx, dest, param, strd, out data);
}
public static bool TryConvertUnsafeString(IManosContext ctx, Type type, ParameterInfo param,
UnsafeString unsafe_str_value, out object data)
{
if (type == typeof (UnsafeString))
{
data = unsafe_str_value;
return true;
}
string str_value = unsafe_str_value == null ? null : unsafe_str_value.SafeValue;
if (TryConvertFormData(type, str_value, out data))
return true;
if (str_value == null && param.DefaultValue != DBNull.Value)
{
data = param.DefaultValue;
return true;
}
try
{
data = Convert.ChangeType(str_value, type);
}
catch
{
Console.Error.WriteLine("Error while converting '{0}' to '{1}'.", str_value, type);
data = null;
return false;
}
return true;
}
public static bool TryConvertFormData(Type type, string str_value, out object data)
{
var converter = new HtmlFormDataTypeConverter(type);
data = converter.ConvertFrom(str_value);
return data != null;
}
}
}
| |
using System;
using System.Collections;
using UnityEngine;
#if !UniRxLibrary
using ObservableUnity = UniRx.Observable;
#endif
namespace UniRx
{
#if !(UNITY_METRO || UNITY_WP8) && (UNITY_4_4 || UNITY_4_3 || UNITY_4_2 || UNITY_4_1 || UNITY_4_0_1 || UNITY_4_0 || UNITY_3_5 || UNITY_3_4 || UNITY_3_3 || UNITY_3_2 || UNITY_3_1 || UNITY_3_0_0 || UNITY_3_0 || UNITY_2_6_1 || UNITY_2_6)
// Fallback for Unity versions below 4.5
using Hash = System.Collections.Hashtable;
using HashEntry = System.Collections.DictionaryEntry;
#else
// Unity 4.5 release notes:
// WWW: deprecated 'WWW(string url, byte[] postData, Hashtable headers)',
// use 'public WWW(string url, byte[] postData, Dictionary<string, string> headers)' instead.
using Hash = System.Collections.Generic.Dictionary<string, string>;
using HashEntry = System.Collections.Generic.KeyValuePair<string, string>;
#endif
public static partial class ObservableWWW
{
public static IObservable<string> Get(string url, Hash headers = null, IProgress<float> progress = null)
{
return ObservableUnity.FromCoroutine<string>((observer, cancellation) => FetchText(new WWW(url, null, (headers ?? new Hash())), observer, progress, cancellation));
}
public static IObservable<byte[]> GetAndGetBytes(string url, Hash headers = null, IProgress<float> progress = null)
{
return ObservableUnity.FromCoroutine<byte[]>((observer, cancellation) => FetchBytes(new WWW(url, null, (headers ?? new Hash())), observer, progress, cancellation));
}
public static IObservable<WWW> GetWWW(string url, Hash headers = null, IProgress<float> progress = null)
{
return ObservableUnity.FromCoroutine<WWW>((observer, cancellation) => Fetch(new WWW(url, null, (headers ?? new Hash())), observer, progress, cancellation));
}
public static IObservable<string> Post(string url, byte[] postData, IProgress<float> progress = null)
{
return ObservableUnity.FromCoroutine<string>((observer, cancellation) => FetchText(new WWW(url, postData), observer, progress, cancellation));
}
public static IObservable<string> Post(string url, byte[] postData, Hash headers, IProgress<float> progress = null)
{
return ObservableUnity.FromCoroutine<string>((observer, cancellation) => FetchText(new WWW(url, postData, headers), observer, progress, cancellation));
}
public static IObservable<string> Post(string url, WWWForm content, IProgress<float> progress = null)
{
return ObservableUnity.FromCoroutine<string>((observer, cancellation) => FetchText(new WWW(url, content), observer, progress, cancellation));
}
public static IObservable<string> Post(string url, WWWForm content, Hash headers, IProgress<float> progress = null)
{
var contentHeaders = content.headers;
return ObservableUnity.FromCoroutine<string>((observer, cancellation) => FetchText(new WWW(url, content.data, MergeHash(contentHeaders, headers)), observer, progress, cancellation));
}
public static IObservable<byte[]> PostAndGetBytes(string url, byte[] postData, IProgress<float> progress = null)
{
return ObservableUnity.FromCoroutine<byte[]>((observer, cancellation) => FetchBytes(new WWW(url, postData), observer, progress, cancellation));
}
public static IObservable<byte[]> PostAndGetBytes(string url, byte[] postData, Hash headers, IProgress<float> progress = null)
{
return ObservableUnity.FromCoroutine<byte[]>((observer, cancellation) => FetchBytes(new WWW(url, postData, headers), observer, progress, cancellation));
}
public static IObservable<byte[]> PostAndGetBytes(string url, WWWForm content, IProgress<float> progress = null)
{
return ObservableUnity.FromCoroutine<byte[]>((observer, cancellation) => FetchBytes(new WWW(url, content), observer, progress, cancellation));
}
public static IObservable<byte[]> PostAndGetBytes(string url, WWWForm content, Hash headers, IProgress<float> progress = null)
{
var contentHeaders = content.headers;
return ObservableUnity.FromCoroutine<byte[]>((observer, cancellation) => FetchBytes(new WWW(url, content.data, MergeHash(contentHeaders, headers)), observer, progress, cancellation));
}
public static IObservable<WWW> PostWWW(string url, byte[] postData, IProgress<float> progress = null)
{
return ObservableUnity.FromCoroutine<WWW>((observer, cancellation) => Fetch(new WWW(url, postData), observer, progress, cancellation));
}
public static IObservable<WWW> PostWWW(string url, byte[] postData, Hash headers, IProgress<float> progress = null)
{
return ObservableUnity.FromCoroutine<WWW>((observer, cancellation) => Fetch(new WWW(url, postData, headers), observer, progress, cancellation));
}
public static IObservable<WWW> PostWWW(string url, WWWForm content, IProgress<float> progress = null)
{
return ObservableUnity.FromCoroutine<WWW>((observer, cancellation) => Fetch(new WWW(url, content), observer, progress, cancellation));
}
public static IObservable<WWW> PostWWW(string url, WWWForm content, Hash headers, IProgress<float> progress = null)
{
var contentHeaders = content.headers;
return ObservableUnity.FromCoroutine<WWW>((observer, cancellation) => Fetch(new WWW(url, content.data, MergeHash(contentHeaders, headers)), observer, progress, cancellation));
}
public static IObservable<AssetBundle> LoadFromCacheOrDownload(string url, int version, IProgress<float> progress = null)
{
return ObservableUnity.FromCoroutine<AssetBundle>((observer, cancellation) => FetchAssetBundle(WWW.LoadFromCacheOrDownload(url, version), observer, progress, cancellation));
}
public static IObservable<AssetBundle> LoadFromCacheOrDownload(string url, int version, uint crc, IProgress<float> progress = null)
{
return ObservableUnity.FromCoroutine<AssetBundle>((observer, cancellation) => FetchAssetBundle(WWW.LoadFromCacheOrDownload(url, version, crc), observer, progress, cancellation));
}
// over Unity5 supports Hash128
#if !(UNITY_4_7 || UNITY_4_6 || UNITY_4_5 || UNITY_4_4 || UNITY_4_3 || UNITY_4_2 || UNITY_4_1 || UNITY_4_0_1 || UNITY_4_0 || UNITY_3_5 || UNITY_3_4 || UNITY_3_3 || UNITY_3_2 || UNITY_3_1 || UNITY_3_0_0 || UNITY_3_0 || UNITY_2_6_1 || UNITY_2_6)
public static IObservable<AssetBundle> LoadFromCacheOrDownload(string url, Hash128 hash128, IProgress<float> progress = null)
{
return ObservableUnity.FromCoroutine<AssetBundle>((observer, cancellation) => FetchAssetBundle(WWW.LoadFromCacheOrDownload(url, hash128), observer, progress, cancellation));
}
public static IObservable<AssetBundle> LoadFromCacheOrDownload(string url, Hash128 hash128, uint crc, IProgress<float> progress = null)
{
return ObservableUnity.FromCoroutine<AssetBundle>((observer, cancellation) => FetchAssetBundle(WWW.LoadFromCacheOrDownload(url, hash128, crc), observer, progress, cancellation));
}
#endif
// over 4.5, Hash define is Dictionary.
// below Unity 4.5, WWW only supports Hashtable.
// Unity 4.5, 4.6 WWW supports Dictionary and [Obsolete]Hashtable but WWWForm.content is Hashtable.
// Unity 5.0 WWW only supports Dictionary and WWWForm.content is also Dictionary.
#if !(UNITY_METRO || UNITY_WP8) && (UNITY_4_5 || UNITY_4_6 || UNITY_4_7)
static Hash MergeHash(Hashtable wwwFormHeaders, Hash externalHeaders)
{
var newHeaders = new Hash();
foreach (DictionaryEntry item in wwwFormHeaders)
{
newHeaders[item.Key.ToString()] = item.Value.ToString();
}
foreach (HashEntry item in externalHeaders)
{
newHeaders[item.Key] = item.Value;
}
return newHeaders;
}
#else
static Hash MergeHash(Hash wwwFormHeaders, Hash externalHeaders)
{
foreach (HashEntry item in externalHeaders)
{
wwwFormHeaders[item.Key] = item.Value;
}
return wwwFormHeaders;
}
#endif
static IEnumerator Fetch(WWW www, IObserver<WWW> observer, IProgress<float> reportProgress, CancellationToken cancel)
{
using (www)
{
if (reportProgress != null)
{
while (!www.isDone && !cancel.IsCancellationRequested)
{
try
{
reportProgress.Report(www.progress);
}
catch (Exception ex)
{
observer.OnError(ex);
yield break;
}
yield return null;
}
}
else
{
if (!www.isDone)
{
yield return www;
}
}
if (cancel.IsCancellationRequested)
{
if (!www.isDone) yield return www; // workaround for freeze bug of dispose WWW when WWW is not completed
yield break;
}
if (reportProgress != null)
{
try
{
reportProgress.Report(www.progress);
}
catch (Exception ex)
{
observer.OnError(ex);
yield break;
}
}
if (!string.IsNullOrEmpty(www.error))
{
observer.OnError(new WWWErrorException(www, www.text));
}
else
{
observer.OnNext(www);
observer.OnCompleted();
}
}
}
static IEnumerator FetchText(WWW www, IObserver<string> observer, IProgress<float> reportProgress, CancellationToken cancel)
{
using (www)
{
if (reportProgress != null)
{
while (!www.isDone && !cancel.IsCancellationRequested)
{
try
{
reportProgress.Report(www.progress);
}
catch (Exception ex)
{
observer.OnError(ex);
yield break;
}
yield return null;
}
}
else
{
if (!www.isDone)
{
yield return www;
}
}
if (cancel.IsCancellationRequested)
{
if (!www.isDone) yield return www; // workaround for freeze bug of dispose WWW when WWW is not completed
yield break;
}
if (reportProgress != null)
{
try
{
reportProgress.Report(www.progress);
}
catch (Exception ex)
{
observer.OnError(ex);
yield break;
}
}
if (!string.IsNullOrEmpty(www.error))
{
observer.OnError(new WWWErrorException(www, www.text));
}
else
{
observer.OnNext(www.text);
observer.OnCompleted();
}
}
}
static IEnumerator FetchBytes(WWW www, IObserver<byte[]> observer, IProgress<float> reportProgress, CancellationToken cancel)
{
using (www)
{
if (reportProgress != null)
{
while (!www.isDone && !cancel.IsCancellationRequested)
{
try
{
reportProgress.Report(www.progress);
}
catch (Exception ex)
{
observer.OnError(ex);
yield break;
}
yield return null;
}
}
else
{
if (!www.isDone)
{
yield return www;
}
}
if (cancel.IsCancellationRequested)
{
if (!www.isDone) yield return www; // workaround for freeze bug of dispose WWW when WWW is not completed
yield break;
}
if (reportProgress != null)
{
try
{
reportProgress.Report(www.progress);
}
catch (Exception ex)
{
observer.OnError(ex);
yield break;
}
}
if (!string.IsNullOrEmpty(www.error))
{
observer.OnError(new WWWErrorException(www, www.text));
}
else
{
observer.OnNext(www.bytes);
observer.OnCompleted();
}
}
}
static IEnumerator FetchAssetBundle(WWW www, IObserver<AssetBundle> observer, IProgress<float> reportProgress, CancellationToken cancel)
{
using (www)
{
if (reportProgress != null)
{
while (!www.isDone && !cancel.IsCancellationRequested)
{
try
{
reportProgress.Report(www.progress);
}
catch (Exception ex)
{
observer.OnError(ex);
yield break;
}
yield return null;
}
}
else
{
if (!www.isDone)
{
yield return www;
}
}
if (cancel.IsCancellationRequested)
{
if (!www.isDone) yield return www; // workaround for freeze bug of dispose WWW when WWW is not completed
yield break;
}
if (reportProgress != null)
{
try
{
reportProgress.Report(www.progress);
}
catch (Exception ex)
{
observer.OnError(ex);
yield break;
}
}
if (!string.IsNullOrEmpty(www.error))
{
observer.OnError(new WWWErrorException(www, ""));
}
else
{
observer.OnNext(www.assetBundle);
observer.OnCompleted();
}
}
}
}
public class WWWErrorException : Exception
{
public string RawErrorMessage { get; private set; }
public bool HasResponse { get; private set; }
public string Text { get; private set; }
public System.Net.HttpStatusCode StatusCode { get; private set; }
public System.Collections.Generic.Dictionary<string, string> ResponseHeaders { get; private set; }
public WWW WWW { get; private set; }
// cache the text because if www was disposed, can't access it.
public WWWErrorException(WWW www, string text)
{
this.WWW = www;
this.RawErrorMessage = www.error;
this.ResponseHeaders = www.responseHeaders;
this.HasResponse = false;
this.Text = text;
var splitted = RawErrorMessage.Split(' ', ':');
if (splitted.Length != 0)
{
int statusCode;
if (int.TryParse(splitted[0], out statusCode))
{
this.HasResponse = true;
this.StatusCode = (System.Net.HttpStatusCode)statusCode;
}
}
}
public override string ToString()
{
var text = this.Text;
if (string.IsNullOrEmpty(text))
{
return RawErrorMessage;
}
else
{
return RawErrorMessage + " " + text;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.Storage;
using System.IO;
using Microsoft.WindowsAzure.Storage.Queue;
using System.Xml.Serialization;
using Microsoft.ServiceBus;
using System.ServiceModel;
using Contoso.Provisioning.Hybrid.Core.SiteTemplates;
using OfficeDevPnP.Core.Utilities;
using Contoso.Provisioning.Hybrid.Contract;
using Contoso.Provisioning.Hybrid;
namespace Contoso.Provisioning.Hybrid.Worker
{
// Use (Get-MsolCompanyInformation).ObjectID to obtain Target/Tenant realm: <guid>
// Manually register an app via the appregnew.aspx page and generate an App ID and App Secret. The App title and App domain can be a simple string like "MyApp"
// Update the AppID in your worker role settings
// Add the AppSecret in your worker role settings. Note that this sample project requires to store the encrypted value of the AppSecret. Use the Contoso.Azure.CloudServices.Encryptor project
// to encrypt the AppId
//
// Manually set the permission XML for you app via the appinv.aspx page:
// 1/ Lookup your app via it's AppID
// 2/ Paste the permission XML and click on create
//
// Sample permission XML:
// <AppPermissionRequests AllowAppOnlyPolicy="true">
// <AppPermissionRequest Scope="http://sharepoint/content/tenant" Right="FullControl" />
// </AppPermissionRequests>
//
// As you're granting tenant wide full control to an app the appsecret is as important as the password from your SharePoint administration account!
//
public class WorkerRole : RoleEntryPoint
{
private const string queueName = "sharepointprovisioning";
private const string azureConnectionSettingKey = "Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString";
private CloudQueue queue;
private static object gate = new Object();
public override void Run()
{
// This is a sample worker implementation. Replace with your logic.
Trace.TraceInformation("Contoso.Azure.CloudServices.Provisioning.Worker entry point called", "Information");
while (true)
{
// retrieve a new message from the queue
CloudQueueMessage msg = queue.GetMessage();
// There's a message in the queue, let's process it
if (msg != null)
{
//Trace.TraceInformation(string.Format("received message {0}", msg.AsString));
if (ProcessMessage(msg.AsString))
{
// Remove the message from the queue after successfull processing
queue.DeleteMessage(msg);
}
}
else
{
// Pause for 1 second before we check the queue again
System.Threading.Thread.Sleep(1000);
}
}
}
private bool ProcessMessage(string message)
{
bool processed = true;
SharePointProvisioningData sharePointProvisioningData = DeserializeData(message);
if (sharePointProvisioningData.DataClassification.Equals("HBI", StringComparison.InvariantCultureIgnoreCase))
{
try
{
// Determine the system connectivity mode based on the command line
// arguments: -http, -tcp or -auto (defaults to auto)
ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.AutoDetect;
string serviceNamespace = RoleEnvironment.GetConfigurationSettingValue("General.SBServiceNameSpace");
string issuerName = RoleEnvironment.GetConfigurationSettingValue("General.SBIssuerName");
string issuerSecret = EncryptionUtility.Decrypt(RoleEnvironment.GetConfigurationSettingValue("General.SBIssuerSecret"), RoleEnvironment.GetConfigurationSettingValue("General.EncryptionThumbPrint"));
// create the service URI based on the service namespace
Uri serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, "SharePointProvisioning");
// create the credentials object for the endpoint
TransportClientEndpointBehavior sharedSecretServiceBusCredential = new TransportClientEndpointBehavior();
sharedSecretServiceBusCredential.TokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerSecret);
// create the channel factory loading the configuration
ChannelFactory<ISharePointProvisioningChannel> channelFactory = new ChannelFactory<ISharePointProvisioningChannel>("RelayEndpoint", new EndpointAddress(serviceUri));
// apply the Service Bus credentials
channelFactory.Endpoint.Behaviors.Add(sharedSecretServiceBusCredential);
// create and open the client channel
ISharePointProvisioningChannel channel = channelFactory.CreateChannel();
channel.Open();
channel.ProvisionSiteCollection(sharePointProvisioningData);
channel.Close();
channelFactory.Close();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
//log error
}
}
else
{
try
{
SiteProvisioningBase siteToProvision = null;
switch (sharePointProvisioningData.Template)
{
case SiteProvisioningTypes.ContosoCollaboration:
siteToProvision = new ContosoCollaboration();
break;
case SiteProvisioningTypes.ContosoProject:
siteToProvision = new ContosoProject();
break;
}
siteToProvision.SharePointProvisioningData = sharePointProvisioningData;
HookupAuthentication(siteToProvision);
// Provision the site collection
processed = siteToProvision.Execute();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
//log error
}
}
// always return true to get the item of the queue...no retry mechanism foreseen
return true;
}
private void HookupAuthentication(SiteProvisioningBase siteProvisioningInstance)
{
siteProvisioningInstance.Realm = RoleEnvironment.GetConfigurationSettingValue("Realm");
siteProvisioningInstance.AppId = RoleEnvironment.GetConfigurationSettingValue("AppId");
siteProvisioningInstance.AppSecret = EncryptionUtility.Decrypt(RoleEnvironment.GetConfigurationSettingValue("AppSecret"), RoleEnvironment.GetConfigurationSettingValue("General.EncryptionThumbPrint"));
siteProvisioningInstance.InstantiateAppOnlyClientContext(RoleEnvironment.GetConfigurationSettingValue("TenantAdminUrl"));
siteProvisioningInstance.InstantiateSiteDirectorySiteClientContext(RoleEnvironment.GetConfigurationSettingValue("General.SiteDirectoryUrl"));
}
public override bool OnStart()
{
// Set the maximum number of concurrent connections
ServicePointManager.DefaultConnectionLimit = 12;
// For information on handling configuration changes
// see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue(azureConnectionSettingKey));
// initialize queue storage
CloudQueueClient queueStorage = cloudStorageAccount.CreateCloudQueueClient();
queue = queueStorage.GetQueueReference(queueName);
bool storageInitialized = false;
while (!storageInitialized)
{
// create the message queue(s)
queue.CreateIfNotExists();
storageInitialized = true;
}
return base.OnStart();
}
/// <summary>
/// Deserializes the retrieved XML message
/// </summary>
/// <param name="sharePointProvisioningData">XML representation as string</param>
/// <returns>SharePointProvisioningData object</returns>
private static SharePointProvisioningData DeserializeData(string sharePointProvisioningData)
{
SharePointProvisioningData deserializedSharePointProvisioningaData = null;
using (Stream stream = new MemoryStream())
{
StreamWriter writer = new StreamWriter(stream);
writer.Write(sharePointProvisioningData);
writer.Flush();
stream.Position = 0;
object result = new XmlSerializer(typeof(SharePointProvisioningData)).Deserialize(stream);
deserializedSharePointProvisioningaData = (SharePointProvisioningData)result;
}
return deserializedSharePointProvisioningaData;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using L10NSharp;
using SIL.Reporting;
using SIL.Windows.Forms.Extensions;
namespace SIL.Windows.Forms.ImageToolbox.ImageGallery
{
public partial class ImageGalleryControl : UserControl, IImageToolboxControl
{
private ImageCollectionManager _imageCollectionManager;
private PalasoImage _previousImage;
public bool InSomeoneElesesDesignMode;
public ImageGalleryControl()
{
InitializeComponent();
_thumbnailViewer.CaptionMethod = ((s) => string.Empty);//don't show a caption
_thumbnailViewer.LoadComplete += ThumbnailViewerOnLoadComplete;
_searchResultStats.Text = "";
if (Environment.OSVersion.Platform == PlatformID.Unix)
{
// For Linux, we can install the package if requested.
_downloadInstallerLink.Text = "Install the Art Of Reading package (this may be very slow)".Localize("ImageToolbox.InstallArtOfReading");
_downloadInstallerLink.URL = null;
_downloadInstallerLink.LinkClicked += InstallLinkClicked;
}
else
{
// Ensure that we can get localized text here.
_downloadInstallerLink.Text = "Download Art Of Reading Installer".Localize("ImageToolbox.DownloadArtOfReading");
}
_labelSearch.Text = "Image Galleries".Localize("ImageToolbox.ImageGalleries");
SearchLanguage = "en"; // until/unless the owner specifies otherwise explicitly
// Get rid of any trace of a border on the toolstrip.
toolStrip1.Renderer = new NoBorderToolStripRenderer();
// For some reason, setting these BackColor values in InitializeComponent() doesn't work.
// The BackColor gets set back to the standard control background color somewhere...
_downloadInstallerLink.BackColor = Color.White;
_messageLabel.BackColor = Color.White;
_messageLabel.SizeChanged += MessageLabelSizeChanged;
}
public void Dispose()
{
_thumbnailViewer.Closing(); //this guy was working away in the background
_messageLabel.SizeChanged -= MessageLabelSizeChanged;
}
/// <summary>
/// use if the calling app already has some notion of what the user might be looking for (e.g. the definition in a dictionary program)
/// </summary>
/// <param name="searchTerm"></param>
public void SetIntialSearchTerm(string searchTerm)
{
_searchTermsBox.Text = searchTerm;
}
/// <summary>
/// Gets or sets the language used in searching for an image by words.
/// </summary>
public string SearchLanguage { get; set; }
void _thumbnailViewer_SelectedIndexChanged(object sender, EventArgs e)
{
if(ImageChanged!=null && _thumbnailViewer.HasSelection)
{
ImageChanged.Invoke(this, null);
}
}
private void _thumbnailViewer_DoubleClick(object sender, EventArgs e)
{
if (ImageChangedAndAccepted != null && _thumbnailViewer.HasSelection)
{
ImageChangedAndAccepted.Invoke(this, null);
}
}
private void _searchButton_Click(object sender, EventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
_searchButton.Enabled = false;
try
{
_thumbnailViewer.Clear();
if (!string.IsNullOrWhiteSpace(_searchTermsBox.Text))
{
bool foundExactMatches;
// (avoid enumerating the returned IEnumerable<object> more than once by copying to a List.)
var results = _imageCollectionManager.GetMatchingImages(_searchTermsBox.Text, true, out foundExactMatches).ToList();
if (results.Any())
{
_messageLabel.Visible = false;
_downloadInstallerLink.Visible = false;
_thumbnailViewer.LoadItems(results);
var fmt = "Found {0} images".Localize("ImageToolbox.MatchingImages", "The {0} will be replaced by the number of matching images");
if (!foundExactMatches)
fmt = "Found {0} images with names close to {1}".Localize("ImageToolbox.AlmostMatchingImages", "The {0} will be replaced by the number of images found. The {1} will be replaced with the search string.");
_searchResultStats.Text = string.Format(fmt, results.Count, _searchTermsBox.Text);
}
else
{
_messageLabel.Visible = true;
if (!_searchLanguageMenu.Visible)
_downloadInstallerLink.Visible = true;
_searchResultStats.Text = "Found no matching images".Localize("ImageToolbox.NoMatchingImages");
}
}
}
catch (Exception)
{
}
_searchButton.Enabled = true;
//_okButton.Enabled = false;
}
private void ThumbnailViewerOnLoadComplete(object sender, EventArgs eventArgs)
{
Cursor.Current = Cursors.Default;
}
public string ChosenPath { get { return _thumbnailViewer.SelectedPath; } }
public bool HaveImageCollectionOnThisComputer
{
get { return _imageCollectionManager != null; }
}
private void OnFormClosing(object sender, FormClosingEventArgs e)
{
_thumbnailViewer.Closing();
}
public void SetImage(PalasoImage image)
{
_previousImage = image;
if(ImageChanged!=null)
ImageChanged.Invoke(this,null);
}
public PalasoImage GetImage()
{
if(ChosenPath!=null && File.Exists(ChosenPath))
{
try
{
return PalasoImage.FromFile(ChosenPath);
}
catch (Exception error)
{
ErrorReport.ReportNonFatalExceptionWithMessage(error, "There was a problem choosing that image.");
return _previousImage;
}
}
return _previousImage;
}
public event EventHandler ImageChanged;
/// <summary>
/// happens when you double click an item
/// </summary>
public event EventHandler ImageChangedAndAccepted;
private void _searchTermsBox_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode ==Keys.Enter)
{
e.SuppressKeyPress = true;
_searchButton_Click(sender, null);
}
else
{
_searchResultStats.Text = "";
}
}
private new bool DesignMode
{
get
{
return (base.DesignMode || GetService(typeof(IDesignerHost)) != null) ||
(LicenseManager.UsageMode == LicenseUsageMode.Designtime);
}
}
private void ArtOfReadingChooser_Load(object sender, EventArgs e)
{
if (DesignMode)
return;
_imageCollectionManager = ImageCollectionManager.FromStandardLocations(SearchLanguage);
_collectionToolStrip.Visible = false;
if (_imageCollectionManager == null)
{
_messageLabel.Visible = true;
_messageLabel.Text = "This computer doesn't appear to have any galleries installed yet.".Localize("ImageToolbox.NoGalleries");
_downloadInstallerLink.Visible = true;
_searchTermsBox.Enabled = false;
_searchButton.Enabled = false;
}
else
{
#if DEBUG
// _searchTermsBox.Text = @"flower";
#endif
SetupSearchLanguageChoice();
_messageLabel.Visible = string.IsNullOrEmpty(_searchTermsBox.Text);
// Adjust size to avoid text truncation
_messageLabel.Height = 200;
SetMessageLabelText();
_thumbnailViewer.SelectedIndexChanged += new EventHandler(_thumbnailViewer_SelectedIndexChanged);
if (_imageCollectionManager.Collections.Count() > 1)
{
_collectionToolStrip.Visible = true;
_collectionDropDown.Visible = true;
_collectionDropDown.Text =
"Galleries".Localize("ImageToolbox.Galleries");
if(ImageToolboxSettings.Default.DisabledImageCollections == null)
{
ImageToolboxSettings.Default.DisabledImageCollections = new StringCollection();
}
foreach (var collection in _imageCollectionManager.Collections)
{
if(ImageToolboxSettings.Default.DisabledImageCollections.Contains(collection.FolderPath))
{
collection.Enabled = false;
}
var text = Path.GetFileNameWithoutExtension(collection.Name);
var item = new ToolStripMenuItem(text);
_collectionDropDown.DropDownItems.Add(item);
item.CheckOnClick = true;
item.CheckState = collection.Enabled ? CheckState.Checked : CheckState.Unchecked;
item.CheckedChanged += (o, args) =>
{
if(_collectionDropDown.DropDownItems.Cast<ToolStripMenuItem>().Count(x => x.Checked) == 0)
item.Checked = true; // tried to uncheck the last one, don't allow it.
else
{
collection.Enabled = item.Checked;
var disabledSettings = ImageToolboxSettings.Default.DisabledImageCollections;
if (disabledSettings == null)
ImageToolboxSettings.Default.DisabledImageCollections = disabledSettings = new StringCollection();
if (item.Checked && disabledSettings.Contains(collection.FolderPath))
disabledSettings.Remove(collection.FolderPath);
if (!item.Checked && !disabledSettings.Contains(collection.FolderPath))
disabledSettings.Add(collection.FolderPath);
ImageToolboxSettings.Default.Save();
}
};
}
}
else
{
// otherwise, just leave them all enabled
}
}
_messageLabel.Font = new Font(SystemFonts.DialogFont.FontFamily, 10);
#if DEBUG
//if (!HaveImageCollectionOnThisComputer)
// return;
//when just testing, I just want to see some choices.
// _searchTermsBox.Text = @"flower";
//_searchButton_Click(this,null);
#endif
}
private void SetMessageLabelText()
{
var msg = "In the box above, type what you are searching for, then press ENTER.".Localize("ImageToolbox.EnterSearchTerms");
// Allow for the old index that contained English and Indonesian together.
var searchLang = "English + Indonesian";
// If we have the new multilingual index, _searchLanguageMenu will be visible. Its tooltip
// contains both the native name of the current search language + its English name in
// parentheses if its in a nonRoman script or otherwise thought to be unguessable by a
// literate speaker of an European language. (The menu displays only the native name, and
// SearchLanguage stores only the ISO code.)
if (_searchLanguageMenu.Visible)
searchLang = _searchLanguageMenu.ToolTipText;
msg += Environment.NewLine + Environment.NewLine +
String.Format("The search box is currently set to {0}".Localize("ImageToolbox.SearchLanguage"), searchLang);
if (PlatformUtilities.Platform.IsWindows && !_searchLanguageMenu.Visible)
{
msg += Environment.NewLine + Environment.NewLine +
"Did you know that there is a new version of this collection which lets you search in Arabic, Bengali, Chinese, English, French, Indonesian, Hindi, Portuguese, Spanish, Thai, or Swahili? It is free and available for downloading."
.Localize("ImageToolbox.NewMultilingual");
_downloadInstallerLink.Visible = true;
_downloadInstallerLink.BackColor = Color.White;
}
// Restore alignment (from center) for messages. (See https://silbloom.myjetbrains.com/youtrack/issue/BL-2753.)
_messageLabel.TextAlign = _messageLabel.RightToLeft==RightToLeft.Yes ? HorizontalAlignment.Right : HorizontalAlignment.Left;
_messageLabel.Text = msg;
}
/// <summary>
/// Position the download link label properly whenever the size of the main message label changes,
/// whether due to changing its text or changing the overall dialog box size. (BL-2853)
/// </summary>
private void MessageLabelSizeChanged(object sender, EventArgs eventArgs)
{
if (_searchLanguageMenu.Visible || !PlatformUtilities.Platform.IsWindows || !_downloadInstallerLink.Visible)
return;
_downloadInstallerLink.Width = _messageLabel.Width; // not sure why this isn't automatic
if (_downloadInstallerLink.Location.Y != _messageLabel.Bottom + 5)
_downloadInstallerLink.Location = new Point(_downloadInstallerLink.Left, _messageLabel.Bottom + 5);
}
protected class LanguageChoice
{
static readonly List<string> idsOfRecognizableLanguages = new List<string> { "en", "fr", "es", "it", "tpi", "pt", "id" };
private readonly CultureInfo _info;
public LanguageChoice(CultureInfo ci)
{
_info = ci;
}
public string Id { get { return _info.Name == "zh-Hans" ? "zh" : _info.Name; } }
public string NativeName
{
get
{
if (_info.Name == "id" && _info.NativeName == "Indonesia")
return "Bahasa Indonesia"; // This is a known problem in Windows/.Net.
return _info.NativeName;
}
}
public override string ToString()
{
if (_info.NativeName == _info.EnglishName)
return NativeName; // English (English) looks rather silly...
if (idsOfRecognizableLanguages.Contains(Id))
return NativeName;
return String.Format("{0} ({1})", _info.NativeName, _info.EnglishName);
}
}
private void SetupSearchLanguageChoice()
{
var indexLangs = _imageCollectionManager.IndexLanguageIds;
if (indexLangs == null)
{
_searchLanguageMenu.Visible = false;
}
else
{
_searchLanguageMenu.Visible = true;
foreach (var id in indexLangs)
{
var ci = id == "zh" ? new CultureInfo("zh-Hans") : new CultureInfo(id);
var choice = new LanguageChoice(ci);
var item = _searchLanguageMenu.DropDownItems.Add(choice.ToString());
item.Tag = choice;
item.Click += SearchLanguageClick;
if (id == SearchLanguage)
{
_searchLanguageMenu.Text = choice.NativeName;
_searchLanguageMenu.ToolTipText = choice.ToString();
}
}
}
// The Mono renderer makes the toolstrip stick out. (This is a Mono bug that
// may not be worth spending time on.) Let's not poke the user in the eye
// with an empty toolstrip.
if (Environment.OSVersion.Platform == PlatformID.Unix)
toolStrip1.Visible = _searchLanguageMenu.Visible;
}
void SearchLanguageClick(object sender, EventArgs e)
{
var item = sender as ToolStripItem;
if (item != null)
{
var lang = item.Tag as LanguageChoice;
if (lang != null && SearchLanguage != lang.Id)
{
_searchLanguageMenu.Text = lang.NativeName;
_searchLanguageMenu.ToolTipText = lang.ToString();
SearchLanguage = lang.Id;
_imageCollectionManager.ChangeSearchLanguageAndReloadIndex(lang.Id);
SetMessageLabelText(); // Update with new language name.
}
}
}
/// <summary>
/// To actually focus on the search box, the Mono runtime library appears to
/// first need us to focus the search button, wait a bit, and then focus the
/// search box. Bizarre, unfortunate, but true. (One of those bugs that we
/// couldn't write code to do if we tried!)
/// See https://jira.sil.org/browse/BL-964.
/// </summary>
internal void FocusSearchBox()
{
_searchButton.GotFocus += _searchButtonGotSetupFocus;
_searchButton.Select();
}
private System.Windows.Forms.Timer _focusTimer1;
private void _searchButtonGotSetupFocus(object sender, EventArgs e)
{
_searchButton.GotFocus -= _searchButtonGotSetupFocus;
_focusTimer1 = new System.Windows.Forms.Timer(this.components);
_focusTimer1.Tick += new System.EventHandler(this._focusTimer1_Tick);
_focusTimer1.Interval = 100;
_focusTimer1.Enabled = true;
}
private void _focusTimer1_Tick(object sender, EventArgs e)
{
_focusTimer1.Enabled = false;
_focusTimer1.Dispose();
_focusTimer1 = null;
_searchTermsBox.TextBox.Focus();
}
/// <summary>
/// Try to install the artofreading package if possible. Use a GUI program if
/// possible, but if not, try the command-line program with a GUI password
/// dialog.
/// </summary>
/// <remarks>
/// On Windows, the link label opens a web page to let the user download the
/// installer. This is the analogous behavior for Linux, but is potentially
/// so slow (300MB download) that we fire off the program without waiting for
/// it to finish.
/// </remarks>
private void InstallLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
if (Environment.OSVersion.Platform != PlatformID.Unix)
return;
// Install the artofreading package if at all possible.
if (File.Exists("/usr/bin/software-center"))
{
using (var process = new Process())
{
process.StartInfo = new ProcessStartInfo {
FileName = "/usr/bin/python",
Arguments = "/usr/bin/software-center art-of-reading",
UseShellExecute = false,
RedirectStandardOutput = false,
CreateNoWindow = false
};
process.Start();
}
}
else if (File.Exists("/usr/bin/ssh-askpass"))
{
using (var process = new Process())
{
process.StartInfo = new ProcessStartInfo {
FileName = "/usr/bin/sudo",
Arguments = "-A /usr/bin/apt-get -y install art-of-reading",
UseShellExecute = false,
RedirectStandardOutput = false,
CreateNoWindow = false
};
process.StartInfo.EnvironmentVariables.Add("SUDO_ASKPASS", "/usr/bin/ssh-askpass");
process.Start();
}
}
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security;
using System.Threading;
using AppLimit.CloudComputing.SharpBox;
using AppLimit.CloudComputing.SharpBox.Exceptions;
using ASC.Common.Data.Sql.Expressions;
using ASC.Core;
using ASC.Files.Core;
using ASC.Web.Files.Resources;
using ASC.Web.Studio.Core;
namespace ASC.Files.Thirdparty.Sharpbox
{
internal class SharpBoxFolderDao : SharpBoxDaoBase, IFolderDao
{
public SharpBoxFolderDao(SharpBoxDaoSelector.SharpBoxInfo sharpBoxInfo, SharpBoxDaoSelector sharpBoxDaoSelector)
: base(sharpBoxInfo, sharpBoxDaoSelector)
{
}
public Folder GetFolder(object folderId)
{
return ToFolder(GetFolderById(folderId));
}
public Folder GetFolder(string title, object parentId)
{
var parentFolder = SharpBoxProviderInfo.Storage.GetFolder(MakePath(parentId));
return ToFolder(parentFolder.OfType<ICloudDirectoryEntry>().FirstOrDefault(x => x.Name.Equals(title, StringComparison.OrdinalIgnoreCase)));
}
public Folder GetRootFolder(object folderId)
{
return ToFolder(RootFolder());
}
public Folder GetRootFolderByFile(object fileId)
{
return ToFolder(RootFolder());
}
public List<Folder> GetFolders(object parentId)
{
var parentFolder = SharpBoxProviderInfo.Storage.GetFolder(MakePath(parentId));
return parentFolder.OfType<ICloudDirectoryEntry>().Select(ToFolder).ToList();
}
public List<Folder> GetFolders(object parentId, OrderBy orderBy, FilterType filterType, bool subjectGroup, Guid subjectID, string searchText, bool withSubfolders = false)
{
if (filterType == FilterType.FilesOnly || filterType == FilterType.ByExtension
|| filterType == FilterType.DocumentsOnly || filterType == FilterType.ImagesOnly
|| filterType == FilterType.PresentationsOnly || filterType == FilterType.SpreadsheetsOnly
|| filterType == FilterType.ArchiveOnly || filterType == FilterType.MediaOnly)
return new List<Folder>();
var folders = GetFolders(parentId).AsEnumerable(); //TODO:!!!
//Filter
if (subjectID != Guid.Empty)
{
folders = folders.Where(x => subjectGroup
? CoreContext.UserManager.IsUserInGroup(x.CreateBy, subjectID)
: x.CreateBy == subjectID);
}
if (!string.IsNullOrEmpty(searchText))
folders = folders.Where(x => x.Title.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) != -1);
if (orderBy == null) orderBy = new OrderBy(SortedByType.DateAndTime, false);
switch (orderBy.SortedBy)
{
case SortedByType.Author:
folders = orderBy.IsAsc ? folders.OrderBy(x => x.CreateBy) : folders.OrderByDescending(x => x.CreateBy);
break;
case SortedByType.AZ:
folders = orderBy.IsAsc ? folders.OrderBy(x => x.Title) : folders.OrderByDescending(x => x.Title);
break;
case SortedByType.DateAndTime:
folders = orderBy.IsAsc ? folders.OrderBy(x => x.ModifiedOn) : folders.OrderByDescending(x => x.ModifiedOn);
break;
case SortedByType.DateAndTimeCreation:
folders = orderBy.IsAsc ? folders.OrderBy(x => x.CreateOn) : folders.OrderByDescending(x => x.CreateOn);
break;
default:
folders = orderBy.IsAsc ? folders.OrderBy(x => x.Title) : folders.OrderByDescending(x => x.Title);
break;
}
return folders.ToList();
}
public List<Folder> GetFolders(IEnumerable<object> folderIds, FilterType filterType = FilterType.None, bool subjectGroup = false, Guid? subjectID = null, string searchText = "", bool searchSubfolders = false, bool checkShare = true)
{
if (filterType == FilterType.FilesOnly || filterType == FilterType.ByExtension
|| filterType == FilterType.DocumentsOnly || filterType == FilterType.ImagesOnly
|| filterType == FilterType.PresentationsOnly || filterType == FilterType.SpreadsheetsOnly
|| filterType == FilterType.ArchiveOnly || filterType == FilterType.MediaOnly)
return new List<Folder>();
var folders = folderIds.Select(GetFolder);
if (subjectID.HasValue && subjectID != Guid.Empty)
{
folders = folders.Where(x => subjectGroup
? CoreContext.UserManager.IsUserInGroup(x.CreateBy, subjectID.Value)
: x.CreateBy == subjectID);
}
if (!string.IsNullOrEmpty(searchText))
folders = folders.Where(x => x.Title.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) != -1);
return folders.ToList();
}
public List<Folder> GetParentFolders(object folderId)
{
var path = new List<Folder>();
var folder = GetFolderById(folderId);
if (folder != null)
{
do
{
path.Add(ToFolder(folder));
} while ((folder = folder.Parent) != null);
}
path.Reverse();
return path;
}
public object SaveFolder(Folder folder)
{
try
{
if (folder.ID != null)
{
//Create with id
var savedfolder = SharpBoxProviderInfo.Storage.CreateFolder(MakePath(folder.ID));
return MakeId(savedfolder);
}
if (folder.ParentFolderID != null)
{
var parentFolder = GetFolderById(folder.ParentFolderID);
folder.Title = GetAvailableTitle(folder.Title, parentFolder, IsExist);
var newFolder = SharpBoxProviderInfo.Storage.CreateFolder(folder.Title, parentFolder);
return MakeId(newFolder);
}
}
catch (SharpBoxException e)
{
var webException = (WebException)e.InnerException;
if (webException != null)
{
var response = ((HttpWebResponse)webException.Response);
if (response != null)
{
if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden)
{
throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_Create);
}
}
throw;
}
}
return null;
}
public void DeleteFolder(object folderId)
{
var folder = GetFolderById(folderId);
var id = MakeId(folder);
using (var db = GetDb())
using (var tx = db.BeginTransaction())
{
var hashIDs = db.ExecuteList(Query("files_thirdparty_id_mapping")
.Select("hash_id")
.Where(Exp.Like("id", id, SqlLike.StartWith)))
.ConvertAll(x => x[0]);
db.ExecuteNonQuery(Delete("files_tag_link").Where(Exp.In("entry_id", hashIDs)));
db.ExecuteNonQuery(Delete("files_security").Where(Exp.In("entry_id", hashIDs)));
db.ExecuteNonQuery(Delete("files_thirdparty_id_mapping").Where(Exp.In("hash_id", hashIDs)));
var tagsToRemove = db.ExecuteList(
Query("files_tag tbl_ft ")
.Select("tbl_ft.id")
.LeftOuterJoin("files_tag_link tbl_ftl", Exp.EqColumns("tbl_ft.tenant_id", "tbl_ftl.tenant_id") &
Exp.EqColumns("tbl_ft.id", "tbl_ftl.tag_id"))
.Where("tbl_ftl.tag_id is null"))
.ConvertAll(r => Convert.ToInt32(r[0]));
db.ExecuteNonQuery(Delete("files_tag").Where(Exp.In("id", tagsToRemove)));
tx.Commit();
}
if (!(folder is ErrorEntry))
SharpBoxProviderInfo.Storage.DeleteFileSystemEntry(folder);
}
public bool IsExist(string title, ICloudDirectoryEntry folder)
{
try
{
return SharpBoxProviderInfo.Storage.GetFileSystemObject(title, folder) != null;
}
catch (ArgumentException)
{
throw;
}
catch (Exception)
{
}
return false;
}
public object MoveFolder(object folderId, object toFolderId, CancellationToken? cancellationToken)
{
var entry = GetFolderById(folderId);
var folder = GetFolderById(toFolderId);
var oldFolderId = MakeId(entry);
if (!SharpBoxProviderInfo.Storage.MoveFileSystemEntry(entry, folder))
throw new Exception("Error while moving");
var newFolderId = MakeId(entry);
UpdatePathInDB(oldFolderId, newFolderId);
return newFolderId;
}
public Folder CopyFolder(object folderId, object toFolderId, CancellationToken? cancellationToken)
{
var folder = GetFolderById(folderId);
if (!SharpBoxProviderInfo.Storage.CopyFileSystemEntry(MakePath(folderId), MakePath(toFolderId)))
throw new Exception("Error while copying");
return ToFolder(GetFolderById(toFolderId).OfType<ICloudDirectoryEntry>().FirstOrDefault(x => x.Name == folder.Name));
}
public IDictionary<object, string> CanMoveOrCopy(object[] folderIds, object to)
{
return new Dictionary<object, string>();
}
public object RenameFolder(Folder folder, string newTitle)
{
var entry = GetFolderById(folder.ID);
var oldId = MakeId(entry);
var newId = oldId;
if ("/".Equals(MakePath(folder.ID)))
{
//It's root folder
SharpBoxDaoSelector.RenameProvider(SharpBoxProviderInfo, newTitle);
//rename provider customer title
}
else
{
var parentFolder = GetFolderById(folder.ParentFolderID);
newTitle = GetAvailableTitle(newTitle, parentFolder, IsExist);
//rename folder
if (SharpBoxProviderInfo.Storage.RenameFileSystemEntry(entry, newTitle))
{
//Folder data must be already updated by provider
//We can't search google folders by title because root can have multiple folders with the same name
//var newFolder = SharpBoxProviderInfo.Storage.GetFileSystemObject(newTitle, folder.Parent);
newId = MakeId(entry);
}
}
UpdatePathInDB(oldId, newId);
return newId;
}
public int GetItemsCount(object folderId)
{
throw new NotImplementedException();
}
public bool IsEmpty(object folderId)
{
return GetFolderById(folderId).Count == 0;
}
public bool UseTrashForRemove(Folder folder)
{
return false;
}
public bool UseRecursiveOperation(object folderId, object toRootFolderId)
{
return false;
}
public bool CanCalculateSubitems(object entryId)
{
return false;
}
public long GetMaxUploadSize(object folderId, bool chunkedUpload)
{
var storageMaxUploadSize =
chunkedUpload
? SharpBoxProviderInfo.Storage.CurrentConfiguration.Limits.MaxChunkedUploadFileSize
: SharpBoxProviderInfo.Storage.CurrentConfiguration.Limits.MaxUploadFileSize;
if (storageMaxUploadSize == -1)
storageMaxUploadSize = long.MaxValue;
return chunkedUpload ? storageMaxUploadSize : Math.Min(storageMaxUploadSize, SetupInfo.AvailableFileSize);
}
#region Only for TMFolderDao
public void ReassignFolders(IEnumerable<object> folderIds, Guid newOwnerId)
{
}
public IEnumerable<Folder> Search(string text, bool bunch)
{
return null;
}
public object GetFolderID(string module, string bunch, string data, bool createIfNotExists)
{
return null;
}
public IEnumerable<object> GetFolderIDs(string module, string bunch, IEnumerable<string> data, bool createIfNotExists)
{
return new List<object>();
}
public object GetFolderIDCommon(bool createIfNotExists)
{
return null;
}
public object GetFolderIDUser(bool createIfNotExists, Guid? userId)
{
return null;
}
public object GetFolderIDShare(bool createIfNotExists)
{
return null;
}
public object GetFolderIDRecent(bool createIfNotExists)
{
return null;
}
public object GetFolderIDFavorites(bool createIfNotExists)
{
return null;
}
public object GetFolderIDTemplates(bool createIfNotExists)
{
return null;
}
public object GetFolderIDPrivacy(bool createIfNotExists, Guid? userId)
{
return null;
}
public object GetFolderIDTrash(bool createIfNotExists, Guid? userId)
{
return null;
}
public object GetFolderIDPhotos(bool createIfNotExists)
{
return null;
}
public object GetFolderIDProjects(bool createIfNotExists)
{
return null;
}
public string GetBunchObjectID(object folderID)
{
return null;
}
public Dictionary<string, string> GetBunchObjectIDs(IEnumerable<object> folderIDs)
{
return null;
}
#endregion
}
}
| |
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using Moq;
using Palmmedia.ReportGenerator.Core.Parser;
using Palmmedia.ReportGenerator.Core.Parser.Analysis;
using Palmmedia.ReportGenerator.Core.Parser.FileReading;
using Palmmedia.ReportGenerator.Core.Parser.Filtering;
using Palmmedia.ReportGenerator.Core.Parser.Preprocessing;
using Xunit;
namespace Palmmedia.ReportGenerator.Core.Test.Parser
{
/// <summary>
/// This is a test class for MultiReportParser and is intended
/// to contain all ParserResultTest Unit Tests
/// </summary>
[Collection("FileManager")]
public class ParserResultTest
{
private static readonly string FilePath = Path.Combine(FileManager.GetCSharpReportDirectory(), "OpenCover.xml");
private readonly ParserResult parserResultWithoutPreprocessing;
private readonly ParserResult parserResultWithPreprocessing;
public ParserResultTest()
{
var filterMock = new Mock<IFilter>();
filterMock.Setup(f => f.IsElementIncludedInReport(It.IsAny<string>())).Returns(true);
this.parserResultWithoutPreprocessing = new OpenCoverParser(filterMock.Object, filterMock.Object, filterMock.Object).Parse(XDocument.Load(FilePath));
this.parserResultWithoutPreprocessing.Merge(new OpenCoverParser(filterMock.Object, filterMock.Object, filterMock.Object).Parse(XDocument.Load(FilePath)));
var report = XDocument.Load(FilePath);
new OpenCoverReportPreprocessor().Execute(report);
this.parserResultWithPreprocessing = new OpenCoverParser(filterMock.Object, filterMock.Object, filterMock.Object).Parse(report);
report = XDocument.Load(FilePath);
new OpenCoverReportPreprocessor().Execute(report);
this.parserResultWithPreprocessing.Merge(new OpenCoverParser(filterMock.Object, filterMock.Object, filterMock.Object).Parse(report));
}
/// <summary>
/// A test for SupportsBranchCoverage
/// </summary>
[Fact]
public void SupportsBranchCoverage()
{
var parserResult = new ParserResult();
Assert.False(parserResult.SupportsBranchCoverage);
parserResult = new ParserResult(new List<Assembly>(), false, "Test");
Assert.False(parserResult.SupportsBranchCoverage);
parserResult.Merge(new ParserResult(new List<Assembly>(), true, "Test"));
Assert.True(parserResult.SupportsBranchCoverage);
}
/// <summary>
/// A test for SourceDirectories
/// </summary>
[Fact]
public void SourceDirectories()
{
var parserResult1 = new ParserResult();
Assert.Equal(0, parserResult1.SourceDirectories.Count);
parserResult1.AddSourceDirectory("C:\\temp1");
parserResult1.AddSourceDirectory("C:\\temp2");
Assert.Equal(2, parserResult1.SourceDirectories.Count);
var parserResult2 = new ParserResult();
parserResult2.AddSourceDirectory("C:\\temp2");
parserResult2.AddSourceDirectory("C:\\temp3");
Assert.Equal(2, parserResult1.SourceDirectories.Count);
parserResult1.Merge(parserResult2);
Assert.Equal(3, parserResult1.SourceDirectories.Count);
}
/// <summary>
/// A test for NumberOfLineVisits
/// </summary>
[Fact]
public void NumberOfLineVisitsTest_WithoutPreprocessing()
{
var fileAnalysis = GetFileAnalysis(this.parserResultWithoutPreprocessing.Assemblies, "Test.TestClass", "C:\\temp\\TestClass.cs");
Assert.Equal(2, fileAnalysis.Lines.Single(l => l.LineNumber == 9).LineVisits);
Assert.Equal(2, fileAnalysis.Lines.Single(l => l.LineNumber == 10).LineVisits);
Assert.Equal(2, fileAnalysis.Lines.Single(l => l.LineNumber == 11).LineVisits);
Assert.Equal(2, fileAnalysis.Lines.Single(l => l.LineNumber == 12).LineVisits);
Assert.Equal(2, fileAnalysis.Lines.Single(l => l.LineNumber == 19).LineVisits);
Assert.Equal(0, fileAnalysis.Lines.Single(l => l.LineNumber == 23).LineVisits);
Assert.Equal(0, fileAnalysis.Lines.Single(l => l.LineNumber == 31).LineVisits);
fileAnalysis = GetFileAnalysis(this.parserResultWithoutPreprocessing.Assemblies, "Test.TestClass2", "C:\\temp\\TestClass2.cs");
Assert.Equal(6, fileAnalysis.Lines.Single(l => l.LineNumber == 13).LineVisits);
Assert.Equal(0, fileAnalysis.Lines.Single(l => l.LineNumber == 15).LineVisits);
Assert.Equal(0, fileAnalysis.Lines.Single(l => l.LineNumber == 19).LineVisits);
Assert.Equal(4, fileAnalysis.Lines.Single(l => l.LineNumber == 25).LineVisits);
Assert.Equal(2, fileAnalysis.Lines.Single(l => l.LineNumber == 31).LineVisits);
Assert.Equal(0, fileAnalysis.Lines.Single(l => l.LineNumber == 37).LineVisits);
Assert.Equal(8, fileAnalysis.Lines.Single(l => l.LineNumber == 54).LineVisits);
Assert.Equal(0, fileAnalysis.Lines.Single(l => l.LineNumber == 81).LineVisits);
Assert.False(fileAnalysis.Lines.Single(l => l.LineNumber == 44).CoveredBranches.HasValue, "No covered branches");
Assert.False(fileAnalysis.Lines.Single(l => l.LineNumber == 44).TotalBranches.HasValue, "No total branches");
Assert.Equal(1, fileAnalysis.Lines.Single(l => l.LineNumber == 54).CoveredBranches.Value);
Assert.Equal(2, fileAnalysis.Lines.Single(l => l.LineNumber == 54).TotalBranches.Value);
fileAnalysis = GetFileAnalysis(this.parserResultWithoutPreprocessing.Assemblies, "Test.PartialClass", "C:\\temp\\PartialClass.cs");
Assert.Equal(2, fileAnalysis.Lines.Single(l => l.LineNumber == 9).LineVisits);
Assert.Equal(0, fileAnalysis.Lines.Single(l => l.LineNumber == 14).LineVisits);
fileAnalysis = GetFileAnalysis(this.parserResultWithoutPreprocessing.Assemblies, "Test.PartialClass", "C:\\temp\\PartialClass2.cs");
Assert.Equal(2, fileAnalysis.Lines.Single(l => l.LineNumber == 9).LineVisits);
Assert.Equal(0, fileAnalysis.Lines.Single(l => l.LineNumber == 14).LineVisits);
fileAnalysis = GetFileAnalysis(this.parserResultWithoutPreprocessing.Assemblies, "Test.ClassWithExcludes", "C:\\temp\\ClassWithExcludes.cs");
Assert.Equal(-1, fileAnalysis.Lines.Single(l => l.LineNumber == 9).LineVisits);
Assert.Equal(-1, fileAnalysis.Lines.Single(l => l.LineNumber == 19).LineVisits);
}
/// <summary>
/// A test for NumberOfLineVisits
/// </summary>
[Fact]
public void NumberOfLineVisitsTest_WithPreprocessing()
{
var fileAnalysis = GetFileAnalysis(this.parserResultWithPreprocessing.Assemblies, "Test.TestClass", "C:\\temp\\TestClass.cs");
Assert.Equal(2, fileAnalysis.Lines.Single(l => l.LineNumber == 9).LineVisits);
Assert.Equal(2, fileAnalysis.Lines.Single(l => l.LineNumber == 10).LineVisits);
Assert.Equal(2, fileAnalysis.Lines.Single(l => l.LineNumber == 11).LineVisits);
Assert.Equal(2, fileAnalysis.Lines.Single(l => l.LineNumber == 12).LineVisits);
Assert.Equal(2, fileAnalysis.Lines.Single(l => l.LineNumber == 19).LineVisits);
Assert.Equal(0, fileAnalysis.Lines.Single(l => l.LineNumber == 23).LineVisits);
Assert.Equal(0, fileAnalysis.Lines.Single(l => l.LineNumber == 31).LineVisits);
fileAnalysis = GetFileAnalysis(this.parserResultWithPreprocessing.Assemblies, "Test.TestClass2", "C:\\temp\\TestClass2.cs");
Assert.Equal(6, fileAnalysis.Lines.Single(l => l.LineNumber == 13).LineVisits);
Assert.Equal(0, fileAnalysis.Lines.Single(l => l.LineNumber == 15).LineVisits);
Assert.Equal(0, fileAnalysis.Lines.Single(l => l.LineNumber == 19).LineVisits);
Assert.Equal(4, fileAnalysis.Lines.Single(l => l.LineNumber == 25).LineVisits);
Assert.Equal(2, fileAnalysis.Lines.Single(l => l.LineNumber == 31).LineVisits);
Assert.Equal(0, fileAnalysis.Lines.Single(l => l.LineNumber == 37).LineVisits);
Assert.Equal(8, fileAnalysis.Lines.Single(l => l.LineNumber == 54).LineVisits);
Assert.Equal(0, fileAnalysis.Lines.Single(l => l.LineNumber == 81).LineVisits);
Assert.False(fileAnalysis.Lines.Single(l => l.LineNumber == 44).CoveredBranches.HasValue);
Assert.False(fileAnalysis.Lines.Single(l => l.LineNumber == 44).TotalBranches.HasValue);
Assert.Equal(1, fileAnalysis.Lines.Single(l => l.LineNumber == 54).CoveredBranches.Value);
Assert.Equal(2, fileAnalysis.Lines.Single(l => l.LineNumber == 54).TotalBranches.Value);
fileAnalysis = GetFileAnalysis(this.parserResultWithPreprocessing.Assemblies, "Test.PartialClass", "C:\\temp\\PartialClass.cs");
Assert.Equal(2, fileAnalysis.Lines.Single(l => l.LineNumber == 9).LineVisits);
Assert.Equal(0, fileAnalysis.Lines.Single(l => l.LineNumber == 14).LineVisits);
fileAnalysis = GetFileAnalysis(this.parserResultWithPreprocessing.Assemblies, "Test.PartialClass", "C:\\temp\\PartialClass2.cs");
Assert.Equal(2, fileAnalysis.Lines.Single(l => l.LineNumber == 9).LineVisits);
Assert.Equal(0, fileAnalysis.Lines.Single(l => l.LineNumber == 14).LineVisits);
fileAnalysis = GetFileAnalysis(this.parserResultWithPreprocessing.Assemblies, "Test.ClassWithExcludes", "C:\\temp\\ClassWithExcludes.cs");
Assert.Equal(-1, fileAnalysis.Lines.Single(l => l.LineNumber == 9).LineVisits);
Assert.Equal(-1, fileAnalysis.Lines.Single(l => l.LineNumber == 19).LineVisits);
}
/// <summary>
/// A test for NumberOfFiles
/// </summary>
[Fact]
public void NumberOfFilesTest()
{
Assert.Equal(15, this.parserResultWithoutPreprocessing.Assemblies.SelectMany(a => a.Classes).SelectMany(a => a.Files).Distinct().Count());
}
/// <summary>
/// A test for FilesOfClass
/// </summary>
[Fact]
public void FilesOfClassTest()
{
Assert.Single(this.parserResultWithoutPreprocessing.Assemblies.Single(a => a.Name == "Test").Classes.Single(c => c.Name == "Test.TestClass").Files);
Assert.Equal(2, this.parserResultWithoutPreprocessing.Assemblies.Single(a => a.Name == "Test").Classes.Single(c => c.Name == "Test.PartialClass").Files.Count());
}
/// <summary>
/// A test for ClassesInAssembly
/// </summary>
[Fact]
public void ClassesInAssemblyTest()
{
Assert.Equal(17, this.parserResultWithoutPreprocessing.Assemblies.SelectMany(a => a.Classes).Count());
}
/// <summary>
/// A test for Assemblies
/// </summary>
[Fact]
public void AssembliesTest()
{
Assert.Single(this.parserResultWithoutPreprocessing.Assemblies);
}
/// <summary>
/// A test for MethodMetrics
/// </summary>
[Fact]
public void MethodMetricsTest()
{
var metrics = this.parserResultWithoutPreprocessing.Assemblies.Single(a => a.Name == "Test").Classes.Single(c => c.Name == "Test.TestClass").Files.Single(f => f.Path == "C:\\temp\\TestClass.cs").MethodMetrics;
Assert.Equal(2, metrics.Count());
Assert.Equal("System.Void Test.TestClass::SampleFunction()", metrics.First().FullName);
Assert.Equal(5, metrics.First().Metrics.Count());
Assert.Equal("Cyclomatic complexity", metrics.First().Metrics.ElementAt(0).Name);
Assert.Equal(3, metrics.First().Metrics.ElementAt(0).Value);
Assert.Equal("NPath complexity", metrics.First().Metrics.ElementAt(1).Name);
Assert.Equal(2, metrics.First().Metrics.ElementAt(1).Value);
Assert.Equal("Sequence coverage", metrics.First().Metrics.ElementAt(2).Name);
Assert.Equal(75M, metrics.First().Metrics.ElementAt(2).Value);
Assert.Equal("Branch coverage", metrics.First().Metrics.ElementAt(3).Name);
Assert.Equal(66.67M, metrics.First().Metrics.ElementAt(3).Value);
Assert.Equal("Crap Score", metrics.First().Metrics.ElementAt(4).Name);
Assert.Equal(3.14M, metrics.First().Metrics.ElementAt(4).Value);
metrics = this.parserResultWithoutPreprocessing.Assemblies.Single(a => a.Name == "Test").Classes.Single(c => c.Name == "Test.AsyncClass").Files.Single(f => f.Path == "C:\\temp\\AsyncClass.cs").MethodMetrics;
Assert.Single(metrics);
Assert.Equal("SendAsync()", metrics.First().FullName);
}
/// <summary>
/// A test for MethodMetrics
/// </summary>
[Fact]
public void OpenCoverMethodMetricsTest()
{
var filterMock = new Mock<IFilter>();
filterMock.Setup(f => f.IsElementIncludedInReport(It.IsAny<string>())).Returns(true);
string filePath = Path.Combine(FileManager.GetCSharpReportDirectory(), "MultiOpenCover.xml");
var parserResult = new CoverageReportParser(1, 1, System.Array.Empty<string>(), filterMock.Object, filterMock.Object, filterMock.Object).ParseFiles(new string[] { filePath });
var metrics = parserResult.Assemblies
.Single(a => a.Name == "Test").Classes
.Single(c => c.Name == "Test.TestClass").Files
.Single(f => f.Path == "C:\\temp\\TestClass.cs")
.MethodMetrics;
Assert.Equal(2, metrics.Count());
Assert.Equal("System.Void Test.TestClass::SampleFunction()", metrics.First().FullName);
Assert.Equal(3, metrics.First().Metrics.Count());
Assert.Equal("Cyclomatic complexity", metrics.First().Metrics.ElementAt(0).Name);
Assert.Equal(3, metrics.First().Metrics.ElementAt(0).Value);
Assert.Equal("Sequence coverage", metrics.First().Metrics.ElementAt(1).Name);
Assert.Equal(222, metrics.First().Metrics.ElementAt(1).Value);
Assert.Equal("Branch coverage", metrics.First().Metrics.ElementAt(2).Name);
Assert.Equal(333, metrics.First().Metrics.ElementAt(2).Value);
}
/// <summary>
/// A test for branches
/// </summary>
[Fact]
public void OpenCoverBranchesTest()
{
var filterMock = new Mock<IFilter>();
filterMock.Setup(f => f.IsElementIncludedInReport(It.IsAny<string>())).Returns(true);
string filePath = Path.Combine(FileManager.GetCSharpReportDirectory(), "MultiOpenCover.xml");
var parserResult = new CoverageReportParser(1, 1, System.Array.Empty<string>(), filterMock.Object, filterMock.Object, filterMock.Object).ParseFiles(new string[] { filePath });
var fileAnalysis = GetFileAnalysis(parserResult.Assemblies, "Test.TestClass2", "C:\\temp\\TestClass2.cs");
Assert.False(fileAnalysis.Lines.Single(l => l.LineNumber == 44).CoveredBranches.HasValue, "No covered branches");
Assert.False(fileAnalysis.Lines.Single(l => l.LineNumber == 44).TotalBranches.HasValue, "No total branches");
Assert.Equal(1, fileAnalysis.Lines.Single(l => l.LineNumber == 45).CoveredBranches.Value);
Assert.Equal(2, fileAnalysis.Lines.Single(l => l.LineNumber == 45).TotalBranches.Value);
}
private static FileAnalysis GetFileAnalysis(IEnumerable<Assembly> assemblies, string className, string fileName) => assemblies
.Single(a => a.Name == "Test").Classes
.Single(c => c.Name == className).Files
.Single(f => f.Path == fileName)
.AnalyzeFile(new CachingFileReader(new LocalFileReader(), 0, null));
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Text;
using System.Reflection;
using System.Diagnostics;
using System.Collections.Generic;
using System.Reflection.Runtime.General;
using System.Reflection.Runtime.TypeInfos;
using System.Reflection.Runtime.TypeInfos.EcmaFormat;
using System.Reflection.Runtime.ParameterInfos;
using System.Reflection.Runtime.ParameterInfos.EcmaFormat;
using System.Reflection.Runtime.CustomAttributes;
using System.Runtime;
using System.Runtime.InteropServices;
using Internal.Reflection.Core;
using Internal.Reflection.Core.Execution;
using Internal.Runtime.CompilerServices;
using Internal.Runtime.TypeLoader;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
namespace System.Reflection.Runtime.MethodInfos.EcmaFormat
{
//
// Implements methods and properties common to RuntimeMethodInfo and RuntimeConstructorInfo.
//
internal struct EcmaFormatMethodCommon : IRuntimeMethodCommon<EcmaFormatMethodCommon>, IEquatable<EcmaFormatMethodCommon>
{
public bool IsGenericMethodDefinition
{
get
{
return _method.GetGenericParameters().Count > 0;
}
}
public MethodInvoker GetUncachedMethodInvoker(RuntimeTypeInfo[] methodArguments, MemberInfo exceptionPertainant)
{
return ReflectionCoreExecution.ExecutionEnvironment.GetMethodInvoker(DeclaringType, new QMethodDefinition(Reader, MethodHandle), methodArguments, exceptionPertainant);
}
public QSignatureTypeHandle[] QualifiedMethodSignature
{
get
{
return this.MethodSignature;
}
}
public EcmaFormatMethodCommon RuntimeMethodCommonOfUninstantiatedMethod
{
get
{
return new EcmaFormatMethodCommon(MethodHandle, _definingTypeInfo, _definingTypeInfo);
}
}
public void FillInMetadataDescribedParameters(ref VirtualRuntimeParameterInfoArray result, QSignatureTypeHandle[] typeSignatures, MethodBase contextMethod, TypeContext typeContext)
{
foreach (ParameterHandle parameterHandle in _method.GetParameters())
{
Parameter parameterRecord = _reader.GetParameter(parameterHandle);
int index = parameterRecord.SequenceNumber;
result[index] =
EcmaFormatMethodParameterInfo.GetEcmaFormatMethodParameterInfo(
contextMethod,
_methodHandle,
index - 1,
parameterHandle,
typeSignatures[index],
typeContext);
}
}
public RuntimeTypeInfo[] GetGenericTypeParametersWithSpecifiedOwningMethod(RuntimeNamedMethodInfo<EcmaFormatMethodCommon> owningMethod)
{
GenericParameterHandleCollection genericParameters = _method.GetGenericParameters();
int genericParametersCount = genericParameters.Count;
if (genericParametersCount == 0)
return Array.Empty<RuntimeTypeInfo>();
RuntimeTypeInfo[] genericTypeParameters = new RuntimeTypeInfo[genericParametersCount];
int i = 0;
foreach (GenericParameterHandle genericParameterHandle in genericParameters)
{
RuntimeTypeInfo genericParameterType = EcmaFormatRuntimeGenericParameterTypeInfoForMethods.GetRuntimeGenericParameterTypeInfoForMethods(owningMethod, Reader, genericParameterHandle);
genericTypeParameters[i++] = genericParameterType;
}
return genericTypeParameters;
}
//
// methodHandle - the "tkMethodDef" that identifies the method.
// definingType - the "tkTypeDef" that defined the method (this is where you get the metadata reader that created methodHandle.)
// contextType - the type that supplies the type context (i.e. substitutions for generic parameters.) Though you
// get your raw information from "definingType", you report "contextType" as your DeclaringType property.
//
// For example:
//
// typeof(Foo<>).GetTypeInfo().DeclaredMembers
//
// The definingType and contextType are both Foo<>
//
// typeof(Foo<int,String>).GetTypeInfo().DeclaredMembers
//
// The definingType is "Foo<,>"
// The contextType is "Foo<int,String>"
//
// We don't report any DeclaredMembers for arrays or generic parameters so those don't apply.
//
public EcmaFormatMethodCommon(MethodDefinitionHandle methodHandle, EcmaFormatRuntimeNamedTypeInfo definingTypeInfo, RuntimeTypeInfo contextTypeInfo)
{
_definingTypeInfo = definingTypeInfo;
_methodHandle = methodHandle;
_contextTypeInfo = contextTypeInfo;
_reader = definingTypeInfo.Reader;
_method = _reader.GetMethodDefinition(methodHandle);
}
public MethodAttributes Attributes
{
get
{
return _method.Attributes;
}
}
public CallingConventions CallingConvention
{
get
{
BlobReader signatureBlob = _reader.GetBlobReader(_method.Signature);
CallingConventions result;
SignatureHeader sigHeader = signatureBlob.ReadSignatureHeader();
if (sigHeader.CallingConvention == SignatureCallingConvention.VarArgs)
result = CallingConventions.VarArgs;
else
result = CallingConventions.Standard;
if (sigHeader.IsInstance)
result |= CallingConventions.HasThis;
if (sigHeader.HasExplicitThis)
result |= CallingConventions.ExplicitThis;
return result;
}
}
public RuntimeTypeInfo ContextTypeInfo
{
get
{
return _contextTypeInfo;
}
}
public IEnumerable<CustomAttributeData> CustomAttributes
{
get
{
IEnumerable<CustomAttributeData> customAttributes = RuntimeCustomAttributeData.GetCustomAttributes(_reader, _method.GetCustomAttributes());
foreach (CustomAttributeData cad in customAttributes)
yield return cad;
if (0 != (_method.ImplAttributes & MethodImplAttributes.PreserveSig))
yield return ReflectionCoreExecution.ExecutionDomain.GetCustomAttributeData(typeof(PreserveSigAttribute), null, null);
}
}
public RuntimeTypeInfo DeclaringType
{
get
{
return _contextTypeInfo;
}
}
public RuntimeNamedTypeInfo DefiningTypeInfo
{
get
{
return _definingTypeInfo;
}
}
public MethodImplAttributes MethodImplementationFlags
{
get
{
return _method.ImplAttributes;
}
}
public Module Module
{
get
{
return _definingTypeInfo.Module;
}
}
public int MetadataToken
{
get
{
return MetadataTokens.GetToken(_methodHandle);
}
}
public RuntimeMethodHandle GetRuntimeMethodHandle(Type[] genericArgs)
{
Debug.Assert(genericArgs == null || genericArgs.Length > 0);
RuntimeTypeHandle[] genericArgHandles;
if (genericArgs != null)
{
genericArgHandles = new RuntimeTypeHandle[genericArgs.Length];
for (int i = 0; i < genericArgHandles.Length; i++)
genericArgHandles[i] = genericArgs[i].TypeHandle;
}
else
{
genericArgHandles = null;
}
IntPtr dynamicModule = ModuleList.Instance.GetModuleInfoForMetadataReader(Reader).DynamicModulePtrAsIntPtr;
return TypeLoaderEnvironment.Instance.GetRuntimeMethodHandleForComponents(
DeclaringType.TypeHandle,
Name,
RuntimeSignature.CreateFromMethodHandle(dynamicModule, MetadataToken),
genericArgHandles);
}
//
// Returns the ParameterInfo objects for the method parameters and return parameter.
//
// The ParameterInfo objects will report "contextMethod" as their Member property and use it to get type variable information from
// the contextMethod's declaring type. The actual metadata, however, comes from "this."
//
// The methodTypeArguments provides the fill-ins for any method type variable elements in the parameter type signatures.
//
// Does not array-copy.
//
public RuntimeParameterInfo[] GetRuntimeParameters(MethodBase contextMethod, RuntimeTypeInfo[] methodTypeArguments, out RuntimeParameterInfo returnParameter)
{
MetadataReader reader = _reader;
TypeContext typeContext = contextMethod.DeclaringType.CastToRuntimeTypeInfo().TypeContext;
typeContext = new TypeContext(typeContext.GenericTypeArguments, methodTypeArguments);
QSignatureTypeHandle[] typeSignatures = this.MethodSignature;
int count = typeSignatures.Length;
VirtualRuntimeParameterInfoArray result = new VirtualRuntimeParameterInfoArray(count);
foreach (ParameterHandle parameterHandle in _method.GetParameters())
{
Parameter parameterRecord = _reader.GetParameter(parameterHandle);
int index = parameterRecord.SequenceNumber;
result[index] =
EcmaFormatMethodParameterInfo.GetEcmaFormatMethodParameterInfo(
contextMethod,
_methodHandle,
index - 1,
parameterHandle,
typeSignatures[index],
typeContext);
}
for (int i = 0; i < count; i++)
{
if (result[i] == null)
{
result[i] =
RuntimeThinMethodParameterInfo.GetRuntimeThinMethodParameterInfo(
contextMethod,
i - 1,
typeSignatures[i],
typeContext);
}
}
returnParameter = result.First;
return result.Remainder;
}
public String Name
{
get
{
return _method.Name.GetString(_reader);
}
}
public MetadataReader Reader
{
get
{
return _reader;
}
}
public MethodDefinitionHandle MethodHandle
{
get
{
return _methodHandle;
}
}
public bool HasSameMetadataDefinitionAs(EcmaFormatMethodCommon other)
{
if (!(_reader == other._reader))
return false;
if (!(_methodHandle.Equals(other._methodHandle)))
return false;
return true;
}
public override bool Equals(Object obj)
{
if (!(obj is EcmaFormatMethodCommon))
return false;
return Equals((EcmaFormatMethodCommon)obj);
}
public bool Equals(EcmaFormatMethodCommon other)
{
if (!(_reader == other._reader))
return false;
if (!(_methodHandle.Equals(other._methodHandle)))
return false;
if (!(_contextTypeInfo.Equals(other._contextTypeInfo)))
return false;
return true;
}
public override int GetHashCode()
{
return _methodHandle.GetHashCode() ^ _contextTypeInfo.GetHashCode();
}
private QSignatureTypeHandle[] MethodSignature
{
get
{
BlobReader signatureBlob = _reader.GetBlobReader(_method.Signature);
SignatureHeader header = signatureBlob.ReadSignatureHeader();
if (header.Kind != SignatureKind.Method)
throw new BadImageFormatException();
int genericParameterCount = 0;
if (header.IsGeneric)
genericParameterCount = signatureBlob.ReadCompressedInteger();
int numParameters = signatureBlob.ReadCompressedInteger();
QSignatureTypeHandle[] signatureHandles = new QSignatureTypeHandle[checked(numParameters + 1)];
signatureHandles[0] = new QSignatureTypeHandle(_reader, signatureBlob);
EcmaMetadataHelpers.SkipType(ref signatureBlob);
for (int i = 0 ; i < numParameters; i++)
{
signatureHandles[i + 1] = new QSignatureTypeHandle(_reader, signatureBlob);
}
return signatureHandles;
}
}
private readonly EcmaFormatRuntimeNamedTypeInfo _definingTypeInfo;
private readonly MethodDefinitionHandle _methodHandle;
private readonly RuntimeTypeInfo _contextTypeInfo;
private readonly MetadataReader _reader;
private readonly MethodDefinition _method;
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using Server;
using Server.ContextMenus;
using Server.Network;
using Server.Prompts;
using Server.Targeting;
using Server.Spells;
using Server.Mobiles;
namespace Server.Items
{
public class BraceletOfBinding : BaseBracelet, TranslocationItem
{
private int m_Charges;
private int m_Recharges;
private string m_Inscription;
private BraceletOfBinding m_Bound;
private TransportTimer m_Timer;
[CommandProperty( AccessLevel.GameMaster )]
public int Charges
{
get{ return m_Charges; }
set
{
if ( value > this.MaxCharges )
m_Charges = this.MaxCharges;
else if ( value < 0 )
m_Charges = 0;
else
m_Charges = value;
InvalidateProperties();
}
}
[CommandProperty( AccessLevel.GameMaster )]
public int Recharges
{
get{ return m_Recharges; }
set
{
if ( value > this.MaxRecharges )
m_Recharges = this.MaxRecharges;
else if ( value < 0 )
m_Recharges = 0;
else
m_Recharges = value;
InvalidateProperties();
}
}
[CommandProperty( AccessLevel.GameMaster )]
public int MaxCharges{ get{ return 20; } }
[CommandProperty( AccessLevel.GameMaster )]
public int MaxRecharges{ get{ return 255; } }
public string TranslocationItemName{ get{ return "bracelet of binding"; } }
[CommandProperty( AccessLevel.GameMaster )]
public string Inscription
{
get{ return m_Inscription; }
set
{
m_Inscription = value;
InvalidateProperties();
}
}
[CommandProperty( AccessLevel.GameMaster )]
public BraceletOfBinding Bound
{
get
{
if ( m_Bound != null && m_Bound.Deleted )
m_Bound = null;
return m_Bound;
}
set{ m_Bound = value; }
}
[Constructable]
public BraceletOfBinding() : base( 0x1086 )
{
Hue = 0x489;
Weight = 1.0;
m_Inscription = "";
}
public override void AddNameProperty( ObjectPropertyList list )
{
list.Add( 1054000, m_Charges.ToString() + ( m_Inscription.Length == 0 ? "\t " : " :\t" + m_Inscription ) ); // a bracelet of binding : ~1_val~ ~2_val~
}
public override void OnSingleClick( Mobile from )
{
LabelTo( from, 1054000, m_Charges.ToString() + ( m_Inscription.Length == 0 ? "\t " : " :\t" + m_Inscription ) ); // a bracelet of binding : ~1_val~ ~2_val~
}
public override void GetContextMenuEntries( Mobile from, List<ContextMenuEntry> list )
{
base.GetContextMenuEntries( from, list );
if ( from.Alive && this.IsChildOf( from ) )
{
BraceletOfBinding bound = this.Bound;
list.Add( new BraceletEntry( new BraceletCallback( Activate ), 6170, bound != null ) );
list.Add( new BraceletEntry( new BraceletCallback( Search ), 6171, bound != null ) );
list.Add( new BraceletEntry( new BraceletCallback( Bind ), bound == null ? 6173 : 6174, true ) );
list.Add( new BraceletEntry( new BraceletCallback( Inscribe ), 6175, true ) );
}
}
private delegate void BraceletCallback( Mobile from );
private class BraceletEntry : ContextMenuEntry
{
private BraceletCallback m_Callback;
public BraceletEntry( BraceletCallback callback, int number, bool enabled ) : base( number )
{
m_Callback = callback;
if ( !enabled )
Flags |= CMEFlags.Disabled;
}
public override void OnClick()
{
Mobile from = Owner.From;
if ( from.CheckAlive() )
m_Callback( from );
}
}
public override void OnDoubleClick( Mobile from )
{
BraceletOfBinding bound = this.Bound;
if ( Bound == null )
{
Bind( from );
}
else
{
Activate( from );
}
}
public void Activate( Mobile from )
{
BraceletOfBinding bound = this.Bound;
if ( Deleted || bound == null )
return;
if ( !this.IsChildOf( from ) )
{
from.SendLocalizedMessage( 1042664 ); // You must have the object in your backpack to use it.
}
else if ( m_Timer != null )
{
from.SendLocalizedMessage( 1054013 ); // The bracelet is already attempting contact. You decide to wait a moment.
}
else
{
from.PlaySound( 0xF9 );
from.LocalOverheadMessage( MessageType.Regular, 0x5D, true, "* You concentrate on the bracelet to summon its power *" );
from.Frozen = true;
m_Timer = new TransportTimer( this, from );
m_Timer.Start();
}
}
private class TransportTimer : Timer
{
private BraceletOfBinding m_Bracelet;
private Mobile m_From;
public TransportTimer( BraceletOfBinding bracelet, Mobile from ) : base( TimeSpan.FromSeconds( 2.0 ) )
{
m_Bracelet = bracelet;
m_From = from;
}
protected override void OnTick()
{
m_Bracelet.m_Timer = null;
m_From.Frozen = false;
if ( m_Bracelet.Deleted || m_From.Deleted )
return;
if ( m_Bracelet.CheckUse( m_From, false ) )
{
Mobile boundRoot = m_Bracelet.Bound.RootParent as Mobile;
if ( boundRoot != null )
{
m_Bracelet.Charges--;
BaseCreature.TeleportPets( m_From, boundRoot.Location, boundRoot.Map, true );
m_From.PlaySound( 0x1FC );
m_From.MoveToWorld( boundRoot.Location, boundRoot.Map );
m_From.PlaySound( 0x1FC );
}
}
}
}
public void Search( Mobile from )
{
BraceletOfBinding bound = this.Bound;
if ( Deleted || bound == null )
return;
if ( !this.IsChildOf( from ) )
{
from.SendLocalizedMessage( 1042664 ); // You must have the object in your backpack to use it.
}
else
{
CheckUse( from, true );
}
}
private bool CheckUse( Mobile from, bool successMessage )
{
BraceletOfBinding bound = this.Bound;
if ( bound == null )
return false;
Mobile boundRoot = bound.RootParent as Mobile;
if ( Charges == 0 )
{
from.SendLocalizedMessage( 1054005 ); // The bracelet glows black. It must be charged before it can be used again.
return false;
}
else if ( from.FindItemOnLayer( Layer.Bracelet ) != this )
{
from.SendLocalizedMessage( 1054004 ); // You must equip the bracelet in order to use its power.
return false;
}
else if ( boundRoot == null || boundRoot.NetState == null || boundRoot.FindItemOnLayer( Layer.Bracelet ) != bound )
{
from.SendLocalizedMessage( 1054006 ); // The bracelet emits a red glow. The bracelet's twin is not available for transport.
return false;
}
else if ( !Core.AOS && from.Map != boundRoot.Map )
{
from.SendLocalizedMessage( 1054014 ); // The bracelet glows black. The bracelet's target is on another facet.
return false;
}
else if ( Factions.Sigil.ExistsOn( from ) )
{
from.SendLocalizedMessage( 1061632 ); // You can't do that while carrying the sigil.
return false;
}
else if ( !SpellHelper.CheckTravel( from, TravelCheckType.RecallFrom ) )
{
return false;
}
else if ( !SpellHelper.CheckTravel( from, boundRoot.Map, boundRoot.Location, TravelCheckType.RecallTo ) )
{
return false;
}
else if ( boundRoot.Map == Map.Felucca && from is PlayerMobile && ((PlayerMobile)from).Young )
{
from.SendLocalizedMessage( 1049543 ); // You decide against traveling to Felucca while you are still young.
return false;
}
else if ( from.Kills >= 5 && boundRoot.Map != Map.Felucca )
{
from.SendLocalizedMessage( 1019004 ); // You are not allowed to travel there.
return false;
}
else if ( from.Criminal )
{
from.SendLocalizedMessage( 1005561, "", 0x22 ); // Thou'rt a criminal and cannot escape so easily.
return false;
}
else if ( SpellHelper.CheckCombat( from ) )
{
from.SendLocalizedMessage( 1005564, "", 0x22 ); // Wouldst thou flee during the heat of battle??
return false;
}
else if ( Server.Misc.WeightOverloading.IsOverloaded( from ) )
{
from.SendLocalizedMessage( 502359, "", 0x22 ); // Thou art too encumbered to move.
return false;
}
else if (from.Region.IsPartOf(typeof(Server.Regions.Jail)))
{
from.SendLocalizedMessage(1114345, "", 0x35); // You'll need a better jailbreak plan then that!
return false;
}
else if ( boundRoot.Region.IsPartOf( typeof( Server.Regions.Jail ) ) )
{
from.SendLocalizedMessage( 1019004 ); // You are not allowed to travel there.
return false;
}
else
{
if ( successMessage )
from.SendLocalizedMessage( 1054015 ); // The bracelet's twin is available for transport.
return true;
}
}
public void Bind( Mobile from )
{
if ( Deleted )
return;
if ( !this.IsChildOf( from ) )
{
from.SendLocalizedMessage( 1042664 ); // You must have the object in your backpack to use it.
}
else
{
from.SendLocalizedMessage( 1054001 ); // Target the bracelet of binding you wish to bind this bracelet to.
from.Target = new BindTarget( this );
}
}
private class BindTarget : Target
{
private BraceletOfBinding m_Bracelet;
public BindTarget( BraceletOfBinding bracelet ) : base( -1, false, TargetFlags.None )
{
m_Bracelet = bracelet;
}
protected override void OnTarget( Mobile from, object targeted )
{
if ( m_Bracelet.Deleted )
return;
if ( !m_Bracelet.IsChildOf( from ) )
{
from.SendLocalizedMessage( 1042664 ); // You must have the object in your backpack to use it.
}
else if ( targeted is BraceletOfBinding )
{
BraceletOfBinding bindBracelet = (BraceletOfBinding)targeted;
if ( bindBracelet == m_Bracelet )
{
from.SendLocalizedMessage( 1054012 ); // You cannot bind a bracelet of binding to itself!
}
else if ( !bindBracelet.IsChildOf( from ) )
{
from.SendLocalizedMessage( 1042664 ); // You must have the object in your backpack to use it.
}
else
{
from.SendLocalizedMessage( 1054003 ); // You bind the bracelet to its counterpart. The bracelets glow with power.
from.PlaySound( 0x1FA );
m_Bracelet.Bound = bindBracelet;
}
}
else
{
from.SendLocalizedMessage( 1054002 ); // You can only bind this bracelet to another bracelet of binding!
}
}
}
public void Inscribe( Mobile from )
{
if ( Deleted )
return;
if ( !this.IsChildOf( from ) )
{
from.SendLocalizedMessage( 1042664 ); // You must have the object in your backpack to use it.
}
else
{
from.SendLocalizedMessage( 1054009 ); // Enter the text to inscribe upon the bracelet :
from.Prompt = new InscribePrompt( this );
}
}
private class InscribePrompt : Prompt
{
private BraceletOfBinding m_Bracelet;
public InscribePrompt( BraceletOfBinding bracelet )
{
m_Bracelet = bracelet;
}
public override void OnResponse( Mobile from, string text )
{
if ( m_Bracelet.Deleted )
return;
if ( !m_Bracelet.IsChildOf( from ) )
{
from.SendLocalizedMessage( 1042664 ); // You must have the object in your backpack to use it.
}
else
{
from.SendLocalizedMessage( 1054011 ); // You mark the bracelet with your inscription.
m_Bracelet.Inscription = text;
}
}
public override void OnCancel( Mobile from )
{
from.SendLocalizedMessage( 1054010 ); // You decide not to inscribe the bracelet at this time.
}
}
public BraceletOfBinding( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.WriteEncodedInt( (int) 1 ); // version
writer.WriteEncodedInt( (int) m_Recharges );
writer.WriteEncodedInt( (int) m_Charges );
writer.Write( (string) m_Inscription );
writer.Write( (Item) this.Bound );
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadEncodedInt();
switch ( version )
{
case 1:
{
m_Recharges = reader.ReadEncodedInt();
goto case 0;
}
case 0:
{
m_Charges = Math.Min( reader.ReadEncodedInt(), MaxCharges );
m_Inscription = reader.ReadString();
this.Bound = (BraceletOfBinding) reader.ReadItem();
break;
}
}
}
}
}
| |
// <copyright file="Batch.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry 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.
// </copyright>
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using OpenTelemetry.Internal;
namespace OpenTelemetry
{
/// <summary>
/// Stores a batch of completed <typeparamref name="T"/> objects to be exported.
/// </summary>
/// <typeparam name="T">The type of object in the <see cref="Batch{T}"/>.</typeparam>
public readonly struct Batch<T> : IDisposable
where T : class
{
private readonly T item;
private readonly CircularBuffer<T> circularBuffer;
private readonly T[] items;
private readonly long targetCount;
/// <summary>
/// Initializes a new instance of the <see cref="Batch{T}"/> struct.
/// </summary>
/// <param name="items">The items to store in the batch.</param>
/// <param name="count">The number of items in the batch.</param>
public Batch(T[] items, int count)
{
Guard.ThrowIfNull(items);
Guard.ThrowIfOutOfRange(count, min: 0, max: items.Length);
this.item = null;
this.circularBuffer = null;
this.items = items;
this.Count = this.targetCount = count;
}
internal Batch(T item)
{
Debug.Assert(item != null, $"{nameof(item)} was null.");
this.item = item;
this.circularBuffer = null;
this.items = null;
this.Count = this.targetCount = 1;
}
internal Batch(CircularBuffer<T> circularBuffer, int maxSize)
{
Debug.Assert(maxSize > 0, $"{nameof(maxSize)} should be a positive number.");
Debug.Assert(circularBuffer != null, $"{nameof(circularBuffer)} was null.");
this.item = null;
this.items = null;
this.circularBuffer = circularBuffer;
this.Count = Math.Min(maxSize, circularBuffer.Count);
this.targetCount = circularBuffer.RemovedCount + this.Count;
}
private delegate bool BatchEnumeratorMoveNextFunc(ref Enumerator enumerator);
/// <summary>
/// Gets the count of items in the batch.
/// </summary>
public long Count { get; }
/// <inheritdoc/>
public void Dispose()
{
if (this.circularBuffer != null)
{
// Drain anything left in the batch.
while (this.circularBuffer.RemovedCount < this.targetCount)
{
this.circularBuffer.Read();
}
}
}
/// <summary>
/// Returns an enumerator that iterates through the <see cref="Batch{T}"/>.
/// </summary>
/// <returns><see cref="Enumerator"/>.</returns>
public Enumerator GetEnumerator()
{
return this.circularBuffer != null
? new Enumerator(this.circularBuffer, this.targetCount)
: this.item != null
? new Enumerator(this.item)
/* In the event someone uses default/new Batch() to create Batch we fallback to empty items mode. */
: new Enumerator(this.items ?? Array.Empty<T>(), this.targetCount);
}
/// <summary>
/// Enumerates the elements of a <see cref="Batch{T}"/>.
/// </summary>
public struct Enumerator : IEnumerator<T>
{
private static readonly BatchEnumeratorMoveNextFunc MoveNextSingleItem = (ref Enumerator enumerator) =>
{
if (enumerator.targetCount >= 0)
{
enumerator.Current = null;
return false;
}
enumerator.targetCount++;
return true;
};
private static readonly BatchEnumeratorMoveNextFunc MoveNextCircularBuffer = (ref Enumerator enumerator) =>
{
var circularBuffer = enumerator.circularBuffer;
if (circularBuffer.RemovedCount < enumerator.targetCount)
{
enumerator.Current = circularBuffer.Read();
return true;
}
enumerator.Current = null;
return false;
};
private static readonly BatchEnumeratorMoveNextFunc MoveNextArray = (ref Enumerator enumerator) =>
{
var items = enumerator.items;
if (enumerator.itemIndex < enumerator.targetCount)
{
enumerator.Current = items[enumerator.itemIndex++];
return true;
}
enumerator.Current = null;
return false;
};
private readonly CircularBuffer<T> circularBuffer;
private readonly T[] items;
private readonly BatchEnumeratorMoveNextFunc moveNextFunc;
private long targetCount;
private int itemIndex;
internal Enumerator(T item)
{
this.Current = item;
this.circularBuffer = null;
this.items = null;
this.targetCount = -1;
this.itemIndex = 0;
this.moveNextFunc = MoveNextSingleItem;
}
internal Enumerator(CircularBuffer<T> circularBuffer, long targetCount)
{
this.Current = null;
this.items = null;
this.circularBuffer = circularBuffer;
this.targetCount = targetCount;
this.itemIndex = 0;
this.moveNextFunc = MoveNextCircularBuffer;
}
internal Enumerator(T[] items, long targetCount)
{
this.Current = null;
this.circularBuffer = null;
this.items = items;
this.targetCount = targetCount;
this.itemIndex = 0;
this.moveNextFunc = MoveNextArray;
}
/// <inheritdoc/>
public T Current { get; private set; }
/// <inheritdoc/>
object IEnumerator.Current => this.Current;
/// <inheritdoc/>
public void Dispose()
{
}
/// <inheritdoc/>
public bool MoveNext()
{
return this.moveNextFunc(ref this);
}
/// <inheritdoc/>
public void Reset()
=> throw new NotSupportedException();
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.SS.Util
{
using System;
using NPOI.SS.UserModel;
using System.Collections.Generic;
using System.Globalization;
/**
* For POI internal use only
*
* @author Josh Micich
*/
public class SSCellRange<K> : ICellRange<K> where K:ICell
{
private int _height;
private int _width;
private K[] _flattenedArray;
private int _firstRow;
private int _firstColumn;
private SSCellRange(int firstRow, int firstColumn, int height, int width, K[] flattenedArray)
{
_firstRow = firstRow;
_firstColumn = firstColumn;
_height = height;
_width = width;
_flattenedArray = flattenedArray;
}
public static SSCellRange<K> Create(int firstRow, int firstColumn, int height, int width, List<K> flattenedList, Type cellClass)
{
int nItems = flattenedList.Count;
if (height * width != nItems)
{
throw new ArgumentException("Array size mismatch.");
}
K[] flattenedArray = (K[])Array.CreateInstance(cellClass, nItems);
flattenedArray=flattenedList.ToArray();
return new SSCellRange<K>(firstRow, firstColumn, height, width, flattenedArray);
}
public K GetCell(int relativeRowIndex, int relativeColumnIndex)
{
if (relativeRowIndex < 0 || relativeRowIndex >= _height)
{
throw new IndexOutOfRangeException("Specified row " + relativeRowIndex
+ " is outside the allowable range (0.." + (_height - 1) + ").");
}
if (relativeColumnIndex < 0 || relativeColumnIndex >= _width)
{
throw new IndexOutOfRangeException("Specified colummn " + relativeColumnIndex
+ " is outside the allowable range (0.." + (_width - 1) + ").");
}
int flatIndex = _width * relativeRowIndex + relativeColumnIndex;
return _flattenedArray[flatIndex];
}
internal class ArrayIterator<D> :IEnumerator<D>
{
private D[] _array;
private int _index;
public ArrayIterator(D[] array)
{
_array = array;
_index = 0;
}
#region IEnumerator<D> Members
public bool MoveNext()
{
return _index < _array.Length;
}
public void Remove()
{
throw new NotSupportedException("Cannot remove cells from this CellRange.");
}
public void Reset()
{
}
public D Current
{
get
{
if (_index >= _array.Length)
{
throw new ArgumentNullException(_index.ToString(CultureInfo.CurrentCulture));
}
return _array[_index++];
}
}
#endregion
#region IDisposable Members
public void Dispose()
{
//do nothing?
}
#endregion
#region IEnumerator Members
object System.Collections.IEnumerator.Current
{
get { return this.Current; }
}
#endregion
}
#region CellRange<K> Members
public K TopLeftCell
{
get { return _flattenedArray[0]; }
}
public K[] FlattenedCells
{
get {
return (K[])_flattenedArray.Clone();
}
}
public K[][] Cells
{
get {
Type itemCls = _flattenedArray.GetType();
K[][] result = (K[][])Array.CreateInstance(itemCls, _height);
itemCls = itemCls.GetElementType();
for (int r = _height - 1; r >= 0; r--)
{
K[] row = (K[])Array.CreateInstance(itemCls, _width);
int flatIndex = _width * r;
Array.Copy(_flattenedArray, flatIndex, row, 0, _width);
}
return result;
}
}
public int Height
{
get
{
return _height;
}
}
public int Width
{
get
{
return _width;
}
}
public int Size
{
get
{
return _height * _width;
}
}
public String ReferenceText
{
get
{
CellRangeAddress cra = new CellRangeAddress(_firstRow, _firstRow + _height - 1, _firstColumn, _firstColumn + _width - 1);
return cra.FormatAsString();
}
}
#endregion
#region IEnumerable<K> Members
public IEnumerator<K> GetEnumerator()
{
return new ArrayIterator<K>(_flattenedArray);
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
#endregion
}
}
| |
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Permissive License.
// See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
// All other rights reserved.
using System;
using System.CodeDom;
using System.Collections;
using System.Drawing;
using System.Globalization;
using System.Threading;
using System.Windows.Automation;
using System.Windows;
namespace InternalHelper.Tests.Patterns
{
using InternalHelper;
using InternalHelper.Tests;
using InternalHelper.Enumerations;
using Microsoft.Test.UIAutomation;
using Microsoft.Test.UIAutomation.Core;
using Microsoft.Test.UIAutomation.TestManager;
using Microsoft.Test.UIAutomation.Interfaces;
/// -----------------------------------------------------------------------
/// <summary></summary>
/// -----------------------------------------------------------------------
public class ValueWrapper : PatternObject
{
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
ValuePattern _pattern;
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
internal ValueWrapper(AutomationElement element, string testSuite, TestPriorities priority, TypeOfControl typeOfControl, TypeOfPattern typeOfPattern, string dirResults, bool testEvents, IApplicationCommands commands)
:
base(element, testSuite, priority, typeOfControl, typeOfPattern, dirResults, testEvents, commands)
{
_pattern = (ValuePattern)GetPattern(m_le, m_useCurrent, ValuePattern.Pattern);
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
internal void pattern_SetValue(object val, Type expectedException, CheckType checkType)
{
string newVal = Convert.ToString(val, CultureInfo.CurrentUICulture);
string call = "SetValue(" + newVal + ")";
try
{
Comment("Before " + call + " Value = " + pattern_Value);
_pattern.SetValue(newVal);
Comment("After " + call + " Value = " + pattern_Value);
// Are we in a "no-clobber" state? If so, bail gracefully
// This is why we throw an IncorrectElementConfiguration instead of
// default value of checkType
if (_noClobber == true)
{
ThrowMe(CheckType.IncorrectElementConfiguration, "/NOCLOBBER flag is set, cannot update the value of the control, exiting gracefully");
}
}
catch (Exception actualException)
{
if (Library.IsCriticalException(actualException))
throw;
TestException(expectedException, actualException, call, checkType);
return;
}
TestNoException(expectedException, call, checkType);
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
internal bool pattern_IsReadOnly
{
get
{
return _pattern.Current.IsReadOnly;
}
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
internal string pattern_Value
{
get
{
return _pattern.Current.Value;
}
}
}
}
namespace Microsoft.Test.UIAutomation.Tests.Patterns
{
using InternalHelper;
using InternalHelper.Tests;
using InternalHelper.Tests.Patterns;
using InternalHelper.Enumerations;
using Microsoft.Test.UIAutomation;
using Microsoft.Test.UIAutomation.Core;
using Microsoft.Test.UIAutomation.TestManager;
using Microsoft.Test.UIAutomation.Interfaces;
/// -----------------------------------------------------------------------
/// <summary></summary>
/// -----------------------------------------------------------------------
public sealed class ValueTests : ValueWrapper
{
#region Member variables
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
const int Checked = 0;
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
const int Unchecked = 1;
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
const int Indeterminate = 2;
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
bool[] m_CheckedStated = new bool[3];
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
const string THIS = "ValueTests";
#endregion Member variables
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
public const string TestSuite = NAMESPACE + "." + THIS;
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
public static readonly string TestWhichPattern = Automation.PatternName(ValuePattern.Pattern);
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
public ValueTests(AutomationElement element, TestPriorities priority, string dirResults, bool testEvents, TypeOfControl typeOfControl, IApplicationCommands commands)
:
base(element, TestSuite, priority, typeOfControl, TypeOfPattern.Value, dirResults, testEvents, commands)
{
}
#region Tests: Pattern Specific
#region SetValue
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("ValuePattern.SetValue.S.1.1",
TestSummary = "Set the Value to a random valid value based on the AutomationElement.ControlTypeProperty",
Priority = TestPriorities.Pri0,
Status = TestStatus.Works, /* For some reason the stack trace is not retailed for this function if it fails on amd64 */
Author = "Microsoft Corp.",
TestCaseType = TestCaseType.Events,
EventTested = "AutomationPropertyChangedEventHandler(ValuePattern.ValueProperty)",
Description = new string[] {
"Precondition: Verify ReadOnly = false",
"Step: Get the value of the current Value",
"Step: Verify that the old value does not equal the new random value",
"Step: Add event that will catch PropertyChangeEvent",
"Step: Set the value of the pattern to the random valid value according to the AutomationElement.ControlTypeProperty",
"Step: Wait for PropertyChangeEvent",
"Verify that the PropertyChangeEvent event is fired and the random string is passed into the event",
"Verify that Value is set correctly to the new value"
})]
public void TestSetValue11(TestCaseAttribute testCase)
{
try
{
HeaderComment(testCase);
SetValue_Test1(false, Helpers.GetRandomValidValue(m_le, null), testCase);
}
catch (Exception e)
{
throw e; /* amd64fre does not include this function (1st called in assembly?) in the trace unless we do this */
}
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("ValuePattern.SetValue.S.1.2",
Priority = TestPriorities.Pri0,
Status = TestStatus.Works, // Issues regarding failures on rich Edit(s) remain
Author = "Microsoft Corp.",
TestCaseType = TestCaseType.Events,
EventTested = "AutomationPropertyChangedEventHandler(ValuePattern.ValueProperty)",
Description = new string[] {
"Precondition: Verify ReadOnly = false",
"Step: Get the value of the current Value",
"Step: Verify that the old value does not equal the new random value",
"Step: Add event that will catch PropertyChangeEvent",
"Step: Set the value of the pattern to \"\"",
"Step: Wait for event",
"Verify that the PropertyChangeEvent event is fired and the random string is passed into the event",
"Verify that Value is set correctly to the new value"
})]
public void TestSetValue12(TestCaseAttribute testCase)
{
HeaderComment(testCase);
if (m_le.Current.ControlType != ControlType.Edit)
ThrowMe(CheckType.IncorrectElementConfiguration, "Test is designed for edit control");
SetValue_Test1(false, "", testCase);
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("ValuePattern.SetValue.S.1.3",
Priority = TestPriorities.Pri0,
Status = TestStatus.Works, // Issues regarding failures on rich Edit(s) remain
Author = "Microsoft Corp.",
TestCaseType = TestCaseType.Events,
EventTested = "AutomationPropertyChangedEventHandler(ValuePattern.ValueProperty)",
Description = new string[] {
"Precondition: Verify ReadOnly = false",
"Step: Get the value of the current Value",
"Step: Verify that the old value does not equal to very large string",
"Step: Add event that will catch PropertyChangeEvent",
"Step: Set the value of the pattern to the very large string",
"Step: Step: Wait for event",
"Verify that the PropertyChangeEvent event is fired and the random string is passed into the event",
"Verify that Value is set correctly to the new value"
})]
public void TestSetValue13(TestCaseAttribute testCase)
{
HeaderComment(testCase);
SetValue_Test1(false, Helpers.GetRandomValidValue(m_le, true), testCase);
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("ValuePattern.SetValue.S.1.7",
Priority = TestPriorities.Pri0,
Status = TestStatus.Works, // Issues regarding failures on rich Edit(s) remain
Author = "Microsoft Corp.",
TestCaseType = TestCaseType.Events,
EventTested = "AutomationPropertyChangedEventHandler(ValuePattern.ValueProperty)",
Description = new string[] {
"Precondition: Verify ReadOnly = false",
"Step: Get the value of the current Value",
"Step: Verify that the old value does not equal to small string",
"Step: Add event that will catch PropertyChangeEvent",
"Step: Set the value of the pattern to the very large string",
"Step: Step: Wait for event",
"Verify that the PropertyChangeEvent event is fired and the random string is passed into the event",
"Verify that Value is set correctly to the new value"
})]
public void TestSetValue17(TestCaseAttribute testCase)
{
HeaderComment(testCase);
SetValue_Test1(false, Helpers.GetRandomValidValue(m_le, false), testCase);
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("ValuePattern.SetValue.S.1.9",
Priority = TestPriorities.Pri0,
Status = TestStatus.Works,
Author = "Microsoft Corp.",
TestCaseType = TestCaseType.Events,
EventTested = "AutomationPropertyChangedEventHandler(ValuePattern.ValueProperty)",
Description = new string[] {
"Precondition: Verify that this control's ReadOnly == false",
"Step: Verify that this control supports string types",
"Step: Get the value of the current Value",
"Step: Add event that will catch PropertyChangeEvent",
"Step: Set the value of the pattern to same string",
"Step: Wait for event",
"Verify that the PropertyChangeEvent event is Undetermined",
})]
public void TestSetValueS19(TestCaseAttribute testCase)
{
HeaderComment(testCase);
SetValue_SetToSameValue(ObjectTypes.String, false);
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("ValuePattern.SetValue.S.1.10",
Priority = TestPriorities.Pri0,
Status = TestStatus.Problem,
Author = "Microsoft Corp.",
TestCaseType = TestCaseType.Events,
EventTested = "AutomationPropertyChangedEventHandler(ValuePattern.ValueProperty)",
Description = new string[] {
"Precondition: Verify that this control's ReadOnly == false",
"Step: Verify that this control supports the enum ItemCheckState types",
"Step: Get the value of the current Value",
"Step: Add event that will catch PropertyChangeEvent",
"Step: Set the value of the pattern to same ItemCheckState",
"Step: Wait for event",
"Verify that the PropertyChangeEvent event is Undetermined",
})]
public void TestSetValue10(TestCaseAttribute testCase)
{
HeaderComment(testCase);
SetValue_SetToSameValue(ObjectTypes.ItemCheckState, false, EventFired.Undetermined);
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("ValuePattern.SetValue.S.1.11",
Priority = TestPriorities.Pri0,
Status = TestStatus.Works,
Author = "Microsoft Corp.",
TestCaseType = TestCaseType.Events,
EventTested = "AutomationPropertyChangedEventHandler(ValuePattern.ValueProperty)",
Description = new string[] {
"Precondition: Verify that this control's ReadOnly == false",
"Step: Verify that this control supports the Integer types",
"Step: Get the value of the current Value",
"Step: Add event that will catch PropertyChangeEvent",
"Step: Set the value of the pattern to same Integer",
"Step: Wait for event",
"Verify that the PropertyChangeEvent event is Undetermined",
})]
public void TestSetValue111(TestCaseAttribute testCase)
{
HeaderComment(testCase);
SetValue_SetToSameValue(ObjectTypes.Int32, false);
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("ValuePattern.SetValue.S.1.12",
Priority = TestPriorities.Pri0,
Status = TestStatus.Problem,
ProblemDescription = "There is a problem in that it will not throw if you pass a wrong datatype such as Int64 to the existing data type of Int32 when you can cast the value such as 10(Int64) to the corRect type 10(Int32)",
Author = "Microsoft Corp.",
Description = new string[]{
"Precondition: Verify that this control's ReadOnly == false",
"Step: Determine a random non-supported data type",
"Step: Get random value of a non-supported random object type",
"Step: Add PropertyChangeEvent event listener",
"Step: Call SetValue with the non-supporting data type and verify that an exception is thrown",
"Step: Step: Wait for event",
"Verify that PropertyChangeEvent event does get fired"
})]
public void TestSetValue112(TestCaseAttribute testCase)
{
HeaderComment(testCase);
object otherType;
ObjectTypes objectType;
// Precondition: Verify that this control's ReadOnly == false
TS_VerifyReadOnly(false, CheckType.IncorrectElementConfiguration);
// Get random value of a non-supported random object type of the current pattern
TS_GetNonSupportedDataType(out objectType, pattern_Value, CheckType.IncorrectElementConfiguration);
// Get a random value of the non-supported data type
TS_GetRandomValue(out otherType, pattern_Value, objectType, true, false, CheckType.Verification);
// Add PropertyChangeEvent event listener
TSC_VerifyPropertyChangedListener(m_le, new EventFired[] { EventFired.True }, new AutomationProperty[] { ValuePattern.ValueProperty }, CheckType.Verification);
// Call SetValue with the non-supporting data type and verify that an exception is thrown
TS_SetValue(otherType, false, typeof(ArgumentException), CheckType.Verification);
TSC_WaitForEvents(1);
// Verify that no event is fired
TSC_VerifyPropertyChangedListener(m_le, new EventFired[] { EventFired.True }, new AutomationProperty[] { ValuePattern.ValueProperty }, CheckType.Verification);
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("ValuePattern.SetValue.S.1.16",
Priority = TestPriorities.Pri0,
Status = TestStatus.Works,
Author = "Microsoft Corp.",
TestCaseType = TestCaseType.Events,
EventTested = "AutomationPropertyChangedEventHandler(ValuePattern.ValueProperty)",
Description = new string[] {
"Precondition: Verify that control is read only",
"Precondition: Verify that this control supports 'String' types",
"Step: Get a random valid value",
"Step: Add event that will catch PropertyChangeEvent",
"Step: Set the pattern to this value",
"Step: Step: Wait for event",
"Verify the pattern is set to this value",
"Verify that the PropertyChangeEvent event is not fired"
})]
public void TestSetValue116(TestCaseAttribute testCase)
{
HeaderComment(testCase);
this.SetValue_SetToRandomValue(ObjectTypes.String, true, true, false, false, false, EventFired.False, typeof(InvalidOperationException));
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("ValuePattern.SetValue.S.1.17",
Priority = TestPriorities.Pri0,
Status = TestStatus.Works,
Author = "Microsoft Corp.",
TestCaseType = TestCaseType.Events,
EventTested = "AutomationPropertyChangedEventHandler(ValuePattern.ValueProperty)",
Description = new string[] {
"Precondition: Verify that control is read only",
"Precondition: Verify that this control supports 'ItemCheckState' types",
"Step: Get a random valid value",
"Step: Add event that will catch PropertyChangeEvent",
"Step: Set the pattern to this value",
"Step: Wait for event",
"Verify the pattern is not set to this value",
"Verify that the PropertyChangeEvent event is not fired"
})]
public void TestSetValue117(TestCaseAttribute testCase)
{
HeaderComment(testCase);
this.SetValue_SetToRandomValue(ObjectTypes.ItemCheckState, false, true, false, false, true, EventFired.False, typeof(InvalidOperationException));
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("ValuePattern.SetValue.S.1.18",
Priority = TestPriorities.Pri0,
Status = TestStatus.Works,
Author = "Microsoft Corp.",
TestCaseType = TestCaseType.Events,
EventTested = "AutomationPropertyChangedEventHandler(ValuePattern.ValueProperty)",
Description = new string[] {
"Precondition: Verify that control is read only",
"Precondition: Verify that this control supports Integer types",
"Step: Get a random valid value",
"Step: Add event that will catch PropertyChangeEvent",
"Step: Set the pattern to this value",
"Step: Wait for event",
"Verify the pattern is not set to this value",
"Verify that the PropertyChangeEvent event is not fired"
})]
public void TestSetValue118(TestCaseAttribute testCase)
{
HeaderComment(testCase);
this.SetValue_SetToRandomValue(ObjectTypes.Int32, true, true, false, false, false, EventFired.False, typeof(InvalidOperationException));
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("ValuePattern.SetValue.S.1.19",
Priority = TestPriorities.Pri0,
Status = TestStatus.Works, // Issues regarding failures on rich Edit(s) remain
Author = "Microsoft Corp.",
TestCaseType = TestCaseType.Events,
EventTested = "AutomationPropertyChangedEventHandler(ValuePattern.ValueProperty)",
Description = new string[] {
"Precondition: ConrolType is not a scrollbar as we do not know valid values that can be set",
"Precondition: Verify ReadOnly = false",
"Step: Get the value of the current Value",
"Step: Verify that the old value does not equal to ''",
"Step: Add event that will catch PropertyChangeEvent",
"Step: Set the value of the pattern to ''",
"Step: Wait for event",
"Verify that the PropertyChangeEvent event is fired and the random string is passed into the event",
"Verify that Value is set correctly to the new value"
})]
public void TestSetValue119(TestCaseAttribute testCase)
{
HeaderComment(testCase);
ControlType ct = m_le.Current.ControlType;
if (ct == null)
ThrowMe(CheckType.IncorrectElementConfiguration, "Cannot determine if control will accept '' since AutomationElement.ControlTypeProperty returns null");
if (ct == ControlType.Custom)
ThrowMe(CheckType.IncorrectElementConfiguration, "Cannot determine if control will accept '' since AutomationElement.ControlTypeProperty returns ControlType.Custom");
// Which controls support value???
if ((ct != ControlType.Edit) &&
(ct != ControlType.ListItem) &&
(ct != ControlType.TreeItem)
)
ThrowMe(CheckType.IncorrectElementConfiguration, Helpers.GetProgrammaticName(ct) + " do not support ''");
SetValue_Test1(false, "", testCase);
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("ValuePattern.SetValue.S.1.27",
Priority = TestPriorities.Pri0,
Status = TestStatus.Works,
Author = "Microsoft Corp.",
TestCaseType = TestCaseType.Events,
EventTested = "AutomationPropertyChangedEventHandler(ValuePattern.ValueProperty)",
Description = new string[] {
"Precondition: Verify that control is not read only",
"Precondition: Verify that this control supports 'DateTime' types",
"Step: Get a random valid value",
"Step: Add event that will catch PropertyChangeEvent",
"Step: Set the pattern to this value",
"Step: Wait for event",
"Verify the pattern is set to this value",
"Verify that the PropertyChangeEvent event is fired"
})]
public void TestSetValue127(TestCaseAttribute testCase)
{
HeaderComment(testCase);
AutomationIdentifier ai = m_le.GetCurrentPropertyValue(AutomationElement.ControlTypeProperty) as AutomationIdentifier;
if (ai == ControlType.Calendar)
SetValue_SetToRandomValue(ObjectTypes.Date, false, false, true, true, true, EventFired.True, null);
else
SetValue_SetToRandomValue(ObjectTypes.DateTime, false, false, true, true, true, EventFired.True, null);
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("ValuePattern.SetValue.S.1.28",
Priority = TestPriorities.Pri0,
Status = TestStatus.Works,
Author = "Microsoft Corp.",
TestCaseType = TestCaseType.Events,
EventTested = "AutomationPropertyChangedEventHandler(ValuePattern.ValueProperty)",
Description = new string[] {
"Precondition: Verify that this control's ReadOnly == false",
"Precondition: Verify that this control supports 'DateTime' data type",
"Step: Get the current value",
"Step: Add event that will catch PropertyChangeEvent",
"Step: Set the value of the pattern to the current value",
"Step: Wait for event",
"Verify that the PropertyChangeEvent event is not fired"
})]
public void TestSetValue128(TestCaseAttribute testCase)
{
HeaderComment(testCase);
SetValue_SetToSameValue(ObjectTypes.DateTime, pattern_Value, EventFired.False);
}
#endregion SetValue
#region ValueProperty
// No controlled environment test cases
#endregion ValueProperty
#region IsReadOnlyProperty
// No controlled environment test cases
#endregion IsReadOnlyProperty
#endregion Tests
#region Test Wrappers
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
void SetValue_Test1(bool readOnly, object newValue, TestCaseAttribute testCaseAttribute)
{
object oldValue;
ControlType ct = m_le.Current.ControlType;
if (m_le.Current.IsPassword)
ThrowMe(CheckType.IncorrectElementConfiguration, "Cannot verify setting Password controls");
if (ct == ControlType.Custom)
ThrowMe(CheckType.IncorrectElementConfiguration, "Cannot verify setting ControlType.Custom is correct");
if (m_le.GetCurrentPropertyValue(AutomationElement.ControlTypeProperty) == ControlType.ScrollBar)
ThrowMe(CheckType.IncorrectElementConfiguration, "Cannot verify correctness of setting the scrollbar's value since we do not know valid values that can be set");
// Verify ReadOnly = false
TS_VerifyReadOnly(readOnly, CheckType.IncorrectElementConfiguration);
if (ct == null)
ThrowMe(CheckType.IncorrectElementConfiguration, "Cannot determine specific control since AutomationElement.ControlTypeProperty returns null");
Comment("DataType: " + newValue.GetType() + "; New Value: " + newValue);
// Get the value of the current Value
TS_GetValue(out oldValue, CheckType.IncorrectElementConfiguration);
// Verify that the old value does not equal the new random value
TS_VerifyObjectNotEqual(newValue, oldValue, CheckType.IncorrectElementConfiguration);
// Add event that will catch PropertyChangeEvent
TSC_AddPropertyChangedListener(m_le, TreeScope.Element, new AutomationProperty[] { ValuePattern.ValueProperty }, CheckType.Verification);
// Set the value of the pattern to the random string
TS_SetValue(newValue, true, null, CheckType.Verification);
// Wait for event
TSC_WaitForEvents(1);
// Verify that the PropertyChangeEvent event is fired and the random string is passed into the event
TSC_VerifyPropertyChangedListener(m_le, new EventFired[] { EventFired.True }, new AutomationProperty[] { ValuePattern.ValueProperty }, CheckType.Verification);
// Verify that Value is set correctly to the new value
TS_VerifyValue(newValue, true, CheckType.Verification);
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
void SetValue_SetToSameValue(ObjectTypes dataType, object Value, EventFired eventFired)
{
object val;
// Precondition: Verify that this control is not ReadOnly
TS_VerifyReadOnly(false, CheckType.IncorrectElementConfiguration);
// Precondition: Verify that this control supports #### types
TS_VerifyObjectType(pattern_Value, dataType, true, CheckType.IncorrectElementConfiguration);
// Get the current value
TS_GetValue(out val, CheckType.Verification);
// Add event that will catch PropertyChangeEvent
TSC_AddPropertyChangedListener(m_le, TreeScope.Element, new AutomationProperty[] { ValuePattern.ValueProperty }, CheckType.Verification);
// Set the value of the pattern to the random string
TS_SetValue(Value, true, null, CheckType.Verification);
TSC_WaitForEvents(1);
// Verify that the PropertyChangeEvent event is fired and the random string is passed into the event
TSC_VerifyPropertyChangedListener(m_le, new EventFired[] { eventFired }, new AutomationProperty[] { ValuePattern.ValueProperty }, CheckType.Verification);
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
void SetValue_SetToSameValue(ObjectTypes dataType, bool CanBeNull)
{
object val;
// Precondition: Verify that this control is not ReadOnly
TS_VerifyReadOnly(false, CheckType.IncorrectElementConfiguration);
// Verify that this control supports string types
TS_SupportsDataType(dataType, pattern_Value, CanBeNull, CheckType.IncorrectElementConfiguration);
// Get the value of the current Value
TS_GetValue(out val, CheckType.Verification);
// Add event that will catch PropertyChangeEvent
TSC_AddPropertyChangedListener(m_le, TreeScope.Element, new AutomationProperty[] { ValuePattern.ValueProperty }, CheckType.Verification);
// Set the value of the pattern to same *
TS_SetValue(val, true, null, CheckType.Verification);
TSC_WaitForEvents(1);
// Verify that the PropertyChangeEvent event is fired and the random string is passed into the event
TSC_VerifyPropertyChangedListener(m_le, new EventFired[] { EventFired.Undetermined }, new AutomationProperty[] { ValuePattern.ValueProperty }, CheckType.Verification);
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
void SetValue_SetToRandomValue(ObjectTypes dataType, bool CanBeNull, bool ShouldBeReadOnly, bool MethodReturnValue, bool DoesValueChange, bool RandomValDifferentFromCurrentValue, EventFired eventFired, Type expectedException)
{
object val = pattern_Value;
// Verify that control is not read only
TS_VerifyReadOnly(ShouldBeReadOnly, CheckType.IncorrectElementConfiguration);
// Verify that this control supports ######### types
TS_VerifyObjectType(pattern_Value, dataType, CanBeNull, CheckType.IncorrectElementConfiguration);
// Get a random valid value
TS_GetRandomValue(out val, pattern_Value, dataType, true, RandomValDifferentFromCurrentValue, CheckType.Verification);
// Add event that will catch PropertyChangeEvent
TSC_AddPropertyChangedListener(m_le, TreeScope.Element, new AutomationProperty[] { ValuePattern.ValueProperty }, CheckType.Verification);
// Set the pattern to this value
TS_SetValue(val, MethodReturnValue, expectedException, CheckType.Verification);
// Wait for event
TSC_WaitForEvents(1);
// Verify the pattern is set to this value
TS_VerifyValue(val, DoesValueChange, CheckType.Verification);
// Verify that the PropertyChangeEvent event is *
TSC_VerifyPropertyChangedListener(m_le, new EventFired[] { eventFired }, new AutomationProperty[] { ValuePattern.ValueProperty }, CheckType.Verification);
}
#endregion Test Wrappers
#region Test Steps
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
void TS_SetValue(object val, bool ReturnValue, Type exceptionExpected, CheckType ct)
{
pattern_SetValue(val, exceptionExpected, ct);
m_TestStep++;
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
void TS_VerifyObjectNotEqual(object val1, object val2, CheckType ct)
{
if (val1.Equals(val2))
ThrowMe(ct, TestCaseCurrentStep + ": Values are equal");
Comment(" '" + val1 + "' != '" + val2 + "'");
m_TestStep++;
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
void TS_GetValue(out object val, CheckType ct)
{
val = pattern_Value;
Comment(" Current Value = " + val);
m_TestStep++;
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
void TS_VerifyReadOnly(bool isReadOnly, CheckType checkType)
{
if (isReadOnly != pattern_IsReadOnly)
ThrowMe(checkType);
Comment(" IsReadOnly property is " + pattern_IsReadOnly);
m_TestStep++;
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
void TS_VerifyValue(object val, bool isEqual, CheckType checkType)
{
string pValue = pattern_Value;
// Trim trailing CR/LF if we're on a richedit
TextTestsHelper.TrimTrailingCRLF(m_le, ref pValue);
bool equal = GenericMath.AreEquals(pValue, val.ToString());
if (!equal.Equals(isEqual))
ThrowMe(checkType, "ValuePattern.Value = '" + pValue + "'(" + pValue.GetType() + ") and expected '" + val + "'(" + val.GetType() + ")");
Comment("Is " + (isEqual == true ? "equal" : "not equal") + " to ValuePattern.Value (" + pValue + ")");
m_TestStep++;
}
#endregion Test Steps
}
}
| |
/* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using XenAPI;
using XenAdmin.Actions;
using XenAdmin.Network;
using XenAdmin.Core;
namespace XenAdmin.Dialogs
{
public partial class RoleElevationDialog : XenDialogBase
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public Session elevatedSession;
public string elevatedPassword;
public string elevatedUsername;
public string originalUsername;
public string originalPassword;
private List<Role> authorizedRoles;
/// <summary>
/// Displays a dialog informing the user they need a different role to complete the task, and offers the chance to switch user. Optionally logs
/// out the elevated session. If successful exposes the elevated session, password and username as fields.
/// </summary>
/// <param name="connection">The current server connection with the role information</param>
/// <param name="session">The session on which we have been denied access</param>
/// <param name="authorizedRoles">A list of roles that are able to complete the task</param>
/// <param name="actionTitle">A description of the current action, if null or empty will not be displayed</param>
public RoleElevationDialog(IXenConnection connection, Session session, List<Role> authorizedRoles, string actionTitle)
{
InitializeComponent();
this.connection = connection;
UserDetails ud = session.CurrentUserDetails;
labelCurrentUserValue.Text = ud.UserDisplayName ?? ud.UserName ?? Messages.UNKNOWN_AD_USER;
labelCurrentRoleValue.Text = Role.FriendlyCSVRoleList(session.Roles);
authorizedRoles.Sort((r1, r2) => r2.CompareTo(r1));
labelRequiredRoleValue.Text = Role.FriendlyCSVRoleList(authorizedRoles);
labelServerValue.Text = Helpers.GetName(connection);
labelServer.Text = Helpers.IsPool(connection) ? Messages.POOL_COLON : Messages.SERVER_COLON;
originalUsername = session.Connection.Username;
originalPassword = session.Connection.Password;
if (string.IsNullOrEmpty(actionTitle))
{
labelCurrentAction.Visible = false;
labelCurrentActionValue.Visible = false;
}
else
{
labelCurrentActionValue.Text = actionTitle;
}
this.authorizedRoles = authorizedRoles;
}
private void buttonAuthorize_Click(object sender, EventArgs e)
{
try
{
Exception delegateException = null;
log.Debug("Testing logging in with the new credentials");
DelegatedAsyncAction loginAction = new DelegatedAsyncAction(connection,
Messages.AUTHORIZING_USER,
Messages.CREDENTIALS_CHECKING,
Messages.CREDENTIALS_CHECK_COMPLETE,
delegate
{
try
{
elevatedSession = connection.ElevatedSession(TextBoxUsername.Text.Trim(), TextBoxPassword.Text);
}
catch (Exception ex)
{
delegateException = ex;
}
});
using (var dlg = new ActionProgressDialog(loginAction, ProgressBarStyle.Marquee, false))
dlg.ShowDialog(this);
// The exception would have been handled by the action progress dialog, just return the user to the sudo dialog
if (loginAction.Exception != null)
return;
if(HandledAnyDelegateException(delegateException))
return;
if (elevatedSession.IsLocalSuperuser || SessionAuthorized(elevatedSession))
{
elevatedUsername = TextBoxUsername.Text.Trim();
elevatedPassword = TextBoxPassword.Text;
DialogResult = DialogResult.OK;
Close();
return;
}
ShowNotAuthorisedDialog();
}
catch (Exception ex)
{
log.DebugFormat("Exception when attempting to sudo action: {0} ", ex);
using (var dlg = new ThreeButtonDialog(
new ThreeButtonDialog.Details(
SystemIcons.Error,
String.Format(Messages.USER_AUTHORIZATION_FAILED, TextBoxUsername.Text),
Messages.XENCENTER)))
{
dlg.ShowDialog(Parent);
}
TextBoxPassword.Focus();
TextBoxPassword.SelectAll();
}
finally
{
// Check whether we have a successful elevated session and whether we have been asked to log it out
// If non successful (most likely the new subject is not authorized) then log it out anyway.
if (elevatedSession != null && DialogResult != DialogResult.OK)
{
elevatedSession.Connection.Logout(elevatedSession);
elevatedSession = null;
}
}
}
private bool HandledAnyDelegateException(Exception delegateException)
{
if (delegateException != null)
{
Failure f = delegateException as Failure;
if (f != null && f.ErrorDescription[0] == Failure.RBAC_PERMISSION_DENIED)
{
ShowNotAuthorisedDialog();
return true;
}
throw delegateException;
}
return false;
}
private void ShowNotAuthorisedDialog()
{
using (var dlg = new ThreeButtonDialog(
new ThreeButtonDialog.Details(
SystemIcons.Error,
Messages.USER_NOT_AUTHORIZED,
Messages.PERMISSION_DENIED)))
{
dlg.ShowDialog(this);
}
TextBoxPassword.Focus();
TextBoxPassword.SelectAll();
}
private bool SessionAuthorized(Session s)
{
UserDetails ud = s.CurrentUserDetails;
foreach (Role r in s.Roles)
{
if (authorizedRoles.Contains(r))
{
log.DebugFormat("Subject '{0}' is authorized to complete the action", ud.UserDisplayName ?? ud.UserName ?? ud.UserSid);
return true;
}
}
log.DebugFormat("Subject '{0}' is not authorized to complete the action", ud.UserDisplayName ?? ud.UserName ?? ud.UserSid);
return false;
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void UpdateButtons()
{
buttonAuthorize.Enabled = TextBoxUsername.Text.Trim() != "" && TextBoxPassword.Text != "";
}
private void TextBoxUsername_TextChanged(object sender, EventArgs e)
{
UpdateButtons();
}
private void TextBoxPassword_TextChanged(object sender, EventArgs e)
{
UpdateButtons();
}
}
}
| |
/* Copyright (C) 2008-2015 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.IO;
using System.Security;
namespace Alphaleonis.Win32.Filesystem
{
partial class Directory
{
#region Compress
/// <summary>[AlphaFS] Compresses a directory using NTFS compression.</summary>
/// <remarks>This will only compress the root items (non recursive).</remarks>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="path">A path that describes a directory to compress.</param>
[SecurityCritical]
public static void Compress(string path)
{
CompressDecompressCore(null, path, Path.WildcardStarMatchAll, DirectoryEnumerationOptions.FilesAndFolders, true, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Compresses a directory using NTFS compression.</summary>
/// <remarks>This will only compress the root items (non recursive).</remarks>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="path">A path that describes a directory to compress.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
public static void Compress(string path, PathFormat pathFormat)
{
CompressDecompressCore(null, path, Path.WildcardStarMatchAll, DirectoryEnumerationOptions.FilesAndFolders, true, pathFormat);
}
/// <summary>[AlphaFS] Compresses a directory using NTFS compression.</summary>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="path">A path that describes a directory to compress.</param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
[SecurityCritical]
public static void Compress(string path, DirectoryEnumerationOptions options)
{
CompressDecompressCore(null, path, Path.WildcardStarMatchAll, options, true, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Compresses a directory using NTFS compression.</summary>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="path">A path that describes a directory to compress.</param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
public static void Compress(string path, DirectoryEnumerationOptions options, PathFormat pathFormat)
{
CompressDecompressCore(null, path, Path.WildcardStarMatchAll, options, true, pathFormat);
}
#region Transactional
/// <summary>[AlphaFS] Compresses a directory using NTFS compression.</summary>
/// <remarks>This will only compress the root items (non recursive).</remarks>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">A path that describes a directory to compress.</param>
[SecurityCritical]
public static void CompressTransacted(KernelTransaction transaction, string path)
{
CompressDecompressCore(transaction, path, Path.WildcardStarMatchAll, DirectoryEnumerationOptions.FilesAndFolders, true, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Compresses a directory using NTFS compression.</summary>
/// <remarks>This will only compress the root items (non recursive).</remarks>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">A path that describes a directory to compress.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
public static void CompressTransacted(KernelTransaction transaction, string path, PathFormat pathFormat)
{
CompressDecompressCore(transaction, path, Path.WildcardStarMatchAll, DirectoryEnumerationOptions.FilesAndFolders, true, pathFormat);
}
/// <summary>[AlphaFS] Compresses a directory using NTFS compression.</summary>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">A path that describes a directory to compress.</param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
[SecurityCritical]
public static void CompressTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options)
{
CompressDecompressCore(transaction, path, Path.WildcardStarMatchAll, options, true, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Compresses a directory using NTFS compression.</summary>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">A path that describes a directory to compress.</param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
public static void CompressTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options, PathFormat pathFormat)
{
CompressDecompressCore(transaction, path, Path.WildcardStarMatchAll, options, true, pathFormat);
}
#endregion // Transactional
#endregion // Compress
#region Decompress
/// <summary>[AlphaFS] Decompresses an NTFS compressed directory.</summary>
/// <remarks>This will only decompress the root items (non recursive).</remarks>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="path">A path that describes a directory to decompress.</param>
[SecurityCritical]
public static void Decompress(string path)
{
CompressDecompressCore(null, path, Path.WildcardStarMatchAll, DirectoryEnumerationOptions.FilesAndFolders, false, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Decompresses an NTFS compressed directory.</summary>
/// <remarks>This will only decompress the root items (non recursive).</remarks>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="path">A path that describes a directory to decompress.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
public static void Decompress(string path, PathFormat pathFormat)
{
CompressDecompressCore(null, path, Path.WildcardStarMatchAll, DirectoryEnumerationOptions.FilesAndFolders, false, pathFormat);
}
/// <summary>[AlphaFS] Decompresses an NTFS compressed directory.</summary>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="path">A path that describes a directory to decompress.</param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
[SecurityCritical]
public static void Decompress(string path, DirectoryEnumerationOptions options)
{
CompressDecompressCore(null, path, Path.WildcardStarMatchAll, options, false, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Decompresses an NTFS compressed directory.</summary>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="path">A path that describes a directory to decompress.</param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
public static void Decompress(string path, DirectoryEnumerationOptions options, PathFormat pathFormat)
{
CompressDecompressCore(null, path, Path.WildcardStarMatchAll, options, false, pathFormat);
}
#region Transactional
/// <summary>[AlphaFS] Decompresses an NTFS compressed directory.</summary>
/// <remarks>This will only decompress the root items (non recursive).</remarks>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">A path that describes a directory to decompress.</param>
[SecurityCritical]
public static void DecompressTransacted(KernelTransaction transaction, string path)
{
CompressDecompressCore(transaction, path, Path.WildcardStarMatchAll, DirectoryEnumerationOptions.FilesAndFolders, false, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Decompresses an NTFS compressed directory.</summary>
/// <remarks>This will only decompress the root items (non recursive).</remarks>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">A path that describes a directory to decompress.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
public static void DecompressTransacted(KernelTransaction transaction, string path, PathFormat pathFormat)
{
CompressDecompressCore(transaction, path, Path.WildcardStarMatchAll, DirectoryEnumerationOptions.FilesAndFolders, false, pathFormat);
}
/// <summary>[AlphaFS] Decompresses an NTFS compressed directory.</summary>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">A path that describes a directory to decompress.</param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
[SecurityCritical]
public static void DecompressTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options)
{
CompressDecompressCore(transaction, path, Path.WildcardStarMatchAll, options, false, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Decompresses an NTFS compressed directory.</summary>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">A path that describes a directory to decompress.</param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
public static void DecompressTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options, PathFormat pathFormat)
{
CompressDecompressCore(transaction, path, Path.WildcardStarMatchAll, options, false, pathFormat);
}
#endregion // Transactional
#endregion // Decompress
#region DisableCompression
/// <summary>[AlphaFS] Disables NTFS compression of the specified directory and the files in it.</summary>
/// <remarks>This method disables the directory-compression attribute. It will not decompress the current contents of the directory. However, newly created files and directories will be uncompressed.</remarks>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="path">A path to a directory to decompress.</param>
[SecurityCritical]
public static void DisableCompression(string path)
{
Device.ToggleCompressionCore(true, null, path, false, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Disables NTFS compression of the specified directory and the files in it.</summary>
/// <remarks>This method disables the directory-compression attribute. It will not decompress the current contents of the directory. However, newly created files and directories will be uncompressed.</remarks>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="path">A path to a directory to decompress.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
public static void DisableCompression(string path, PathFormat pathFormat)
{
Device.ToggleCompressionCore(true, null, path, false, pathFormat);
}
/// <summary>[AlphaFS] Disables NTFS compression of the specified directory and the files in it.</summary>
/// <remarks>This method disables the directory-compression attribute. It will not decompress the current contents of the directory. However, newly created files and directories will be uncompressed.</remarks>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">A path to a directory to decompress.</param>
[SecurityCritical]
public static void DisableCompressionTransacted(KernelTransaction transaction, string path)
{
Device.ToggleCompressionCore(true, transaction, path, false, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Disables NTFS compression of the specified directory and the files in it.</summary>
/// <remarks>This method disables the directory-compression attribute. It will not decompress the current contents of the directory. However, newly created files and directories will be uncompressed.</remarks>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
/// <param name="path">A path to a directory to decompress.</param>
[SecurityCritical]
public static void DisableCompressionTransacted(KernelTransaction transaction, string path, PathFormat pathFormat)
{
Device.ToggleCompressionCore(true, transaction, path, false, pathFormat);
}
#endregion // DisableCompression
#region EnableCompression
/// <summary>[AlphaFS] Enables NTFS compression of the specified directory and the files in it.</summary>
/// <remarks>This method enables the directory-compression attribute. It will not compress the current contents of the directory. However, newly created files and directories will be compressed.</remarks>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="path">A path to a directory to compress.</param>
[SecurityCritical]
public static void EnableCompression(string path)
{
Device.ToggleCompressionCore(true, null, path, true, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Enables NTFS compression of the specified directory and the files in it.</summary>
/// <remarks>This method enables the directory-compression attribute. It will not compress the current contents of the directory. However, newly created files and directories will be compressed.</remarks>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="path">A path to a directory to compress.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
public static void EnableCompression(string path, PathFormat pathFormat)
{
Device.ToggleCompressionCore(true, null, path, true, pathFormat);
}
/// <summary>[AlphaFS] Enables NTFS compression of the specified directory and the files in it.</summary>
/// <remarks>This method enables the directory-compression attribute. It will not compress the current contents of the directory. However, newly created files and directories will be compressed.</remarks>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">A path to a directory to compress.</param>
[SecurityCritical]
public static void EnableCompressionTransacted(KernelTransaction transaction, string path)
{
Device.ToggleCompressionCore(true, transaction, path, true, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Enables NTFS compression of the specified directory and the files in it.</summary>
/// <remarks>This method enables the directory-compression attribute. It will not compress the current contents of the directory. However, newly created files and directories will be compressed.</remarks>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">A path to a directory to compress.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
public static void EnableCompressionTransacted(KernelTransaction transaction, string path, PathFormat pathFormat)
{
Device.ToggleCompressionCore(true, transaction, path, true, pathFormat);
}
#endregion // EnableCompression
#region Internal Methods
/// <summary>Compress/decompress Non-/Transacted files/directories.</summary>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">A path that describes a directory to compress.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
/// <param name="compress"><see langword="true"/> compress, when <see langword="false"/> decompress.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
internal static void CompressDecompressCore(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationOptions options, bool compress, PathFormat pathFormat)
{
string pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck);
// Process directories and files.
foreach (var fso in EnumerateFileSystemEntryInfosCore<string>(transaction, pathLp, searchPattern, options | DirectoryEnumerationOptions.AsLongPath, PathFormat.LongFullPath))
Device.ToggleCompressionCore(true, transaction, fso, compress, PathFormat.LongFullPath);
// Compress the root directory, the given path.
Device.ToggleCompressionCore(true, transaction, pathLp, compress, PathFormat.LongFullPath);
}
#endregion // Internal Methods
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System.Diagnostics;
using System.IO;
using System.Runtime;
using System.ServiceModel.Diagnostics;
using System.Xml;
using System.ServiceModel.Diagnostics.Application;
class PacketRoutableHeader : DictionaryHeader
{
PacketRoutableHeader()
: base()
{
}
public static void AddHeadersTo(Message message, MessageHeader header)
{
int index = message.Headers.FindHeader(DotNetOneWayStrings.HeaderName, DotNetOneWayStrings.Namespace);
if (index == -1)
{
if (header == null)
{
header = PacketRoutableHeader.Create();
}
message.Headers.Add(header);
}
}
public static void ValidateMessage(Message message)
{
if (!TryValidateMessage(message))
{
throw TraceUtility.ThrowHelperError(
new ProtocolException(SR.GetString(SR.OneWayHeaderNotFound)), message);
}
}
public static bool TryValidateMessage(Message message)
{
int index = message.Headers.FindHeader(
DotNetOneWayStrings.HeaderName, DotNetOneWayStrings.Namespace);
return (index != -1);
}
public static PacketRoutableHeader Create()
{
return new PacketRoutableHeader();
}
public override XmlDictionaryString DictionaryName
{
get { return XD.DotNetOneWayDictionary.HeaderName; }
}
public override XmlDictionaryString DictionaryNamespace
{
get { return XD.DotNetOneWayDictionary.Namespace; }
}
protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
// no contents necessary
}
}
/// <summary>
/// OneWayChannelFactory built on top of IRequestChannel
/// </summary>
class RequestOneWayChannelFactory : LayeredChannelFactory<IOutputChannel>
{
PacketRoutableHeader packetRoutableHeader;
public RequestOneWayChannelFactory(OneWayBindingElement bindingElement, BindingContext context)
: base(context.Binding, context.BuildInnerChannelFactory<IRequestChannel>())
{
if (bindingElement.PacketRoutable)
{
this.packetRoutableHeader = PacketRoutableHeader.Create();
}
}
protected override IOutputChannel OnCreateChannel(EndpointAddress to, Uri via)
{
IRequestChannel innerChannel =
((IChannelFactory<IRequestChannel>)this.InnerChannelFactory).CreateChannel(to, via);
return new RequestOutputChannel(this, innerChannel, this.packetRoutableHeader);
}
class RequestOutputChannel : OutputChannel
{
IRequestChannel innerChannel;
MessageHeader packetRoutableHeader;
public RequestOutputChannel(ChannelManagerBase factory,
IRequestChannel innerChannel, MessageHeader packetRoutableHeader)
: base(factory)
{
this.innerChannel = innerChannel;
this.packetRoutableHeader = packetRoutableHeader;
}
#region Inner Channel delegation
public override EndpointAddress RemoteAddress
{
get { return this.innerChannel.RemoteAddress; }
}
public override Uri Via
{
get { return this.innerChannel.Via; }
}
protected override void OnAbort()
{
this.innerChannel.Abort();
}
protected override void OnOpen(TimeSpan timeout)
{
this.innerChannel.Open(timeout);
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return this.innerChannel.BeginOpen(timeout, callback, state);
}
protected override void OnEndOpen(IAsyncResult result)
{
this.innerChannel.EndOpen(result);
}
protected override void OnClose(TimeSpan timeout)
{
this.innerChannel.Close(timeout);
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return this.innerChannel.BeginClose(timeout, callback, state);
}
protected override void OnEndClose(IAsyncResult result)
{
this.innerChannel.EndClose(result);
}
public override T GetProperty<T>()
{
T result = base.GetProperty<T>();
if (result == null)
{
result = this.innerChannel.GetProperty<T>();
}
return result;
}
#endregion
// add our oneWay header to every message (if it's not already there)
protected override void AddHeadersTo(Message message)
{
base.AddHeadersTo(message);
if (this.packetRoutableHeader != null)
{
PacketRoutableHeader.AddHeadersTo(message, this.packetRoutableHeader);
}
}
protected override void OnSend(Message message, TimeSpan timeout)
{
Message response = this.innerChannel.Request(message, timeout);
using (response)
{
ValidateResponse(response);
}
}
protected override IAsyncResult OnBeginSend(Message message, TimeSpan timeout, AsyncCallback callback, object state)
{
return this.innerChannel.BeginRequest(message, timeout, callback, state);
}
protected override void OnEndSend(IAsyncResult result)
{
Message response = this.innerChannel.EndRequest(result);
using (response)
{
ValidateResponse(response);
}
}
void ValidateResponse(Message response)
{
if (response != null)
{
if (response.Version == MessageVersion.None && response is NullMessage)
{
response.Close();
return;
}
Exception innerException = null;
if (response.IsFault)
{
try
{
MessageFault messageFault = MessageFault.CreateFault(response, TransportDefaults.MaxFaultSize);
innerException = new FaultException(messageFault);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
if (e is CommunicationException ||
e is TimeoutException ||
e is XmlException ||
e is IOException)
{
innerException = e; // expected exception generating fault
}
else
{
throw;
}
}
}
throw TraceUtility.ThrowHelperError(
new ProtocolException(SR.GetString(SR.OneWayUnexpectedResponse), innerException),
response);
}
}
}
}
// <summary>
// OneWayChannelFactory built on top of IDuplexChannel
// </summary>
class DuplexOneWayChannelFactory : LayeredChannelFactory<IOutputChannel>
{
IChannelFactory<IDuplexChannel> innnerFactory;
bool packetRoutable;
public DuplexOneWayChannelFactory(OneWayBindingElement bindingElement, BindingContext context)
: base(context.Binding, context.BuildInnerChannelFactory<IDuplexChannel>())
{
this.innnerFactory = (IChannelFactory<IDuplexChannel>)this.InnerChannelFactory;
this.packetRoutable = bindingElement.PacketRoutable;
}
protected override IOutputChannel OnCreateChannel(EndpointAddress address, Uri via)
{
IDuplexChannel channel = this.innnerFactory.CreateChannel(address, via);
return new DuplexOutputChannel(this, channel);
}
class DuplexOutputChannel : OutputChannel
{
IDuplexChannel innerChannel;
bool packetRoutable;
public DuplexOutputChannel(DuplexOneWayChannelFactory factory, IDuplexChannel innerChannel)
: base(factory)
{
this.packetRoutable = factory.packetRoutable;
this.innerChannel = innerChannel;
}
public override EndpointAddress RemoteAddress
{
get { return this.innerChannel.RemoteAddress; }
}
public override Uri Via
{
get { return this.innerChannel.Via; }
}
protected override void OnAbort()
{
this.innerChannel.Abort();
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return this.innerChannel.BeginClose(timeout, callback, state);
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return this.innerChannel.BeginOpen(timeout, callback, state);
}
protected override IAsyncResult OnBeginSend(Message message, TimeSpan timeout, AsyncCallback callback, object state)
{
StampMessage(message);
return this.innerChannel.BeginSend(message, timeout, callback, state);
}
protected override void OnClose(TimeSpan timeout)
{
this.innerChannel.Close(timeout);
}
protected override void OnEndClose(IAsyncResult result)
{
this.innerChannel.EndClose(result);
}
protected override void OnEndOpen(IAsyncResult result)
{
this.innerChannel.EndOpen(result);
}
protected override void OnEndSend(IAsyncResult result)
{
this.innerChannel.EndSend(result);
}
protected override void OnOpen(TimeSpan timeout)
{
this.innerChannel.Open(timeout);
}
protected override void OnSend(Message message, TimeSpan timeout)
{
StampMessage(message);
this.innerChannel.Send(message, timeout);
}
void StampMessage(Message message)
{
if (this.packetRoutable)
{
PacketRoutableHeader.AddHeadersTo(message, null);
}
}
}
}
/// <summary>
/// OneWayChannelFactory built on top of IDuplexSessionChannel
/// </summary>
class DuplexSessionOneWayChannelFactory : LayeredChannelFactory<IOutputChannel>
{
ChannelPool<IDuplexSessionChannel> channelPool;
ChannelPoolSettings channelPoolSettings;
bool packetRoutable;
public DuplexSessionOneWayChannelFactory(OneWayBindingElement bindingElement, BindingContext context)
: base(context.Binding, context.BuildInnerChannelFactory<IDuplexSessionChannel>())
{
this.packetRoutable = bindingElement.PacketRoutable;
ISecurityCapabilities innerSecurityCapabilities = this.InnerChannelFactory.GetProperty<ISecurityCapabilities>();
// can't pool across outer channels if the inner channels support client auth
if (innerSecurityCapabilities != null && innerSecurityCapabilities.SupportsClientAuthentication)
{
this.channelPoolSettings = bindingElement.ChannelPoolSettings.Clone();
}
else
{
this.channelPool = new ChannelPool<IDuplexSessionChannel>(bindingElement.ChannelPoolSettings);
}
}
internal ChannelPool<IDuplexSessionChannel> GetChannelPool(out bool cleanupChannelPool)
{
if (this.channelPool != null)
{
cleanupChannelPool = false;
return this.channelPool;
}
else
{
cleanupChannelPool = true;
Fx.Assert(this.channelPoolSettings != null, "Need either settings or a pool");
return new ChannelPool<IDuplexSessionChannel>(this.channelPoolSettings);
}
}
protected override void OnAbort()
{
if (this.channelPool != null)
{
this.channelPool.Close(TimeSpan.Zero);
}
base.OnAbort();
}
protected override void OnClose(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
if (this.channelPool != null)
{
this.channelPool.Close(timeoutHelper.RemainingTime());
}
base.OnClose(timeoutHelper.RemainingTime());
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
if (this.channelPool != null)
{
this.channelPool.Close(timeoutHelper.RemainingTime());
}
return base.OnBeginClose(timeoutHelper.RemainingTime(), callback, state);
}
protected override IOutputChannel OnCreateChannel(EndpointAddress address, Uri via)
{
return new DuplexSessionOutputChannel(this, address, via);
}
class DuplexSessionOutputChannel : OutputChannel
{
ChannelPool<IDuplexSessionChannel> channelPool;
EndpointAddress remoteAddress;
IChannelFactory<IDuplexSessionChannel> innerFactory;
AsyncCallback onReceive;
bool packetRoutable;
bool cleanupChannelPool;
Uri via;
public DuplexSessionOutputChannel(DuplexSessionOneWayChannelFactory factory,
EndpointAddress remoteAddress, Uri via)
: base(factory)
{
this.channelPool = factory.GetChannelPool(out cleanupChannelPool);
this.packetRoutable = factory.packetRoutable;
this.innerFactory = (IChannelFactory<IDuplexSessionChannel>)factory.InnerChannelFactory;
this.remoteAddress = remoteAddress;
this.via = via;
}
public override EndpointAddress RemoteAddress
{
get { return this.remoteAddress; }
}
public override Uri Via
{
get { return this.via; }
}
#region Channel Lifetime
protected override void OnOpen(TimeSpan timeout)
{
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return new CompletedAsyncResult(callback, state);
}
protected override void OnEndOpen(IAsyncResult result)
{
CompletedAsyncResult.End(result);
}
protected override void OnAbort()
{
if (cleanupChannelPool)
{
this.channelPool.Close(TimeSpan.Zero);
}
}
protected override void OnClose(TimeSpan timeout)
{
if (cleanupChannelPool)
{
this.channelPool.Close(timeout);
}
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
if (cleanupChannelPool)
{
this.channelPool.Close(timeout);
}
return new CompletedAsyncResult(callback, state);
}
protected override void OnEndClose(IAsyncResult result)
{
CompletedAsyncResult.End(result);
}
#endregion
protected override IAsyncResult OnBeginSend(Message message, TimeSpan timeout, AsyncCallback callback, object state)
{
return new SendAsyncResult(this, message, timeout, callback, state);
}
protected override void OnEndSend(IAsyncResult result)
{
SendAsyncResult.End(result);
}
protected override void OnSend(Message message, TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
ChannelPoolKey key = null;
bool isConnectionFromPool = true;
IDuplexSessionChannel innerChannel =
GetChannelFromPool(ref timeoutHelper, out key, out isConnectionFromPool);
bool success = false;
try
{
if (!isConnectionFromPool)
{
StampInitialMessage(message);
innerChannel.Open(timeoutHelper.RemainingTime());
StartBackgroundReceive(innerChannel);
}
innerChannel.Send(message, timeoutHelper.RemainingTime());
success = true;
}
finally
{
if (!success)
{
CleanupChannel(innerChannel, false, key, isConnectionFromPool, ref timeoutHelper);
}
}
CleanupChannel(innerChannel, true, key, isConnectionFromPool, ref timeoutHelper);
}
// kick off an async receive so that we notice when the server is trying to shutdown
void StartBackgroundReceive(IDuplexSessionChannel channel)
{
if (this.onReceive == null)
{
this.onReceive = Fx.ThunkCallback(new AsyncCallback(OnReceive));
}
channel.BeginReceive(TimeSpan.MaxValue, this.onReceive, channel);
}
void OnReceive(IAsyncResult result)
{
IDuplexSessionChannel channel = (IDuplexSessionChannel)result.AsyncState;
bool success = false;
try
{
Message message = channel.EndReceive(result);
if (message == null)
{
channel.Close(this.channelPool.IdleTimeout);
success = true;
}
else
{
message.Close();
}
}
catch (CommunicationException e)
{
DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
}
catch (TimeoutException e)
{
if (TD.CloseTimeoutIsEnabled())
{
TD.CloseTimeout(e.Message);
}
DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
}
finally
{
if (!success)
{
channel.Abort();
}
}
}
void StampInitialMessage(Message message)
{
if (this.packetRoutable)
{
PacketRoutableHeader.AddHeadersTo(message, null);
}
}
void CleanupChannel(IDuplexSessionChannel channel, bool connectionStillGood, ChannelPoolKey key, bool isConnectionFromPool, ref TimeoutHelper timeoutHelper)
{
if (isConnectionFromPool)
{
this.channelPool.ReturnConnection(key, channel, connectionStillGood, timeoutHelper.RemainingTime());
}
else
{
if (connectionStillGood)
{
this.channelPool.AddConnection(key, channel, timeoutHelper.RemainingTime());
}
else
{
channel.Abort();
}
}
}
IDuplexSessionChannel GetChannelFromPool(ref TimeoutHelper timeoutHelper, out ChannelPoolKey key,
out bool isConnectionFromPool)
{
isConnectionFromPool = true;
while (true)
{
IDuplexSessionChannel pooledChannel
= this.channelPool.TakeConnection(this.RemoteAddress, this.Via, timeoutHelper.RemainingTime(), out key);
if (pooledChannel == null)
{
isConnectionFromPool = false;
return this.innerFactory.CreateChannel(RemoteAddress, Via);
}
// only return good connections
if (pooledChannel.State == CommunicationState.Opened)
{
return pooledChannel;
}
// Abort stale connections from the pool
this.channelPool.ReturnConnection(key, pooledChannel, false, timeoutHelper.RemainingTime());
}
}
class SendAsyncResult : AsyncResult
{
DuplexSessionOutputChannel parent;
IDuplexSessionChannel innerChannel;
Message message;
TimeoutHelper timeoutHelper;
static AsyncCallback onOpen;
static AsyncCallback onInnerSend = Fx.ThunkCallback(new AsyncCallback(OnInnerSend));
ChannelPoolKey key;
bool isConnectionFromPool;
public SendAsyncResult(DuplexSessionOutputChannel parent, Message message, TimeSpan timeout,
AsyncCallback callback, object state)
: base(callback, state)
{
this.parent = parent;
this.message = message;
this.timeoutHelper = new TimeoutHelper(timeout);
this.innerChannel =
parent.GetChannelFromPool(ref this.timeoutHelper, out this.key, out this.isConnectionFromPool);
bool success = false;
bool completeSelf = true;
try
{
if (!this.isConnectionFromPool)
{
completeSelf = OpenNewChannel();
}
if (completeSelf)
{
completeSelf = SendMessage();
}
success = true;
}
finally
{
if (!success)
{
Cleanup(false);
}
}
if (completeSelf)
{
Cleanup(true);
base.Complete(true);
}
}
public static void End(IAsyncResult result)
{
AsyncResult.End<SendAsyncResult>(result);
}
void Cleanup(bool connectionStillGood)
{
parent.CleanupChannel(this.innerChannel, connectionStillGood, this.key,
this.isConnectionFromPool, ref this.timeoutHelper);
}
bool OpenNewChannel()
{
if (onOpen == null)
{
onOpen = Fx.ThunkCallback(new AsyncCallback(OnOpen));
}
this.parent.StampInitialMessage(this.message);
IAsyncResult result = this.innerChannel.BeginOpen(timeoutHelper.RemainingTime(), onOpen, this);
if (!result.CompletedSynchronously)
{
return false;
}
this.CompleteOpen(result);
return true;
}
void CompleteOpen(IAsyncResult result)
{
this.innerChannel.EndOpen(result);
this.parent.StartBackgroundReceive(this.innerChannel);
}
bool SendMessage()
{
IAsyncResult result = innerChannel.BeginSend(this.message, onInnerSend, this);
if (!result.CompletedSynchronously)
{
return false;
}
innerChannel.EndSend(result);
return true;
}
static void OnOpen(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
SendAsyncResult thisPtr = (SendAsyncResult)result.AsyncState;
Exception completionException = null;
bool completeSelf = false;
try
{
thisPtr.CompleteOpen(result);
completeSelf = thisPtr.SendMessage();
}
#pragma warning suppress 56500 // [....], transferring exception to another thread
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
completeSelf = true;
completionException = e;
}
if (completeSelf)
{
thisPtr.Cleanup(completionException == null);
thisPtr.Complete(false, completionException);
}
}
static void OnInnerSend(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
SendAsyncResult thisPtr = (SendAsyncResult)result.AsyncState;
Exception completionException = null;
try
{
thisPtr.innerChannel.EndSend(result);
}
#pragma warning suppress 56500 // [....], transferring exception to another thread
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
completionException = e;
}
thisPtr.Cleanup(completionException == null);
thisPtr.Complete(false, completionException);
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Web.UI;
namespace umbraco
{
/// <summary>
/// Class that adapts an <see cref="AttributeCollection"/> to the <see cref="IDictionary"/> interface.
/// </summary>
public class AttributeCollectionAdapter : IDictionary
{
private readonly AttributeCollection _collection;
/// <summary>
/// Initializes a new instance of the <see cref="AttributeCollectionAdapter"/> class.
/// </summary>
/// <param name="collection">The collection.</param>
public AttributeCollectionAdapter(AttributeCollection collection)
{
_collection = collection;
}
#region IDictionary Members
/// <summary>
/// Adds an element with the provided key and value to the <see cref="T:System.Collections.IDictionary"/> object.
/// </summary>
/// <param name="key">The <see cref="T:System.Object"/> to use as the key of the element to add.</param>
/// <param name="value">The <see cref="T:System.Object"/> to use as the value of the element to add.</param>
public void Add(object key, object value)
{
_collection.Add(key.ToString(), value.ToString());
}
/// <summary>
/// Removes all elements from the <see cref="T:System.Collections.IDictionary"/> object.
/// </summary>
/// <exception cref="T:System.NotSupportedException">
/// The <see cref="T:System.Collections.IDictionary"/> object is read-only.
/// </exception>
public void Clear()
{
_collection.Clear();
}
/// <summary>
/// Determines whether the <see cref="T:System.Collections.IDictionary"/> object contains an element with the specified key.
/// </summary>
/// <param name="key">The key to locate in the <see cref="T:System.Collections.IDictionary"/> object.</param>
/// <returns>
/// true if the <see cref="T:System.Collections.IDictionary"/> contains an element with the key; otherwise, false.
/// </returns>
public bool Contains(object key)
{
return _collection[key.ToString()] != null;
}
/// <summary>
/// Returns an <see cref="T:System.Collections.IDictionaryEnumerator"/> object for the <see cref="T:System.Collections.IDictionary"/> object.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IDictionaryEnumerator"/> object for the <see cref="T:System.Collections.IDictionary"/> object.
/// </returns>
public IDictionaryEnumerator GetEnumerator()
{
return new AttributeCollectionAdapterEnumerator(this);
}
/// <summary>
/// Gets a value indicating whether the <see cref="T:System.Collections.IDictionary"/> object has a fixed size.
/// </summary>
/// <value></value>
/// <returns>true if the <see cref="T:System.Collections.IDictionary"/> object has a fixed size; otherwise, false.
/// </returns>
public bool IsFixedSize
{
get { return false; }
}
/// <summary>
/// Gets a value indicating whether the <see cref="T:System.Collections.IDictionary"/> object is read-only.
/// </summary>
/// <value></value>
/// <returns>true if the <see cref="T:System.Collections.IDictionary"/> object is read-only; otherwise, false.
/// </returns>
public bool IsReadOnly
{
get { return false; }
}
/// <summary>
/// Gets an <see cref="T:System.Collections.ICollection"/> object containing the keys of the <see cref="T:System.Collections.IDictionary"/> object.
/// </summary>
/// <value></value>
/// <returns>
/// An <see cref="T:System.Collections.ICollection"/> object containing the keys of the <see cref="T:System.Collections.IDictionary"/> object.
/// </returns>
public ICollection Keys
{
get { return _collection.Keys; }
}
/// <summary>
/// Removes the element with the specified key from the <see cref="T:System.Collections.IDictionary"/> object.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
public void Remove(object key)
{
_collection.Remove(key.ToString());
}
/// <summary>
/// Gets an <see cref="T:System.Collections.ICollection"/> object containing the values in the <see cref="T:System.Collections.IDictionary"/> object.
/// </summary>
/// <value></value>
/// <returns>
/// An <see cref="T:System.Collections.ICollection"/> object containing the values in the <see cref="T:System.Collections.IDictionary"/> object.
/// </returns>
public ICollection Values
{
get { throw new NotImplementedException(); }
}
/// <summary>
/// Gets or sets the <see cref="System.Object"/> with the specified key.
/// </summary>
/// <value></value>
public object this[object key]
{
get { return _collection[key.ToString()]; }
set { _collection[key.ToString()] = value.ToString(); }
}
#endregion
#region ICollection Members
/// <summary>Not implemented.</summary>
/// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.ICollection"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param>
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param>
public void CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
/// <summary>
/// Gets the number of elements contained in the <see cref="T:System.Collections.ICollection"/>.
/// </summary>
/// <value></value>
/// <returns>
/// The number of elements contained in the <see cref="T:System.Collections.ICollection"/>.
/// </returns>
public int Count
{
get { return _collection.Count; }
}
/// <summary>
/// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> is synchronized (thread safe).
/// </summary>
/// <value></value>
/// <returns>true if access to the <see cref="T:System.Collections.ICollection"/> is synchronized (thread safe); otherwise, false.
/// </returns>
public bool IsSynchronized
{
get { return false; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection"/>.
/// </summary>
/// <value></value>
/// <returns>
/// An object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection"/>.
/// </returns>
public object SyncRoot
{
get { return _collection; }
}
#endregion
#region IEnumerable Members
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
foreach (object key in _collection.Keys)
yield return _collection[(string)key];
}
#endregion
/// <summary>
/// <see cref="IDictionaryEnumerator"/> for the <see cref="AttributeCollectionAdapter"/> class.
/// </summary>
private class AttributeCollectionAdapterEnumerator : IDictionaryEnumerator
{
private readonly AttributeCollectionAdapter _adapter;
private readonly IEnumerator _enumerator;
/// <summary>
/// Initializes a new instance of the <see cref="AttributeCollectionAdapterEnumerator"/> class.
/// </summary>
/// <param name="adapter">The adapter.</param>
public AttributeCollectionAdapterEnumerator(AttributeCollectionAdapter adapter)
{
_adapter = adapter;
_enumerator = ((IEnumerable)adapter).GetEnumerator();
}
#region IDictionaryEnumerator Members
/// <summary>
/// Gets both the key and the value of the current dictionary entry.
/// </summary>
/// <value></value>
/// <returns>
/// A <see cref="T:System.Collections.DictionaryEntry"/> containing both the key and the value of the current dictionary entry.
/// </returns>
/// <exception cref="T:System.InvalidOperationException">
/// The <see cref="T:System.Collections.IDictionaryEnumerator"/> is positioned before the first entry of the dictionary or after the last entry.
/// </exception>
public DictionaryEntry Entry
{
get { return new DictionaryEntry(Key, Value); }
}
/// <summary>
/// Gets the key of the current dictionary entry.
/// </summary>
/// <value></value>
/// <returns>
/// The key of the current element of the enumeration.
/// </returns>
/// <exception cref="T:System.InvalidOperationException">
/// The <see cref="T:System.Collections.IDictionaryEnumerator"/> is positioned before the first entry of the dictionary or after the last entry.
/// </exception>
public object Key
{
get { return _enumerator.Current; }
}
/// <summary>
/// Gets the value of the current dictionary entry.
/// </summary>
/// <value></value>
/// <returns>
/// The value of the current element of the enumeration.
/// </returns>
/// <exception cref="T:System.InvalidOperationException">
/// The <see cref="T:System.Collections.IDictionaryEnumerator"/> is positioned before the first entry of the dictionary or after the last entry.
/// </exception>
public object Value
{
get { return _adapter[_enumerator.Current]; }
}
#endregion
#region IEnumerator Members
/// <summary>
/// Gets the current element in the collection.
/// </summary>
/// <value></value>
/// <returns>
/// The current element in the collection.
/// </returns>
/// <exception cref="T:System.InvalidOperationException">
/// The enumerator is positioned before the first element of the collection or after the last element.
/// </exception>
public object Current
{
get { return _enumerator.Current; }
}
/// <summary>
/// Advances the enumerator to the next element of the collection.
/// </summary>
/// <returns>
/// true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.
/// </returns>
/// <exception cref="T:System.InvalidOperationException">
/// The collection was modified after the enumerator was created.
/// </exception>
public bool MoveNext()
{
return _enumerator.MoveNext();
}
/// <summary>
/// Sets the enumerator to its initial position, which is before the first element in the collection.
/// </summary>
/// <exception cref="T:System.InvalidOperationException">
/// The collection was modified after the enumerator was created.
/// </exception>
public void Reset()
{
_enumerator.Reset();
}
#endregion
}
}
}
| |
using System;
using System.Linq;
using System.Threading.Tasks;
using Models = Login.Api.Features.Shared.Models;
using Login.Api.Features.Shared.Persistence;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
namespace Login.Api.Features.User
{
public interface ILoginService
{
Task<Models.User> GetUserByEmail(string email, bool noCache=false);
Task<Models.UserSite> GetSiteById(string id, bool noCache = false);
void SaveLoginSession(string username, string displayname, Models.LoginType loginType);
bool IsValidRedirectUrl(Models.User user, String siteName, String redirectUrl);
bool SaveSiteList(List<Models.UserSite> sitesToSave, List<Models.UserSite> sitesToDelete);
}
public class LoginService : ILoginService
{
private LoginContext _context;
private IMemoryCache _cache;
private readonly ILogger _logger;
const int CacheTime = 60;
private static readonly object _lock = new object();
public LoginService(LoginContext context, IMemoryCache cache, ILogger<LoginService> logger)
{
this._context = context;
this._cache = cache;
this._logger = logger;
}
public async Task<Models.User> GetUserByEmail(string email, bool noCache)
{
var query = from u in _context.Users.Include(s => s.Sites) /* eager load the dependant entities */
where email.ToLower() == u.Email.ToLower() select u;
if (_cache == null || noCache)
{
return await query.FirstOrDefaultAsync();
}
var user = await _cache.GetOrCreateAsync<Models.User>(email, entry =>
{
entry.SlidingExpiration = TimeSpan.FromSeconds(CacheTime);
return query.FirstOrDefaultAsync();
});
return user;
}
public async Task<Models.UserSite> GetSiteById(string id, bool noCache)
{
var query = from s in _context.UserSites where s.Id == id select s;
if (_cache == null || noCache)
{
return await query.FirstOrDefaultAsync();
}
var site = await _cache.GetOrCreateAsync<Models.UserSite>(id, entry =>
{
entry.SlidingExpiration = TimeSpan.FromSeconds(CacheTime);
return query.FirstOrDefaultAsync();
});
return site;
}
public void SaveLoginSession(string username, string displayname, Models.LoginType loginType)
{
lock(_lock)
{
// sqlite is not that happy with concurrent processes
using(var tx = _context.Database.BeginTransaction())
{
try
{
_context.Logins.Add(new Models.Login
{
Created = DateTime.Now,
Modified = DateTime.Now,
UserDisplayName = displayname,
UserName = username,
Type = loginType
});
var awaiter = _context.SaveChangesAsync();
awaiter.Wait();
tx.Commit();
}
catch(Exception EX)
{
_logger.LogError($"Could not save the login operation {EX}!");
tx.Rollback();
throw new Commons.Api.Exceptions.ApplicationException("Could not save the login.", EX);
}
}
}
}
public bool SaveSiteList(List<Models.UserSite> sitesToSave, List<Models.UserSite> sitesToDelete)
{
bool result = false;
// sqlite is not that happy with concurrent processes
lock(_lock)
{
using (var tx = _context.Database.BeginTransaction())
{
try
{
foreach (var site in sitesToSave)
{
var item = _context.UserSites.FirstOrDefault(i => i.Id == site.Id);
if (item == null)
{
_context.UserSites.Add(site);
}
}
if (sitesToDelete != null)
{
foreach (var site in sitesToDelete)
{
var item = _context.UserSites.FirstOrDefault(i => i.Id == site.Id);
if (item != null)
{
_context.UserSites.Remove(item);
}
}
}
var awaiter = _context.SaveChangesAsync();
awaiter.Wait();
tx.Commit();
if (this._cache != null)
{
// remove the updated sites from cache
sitesToSave.ForEach(s => this._cache.Remove(s.Id));
// clear the user cache-entry
sitesToSave.ForEach(s => this._cache.Remove(s.User.Email));
if (sitesToDelete != null)
{
// cler the deleted sites from cache
sitesToDelete.ForEach(s => this._cache.Remove(s.Id));
// clear the user cache-entry
sitesToDelete.ForEach(s => this._cache.Remove(s.User.Email));
}
}
result = true;
}
catch (Exception EX)
{
_logger.LogError($"Could not save the site-list {EX}!");
tx.Rollback();
throw new Commons.Api.Exceptions.ApplicationException("Could not save the site-list.", EX);
}
}
}
return result;
}
public bool IsValidRedirectUrl(Models.User user, String siteName, String redirectUrl)
{
bool result = false;
_logger.LogDebug($"Find the site {siteName} and check the redirect-url {redirectUrl}");
// find the permissions of the given user
var query = from s in user.Sites where s.Name.ToLower() == siteName.ToLower() select s;
if(query.Any())
{
var entry = query.FirstOrDefault();
// match the given URL
// the redirect-URL must start with the url defined for the given site
Uri site = new Uri(entry.Url);
Uri redirect = new Uri(redirectUrl);
if (site.Scheme == redirect.Scheme
&& site.Host == redirect.Host
&& site.Port == redirect.Port)
{
_logger.LogDebug($"Matching of url succeeded for protocol/host/port site: {site}, redirect: {redirect}");
// specifically check the path
string sitePath = site.AbsolutePath;
if (string.IsNullOrEmpty(sitePath))
{
return true;
}
string redirectPath = redirect.AbsolutePath;
if (redirectPath.StartsWith(sitePath))
{
_logger.LogDebug($"The redirect url starts with the same path as the site-url. site: {sitePath}, redirect: {redirectPath}");
return true;
}
}
}
_logger.LogDebug("Could not find a site with the given name or the redirect url did not match!");
return result;
}
}
}
| |
// 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.
// The GroupCollection lists the captured Capture numbers
// contained in a compiled Regex.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
namespace Flatbox.RegularExpressions
{
/// <summary>
/// Represents a sequence of capture substrings. The object is used
/// to return the set of captures done by a single capturing group.
/// </summary>
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(RegexCollectionDebuggerProxy<Group>))]
public class GroupCollection : IList<Group>, IReadOnlyList<Group>, IList
{
private readonly Match _match;
private readonly Hashtable _captureMap;
// cache of Group objects fed to the user
private Group[] _groups;
internal GroupCollection(Match match, Hashtable caps)
{
_match = match;
_captureMap = caps;
}
public bool IsReadOnly => true;
/// <summary>
/// Returns the number of groups.
/// </summary>
public int Count => _match._matchcount.Length;
public Group this[int groupnum] => GetGroup(groupnum);
public Group this[string groupname] => _match._regex == null ?
Group.s_emptyGroup :
GetGroup(_match._regex.GroupNumberFromName(groupname));
/// <summary>
/// Provides an enumerator in the same order as Item[].
/// </summary>
public IEnumerator GetEnumerator() => new Enumerator(this);
IEnumerator<Group> IEnumerable<Group>.GetEnumerator() => new Enumerator(this);
private Group GetGroup(int groupnum)
{
if (_captureMap != null)
{
int groupNumImpl;
if (_captureMap.TryGetValue(groupnum, out groupNumImpl))
{
return GetGroupImpl(groupNumImpl);
}
}
else if (groupnum < _match._matchcount.Length && groupnum >= 0)
{
return GetGroupImpl(groupnum);
}
return Group.s_emptyGroup;
}
/// <summary>
/// Caches the group objects
/// </summary>
private Group GetGroupImpl(int groupnum)
{
if (groupnum == 0)
return _match;
// Construct all the Group objects the first time GetGroup is called
if (_groups == null)
{
_groups = new Group[_match._matchcount.Length - 1];
for (int i = 0; i < _groups.Length; i++)
{
string groupname = _match._regex.GroupNameFromNumber(i + 1);
_groups[i] = new Group(_match._text, _match._matches[i + 1], _match._matchcount[i + 1], groupname);
}
}
return _groups[groupnum - 1];
}
public bool IsSynchronized => false;
public object SyncRoot => _match;
public void CopyTo(Array array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
for (int i = arrayIndex, j = 0; j < Count; i++, j++)
{
array.SetValue(this[j], i);
}
}
public void CopyTo(Group[] array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (arrayIndex < 0 || arrayIndex > array.Length)
throw new ArgumentOutOfRangeException(nameof(arrayIndex));
if (array.Length - arrayIndex < Count)
throw new ArgumentException("");
for (int i = arrayIndex, j = 0; j < Count; i++, j++)
{
array[i] = this[j];
}
}
int IList<Group>.IndexOf(Group item)
{
var comparer = EqualityComparer<Group>.Default;
for (int i = 0; i < Count; i++)
{
if (comparer.Equals(this[i], item))
return i;
}
return -1;
}
void IList<Group>.Insert(int index, Group item)
{
throw new NotSupportedException("");
}
void IList<Group>.RemoveAt(int index)
{
throw new NotSupportedException("");
}
Group IList<Group>.this[int index]
{
get { return this[index]; }
set { throw new NotSupportedException(""); }
}
void ICollection<Group>.Add(Group item)
{
throw new NotSupportedException("");
}
void ICollection<Group>.Clear()
{
throw new NotSupportedException("");
}
bool ICollection<Group>.Contains(Group item) =>
((IList<Group>)this).IndexOf(item) >= 0;
bool ICollection<Group>.Remove(Group item)
{
throw new NotSupportedException("");
}
int IList.Add(object value)
{
throw new NotSupportedException("");
}
void IList.Clear()
{
throw new NotSupportedException("");
}
bool IList.Contains(object value) =>
value is Group && ((ICollection<Group>)this).Contains((Group)value);
int IList.IndexOf(object value) =>
value is Group ? ((IList<Group>)this).IndexOf((Group)value) : -1;
void IList.Insert(int index, object value)
{
throw new NotSupportedException("");
}
bool IList.IsFixedSize => true;
void IList.Remove(object value)
{
throw new NotSupportedException("");
}
void IList.RemoveAt(int index)
{
throw new NotSupportedException("");
}
object IList.this[int index]
{
get { return this[index]; }
set { throw new NotSupportedException(""); }
}
private sealed class Enumerator : IEnumerator<Group>
{
private readonly GroupCollection _collection;
private int _index;
internal Enumerator(GroupCollection collection)
{
Debug.Assert(collection != null, "collection cannot be null.");
_collection = collection;
_index = -1;
}
public bool MoveNext()
{
int size = _collection.Count;
if (_index >= size)
return false;
_index++;
return _index < size;
}
public Group Current
{
get
{
if (_index < 0 || _index >= _collection.Count)
throw new InvalidOperationException("");
return _collection[_index];
}
}
object IEnumerator.Current => Current;
void IEnumerator.Reset()
{
_index = -1;
}
void IDisposable.Dispose() { }
}
}
}
| |
using System.Reactive.Linq;
using System;
using CoreGraphics;
using Toggl.Core;
using Toggl.Core.Calendar;
using Toggl.Core.UI.ViewModels.Calendar;
using Toggl.iOS.Presentation;
using Toggl.iOS.Views.Calendar;
using Toggl.iOS.ViewSources;
using Toggl.Shared.Extensions;
using UIKit;
using System.Collections.Immutable;
using System.Linq;
using System.Reactive;
using Accord.Statistics.Analysis;
using Foundation;
using Toggl.Core.Analytics;
using Toggl.Core.Extensions;
using Toggl.Core.Services;
using Toggl.Core.UI.Helper;
using Toggl.Core.UI.ViewModels.Calendar.ContextualMenu;
using Toggl.iOS.Cells.Calendar;
using Toggl.iOS.Extensions;
using Toggl.iOS.Extensions.Reactive;
using Toggl.iOS.Views;
using Toggl.Shared;
using Toggl.Shared.Extensions.Reactive;
using Toggl.Storage;
namespace Toggl.iOS.ViewControllers
{
public sealed partial class CalendarDayViewController : ReactiveViewController<CalendarDayViewModel>, IScrollableToTop
{
private const double minimumOffsetOfCurrentTimeIndicatorFromScreenEdge = 0.2;
private const double middleOfTheDay = 12;
private const float collectionViewDefaultInset = 20;
private const float additionalContentOffsetWhenContextualMenuIsVisible = 128;
private readonly ITimeService timeService;
private readonly IRxActionFactory rxActionFactory;
private readonly Action addOnboardingBadgeToReportsTab;
private bool contextualMenuInitialised;
private CalendarCollectionViewLayout layout;
private CalendarCollectionViewSource dataSource;
private CalendarCollectionViewEditItemHelper editItemHelper;
private CalendarCollectionViewCreateFromSpanHelper createFromSpanHelper;
private CalendarCollectionViewZoomHelper zoomHelper;
private CalendarCollectionViewContextualMenuDismissHelper tapToDismissHelper;
public float ScrollOffset => (float)CalendarCollectionView.ContentOffset.Y;
private readonly BehaviorRelay<bool> contextualMenuVisible;
private readonly BehaviorRelay<nfloat> runningTimeEntryCardHeight;
private readonly BehaviorRelay<string> timeTrackedOnDay;
private readonly BehaviorRelay<int> currentPageRelay;
private UIView calendarTimeEntryTooltip;
public CalendarDayViewController(CalendarDayViewModel viewModel,
BehaviorRelay<int> currentPageRelay,
BehaviorRelay<string> timeTrackedOnDay,
BehaviorRelay<bool> contextualMenuVisible,
BehaviorRelay<nfloat> runningTimeEntryCardHeight,
Action addOnboardingBadgeToReportsTab)
: base(viewModel, nameof(CalendarDayViewController))
{
Ensure.Argument.IsNotNull(ViewModel, nameof(ViewModel));
Ensure.Argument.IsNotNull(currentPageRelay, nameof(currentPageRelay));
Ensure.Argument.IsNotNull(timeTrackedOnDay, nameof(timeTrackedOnDay));
Ensure.Argument.IsNotNull(contextualMenuVisible, nameof(contextualMenuVisible));
Ensure.Argument.IsNotNull(runningTimeEntryCardHeight, nameof(runningTimeEntryCardHeight));
Ensure.Argument.IsNotNull(addOnboardingBadgeToReportsTab, nameof(addOnboardingBadgeToReportsTab));
timeService = IosDependencyContainer.Instance.TimeService;
rxActionFactory = IosDependencyContainer.Instance.RxActionFactory;
this.addOnboardingBadgeToReportsTab = addOnboardingBadgeToReportsTab;
this.currentPageRelay = currentPageRelay;
this.timeTrackedOnDay = timeTrackedOnDay;
this.contextualMenuVisible = contextualMenuVisible;
this.runningTimeEntryCardHeight = runningTimeEntryCardHeight;
}
public void SetScrollOffset(float scrollOffset)
{
CalendarCollectionView?.SetContentOffset(new CGPoint(0, scrollOffset), false);
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
var emptyStateText = new NSMutableAttributedString(Resources.CalendarEmptyStateMessage);
emptyStateText.AddAttributes(
new UIStringAttributes
{
ForegroundColor = ColorAssets.CustomGray,
StrokeColor = ColorAssets.TableBackground,
StrokeWidth = -3
},
new NSRange(0, emptyStateText.Length));
EmptyStateLabel.AttributedText = emptyStateText;
ViewModel.ContextualMenuViewModel.AttachView(this);
ContextualMenu.Layer.CornerRadius = 8;
ContextualMenu.Layer.ShadowColor = UIColor.Black.CGColor;
ContextualMenu.Layer.ShadowOpacity = 0.1f;
ContextualMenu.Layer.ShadowOffset = new CGSize(0, -2);
ContextualMenuBottonConstraint.Constant = -ContextualMenu.Frame.Height - 10;
ContextualMenuFadeView.FadeLeft = true;
ContextualMenuFadeView.FadeRight = true;
dataSource = new CalendarCollectionViewSource(
timeService,
CalendarCollectionView,
ViewModel.TimeOfDayFormat,
ViewModel.DurationFormat,
ViewModel.CalendarItems);
layout = new CalendarCollectionViewLayout(ViewModel.Date, timeService, dataSource);
editItemHelper = new CalendarCollectionViewEditItemHelper(CalendarCollectionView, timeService, rxActionFactory, dataSource, layout);
createFromSpanHelper = new CalendarCollectionViewCreateFromSpanHelper(CalendarCollectionView, dataSource, layout);
zoomHelper = new CalendarCollectionViewZoomHelper(CalendarCollectionView, layout);
tapToDismissHelper = new CalendarCollectionViewContextualMenuDismissHelper(CalendarCollectionView, dataSource);
CalendarCollectionView.SetCollectionViewLayout(layout, false);
CalendarCollectionView.Delegate = dataSource;
CalendarCollectionView.DataSource = dataSource;
//Onboarding
ViewModel.CalendarLinkingCompleted
.ObserveOn(IosDependencyContainer.Instance.SchedulerProvider.MainScheduler)
.Subscribe(_ => addOnboardingBadgeToReportsTab?.Invoke())
.DisposedBy(DisposeBag);
//Editing items
dataSource.ItemTapped
.Select(item => (CalendarItem?)item)
.Subscribe(ViewModel.ContextualMenuViewModel.OnCalendarItemUpdated.Inputs)
.DisposedBy(DisposeBag);
ViewModel.ContextualMenuViewModel.CalendarItemInEditMode
.Subscribe(editItemHelper.StartEditingItem.Inputs)
.DisposedBy(DisposeBag);
ViewModel.ContextualMenuViewModel.MenuVisible
.Where(isVisible => !isVisible)
.SelectUnit()
.Subscribe(editItemHelper.StopEditing.Inputs)
.DisposedBy(DisposeBag);
editItemHelper.ItemUpdated
.Subscribe(dataSource.UpdateItemView)
.DisposedBy(DisposeBag);
editItemHelper.ItemUpdated
.Select(item => (CalendarItem?)item)
.Subscribe(ViewModel.ContextualMenuViewModel.OnCalendarItemUpdated.Inputs)
.DisposedBy(DisposeBag);
ViewModel.ContextualMenuViewModel.DiscardChanges
.Subscribe(_ => editItemHelper.DiscardChanges())
.DisposedBy(DisposeBag);
ViewModel.ContextualMenuViewModel.DiscardChanges
.Subscribe(_ => createFromSpanHelper.DiscardChanges())
.DisposedBy(DisposeBag);
//Contextual menu
ViewModel.ContextualMenuViewModel.CurrentMenu
.Select(menu => menu.Actions)
.Subscribe(replaceContextualMenuActions)
.DisposedBy(DisposeBag);
ViewModel.ContextualMenuViewModel.MenuVisible
.Where(isVisible => isVisible)
.Subscribe(_ => showContextualMenu())
.DisposedBy(DisposeBag);
ViewModel.ContextualMenuViewModel.MenuVisible
.Where(isVisible => !isVisible)
.Subscribe(_ => dismissContextualMenu())
.DisposedBy(DisposeBag);
ViewModel.ContextualMenuViewModel.CalendarItemRemoved
.Subscribe(dataSource.RemoveItemView)
.DisposedBy(DisposeBag);
ViewModel.ContextualMenuViewModel.CalendarItemUpdated
.Subscribe(dataSource.UpdateItemView)
.DisposedBy(DisposeBag);
ContextualMenuCloseButton.Rx().Tap()
.Subscribe(_ => ViewModel.ContextualMenuViewModel.OnCalendarItemUpdated.Execute(null))
.DisposedBy(DisposeBag);
tapToDismissHelper.DidTapOnEmptySpace
.Subscribe(_ => ViewModel.ContextualMenuViewModel.OnCalendarItemUpdated.Execute(null))
.DisposedBy(DisposeBag);
ViewModel.ContextualMenuViewModel.TimeEntryPeriod
.Subscribe(ContextualMenuTimeEntryPeriodLabel.Rx().Text())
.DisposedBy(DisposeBag);
ViewModel.ContextualMenuViewModel.TimeEntryInfo
.Select(timeEntryInfo => timeEntryInfo.ToAttributedString(ContextualMenuTimeEntryDescriptionProjectTaskClientLabel.Font.CapHeight))
.Subscribe(ContextualMenuTimeEntryDescriptionProjectTaskClientLabel.Rx().AttributedText())
.DisposedBy(DisposeBag);
ViewModel.ContextualMenuViewModel.TimeEntryInfo
.Subscribe(_ => ViewModel.CalendarTimeEntryTooltipCondition.Dismiss())
.DisposedBy(DisposeBag);
ViewModel.TimeTrackedOnDay
.ReemitWhen(currentPageRelay.SelectUnit())
.Subscribe(notifyTotalDurationIfCurrentPage)
.DisposedBy(DisposeBag);
runningTimeEntryCardHeight
.Subscribe(_ => updateContentInset())
.DisposedBy(DisposeBag);
//Empty state
ViewModel.CalendarItems.Empty
.Throttle(TimeSpan.FromMilliseconds(1)) //Throttling prevents a small glitch, where the empty state view appears for a split second
.ObserveOn(IosDependencyContainer.Instance.SchedulerProvider.MainScheduler)
.Subscribe(updateEmptyStateVisibility)
.DisposedBy(DisposeBag);
CalendarCollectionView.LayoutIfNeeded();
dataSource.WillDisplayCellObservable
.CombineLatest(ViewModel.CalendarTimeEntryTooltipCondition.ConditionMet, (cell, conditionMet) => (cell, conditionMet))
.Subscribe(tuple => showCalendarTimeEntryTooltipIfNecessary(tuple.cell, tuple.conditionMet));
ViewModel.ContextualMenuViewModel.TimeEntryInfo
.Subscribe(_ => removeCalendarTimeEntryTooltip(TooltipDismissReason.ConditionMet))
.DisposedBy(DisposeBag);
}
private void showCalendarTimeEntryTooltipIfNecessary(UICollectionViewCell cell, bool shouldShow)
{
if (!shouldShow)
{
calendarTimeEntryTooltip?.RemoveFromSuperview();
calendarTimeEntryTooltip = null;
return;
}
if (calendarTimeEntryTooltip != null)
return;
if (cell is CalendarItemView calendarItemView&& calendarItemView.Item.Source != CalendarItemSource.TimeEntry)
return;
var (tooltip, tooltipPointsUpwards, tooltipArrow) = createCalendarEntryTooltip(cell);
calendarTimeEntryTooltip = tooltip;
calendarTimeEntryTooltip.Rx()
.Tap()
.Subscribe(_ => ViewModel.CalendarTimeEntryTooltipCondition.Dismiss())
.DisposedBy(DisposeBag);
View.AddSubview(tooltip);
var cellHasHorizontalNeighbours = cell.Frame.Right < CalendarCollectionView.Frame.Right - 16;
if (cellHasHorizontalNeighbours)
tooltipArrow.LeadingAnchor.ConstraintEqualTo(tooltip.LeadingAnchor, 14).Active = true;
else
tooltip.CenterXAnchor.ConstraintEqualTo(tooltipArrow.CenterXAnchor).Active = true;
if (tooltipPointsUpwards)
tooltip.TopAnchor.ConstraintEqualTo(cell.BottomAnchor).Active = true;
else
tooltip.BottomAnchor.ConstraintEqualTo(cell.TopAnchor).Active = true;
tooltip.WidthAnchor.ConstraintEqualTo(220).Active = true;
tooltipArrow.CenterXAnchor.ConstraintEqualTo(cell.CenterXAnchor).Active = true;
}
private void removeCalendarTimeEntryTooltip(TooltipDismissReason reason)
{
if (calendarTimeEntryTooltip == null) return;
calendarTimeEntryTooltip.RemoveFromSuperview();
calendarTimeEntryTooltip = null;
IosDependencyContainer.Instance.AnalyticsService.TooltipDismissed.Track(OnboardingConditionKey.CalendarTimeEntryTooltip, reason);
}
private (UIView tooltip, bool tooltipPointsUpwards, TriangleView tooltipArrow) createCalendarEntryTooltip(UICollectionViewCell cell)
{
var arrowHeight = 8;
var arrowWidth = 16;
var closeImageSize = 24;
var tooltip = new UIView();
tooltip.TranslatesAutoresizingMaskIntoConstraints = false;
var background = new UIView();
background.BackgroundColor = ColorAssets.DarkAccent;
background.Layer.CornerRadius = 8;
background.TranslatesAutoresizingMaskIntoConstraints = false;
var arrow = new TriangleView();
arrow.Color = ColorAssets.DarkAccent;
arrow.BackgroundColor = UIColor.Clear;
arrow.TranslatesAutoresizingMaskIntoConstraints = false;
var messageLabel = new UILabel();
messageLabel.Lines = 0;
messageLabel.TranslatesAutoresizingMaskIntoConstraints = false;
messageLabel.Font = UIFont.SystemFontOfSize(15, UIFontWeight.Semibold);
var attributes = new UIStringAttributes()
{
ParagraphStyle = new NSMutableParagraphStyle()
{
LineSpacing = 6
},
ForegroundColor = ColorAssets.AlwaysWhite
};
var messasgeString = new NSMutableAttributedString(Resources.HereIsYourTimeEntryInCalendarView);
messasgeString.AddAttributes(attributes, new NSRange(0, messasgeString.Length));
messageLabel.AttributedText = messasgeString;
var gotItLabel = new UILabel();
gotItLabel.Text = Resources.OkGotIt;
gotItLabel.TranslatesAutoresizingMaskIntoConstraints = false;
gotItLabel.Font = UIFont.SystemFontOfSize(15, UIFontWeight.Semibold);
gotItLabel.TextColor = ColorAssets.AlwaysWhite;
var closeImage = new UIImageView();
closeImage.Image = UIImage.FromBundle("x").ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate);
closeImage.TintColor = UIColor.White;
closeImage.ContentMode = UIViewContentMode.Center;
closeImage.TranslatesAutoresizingMaskIntoConstraints = false;
tooltip.AddSubview(arrow);
tooltip.AddSubview(background);
background.AddSubview(gotItLabel);
background.AddSubview(closeImage);
background.AddSubview(messageLabel);
//Background
background.LeadingAnchor.ConstraintEqualTo(tooltip.LeadingAnchor).Active = true;
background.TrailingAnchor.ConstraintEqualTo(tooltip.TrailingAnchor).Active = true;
var verticalSpaceNeeded = 150;
var verticalSpaceavailable = CalendarCollectionView.ContentSize.Height - cell.Frame.Bottom;
var tooltipPointsUpwards = verticalSpaceavailable >= verticalSpaceNeeded;
if (tooltipPointsUpwards)
{
arrow.Direction = TriangleView.TriangleDirection.Up;
arrow.TopAnchor.ConstraintEqualTo(tooltip.TopAnchor).Active = true;
background.TopAnchor.ConstraintEqualTo(arrow.BottomAnchor).Active = true;
background.BottomAnchor.ConstraintEqualTo(tooltip.BottomAnchor).Active = true;
}
else
{
arrow.Direction = TriangleView.TriangleDirection.Down;
background.TopAnchor.ConstraintEqualTo(tooltip.TopAnchor).Active = true;
background.BottomAnchor.ConstraintEqualTo(arrow.TopAnchor).Active = true;
arrow.BottomAnchor.ConstraintEqualTo(tooltip.BottomAnchor).Active = true;
}
//Arrow
arrow.WidthAnchor.ConstraintEqualTo(arrowWidth).Active = true;
arrow.HeightAnchor.ConstraintEqualTo(arrowHeight).Active = true;
//Message
messageLabel.TopAnchor.ConstraintEqualTo(background.TopAnchor, 12).Active = true;
messageLabel.LeadingAnchor.ConstraintEqualTo(background.LeadingAnchor, 14).Active = true;
messageLabel.TrailingAnchor.ConstraintEqualTo(background.TrailingAnchor, -28).Active = true;
messageLabel.BottomAnchor.ConstraintEqualTo(gotItLabel.TopAnchor, -10).Active = true;
//Got it
gotItLabel.TrailingAnchor.ConstraintEqualTo(background.TrailingAnchor, -22).Active = true;
gotItLabel.BottomAnchor.ConstraintEqualTo(background.BottomAnchor, -10).Active = true;
//Close icon
closeImage.TrailingAnchor.ConstraintEqualTo(background.TrailingAnchor).Active = true;
closeImage.TopAnchor.ConstraintEqualTo(background.TopAnchor).Active = true;
closeImage.WidthAnchor.ConstraintEqualTo(closeImageSize).Active = true;
closeImage.HeightAnchor.ConstraintEqualTo(closeImageSize).Active = true;
return (tooltip, tooltipPointsUpwards, arrow);
}
private void updateEmptyStateVisibility(bool noCalendarItemsExist)
{
EmptyStateView.Alpha = noCalendarItemsExist ? 1 : 0;
}
private void notifyTotalDurationIfCurrentPage(string durationString)
{
if (currentPageRelay.Value == View.Tag)
{
timeTrackedOnDay.Accept(durationString);
}
}
public override void ViewDidLayoutSubviews()
{
base.ViewDidLayoutSubviews();
updateContentInset();
layout.InvalidateLayoutForVisibleItems();
if (contextualMenuInitialised) return;
contextualMenuInitialised = true;
ContextualMenuBottonConstraint.Constant = -ContextualMenu.Frame.Height - 10;
ContextualMenu.Layer.ShadowPath = CGPath.FromRect(ContextualMenu.Layer.Bounds);
View.LayoutIfNeeded();
updateemptyStateViewCentering();
}
private void updateemptyStateViewCentering()
{
var leftCenteringPoint = CalendarCollectionViewLayout.LeftPadding + layout.SideMargin;
var rightCenteringPoint = CalendarCollectionView.Frame.Width - layout.RightPadding - layout.SideMargin;
var currentCenter = CalendarCollectionView.Center.X;
var newCenter = (rightCenteringPoint - leftCenteringPoint) / 2 + leftCenteringPoint;
EmptyStateCenterConstraint.Constant = newCenter - currentCenter;
}
private void replaceContextualMenuActions(IImmutableList<CalendarMenuAction> actions)
{
if (actions == null || actions.Count == 0) return;
ContextualMenuStackView.ArrangedSubviews.ForEach(view => view.RemoveFromSuperview());
actions.Select(action => new CalendarContextualMenuActionView(action)
{
TranslatesAutoresizingMaskIntoConstraints = false
})
.Do(ContextualMenuStackView.AddArrangedSubview);
}
private void showContextualMenu()
{
if (!contextualMenuInitialised) return;
contextualMenuVisible?.Accept(true);
View.LayoutIfNeeded();
ContextualMenuBottonConstraint.Constant = 0;
AnimationExtensions.Animate(
Animation.Timings.EnterTiming,
Animation.Curves.EaseOut,
() => View.LayoutIfNeeded(),
scrollUpIfEditingItemIsCoveredByContextualMenu);
}
private void dismissContextualMenu()
{
if (!contextualMenuInitialised) return;
ContextualMenuBottonConstraint.Constant = -ContextualMenu.Frame.Height - 10;
AnimationExtensions.Animate(
Animation.Timings.EnterTiming,
Animation.Curves.EaseOut,
() => View.LayoutIfNeeded(),
() =>
{
contextualMenuVisible?.Accept(false);
updateContentInset(true);
});
}
private void scrollUpIfEditingItemIsCoveredByContextualMenu()
{
var editingItemFrame = dataSource.FrameOfEditingItem();
if (editingItemFrame == null) return;
var editingItemTop = editingItemFrame.Value.Top - CalendarCollectionView.ContentOffset.Y;
var shouldScrollUp = ContextualMenu.Frame.Top <= editingItemTop + additionalContentOffsetWhenContextualMenuIsVisible;
if (!shouldScrollUp) return;
var scrollDelta = editingItemTop - ContextualMenu.Frame.Top - additionalContentOffsetWhenContextualMenuIsVisible;
var newContentOffset = new CGPoint(
CalendarCollectionView.ContentOffset.X,
CalendarCollectionView.ContentOffset.Y - scrollDelta);
CalendarCollectionView.SetContentOffset(newContentOffset, true);
}
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
updateContentInset();
layout.InvalidateCurrentTimeLayout();
}
private void updateContentInset(bool animate = false)
{
var topInset = collectionViewDefaultInset;
var sideInset = 0;
var bottomInset = contextualMenuVisible.Value
? collectionViewDefaultInset * 2 + ContextualMenu.Frame.Height
: collectionViewDefaultInset * 2;
bottomInset += runningTimeEntryCardHeight.Value;
if (animate)
{
AnimationExtensions.Animate(
Animation.Timings.EnterTiming,
Animation.Curves.EaseOut,
() => CalendarCollectionView.ContentInset = new UIEdgeInsets(
topInset, sideInset, bottomInset, sideInset)
);
}
else
{
CalendarCollectionView.ContentInset = new UIEdgeInsets(
topInset, sideInset, bottomInset, sideInset);
}
}
public override void ViewWillTransitionToSize(CGSize toSize, IUIViewControllerTransitionCoordinator coordinator)
{
base.ViewWillTransitionToSize(toSize, coordinator);
updateContentInset();
}
public void ScrollToTop()
{
var point = layout.PointAtDate(timeService.CurrentDateTime);
CalendarCollectionView?.SetContentOffset(point, true);
}
public void SetGoodScrollPoint()
{
var frameHeight =
CalendarCollectionView.Frame.Height
- CalendarCollectionView.ContentInset.Top
- CalendarCollectionView.ContentInset.Bottom;
var hoursOnScreen = frameHeight / (CalendarCollectionView.ContentSize.Height / 24);
var centeredHour = calculateCenteredHour(timeService.CurrentDateTime.ToLocalTime().TimeOfDay.TotalHours, hoursOnScreen);
var offsetY = (centeredHour / 24) * CalendarCollectionView.ContentSize.Height - (frameHeight / 2);
var scrollPointY = offsetY.Clamp(0, CalendarCollectionView.ContentSize.Height - frameHeight);
var offset = new CGPoint(0, scrollPointY);
CalendarCollectionView.SetContentOffset(offset, false);
}
private static double calculateCenteredHour(double currentHour, double hoursOnScreen)
{
var hoursPerHalfOfScreen = hoursOnScreen / 2;
var minimumOffset = hoursOnScreen * minimumOffsetOfCurrentTimeIndicatorFromScreenEdge;
var center = (currentHour + middleOfTheDay) / 2;
if (currentHour < center - hoursPerHalfOfScreen + minimumOffset)
{
// the current time indicator would be too close to the top edge of the screen
return currentHour - minimumOffset + hoursPerHalfOfScreen;
}
if (currentHour > center + hoursPerHalfOfScreen - minimumOffset)
{
// the current time indicator would be too close to the bottom edge of the screen
return currentHour + minimumOffset - hoursPerHalfOfScreen;
}
return center;
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Linq;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Generic;
using Newtonsoft.Json4.Linq;
using Newtonsoft.Json4.Utilities;
using Newtonsoft.Json4.Serialization;
namespace Newtonsoft.Json4.Schema
{
/// <summary>
/// Generates a <see cref="JsonSchema"/> from a specified <see cref="Type"/>.
/// </summary>
public class JsonSchemaGenerator
{
/// <summary>
/// Gets or sets how undefined schemas are handled by the serializer.
/// </summary>
public UndefinedSchemaIdHandling UndefinedSchemaIdHandling { get; set; }
private IContractResolver _contractResolver;
/// <summary>
/// Gets or sets the contract resolver.
/// </summary>
/// <value>The contract resolver.</value>
public IContractResolver ContractResolver
{
get
{
if (_contractResolver == null)
return DefaultContractResolver.Instance;
return _contractResolver;
}
set { _contractResolver = value; }
}
private class TypeSchema
{
public Type Type { get; private set; }
public JsonSchema Schema { get; private set;}
public TypeSchema(Type type, JsonSchema schema)
{
ValidationUtils.ArgumentNotNull(type, "type");
ValidationUtils.ArgumentNotNull(schema, "schema");
Type = type;
Schema = schema;
}
}
private JsonSchemaResolver _resolver;
private readonly IList<TypeSchema> _stack = new List<TypeSchema>();
private JsonSchema _currentSchema;
private JsonSchema CurrentSchema
{
get { return _currentSchema; }
}
private void Push(TypeSchema typeSchema)
{
_currentSchema = typeSchema.Schema;
_stack.Add(typeSchema);
_resolver.LoadedSchemas.Add(typeSchema.Schema);
}
private TypeSchema Pop()
{
TypeSchema popped = _stack[_stack.Count - 1];
_stack.RemoveAt(_stack.Count - 1);
TypeSchema newValue = _stack.LastOrDefault();
if (newValue != null)
{
_currentSchema = newValue.Schema;
}
else
{
_currentSchema = null;
}
return popped;
}
/// <summary>
/// Generate a <see cref="JsonSchema"/> from the specified type.
/// </summary>
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
public JsonSchema Generate(Type type)
{
return Generate(type, new JsonSchemaResolver(), false);
}
/// <summary>
/// Generate a <see cref="JsonSchema"/> from the specified type.
/// </summary>
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <param name="resolver">The <see cref="JsonSchemaResolver"/> used to resolve schema references.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
public JsonSchema Generate(Type type, JsonSchemaResolver resolver)
{
return Generate(type, resolver, false);
}
/// <summary>
/// Generate a <see cref="JsonSchema"/> from the specified type.
/// </summary>
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <param name="rootSchemaNullable">Specify whether the generated root <see cref="JsonSchema"/> will be nullable.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
public JsonSchema Generate(Type type, bool rootSchemaNullable)
{
return Generate(type, new JsonSchemaResolver(), rootSchemaNullable);
}
/// <summary>
/// Generate a <see cref="JsonSchema"/> from the specified type.
/// </summary>
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <param name="resolver">The <see cref="JsonSchemaResolver"/> used to resolve schema references.</param>
/// <param name="rootSchemaNullable">Specify whether the generated root <see cref="JsonSchema"/> will be nullable.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
public JsonSchema Generate(Type type, JsonSchemaResolver resolver, bool rootSchemaNullable)
{
ValidationUtils.ArgumentNotNull(type, "type");
ValidationUtils.ArgumentNotNull(resolver, "resolver");
_resolver = resolver;
return GenerateInternal(type, (!rootSchemaNullable) ? Required.Always : Required.Default, false);
}
private string GetTitle(Type type)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type);
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Title))
return containerAttribute.Title;
return null;
}
private string GetDescription(Type type)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type);
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Description))
return containerAttribute.Description;
#if !PocketPC
DescriptionAttribute descriptionAttribute = ReflectionUtils.GetAttribute<DescriptionAttribute>(type);
if (descriptionAttribute != null)
return descriptionAttribute.Description;
#endif
return null;
}
private string GetTypeId(Type type, bool explicitOnly)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type);
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Id))
return containerAttribute.Id;
if (explicitOnly)
return null;
switch (UndefinedSchemaIdHandling)
{
case UndefinedSchemaIdHandling.UseTypeName:
return type.FullName;
case UndefinedSchemaIdHandling.UseAssemblyQualifiedName:
return type.AssemblyQualifiedName;
default:
return null;
}
}
private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required)
{
ValidationUtils.ArgumentNotNull(type, "type");
string resolvedId = GetTypeId(type, false);
string explicitId = GetTypeId(type, true);
if (!string.IsNullOrEmpty(resolvedId))
{
JsonSchema resolvedSchema = _resolver.GetSchema(resolvedId);
if (resolvedSchema != null)
{
// resolved schema is not null but referencing member allows nulls
// change resolved schema to allow nulls. hacky but what are ya gonna do?
if (valueRequired != Required.Always && !HasFlag(resolvedSchema.Type, JsonSchemaType.Null))
resolvedSchema.Type |= JsonSchemaType.Null;
if (required && resolvedSchema.Required != true)
resolvedSchema.Required = true;
return resolvedSchema;
}
}
// test for unresolved circular reference
if (_stack.Any(tc => tc.Type == type))
{
throw new Exception("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.".FormatWith(CultureInfo.InvariantCulture, type));
}
JsonContract contract = ContractResolver.ResolveContract(type);
JsonConverter converter;
if ((converter = contract.Converter) != null || (converter = contract.InternalConverter) != null)
{
JsonSchema converterSchema = converter.GetSchema();
if (converterSchema != null)
return converterSchema;
}
Push(new TypeSchema(type, new JsonSchema()));
if (explicitId != null)
CurrentSchema.Id = explicitId;
if (required)
CurrentSchema.Required = true;
CurrentSchema.Title = GetTitle(type);
CurrentSchema.Description = GetDescription(type);
if (converter != null)
{
// todo: Add GetSchema to JsonConverter and use here?
CurrentSchema.Type = JsonSchemaType.Any;
}
else
{
switch (contract.ContractType)
{
case JsonContractType.Object:
CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);
CurrentSchema.Id = GetTypeId(type, false);
GenerateObjectSchema(type, (JsonObjectContract) contract);
break;
case JsonContractType.Array:
CurrentSchema.Type = AddNullType(JsonSchemaType.Array, valueRequired);
CurrentSchema.Id = GetTypeId(type, false);
JsonArrayAttribute arrayAttribute = JsonTypeReflector.GetJsonContainerAttribute(type) as JsonArrayAttribute;
bool allowNullItem = (arrayAttribute == null || arrayAttribute.AllowNullItems);
Type collectionItemType = ReflectionUtils.GetCollectionItemType(type);
if (collectionItemType != null)
{
CurrentSchema.Items = new List<JsonSchema>();
CurrentSchema.Items.Add(GenerateInternal(collectionItemType, (!allowNullItem) ? Required.Always : Required.Default, false));
}
break;
case JsonContractType.Primitive:
CurrentSchema.Type = GetJsonSchemaType(type, valueRequired);
if (CurrentSchema.Type == JsonSchemaType.Integer && type.IsEnum && !type.IsDefined(typeof (FlagsAttribute), true))
{
CurrentSchema.Enum = new List<JToken>();
CurrentSchema.Options = new Dictionary<JToken, string>();
EnumValues<long> enumValues = EnumUtils.GetNamesAndValues<long>(type);
foreach (EnumValue<long> enumValue in enumValues)
{
JToken value = JToken.FromObject(enumValue.Value);
CurrentSchema.Enum.Add(value);
CurrentSchema.Options.Add(value, enumValue.Name);
}
}
break;
case JsonContractType.String:
JsonSchemaType schemaType = (!ReflectionUtils.IsNullable(contract.UnderlyingType))
? JsonSchemaType.String
: AddNullType(JsonSchemaType.String, valueRequired);
CurrentSchema.Type = schemaType;
break;
case JsonContractType.Dictionary:
CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);
Type keyType;
Type valueType;
ReflectionUtils.GetDictionaryKeyValueTypes(type, out keyType, out valueType);
if (keyType != null)
{
// can be converted to a string
if (typeof (IConvertible).IsAssignableFrom(keyType))
{
CurrentSchema.AdditionalProperties = GenerateInternal(valueType, Required.Default, false);
}
}
break;
#if !SILVERLIGHT && !PocketPC
case JsonContractType.Serializable:
CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);
CurrentSchema.Id = GetTypeId(type, false);
GenerateISerializableContract(type, (JsonISerializableContract) contract);
break;
#endif
#if !(NET35 || NET20 || WINDOWS_PHONE)
case JsonContractType.Dynamic:
#endif
case JsonContractType.Linq:
CurrentSchema.Type = JsonSchemaType.Any;
break;
default:
throw new Exception("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, contract));
}
}
return Pop().Schema;
}
private JsonSchemaType AddNullType(JsonSchemaType type, Required valueRequired)
{
if (valueRequired != Required.Always)
return type | JsonSchemaType.Null;
return type;
}
private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag)
{
return ((value & flag) == flag);
}
private void GenerateObjectSchema(Type type, JsonObjectContract contract)
{
CurrentSchema.Properties = new Dictionary<string, JsonSchema>();
foreach (JsonProperty property in contract.Properties)
{
if (!property.Ignored)
{
bool optional = property.NullValueHandling == NullValueHandling.Ignore ||
HasFlag(property.DefaultValueHandling.GetValueOrDefault(), DefaultValueHandling.Ignore) ||
property.ShouldSerialize != null ||
property.GetIsSpecified != null;
JsonSchema propertySchema = GenerateInternal(property.PropertyType, property.Required, !optional);
if (property.DefaultValue != null)
propertySchema.Default = JToken.FromObject(property.DefaultValue);
CurrentSchema.Properties.Add(property.PropertyName, propertySchema);
}
}
if (type.IsSealed)
CurrentSchema.AllowAdditionalProperties = false;
}
#if !SILVERLIGHT && !PocketPC
private void GenerateISerializableContract(Type type, JsonISerializableContract contract)
{
CurrentSchema.AllowAdditionalProperties = true;
}
#endif
internal static bool HasFlag(JsonSchemaType? value, JsonSchemaType flag)
{
// default value is Any
if (value == null)
return true;
bool match = ((value & flag) == flag);
if (match)
return true;
// integer is a subset of float
if (value == JsonSchemaType.Float && flag == JsonSchemaType.Integer)
return true;
return false;
}
private JsonSchemaType GetJsonSchemaType(Type type, Required valueRequired)
{
JsonSchemaType schemaType = JsonSchemaType.None;
if (valueRequired != Required.Always && ReflectionUtils.IsNullable(type))
{
schemaType = JsonSchemaType.Null;
if (ReflectionUtils.IsNullableType(type))
type = Nullable.GetUnderlyingType(type);
}
TypeCode typeCode = Type.GetTypeCode(type);
switch (typeCode)
{
case TypeCode.Empty:
case TypeCode.Object:
return schemaType | JsonSchemaType.String;
case TypeCode.DBNull:
return schemaType | JsonSchemaType.Null;
case TypeCode.Boolean:
return schemaType | JsonSchemaType.Boolean;
case TypeCode.Char:
return schemaType | JsonSchemaType.String;
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
return schemaType | JsonSchemaType.Integer;
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return schemaType | JsonSchemaType.Float;
// convert to string?
case TypeCode.DateTime:
return schemaType | JsonSchemaType.String;
case TypeCode.String:
return schemaType | JsonSchemaType.String;
default:
throw new Exception("Unexpected type code '{0}' for type '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeCode, type));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Extensions.DependencyModel;
namespace Microsoft.DotNet.Cli.Utils
{
public class DepsJsonCommandResolver : ICommandResolver
{
private static readonly string[] s_extensionPreferenceOrder = new[]
{
"",
".exe",
".dll"
};
private string _nugetPackageRoot;
private Muxer _muxer;
public DepsJsonCommandResolver(string nugetPackageRoot)
: this(new Muxer(), nugetPackageRoot) { }
public DepsJsonCommandResolver(Muxer muxer, string nugetPackageRoot)
{
_muxer = muxer;
_nugetPackageRoot = nugetPackageRoot;
}
public CommandSpec Resolve(CommandResolverArguments commandResolverArguments)
{
if (commandResolverArguments.CommandName == null
|| commandResolverArguments.DepsJsonFile == null)
{
return null;
}
return ResolveFromDepsJsonFile(
commandResolverArguments.CommandName,
commandResolverArguments.CommandArguments.OrEmptyIfNull(),
commandResolverArguments.DepsJsonFile);
}
private CommandSpec ResolveFromDepsJsonFile(
string commandName,
IEnumerable<string> commandArgs,
string depsJsonFile)
{
var dependencyContext = LoadDependencyContextFromFile(depsJsonFile);
var commandPath = GetCommandPathFromDependencyContext(commandName, dependencyContext);
if (commandPath == null)
{
return null;
}
return CreateCommandSpecUsingMuxerIfPortable(
commandPath,
commandArgs,
depsJsonFile,
CommandResolutionStrategy.DepsFile,
_nugetPackageRoot,
IsPortableApp(commandPath));
}
public DependencyContext LoadDependencyContextFromFile(string depsJsonFile)
{
DependencyContext dependencyContext = null;
DependencyContextJsonReader contextReader = new DependencyContextJsonReader();
using (var contextStream = File.OpenRead(depsJsonFile))
{
dependencyContext = contextReader.Read(contextStream);
}
return dependencyContext;
}
public string GetCommandPathFromDependencyContext(string commandName, DependencyContext dependencyContext)
{
var commandCandidates = new List<CommandCandidate>();
var assemblyCommandCandidates = GetCommandCandidates(
commandName,
dependencyContext,
CommandCandidateType.RuntimeCommandCandidate);
var nativeCommandCandidates = GetCommandCandidates(
commandName,
dependencyContext,
CommandCandidateType.NativeCommandCandidate);
commandCandidates.AddRange(assemblyCommandCandidates);
commandCandidates.AddRange(nativeCommandCandidates);
var command = ChooseCommandCandidate(commandCandidates);
return command?.GetAbsoluteCommandPath(_nugetPackageRoot);
}
private IEnumerable<CommandCandidate> GetCommandCandidates(
string commandName,
DependencyContext dependencyContext,
CommandCandidateType commandCandidateType)
{
var commandCandidates = new List<CommandCandidate>();
foreach (var runtimeLibrary in dependencyContext.RuntimeLibraries)
{
IEnumerable<RuntimeAssetGroup> runtimeAssetGroups = null;
if (commandCandidateType == CommandCandidateType.NativeCommandCandidate)
{
runtimeAssetGroups = runtimeLibrary.NativeLibraryGroups;
}
else if (commandCandidateType == CommandCandidateType.RuntimeCommandCandidate)
{
runtimeAssetGroups = runtimeLibrary.RuntimeAssemblyGroups;
}
commandCandidates.AddRange(GetCommandCandidatesFromRuntimeAssetGroups(
commandName,
runtimeAssetGroups,
runtimeLibrary.Name,
runtimeLibrary.Version));
}
return commandCandidates;
}
private IEnumerable<CommandCandidate> GetCommandCandidatesFromRuntimeAssetGroups(
string commandName,
IEnumerable<RuntimeAssetGroup> runtimeAssetGroups,
string PackageName,
string PackageVersion)
{
var candidateAssetGroups = runtimeAssetGroups
.Where(r => r.Runtime == string.Empty)
.Where(a =>
a.AssetPaths.Any(p =>
Path.GetFileNameWithoutExtension(p).Equals(commandName, StringComparison.OrdinalIgnoreCase)));
var commandCandidates = new List<CommandCandidate>();
foreach (var candidateAssetGroup in candidateAssetGroups)
{
var candidateAssetPaths = candidateAssetGroup.AssetPaths.Where(
p => Path.GetFileNameWithoutExtension(p)
.Equals(commandName, StringComparison.OrdinalIgnoreCase));
foreach (var candidateAssetPath in candidateAssetPaths)
{
commandCandidates.Add(new CommandCandidate
{
PackageName = PackageName,
PackageVersion = PackageVersion,
RelativeCommandPath = candidateAssetPath
});
}
}
return commandCandidates;
}
private CommandCandidate ChooseCommandCandidate(IEnumerable<CommandCandidate> commandCandidates)
{
foreach (var extension in s_extensionPreferenceOrder)
{
var candidate = commandCandidates
.FirstOrDefault(p => Path.GetExtension(p.RelativeCommandPath)
.Equals(extension, StringComparison.OrdinalIgnoreCase));
if (candidate != null)
{
return candidate;
}
}
return null;
}
private CommandSpec CreateCommandSpecUsingMuxerIfPortable(
string commandPath,
IEnumerable<string> commandArgs,
string depsJsonFile,
CommandResolutionStrategy commandResolutionStrategy,
string nugetPackagesRoot,
bool isPortable)
{
var depsFileArguments = GetDepsFileArguments(depsJsonFile);
var additionalProbingPathArguments = GetAdditionalProbingPathArguments();
var muxerArgs = new List<string>();
muxerArgs.Add("exec");
muxerArgs.AddRange(depsFileArguments);
muxerArgs.AddRange(additionalProbingPathArguments);
muxerArgs.Add(commandPath);
muxerArgs.AddRange(commandArgs);
var escapedArgString = ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart(muxerArgs);
return new CommandSpec(_muxer.MuxerPath, escapedArgString, commandResolutionStrategy);
}
private bool IsPortableApp(string commandPath)
{
var commandDir = Path.GetDirectoryName(commandPath);
var runtimeConfigPath = Directory.EnumerateFiles(commandDir)
.FirstOrDefault(x => x.EndsWith("runtimeconfig.json"));
if (runtimeConfigPath == null)
{
return false;
}
var runtimeConfig = new RuntimeConfig(runtimeConfigPath);
return runtimeConfig.IsPortable;
}
private IEnumerable<string> GetDepsFileArguments(string depsJsonFile)
{
return new[] { "--depsfile", depsJsonFile };
}
private IEnumerable<string> GetAdditionalProbingPathArguments()
{
return new[] { "--additionalProbingPath", _nugetPackageRoot };
}
private class CommandCandidate
{
public string PackageName { get; set; }
public string PackageVersion { get; set; }
public string RelativeCommandPath { get; set; }
public string GetAbsoluteCommandPath(string nugetPackageRoot)
{
return Path.Combine(
nugetPackageRoot.Replace('/', Path.DirectorySeparatorChar),
PackageName.Replace('/', Path.DirectorySeparatorChar),
PackageVersion.Replace('/', Path.DirectorySeparatorChar),
RelativeCommandPath.Replace('/', Path.DirectorySeparatorChar));
}
}
private enum CommandCandidateType
{
NativeCommandCandidate,
RuntimeCommandCandidate
}
}
}
| |
#region License
// Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com>
//
// 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.Data;
using FluentMigrator.Expressions;
using FluentMigrator.Infrastructure;
using FluentMigrator.Model;
namespace FluentMigrator.Builders.Create.Table
{
public class CreateTableExpressionBuilder : ExpressionBuilderWithColumnTypesBase<CreateTableExpression, ICreateTableColumnOptionOrWithColumnSyntax>,
ICreateTableWithColumnOrSchemaSyntax,
ICreateTableColumnAsTypeSyntax,
ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax
{
private readonly IMigrationContext _context;
public CreateTableExpressionBuilder(CreateTableExpression expression, IMigrationContext context)
: base(expression)
{
_context = context;
}
public ColumnDefinition CurrentColumn { get; set; }
public ForeignKeyDefinition CurrentForeignKey { get; set; }
public ICreateTableWithColumnSyntax InSchema(string schemaName)
{
Expression.SchemaName = schemaName;
return this;
}
public ICreateTableColumnAsTypeSyntax WithColumn(string name)
{
var column = new ColumnDefinition {Name = name, TableName = Expression.TableName, ModificationType = ColumnModificationType.Create};
Expression.Columns.Add(column);
CurrentColumn = column;
return this;
}
public ICreateTableColumnOptionOrWithColumnSyntax WithDefault(SystemMethods method)
{
CurrentColumn.DefaultValue = method;
return this;
}
public ICreateTableColumnOptionOrWithColumnSyntax WithDefaultValue(object value)
{
CurrentColumn.DefaultValue = value;
return this;
}
public ICreateTableColumnOptionOrWithColumnSyntax Identity()
{
CurrentColumn.IsIdentity = true;
return this;
}
public ICreateTableColumnOptionOrWithColumnSyntax Indexed()
{
return Indexed(null);
}
public ICreateTableColumnOptionOrWithColumnSyntax Indexed(string indexName)
{
CurrentColumn.IsIndexed = true;
var index = new CreateIndexExpression
{
Index = new IndexDefinition
{
Name = indexName,
SchemaName = Expression.SchemaName,
TableName = Expression.TableName
}
};
index.Index.Columns.Add(new IndexColumnDefinition
{
Name = CurrentColumn.Name
});
_context.Expressions.Add(index);
return this;
}
public ICreateTableColumnOptionOrWithColumnSyntax PrimaryKey()
{
CurrentColumn.IsPrimaryKey = true;
return this;
}
public ICreateTableColumnOptionOrWithColumnSyntax PrimaryKey(string primaryKeyName)
{
CurrentColumn.IsPrimaryKey = true;
CurrentColumn.PrimaryKeyName = primaryKeyName;
return this;
}
public ICreateTableColumnOptionOrWithColumnSyntax Nullable()
{
CurrentColumn.IsNullable = true;
return this;
}
public ICreateTableColumnOptionOrWithColumnSyntax NotNullable()
{
CurrentColumn.IsNullable = false;
return this;
}
public ICreateTableColumnOptionOrWithColumnSyntax Unique()
{
return Unique(null);
}
public ICreateTableColumnOptionOrWithColumnSyntax Unique(string indexName)
{
CurrentColumn.IsUnique = true;
var index = new CreateIndexExpression
{
Index = new IndexDefinition
{
Name = indexName,
SchemaName = Expression.SchemaName,
TableName = Expression.TableName,
IsUnique = true
}
};
index.Index.Columns.Add(new IndexColumnDefinition
{
Name = CurrentColumn.Name
});
_context.Expressions.Add(index);
return this;
}
public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax ForeignKey(string primaryTableName, string primaryColumnName)
{
return ForeignKey(null, null, primaryTableName, primaryColumnName);
}
public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax ForeignKey(string foreignKeyName, string primaryTableName, string primaryColumnName)
{
return ForeignKey(foreignKeyName, null, primaryTableName, primaryColumnName);
}
public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax ForeignKey(string foreignKeyName, string primaryTableSchema,
string primaryTableName, string primaryColumnName)
{
CurrentColumn.IsForeignKey = true;
var fk = new CreateForeignKeyExpression
{
ForeignKey = new ForeignKeyDefinition
{
Name = foreignKeyName,
PrimaryTable = primaryTableName,
PrimaryTableSchema = primaryTableSchema,
ForeignTable = Expression.TableName,
ForeignTableSchema = Expression.SchemaName
}
};
fk.ForeignKey.PrimaryColumns.Add(primaryColumnName);
fk.ForeignKey.ForeignColumns.Add(CurrentColumn.Name);
_context.Expressions.Add(fk);
CurrentForeignKey = fk.ForeignKey;
return this;
}
public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax ReferencedBy(string foreignTableName, string foreignColumnName)
{
return ReferencedBy(null, null, foreignTableName, foreignColumnName);
}
public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax ReferencedBy(string foreignKeyName, string foreignTableName,
string foreignColumnName)
{
return ReferencedBy(foreignKeyName, null, foreignTableName, foreignColumnName);
}
public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax ReferencedBy(string foreignKeyName, string foreignTableSchema,
string foreignTableName, string foreignColumnName)
{
var fk = new CreateForeignKeyExpression
{
ForeignKey = new ForeignKeyDefinition
{
Name = foreignKeyName,
PrimaryTable = Expression.TableName,
PrimaryTableSchema = Expression.SchemaName,
ForeignTable = foreignTableName,
ForeignTableSchema = foreignTableSchema
}
};
fk.ForeignKey.PrimaryColumns.Add(CurrentColumn.Name);
fk.ForeignKey.ForeignColumns.Add(foreignColumnName);
_context.Expressions.Add(fk);
CurrentForeignKey = fk.ForeignKey;
return this;
}
public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax ForeignKey()
{
CurrentColumn.IsForeignKey = true;
return this;
}
[Obsolete("Please use ReferencedBy syntax. This method will be removed in the next version")]
public ICreateTableColumnOptionOrWithColumnSyntax References(string foreignKeyName, string foreignTableName, IEnumerable<string> foreignColumnNames)
{
return References(foreignKeyName, null, foreignTableName, foreignColumnNames);
}
[Obsolete("Please use ReferencedBy syntax. This method will be removed in the next version")]
public ICreateTableColumnOptionOrWithColumnSyntax References(string foreignKeyName, string foreignTableSchema, string foreignTableName,
IEnumerable<string> foreignColumnNames)
{
var fk = new CreateForeignKeyExpression
{
ForeignKey = new ForeignKeyDefinition
{
Name = foreignKeyName,
PrimaryTable = Expression.TableName,
PrimaryTableSchema = Expression.SchemaName,
ForeignTable = foreignTableName,
ForeignTableSchema = foreignTableSchema
}
};
fk.ForeignKey.PrimaryColumns.Add(CurrentColumn.Name);
foreach (var foreignColumnName in foreignColumnNames)
fk.ForeignKey.ForeignColumns.Add(foreignColumnName);
_context.Expressions.Add(fk);
return this;
}
public override ColumnDefinition GetColumnForType()
{
return CurrentColumn;
}
public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax OnDelete(Rule rule)
{
CurrentForeignKey.OnDelete = rule;
return this;
}
public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax OnUpdate(Rule rule)
{
CurrentForeignKey.OnUpdate = rule;
return this;
}
public ICreateTableColumnOptionOrWithColumnSyntax OnDeleteOrUpdate(Rule rule)
{
OnDelete(rule);
OnUpdate(rule);
return this;
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Web.Razor;
using JabbR.Infrastructure;
using Microsoft.CSharp;
namespace JabbR.Services
{
public class RazorEmailTemplateEngine : IEmailTemplateEngine
{
public const string DefaultSharedTemplateSuffix = "";
public const string DefaultHtmlTemplateSuffix = "html";
public const string DefaultTextTemplateSuffix = "text";
private const string NamespaceName = "JabbR.Views.EmailTemplates";
private static readonly string[] _referencedAssemblies = BuildReferenceList().ToArray();
private static readonly RazorTemplateEngine _razorEngine = CreateRazorEngine();
private static readonly Dictionary<string, IDictionary<string, Type>> _typeMapping = new Dictionary<string, IDictionary<string, Type>>(StringComparer.OrdinalIgnoreCase);
private static readonly ReaderWriterLockSlim _syncLock = new ReaderWriterLockSlim();
private readonly IEmailTemplateContentReader _contentReader;
private readonly string _sharedTemplateSuffix;
private readonly string _htmlTemplateSuffix;
private readonly string _textTemplateSuffix;
private readonly IDictionary<string, string> _templateSuffixes;
public RazorEmailTemplateEngine(IEmailTemplateContentReader contentReader)
: this(contentReader, DefaultSharedTemplateSuffix, DefaultHtmlTemplateSuffix, DefaultTextTemplateSuffix)
{
_contentReader = contentReader;
}
public RazorEmailTemplateEngine(IEmailTemplateContentReader contentReader, string sharedTemplateSuffix, string htmlTemplateSuffix, string textTemplateSuffix)
{
if (contentReader == null)
{
throw new ArgumentNullException("contentReader");
}
_contentReader = contentReader;
_sharedTemplateSuffix = sharedTemplateSuffix;
_htmlTemplateSuffix = htmlTemplateSuffix;
_textTemplateSuffix = textTemplateSuffix;
_templateSuffixes = new Dictionary<string, string>
{
{ _sharedTemplateSuffix, String.Empty },
{ _htmlTemplateSuffix, ContentTypes.Html },
{ _textTemplateSuffix, ContentTypes.Text }
};
}
public Email RenderTemplate(string templateName, object model = null)
{
if (String.IsNullOrWhiteSpace(templateName))
{
throw new System.ArgumentException(String.Format(System.Globalization.CultureInfo.CurrentUICulture, "\"{0}\" cannot be blank.", "templateName"));
}
var templates = CreateTemplateInstances(templateName);
foreach (var pair in templates)
{
pair.Value.SetModel(CreateModel(model));
pair.Value.Execute();
}
var mail = new Email();
templates.SelectMany(x => x.Value.To)
.Distinct(StringComparer.OrdinalIgnoreCase)
.Each(email => mail.To.Add(email));
templates.SelectMany(x => x.Value.ReplyTo)
.Distinct(StringComparer.OrdinalIgnoreCase)
.Each(email => mail.ReplyTo.Add(email));
templates.SelectMany(x => x.Value.Bcc)
.Distinct(StringComparer.OrdinalIgnoreCase)
.Each(email => mail.Bcc.Add(email));
templates.SelectMany(x => x.Value.CC)
.Distinct(StringComparer.OrdinalIgnoreCase)
.Each(email => mail.CC.Add(email));
IEmailTemplate template = null;
// text template (.text.cshtml file)
if (templates.TryGetValue(ContentTypes.Text, out template))
{
SetProperties(template, mail, body => { mail.TextBody = body; });
}
// html template (.html.cshtml file)
if (templates.TryGetValue(ContentTypes.Html, out template))
{
SetProperties(template, mail, body => { mail.HtmlBody = body; });
}
// shared template (.cshtml file)
if (templates.TryGetValue(String.Empty, out template))
{
SetProperties(template, mail, null);
}
return mail;
}
private IDictionary<string, IEmailTemplate> CreateTemplateInstances(string templateName)
{
return GetTemplateTypes(templateName).Select(pair => new { ContentType = pair.Key, Template = (IEmailTemplate)Activator.CreateInstance(pair.Value) })
.ToDictionary(k => k.ContentType, e => e.Template);
}
private IDictionary<string, Type> GetTemplateTypes(string templateName)
{
IDictionary<string, Type> templateTypes;
_syncLock.EnterUpgradeableReadLock();
try
{
if (!_typeMapping.TryGetValue(templateName, out templateTypes))
{
_syncLock.EnterWriteLock();
try
{
templateTypes = GenerateTemplateTypes(templateName);
_typeMapping.Add(templateName, templateTypes);
}
finally
{
_syncLock.ExitWriteLock();
}
}
}
finally
{
_syncLock.ExitUpgradeableReadLock();
}
return templateTypes;
}
private IDictionary<string, Type> GenerateTemplateTypes(string templateName)
{
var templates = _templateSuffixes.Select(pair => new
{
Suffix = pair.Key,
TemplateName = templateName + pair.Key,
Content = _contentReader.Read(templateName, pair.Key),
ContentType = pair.Value
})
.Where(x => !String.IsNullOrWhiteSpace(x.Content))
.ToList();
var compilableTemplates = templates.Select(x => new KeyValuePair<string, string>(x.TemplateName, x.Content)).ToArray();
var assembly = GenerateAssembly(compilableTemplates);
return templates.Select(x => new { ContentType = x.ContentType, Type = assembly.GetType(NamespaceName + "." + x.TemplateName, true, false) })
.ToDictionary(k => k.ContentType, e => e.Type);
}
private static void SetProperties(IEmailTemplate template, Email mail, Action<string> updateBody)
{
if (template != null)
{
if (!String.IsNullOrWhiteSpace(template.From))
{
mail.From = template.From;
}
if (!String.IsNullOrWhiteSpace(template.Sender))
{
mail.Sender = template.Sender;
}
if (!String.IsNullOrWhiteSpace(template.Subject))
{
mail.Subject = template.Subject;
}
template.Headers.Each(pair => mail.Headers[pair.Key] = pair.Value);
if (updateBody != null)
{
updateBody(template.Body);
}
}
}
private static Assembly GenerateAssembly(params KeyValuePair<string, string>[] templates)
{
var templateResults = templates.Select(pair => _razorEngine.GenerateCode(new StringReader(pair.Value), pair.Key, NamespaceName, pair.Key + ".cs")).ToList();
if (templateResults.Any(result => result.ParserErrors.Any()))
{
var parseExceptionMessage = String.Join(Environment.NewLine + Environment.NewLine, templateResults.SelectMany(r => r.ParserErrors).Select(e => e.Location + ":" + Environment.NewLine + e.Message).ToArray());
throw new InvalidOperationException(parseExceptionMessage);
}
using (var codeProvider = new CSharpCodeProvider())
{
var compilerParameter = new CompilerParameters(_referencedAssemblies)
{
IncludeDebugInformation = false,
GenerateInMemory = true,
CompilerOptions = "/optimize"
};
var compilerResults = codeProvider.CompileAssemblyFromDom(compilerParameter, templateResults.Select(r => r.GeneratedCode).ToArray());
if (compilerResults.Errors.HasErrors)
{
var compileExceptionMessage = String.Join(Environment.NewLine + Environment.NewLine, compilerResults.Errors.OfType<CompilerError>().Where(ce => !ce.IsWarning).Select(e => e.FileName + ":" + Environment.NewLine + e.ErrorText).ToArray());
throw new InvalidOperationException(compileExceptionMessage);
}
return compilerResults.CompiledAssembly;
}
}
private static dynamic CreateModel(object model)
{
if (model == null)
{
return null;
}
if (model is IDynamicMetaObjectProvider)
{
return model;
}
var propertyMap = model.GetType()
.GetProperties()
.Where(property => property.CanRead && property.GetIndexParameters().Length == 0)
.ToDictionary(property => property.Name, property => property.GetValue(model, null));
return new DynamicModel(propertyMap);
}
private static RazorTemplateEngine CreateRazorEngine()
{
var host = new RazorEngineHost(new CSharpRazorCodeLanguage())
{
DefaultBaseClass = typeof(EmailTemplate).FullName,
DefaultNamespace = NamespaceName
};
host.NamespaceImports.Add("System");
host.NamespaceImports.Add("System.Collections");
host.NamespaceImports.Add("System.Collections.Generic");
host.NamespaceImports.Add("System.Dynamic");
host.NamespaceImports.Add("System.Linq");
return new RazorTemplateEngine(host);
}
private static IEnumerable<string> BuildReferenceList()
{
string currentAssemblyLocation = typeof(RazorEmailTemplateEngine).Assembly.CodeBase.Replace("file:///", String.Empty).Replace("/", "\\");
return new List<string>
{
"mscorlib.dll",
"system.dll",
"system.core.dll",
"microsoft.csharp.dll",
currentAssemblyLocation
};
}
}
}
| |
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxres = Google.Api.Gax.ResourceNames;
using gcscv = Google.Cloud.Spanner.Common.V1;
using sys = System;
using linq = System.Linq;
namespace Google.Cloud.Spanner.Admin.Instance.V1
{
/// <summary>
/// Resource name for the 'instance_config' resource.
/// </summary>
public sealed partial class InstanceConfigName : gax::IResourceName, sys::IEquatable<InstanceConfigName>
{
private static readonly gax::PathTemplate s_template = new gax::PathTemplate("projects/{project}/instanceConfigs/{instance_config}");
/// <summary>
/// Parses the given instance_config resource name in string form into a new
/// <see cref="InstanceConfigName"/> instance.
/// </summary>
/// <param name="instanceConfigName">The instance_config resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="InstanceConfigName"/> if successful.</returns>
public static InstanceConfigName Parse(string instanceConfigName)
{
gax::GaxPreconditions.CheckNotNull(instanceConfigName, nameof(instanceConfigName));
gax::TemplatedResourceName resourceName = s_template.ParseName(instanceConfigName);
return new InstanceConfigName(resourceName[0], resourceName[1]);
}
/// <summary>
/// Tries to parse the given instance_config resource name in string form into a new
/// <see cref="InstanceConfigName"/> instance.
/// </summary>
/// <remarks>
/// This method still throws <see cref="sys::ArgumentNullException"/> if <paramref name="instanceConfigName"/> is null,
/// as this would usually indicate a programming error rather than a data error.
/// </remarks>
/// <param name="instanceConfigName">The instance_config resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">When this method returns, the parsed <see cref="InstanceConfigName"/>,
/// or <c>null</c> if parsing fails.</param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string instanceConfigName, out InstanceConfigName result)
{
gax::GaxPreconditions.CheckNotNull(instanceConfigName, nameof(instanceConfigName));
gax::TemplatedResourceName resourceName;
if (s_template.TryParseName(instanceConfigName, out resourceName))
{
result = new InstanceConfigName(resourceName[0], resourceName[1]);
return true;
}
else
{
result = null;
return false;
}
}
/// <summary>
/// Constructs a new instance of the <see cref="InstanceConfigName"/> resource name class
/// from its component parts.
/// </summary>
/// <param name="projectId">The project ID. Must not be <c>null</c>.</param>
/// <param name="instanceConfigId">The instanceConfig ID. Must not be <c>null</c>.</param>
public InstanceConfigName(string projectId, string instanceConfigId)
{
ProjectId = gax::GaxPreconditions.CheckNotNull(projectId, nameof(projectId));
InstanceConfigId = gax::GaxPreconditions.CheckNotNull(instanceConfigId, nameof(instanceConfigId));
}
/// <summary>
/// The project ID. Never <c>null</c>.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The instanceConfig ID. Never <c>null</c>.
/// </summary>
public string InstanceConfigId { get; }
/// <inheritdoc />
public gax::ResourceNameKind Kind => gax::ResourceNameKind.Simple;
/// <inheritdoc />
public override string ToString() => s_template.Expand(ProjectId, InstanceConfigId);
/// <inheritdoc />
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc />
public override bool Equals(object obj) => Equals(obj as InstanceConfigName);
/// <inheritdoc />
public bool Equals(InstanceConfigName other) => ToString() == other?.ToString();
/// <inheritdoc />
public static bool operator ==(InstanceConfigName a, InstanceConfigName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc />
public static bool operator !=(InstanceConfigName a, InstanceConfigName b) => !(a == b);
}
public partial class CreateInstanceRequest
{
/// <summary>
/// <see cref="gaxres::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gaxres::ProjectName ParentAsProjectName
{
get { return string.IsNullOrEmpty(Parent) ? null : gaxres::ProjectName.Parse(Parent); }
set { Parent = value != null ? value.ToString() : ""; }
}
/// <summary>
/// <see cref="gcscv::InstanceName"/>-typed view over the <see cref="InstanceId"/> resource name property.
/// </summary>
public gcscv::InstanceName InstanceIdAsInstanceName
{
get { return string.IsNullOrEmpty(InstanceId) ? null : gcscv::InstanceName.Parse(InstanceId); }
set { InstanceId = value != null ? value.ToString() : ""; }
}
}
public partial class DeleteInstanceRequest
{
/// <summary>
/// <see cref="gcscv::InstanceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcscv::InstanceName InstanceName
{
get { return string.IsNullOrEmpty(Name) ? null : gcscv::InstanceName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class GetInstanceConfigRequest
{
/// <summary>
/// <see cref="Google.Cloud.Spanner.Admin.Instance.V1.InstanceConfigName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public Google.Cloud.Spanner.Admin.Instance.V1.InstanceConfigName InstanceConfigName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Spanner.Admin.Instance.V1.InstanceConfigName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class GetInstanceRequest
{
/// <summary>
/// <see cref="gcscv::InstanceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcscv::InstanceName InstanceName
{
get { return string.IsNullOrEmpty(Name) ? null : gcscv::InstanceName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class Instance
{
/// <summary>
/// <see cref="gcscv::InstanceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcscv::InstanceName InstanceName
{
get { return string.IsNullOrEmpty(Name) ? null : gcscv::InstanceName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
/// <summary>
/// <see cref="Google.Cloud.Spanner.Admin.Instance.V1.InstanceConfigName"/>-typed view over the <see cref="Config"/> resource name property.
/// </summary>
public Google.Cloud.Spanner.Admin.Instance.V1.InstanceConfigName ConfigAsInstanceConfigName
{
get { return string.IsNullOrEmpty(Config) ? null : Google.Cloud.Spanner.Admin.Instance.V1.InstanceConfigName.Parse(Config); }
set { Config = value != null ? value.ToString() : ""; }
}
}
public partial class InstanceConfig
{
/// <summary>
/// <see cref="Google.Cloud.Spanner.Admin.Instance.V1.InstanceConfigName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public Google.Cloud.Spanner.Admin.Instance.V1.InstanceConfigName InstanceConfigName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Spanner.Admin.Instance.V1.InstanceConfigName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class ListInstanceConfigsRequest
{
/// <summary>
/// <see cref="gaxres::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gaxres::ProjectName ParentAsProjectName
{
get { return string.IsNullOrEmpty(Parent) ? null : gaxres::ProjectName.Parse(Parent); }
set { Parent = value != null ? value.ToString() : ""; }
}
}
public partial class ListInstancesRequest
{
/// <summary>
/// <see cref="gaxres::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gaxres::ProjectName ParentAsProjectName
{
get { return string.IsNullOrEmpty(Parent) ? null : gaxres::ProjectName.Parse(Parent); }
set { Parent = value != null ? value.ToString() : ""; }
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using wkt = Google.Protobuf.WellKnownTypes;
using gr = Google.Rpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Dataflow.V1Beta3.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedTemplatesServiceClientTest
{
[xunit::FactAttribute]
public void CreateJobFromTemplateRequestObject()
{
moq::Mock<TemplatesService.TemplatesServiceClient> mockGrpcClient = new moq::Mock<TemplatesService.TemplatesServiceClient>(moq::MockBehavior.Strict);
CreateJobFromTemplateRequest request = new CreateJobFromTemplateRequest
{
ProjectId = "project_id43ad98b0",
GcsPath = "gcs_path83b28bb9",
Parameters =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
JobName = "job_namedc176648",
Environment = new RuntimeEnvironment(),
Location = "locatione09d18d5",
};
Job expectedResponse = new Job
{
Id = "id74b70bb8",
ProjectId = "project_id43ad98b0",
Name = "name1c9368b0",
Type = JobType.Unknown,
Environment = new Environment(),
Steps = { new Step(), },
CurrentState = JobState.Unknown,
CurrentStateTime = new wkt::Timestamp(),
RequestedState = JobState.Stopped,
ExecutionInfo = new JobExecutionInfo(),
CreateTime = new wkt::Timestamp(),
ReplaceJobId = "replace_job_id4a0fad7e",
TransformNameMapping =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
ClientRequestId = "client_request_ide162ec50",
ReplacedByJobId = "replaced_by_job_ida56afc22",
TempFiles =
{
"temp_filescb023328",
},
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Location = "locatione09d18d5",
PipelineDescription = new PipelineDescription(),
StageStates =
{
new ExecutionStageState(),
},
JobMetadata = new JobMetadata(),
StartTime = new wkt::Timestamp(),
CreatedFromSnapshotId = "created_from_snapshot_id9b426c65",
StepsLocation = "steps_location41e078c5",
SatisfiesPzs = false,
};
mockGrpcClient.Setup(x => x.CreateJobFromTemplate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TemplatesServiceClient client = new TemplatesServiceClientImpl(mockGrpcClient.Object, null);
Job response = client.CreateJobFromTemplate(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateJobFromTemplateRequestObjectAsync()
{
moq::Mock<TemplatesService.TemplatesServiceClient> mockGrpcClient = new moq::Mock<TemplatesService.TemplatesServiceClient>(moq::MockBehavior.Strict);
CreateJobFromTemplateRequest request = new CreateJobFromTemplateRequest
{
ProjectId = "project_id43ad98b0",
GcsPath = "gcs_path83b28bb9",
Parameters =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
JobName = "job_namedc176648",
Environment = new RuntimeEnvironment(),
Location = "locatione09d18d5",
};
Job expectedResponse = new Job
{
Id = "id74b70bb8",
ProjectId = "project_id43ad98b0",
Name = "name1c9368b0",
Type = JobType.Unknown,
Environment = new Environment(),
Steps = { new Step(), },
CurrentState = JobState.Unknown,
CurrentStateTime = new wkt::Timestamp(),
RequestedState = JobState.Stopped,
ExecutionInfo = new JobExecutionInfo(),
CreateTime = new wkt::Timestamp(),
ReplaceJobId = "replace_job_id4a0fad7e",
TransformNameMapping =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
ClientRequestId = "client_request_ide162ec50",
ReplacedByJobId = "replaced_by_job_ida56afc22",
TempFiles =
{
"temp_filescb023328",
},
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Location = "locatione09d18d5",
PipelineDescription = new PipelineDescription(),
StageStates =
{
new ExecutionStageState(),
},
JobMetadata = new JobMetadata(),
StartTime = new wkt::Timestamp(),
CreatedFromSnapshotId = "created_from_snapshot_id9b426c65",
StepsLocation = "steps_location41e078c5",
SatisfiesPzs = false,
};
mockGrpcClient.Setup(x => x.CreateJobFromTemplateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TemplatesServiceClient client = new TemplatesServiceClientImpl(mockGrpcClient.Object, null);
Job responseCallSettings = await client.CreateJobFromTemplateAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Job responseCancellationToken = await client.CreateJobFromTemplateAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void LaunchTemplateRequestObject()
{
moq::Mock<TemplatesService.TemplatesServiceClient> mockGrpcClient = new moq::Mock<TemplatesService.TemplatesServiceClient>(moq::MockBehavior.Strict);
LaunchTemplateRequest request = new LaunchTemplateRequest
{
ProjectId = "project_id43ad98b0",
ValidateOnly = true,
GcsPath = "gcs_path83b28bb9",
LaunchParameters = new LaunchTemplateParameters(),
Location = "locatione09d18d5",
DynamicTemplate = new DynamicTemplateLaunchParams(),
};
LaunchTemplateResponse expectedResponse = new LaunchTemplateResponse { Job = new Job(), };
mockGrpcClient.Setup(x => x.LaunchTemplate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TemplatesServiceClient client = new TemplatesServiceClientImpl(mockGrpcClient.Object, null);
LaunchTemplateResponse response = client.LaunchTemplate(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task LaunchTemplateRequestObjectAsync()
{
moq::Mock<TemplatesService.TemplatesServiceClient> mockGrpcClient = new moq::Mock<TemplatesService.TemplatesServiceClient>(moq::MockBehavior.Strict);
LaunchTemplateRequest request = new LaunchTemplateRequest
{
ProjectId = "project_id43ad98b0",
ValidateOnly = true,
GcsPath = "gcs_path83b28bb9",
LaunchParameters = new LaunchTemplateParameters(),
Location = "locatione09d18d5",
DynamicTemplate = new DynamicTemplateLaunchParams(),
};
LaunchTemplateResponse expectedResponse = new LaunchTemplateResponse { Job = new Job(), };
mockGrpcClient.Setup(x => x.LaunchTemplateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<LaunchTemplateResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TemplatesServiceClient client = new TemplatesServiceClientImpl(mockGrpcClient.Object, null);
LaunchTemplateResponse responseCallSettings = await client.LaunchTemplateAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
LaunchTemplateResponse responseCancellationToken = await client.LaunchTemplateAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetTemplateRequestObject()
{
moq::Mock<TemplatesService.TemplatesServiceClient> mockGrpcClient = new moq::Mock<TemplatesService.TemplatesServiceClient>(moq::MockBehavior.Strict);
GetTemplateRequest request = new GetTemplateRequest
{
ProjectId = "project_id43ad98b0",
GcsPath = "gcs_path83b28bb9",
View = GetTemplateRequest.Types.TemplateView.MetadataOnly,
Location = "locatione09d18d5",
};
GetTemplateResponse expectedResponse = new GetTemplateResponse
{
Status = new gr::Status(),
Metadata = new TemplateMetadata(),
TemplateType = GetTemplateResponse.Types.TemplateType.Flex,
RuntimeMetadata = new RuntimeMetadata(),
};
mockGrpcClient.Setup(x => x.GetTemplate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TemplatesServiceClient client = new TemplatesServiceClientImpl(mockGrpcClient.Object, null);
GetTemplateResponse response = client.GetTemplate(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetTemplateRequestObjectAsync()
{
moq::Mock<TemplatesService.TemplatesServiceClient> mockGrpcClient = new moq::Mock<TemplatesService.TemplatesServiceClient>(moq::MockBehavior.Strict);
GetTemplateRequest request = new GetTemplateRequest
{
ProjectId = "project_id43ad98b0",
GcsPath = "gcs_path83b28bb9",
View = GetTemplateRequest.Types.TemplateView.MetadataOnly,
Location = "locatione09d18d5",
};
GetTemplateResponse expectedResponse = new GetTemplateResponse
{
Status = new gr::Status(),
Metadata = new TemplateMetadata(),
TemplateType = GetTemplateResponse.Types.TemplateType.Flex,
RuntimeMetadata = new RuntimeMetadata(),
};
mockGrpcClient.Setup(x => x.GetTemplateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GetTemplateResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TemplatesServiceClient client = new TemplatesServiceClientImpl(mockGrpcClient.Object, null);
GetTemplateResponse responseCallSettings = await client.GetTemplateAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
GetTemplateResponse responseCancellationToken = await client.GetTemplateAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using Shouldly;
using StructureMap.Pipeline;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace StructureMap.Testing.Configuration.DSL
{
public class InjectArrayTester
{
public class Processor
{
private readonly IHandler[] _handlers;
private readonly string _name;
public Processor(IHandler[] handlers, string name)
{
_handlers = handlers;
_name = name;
}
public IHandler[] Handlers
{
get { return _handlers; }
}
public string Name
{
get { return _name; }
}
}
public class ProcessorWithList
{
private readonly IList<IHandler> _handlers;
private readonly string _name;
public ProcessorWithList(IList<IHandler> handlers, string name)
{
_handlers = handlers;
_name = name;
}
public IList<IHandler> Handlers
{
get { return _handlers; }
}
public string Name
{
get { return _name; }
}
}
public class ProcessorWithConcreteList
{
private readonly List<IHandler> _handlers;
private readonly string _name;
public ProcessorWithConcreteList(List<IHandler> handlers, string name)
{
_handlers = handlers;
_name = name;
}
public IList<IHandler> Handlers
{
get { return _handlers; }
}
public string Name
{
get { return _name; }
}
}
public class ProcessorWithEnumerable
{
private readonly IList<IHandler> _handlers;
private readonly string _name;
public ProcessorWithEnumerable(IEnumerable<IHandler> handlers, string name)
{
_handlers = handlers.ToList();
_name = name;
}
public IList<IHandler> Handlers
{
get { return _handlers; }
}
public string Name
{
get { return _name; }
}
}
public class Processor2
{
private readonly IHandler[] _first;
private readonly IHandler[] _second;
public Processor2(IHandler[] first, IHandler[] second)
{
_first = first;
_second = second;
}
public IHandler[] First
{
get { return _first; }
}
public IHandler[] Second
{
get { return _second; }
}
}
public interface IHandler
{
}
public class Handler1 : IHandler
{
}
public class Handler2 : IHandler
{
}
public class Handler3 : IHandler
{
}
[Fact]
public void CanStillAddOtherPropertiesAfterTheCallToChildArray()
{
var container = new Container(x =>
{
x.For<Processor>().Use<Processor>()
.EnumerableOf<IHandler>().Contains(
new SmartInstance<Handler1>(),
new SmartInstance<Handler2>(),
new SmartInstance<Handler3>()
)
.Ctor<string>("name").Is("Jeremy");
});
container.GetInstance<Processor>().Name.ShouldBe("Jeremy");
}
[Fact]
public void get_a_configured_list()
{
var container = new Container(x =>
{
x.For<ProcessorWithList>().Use<ProcessorWithList>()
.EnumerableOf<IHandler>().Contains(
new SmartInstance<Handler1>(),
new SmartInstance<Handler2>(),
new SmartInstance<Handler3>()
)
.Ctor<string>("name").Is("Jeremy");
});
container.GetInstance<ProcessorWithList>()
.Handlers.Select(x => x.GetType())
.ShouldHaveTheSameElementsAs(typeof(Handler1), typeof(Handler2), typeof(Handler3));
}
[Fact]
public void get_a_configured_concrete_list()
{
var container = new Container(x =>
{
x.For<ProcessorWithConcreteList>().Use<ProcessorWithConcreteList>()
.EnumerableOf<IHandler>().Contains(
new SmartInstance<Handler1>(),
new SmartInstance<Handler2>(),
new SmartInstance<Handler3>()
)
.Ctor<string>("name").Is("Jeremy");
});
container.GetInstance<ProcessorWithConcreteList>()
.Handlers.Select(x => x.GetType())
.ShouldHaveTheSameElementsAs(typeof(Handler1), typeof(Handler2), typeof(Handler3));
}
[Fact]
public void get_a_configured_ienumerable()
{
var container = new Container(x =>
{
x.For<ProcessorWithEnumerable>().Use<ProcessorWithEnumerable>()
.EnumerableOf<IHandler>().Contains(
new SmartInstance<Handler1>(),
new SmartInstance<Handler2>(),
new SmartInstance<Handler3>()
)
.Ctor<string>("name").Is("Jeremy");
});
container.GetInstance<ProcessorWithEnumerable>()
.Handlers.Select(x => x.GetType())
.ShouldHaveTheSameElementsAs(typeof(Handler1), typeof(Handler2), typeof(Handler3));
}
[Fact]
public void InjectPropertiesByName()
{
var container = new Container(r =>
{
r.For<Processor2>().Use<Processor2>()
.EnumerableOf<IHandler>("first").Contains(x =>
{
x.Type<Handler1>();
x.Type<Handler2>();
})
.EnumerableOf<IHandler>("second").Contains(x =>
{
x.Type<Handler2>();
x.Type<Handler3>();
});
});
var processor = container.GetInstance<Processor2>();
processor.First[0].ShouldBeOfType<Handler1>();
processor.First[1].ShouldBeOfType<Handler2>();
processor.Second[0].ShouldBeOfType<Handler2>();
processor.Second[1].ShouldBeOfType<Handler3>();
}
[Fact]
public void inline_definition_of_enumerable_child_respects_order_of_registration()
{
IContainer container = new Container(r =>
{
r.For<IHandler>().Add<Handler1>().Named("One");
r.For<IHandler>().Add<Handler2>().Named("Two");
r.For<Processor>().Use<Processor>()
.Ctor<string>("name").Is("Jeremy")
.EnumerableOf<IHandler>().Contains(x =>
{
x.TheInstanceNamed("Two");
x.TheInstanceNamed("One");
});
});
var processor = container.GetInstance<Processor>();
processor.Handlers[0].ShouldBeOfType<Handler2>();
processor.Handlers[1].ShouldBeOfType<Handler1>();
}
[Fact]
public void PlaceMemberInArrayByReference_with_SmartInstance()
{
IContainer manager = new Container(registry =>
{
registry.For<IHandler>().Add<Handler1>().Named("One");
registry.For<IHandler>().Add<Handler2>().Named("Two");
registry.For<Processor>().Use<Processor>()
.Ctor<string>("name").Is("Jeremy")
.EnumerableOf<IHandler>().Contains(x =>
{
x.TheInstanceNamed("Two");
x.TheInstanceNamed("One");
});
});
var processor = manager.GetInstance<Processor>();
processor.Handlers[0].ShouldBeOfType<Handler2>();
processor.Handlers[1].ShouldBeOfType<Handler1>();
}
[Fact]
public void ProgrammaticallyInjectArrayAllInline()
{
var container = new Container(x =>
{
x.For<Processor>().Use<Processor>()
.Ctor<string>("name").Is("Jeremy")
.EnumerableOf<IHandler>().Contains(y =>
{
y.Type<Handler1>();
y.Type<Handler2>();
y.Type<Handler3>();
});
});
var processor = container.GetInstance<Processor>();
processor.Handlers[0].ShouldBeOfType<Handler1>();
processor.Handlers[1].ShouldBeOfType<Handler2>();
processor.Handlers[2].ShouldBeOfType<Handler3>();
}
[Fact]
public void ProgrammaticallyInjectArrayAllInline_with_smart_instance()
{
IContainer container = new Container(r =>
{
r.For<Processor>().Use<Processor>()
.Ctor<string>("name").Is("Jeremy")
.EnumerableOf<IHandler>().Contains(x =>
{
x.Type<Handler1>();
x.Type<Handler2>();
x.Type<Handler3>();
});
});
var processor = container.GetInstance<Processor>();
processor.Handlers[0].ShouldBeOfType<Handler1>();
processor.Handlers[1].ShouldBeOfType<Handler2>();
processor.Handlers[2].ShouldBeOfType<Handler3>();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Media;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.Utilities;
using NuGet.VisualStudio;
using EditorDefGuidList = Microsoft.VisualStudio.Editor.DefGuidList;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
namespace NuGetConsole.Implementation.Console
{
internal interface IPrivateWpfConsole : IWpfConsole
{
SnapshotPoint? InputLineStart { get; }
InputHistory InputHistory { get; }
void BeginInputLine();
SnapshotSpan? EndInputLine(bool isEcho);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Maintainability",
"CA1506:AvoidExcessiveClassCoupling",
Justification = "We don't have resources to refactor this class.")]
internal class WpfConsole : ObjectWithFactory<WpfConsoleService>, IDisposable
{
private readonly IPrivateConsoleStatus _consoleStatus;
private IVsTextBuffer _bufferAdapter;
private int _consoleWidth = -1;
private IContentType _contentType;
private int _currentHistoryInputIndex;
private IPrivateConsoleDispatcher _dispatcher;
private IList<string> _historyInputs;
private IHost _host;
private InputHistory _inputHistory;
private SnapshotPoint? _inputLineStart;
private PrivateMarshaler _marshaler;
private uint _pdwCookieForStatusBar;
private IReadOnlyRegion _readOnlyRegionBegin;
private IReadOnlyRegion _readOnlyRegionBody;
private IVsTextView _view;
private IVsStatusbar _vsStatusBar;
private IWpfTextView _wpfTextView;
private bool _startedWritingOutput;
private List<Tuple<string, Color?, Color?>> _outputCache = new List<Tuple<string, Color?, Color?>>();
public WpfConsole(
WpfConsoleService factory,
IServiceProvider sp,
IPrivateConsoleStatus consoleStatus,
string contentTypeName,
string hostName)
: base(factory)
{
UtilityMethods.ThrowIfArgumentNull(sp);
_consoleStatus = consoleStatus;
ServiceProvider = sp;
ContentTypeName = contentTypeName;
HostName = hostName;
}
private IServiceProvider ServiceProvider { get; set; }
public string ContentTypeName { get; private set; }
public string HostName { get; private set; }
public IPrivateConsoleDispatcher Dispatcher
{
get
{
if (_dispatcher == null)
{
_dispatcher = new ConsoleDispatcher(Marshaler);
}
return _dispatcher;
}
}
public IVsUIShell VsUIShell
{
get { return ServiceProvider.GetService<IVsUIShell>(typeof(SVsUIShell)); }
}
private IVsStatusbar VsStatusBar
{
get
{
if (_vsStatusBar == null)
{
_vsStatusBar = ServiceProvider.GetService<IVsStatusbar>(typeof(SVsStatusbar));
}
return _vsStatusBar;
}
}
private IOleServiceProvider OleServiceProvider
{
get { return ServiceProvider.GetService<IOleServiceProvider>(typeof(IOleServiceProvider)); }
}
private IContentType ContentType
{
get
{
if (_contentType == null)
{
_contentType = Factory.ContentTypeRegistryService.GetContentType(this.ContentTypeName);
if (_contentType == null)
{
_contentType = Factory.ContentTypeRegistryService.AddContentType(
this.ContentTypeName, new string[] { "text" });
}
}
return _contentType;
}
}
private IVsTextBuffer VsTextBuffer
{
get
{
if (_bufferAdapter == null)
{
// make sure we only create text editor after StartWritingOutput() is called.
Debug.Assert(_startedWritingOutput);
_bufferAdapter = Factory.VsEditorAdaptersFactoryService.CreateVsTextBufferAdapter(
OleServiceProvider, ContentType);
_bufferAdapter.InitializeContent(string.Empty, 0);
}
return _bufferAdapter;
}
}
public IWpfTextView WpfTextView
{
get
{
if (_wpfTextView == null)
{
// make sure we only create text editor after StartWritingOutput() is called.
Debug.Assert(_startedWritingOutput);
_wpfTextView = Factory.VsEditorAdaptersFactoryService.GetWpfTextView(VsTextView);
}
return _wpfTextView;
}
}
private IWpfTextViewHost WpfTextViewHost
{
get
{
var userData = VsTextView as IVsUserData;
object data;
Guid guidIWpfTextViewHost = EditorDefGuidList.guidIWpfTextViewHost;
userData.GetData(ref guidIWpfTextViewHost, out data);
var wpfTextViewHost = data as IWpfTextViewHost;
return wpfTextViewHost;
}
}
/// <summary>
/// Get current input line start point (updated to current WpfTextView's text snapshot).
/// </summary>
public SnapshotPoint? InputLineStart
{
get
{
if (_inputLineStart != null)
{
ITextSnapshot snapshot = WpfTextView.TextSnapshot;
if (_inputLineStart.Value.Snapshot != snapshot)
{
_inputLineStart = _inputLineStart.Value.TranslateTo(snapshot, PointTrackingMode.Negative);
}
}
return _inputLineStart;
}
}
public SnapshotSpan InputLineExtent
{
get { return GetInputLineExtent(); }
}
/// <summary>
/// Get the snapshot extent from InputLineStart to END. Normally this console expects
/// one line only on InputLine. However in some cases multiple lines could appear, e.g.
/// when a DTE event handler writes to the console. This scenario is not fully supported,
/// but it is better to clean up nicely with ESC/ArrowUp/Return.
/// </summary>
public SnapshotSpan AllInputExtent
{
get
{
SnapshotPoint start = InputLineStart.Value;
return new SnapshotSpan(start, start.Snapshot.GetEnd());
}
}
public string InputLineText
{
get { return InputLineExtent.GetText(); }
}
private PrivateMarshaler Marshaler
{
get
{
if (_marshaler == null)
{
_marshaler = new PrivateMarshaler(this);
}
return _marshaler;
}
}
public IWpfConsole MarshaledConsole
{
get { return this.Marshaler; }
}
public IHost Host
{
get { return _host; }
set
{
if (_host != null)
{
throw new InvalidOperationException();
}
_host = value;
}
}
public int ConsoleWidth
{
get
{
if (_consoleWidth < 0)
{
ITextViewMargin leftMargin = WpfTextViewHost.GetTextViewMargin(PredefinedMarginNames.Left);
ITextViewMargin rightMargin = WpfTextViewHost.GetTextViewMargin(PredefinedMarginNames.Right);
double marginSize = 0.0;
if (leftMargin != null && leftMargin.Enabled)
{
marginSize += leftMargin.MarginSize;
}
if (rightMargin != null && rightMargin.Enabled)
{
marginSize += rightMargin.MarginSize;
}
var n = (int)((WpfTextView.ViewportWidth - marginSize) / WpfTextView.FormattedLineSource.ColumnWidth);
_consoleWidth = Math.Max(80, n); // Larger of 80 or n
}
return _consoleWidth;
}
}
private InputHistory InputHistory
{
get
{
if (_inputHistory == null)
{
_inputHistory = new InputHistory();
}
return _inputHistory;
}
}
public IVsTextView VsTextView
{
get
{
if (_view == null)
{
var textViewRoleSet = Factory.TextEditorFactoryService.CreateTextViewRoleSet(
PredefinedTextViewRoles.Interactive,
PredefinedTextViewRoles.Editable,
PredefinedTextViewRoles.Analyzable);
_view = Factory.VsEditorAdaptersFactoryService.CreateVsTextViewAdapter(OleServiceProvider, textViewRoleSet);
_view.Initialize(
VsTextBuffer as IVsTextLines,
IntPtr.Zero,
(uint)(TextViewInitFlags.VIF_HSCROLL | TextViewInitFlags.VIF_VSCROLL) |
(uint)TextViewInitFlags3.VIF_NO_HWND_SUPPORT,
null);
// Set font and color
var propCategoryContainer = _view as IVsTextEditorPropertyCategoryContainer;
if (propCategoryContainer != null)
{
IVsTextEditorPropertyContainer propContainer;
Guid guidPropCategory = EditorDefGuidList.guidEditPropCategoryViewMasterSettings;
int hr = propCategoryContainer.GetPropertyCategory(ref guidPropCategory, out propContainer);
if (hr == 0)
{
propContainer.SetProperty(VSEDITPROPID.VSEDITPROPID_ViewGeneral_FontCategory,
GuidList.guidPackageManagerConsoleFontAndColorCategory);
propContainer.SetProperty(VSEDITPROPID.VSEDITPROPID_ViewGeneral_ColorCategory,
GuidList.guidPackageManagerConsoleFontAndColorCategory);
}
}
// add myself as IConsole
WpfTextView.TextBuffer.Properties.AddProperty(typeof(IConsole), this);
// Initial mark readonly region. Must call Start() to start accepting inputs.
SetReadOnlyRegionType(ReadOnlyRegionType.All);
// Set some EditorOptions: -DragDropEditing, +WordWrap
IEditorOptions editorOptions = Factory.EditorOptionsFactoryService.GetOptions(WpfTextView);
editorOptions.SetOptionValue(DefaultTextViewOptions.DragDropEditingId, false);
editorOptions.SetOptionValue(DefaultTextViewOptions.WordWrapStyleId, WordWrapStyles.WordWrap);
// Reset console width when needed
WpfTextView.ViewportWidthChanged += (sender, e) => ResetConsoleWidth();
WpfTextView.ZoomLevelChanged += (sender, e) => ResetConsoleWidth();
// Create my Command Filter
new WpfConsoleKeyProcessor(this);
}
return _view;
}
}
public object Content
{
get { return WpfTextViewHost.HostControl; }
}
#region IDisposable Members
void IDisposable.Dispose()
{
try
{
Dispose(true);
}
finally
{
GC.SuppressFinalize(this);
}
}
#endregion
public event EventHandler<EventArgs<Tuple<SnapshotSpan, Color?, Color?>>> NewColorSpan;
public event EventHandler ConsoleCleared;
private void SetReadOnlyRegionType(ReadOnlyRegionType value)
{
if (!_startedWritingOutput)
{
return;
}
ITextBuffer buffer = WpfTextView.TextBuffer;
ITextSnapshot snapshot = buffer.CurrentSnapshot;
using (IReadOnlyRegionEdit edit = buffer.CreateReadOnlyRegionEdit())
{
edit.ClearReadOnlyRegion(ref _readOnlyRegionBegin);
edit.ClearReadOnlyRegion(ref _readOnlyRegionBody);
switch (value)
{
case ReadOnlyRegionType.BeginAndBody:
if (snapshot.Length > 0)
{
_readOnlyRegionBegin = edit.CreateReadOnlyRegion(new Span(0, 0),
SpanTrackingMode.EdgeExclusive,
EdgeInsertionMode.Deny);
_readOnlyRegionBody = edit.CreateReadOnlyRegion(new Span(0, snapshot.Length));
}
break;
case ReadOnlyRegionType.All:
_readOnlyRegionBody = edit.CreateReadOnlyRegion(new Span(0, snapshot.Length),
SpanTrackingMode.EdgeExclusive,
EdgeInsertionMode.Deny);
break;
}
edit.Apply();
}
}
public SnapshotSpan GetInputLineExtent(int start = 0, int length = -1)
{
SnapshotPoint beginPoint = InputLineStart.Value + start;
return length >= 0
? new SnapshotSpan(beginPoint, length)
: new SnapshotSpan(beginPoint, beginPoint.GetContainingLine().End);
}
public void BeginInputLine()
{
if (!_startedWritingOutput)
{
return;
}
if (_inputLineStart == null)
{
SetReadOnlyRegionType(ReadOnlyRegionType.BeginAndBody);
_inputLineStart = WpfTextView.TextSnapshot.GetEnd();
}
}
public SnapshotSpan? EndInputLine(bool isEcho = false)
{
if (!_startedWritingOutput)
{
return null;
}
// Reset history navigation upon end of a command line
ResetNavigateHistory();
if (_inputLineStart != null)
{
SnapshotSpan inputSpan = InputLineExtent;
_inputLineStart = null;
SetReadOnlyRegionType(ReadOnlyRegionType.All);
if (!isEcho)
{
Dispatcher.PostInputLine(new InputLine(inputSpan));
}
return inputSpan;
}
return null;
}
private void ResetConsoleWidth()
{
_consoleWidth = -1;
}
public void Write(string text)
{
if (!_startedWritingOutput)
{
_outputCache.Add(Tuple.Create<string, Color?, Color?>(text, null, null));
return;
}
if (_inputLineStart == null) // If not in input mode, need unlock to enable output
{
SetReadOnlyRegionType(ReadOnlyRegionType.None);
}
// Append text to editor buffer
ITextBuffer textBuffer = WpfTextView.TextBuffer;
textBuffer.Insert(textBuffer.CurrentSnapshot.Length, text);
// Ensure caret visible (scroll)
WpfTextView.Caret.EnsureVisible();
if (_inputLineStart == null) // If not in input mode, need lock again
{
SetReadOnlyRegionType(ReadOnlyRegionType.All);
}
}
public void WriteLine(string text)
{
// If append \n only, text becomes 1 line when copied to notepad.
Write(text + Environment.NewLine);
}
public void WriteBackspace()
{
if (_inputLineStart == null) // If not in input mode, need unlock to enable output
{
SetReadOnlyRegionType(ReadOnlyRegionType.None);
}
// Delete last character from input buffer.
ITextBuffer textBuffer = WpfTextView.TextBuffer;
if (textBuffer.CurrentSnapshot.Length > 0)
{
textBuffer.Delete(new Span(textBuffer.CurrentSnapshot.Length - 1, 1));
}
// Ensure caret visible (scroll)
WpfTextView.Caret.EnsureVisible();
if (_inputLineStart == null) // If not in input mode, need lock again
{
SetReadOnlyRegionType(ReadOnlyRegionType.All);
}
}
public void Write(string text, Color? foreground, Color? background)
{
if (!_startedWritingOutput)
{
_outputCache.Add(Tuple.Create(text, foreground, background));
return;
}
int begin = WpfTextView.TextSnapshot.Length;
Write(text);
int end = WpfTextView.TextSnapshot.Length;
if (foreground != null || background != null)
{
var span = new SnapshotSpan(WpfTextView.TextSnapshot, begin, end - begin);
NewColorSpan.Raise(this, Tuple.Create(span, foreground, background));
}
}
public void StartWritingOutput()
{
_startedWritingOutput = true;
FlushOutput();
}
private void FlushOutput()
{
foreach (var tuple in _outputCache)
{
Write(tuple.Item1, tuple.Item2, tuple.Item3);
}
_outputCache.Clear();
_outputCache = null;
}
private void ResetNavigateHistory()
{
_historyInputs = null;
_currentHistoryInputIndex = -1;
}
public void NavigateHistory(int offset)
{
if (_historyInputs == null)
{
_historyInputs = InputHistory.History;
if (_historyInputs == null)
{
_historyInputs = new string[] { };
}
_currentHistoryInputIndex = _historyInputs.Count;
}
int index = _currentHistoryInputIndex + offset;
if (index >= -1 && index <= _historyInputs.Count)
{
_currentHistoryInputIndex = index;
string input = (index >= 0 && index < _historyInputs.Count)
? _historyInputs[_currentHistoryInputIndex]
: string.Empty;
// Replace all text after InputLineStart with new text
WpfTextView.TextBuffer.Replace(AllInputExtent, input);
WpfTextView.Caret.EnsureVisible();
}
}
private void WriteProgress(string operation, int percentComplete)
{
if (operation == null)
{
throw new ArgumentNullException("operation");
}
if (percentComplete < 0)
{
percentComplete = 0;
}
if (percentComplete > 100)
{
percentComplete = 100;
}
if (percentComplete == 100)
{
HideProgress();
}
else
{
VsStatusBar.Progress(
ref _pdwCookieForStatusBar,
1 /* in progress */,
operation,
(uint)percentComplete,
(uint)100);
}
}
private void HideProgress()
{
VsStatusBar.Progress(
ref _pdwCookieForStatusBar,
0 /* completed */,
String.Empty,
(uint)100,
(uint)100);
}
public void SetExecutionMode(bool isExecuting)
{
_consoleStatus.SetBusyState(isExecuting);
if (!isExecuting)
{
HideProgress();
VsUIShell.UpdateCommandUI(0 /* false = update UI asynchronously */);
}
}
public void Clear()
{
if (!_startedWritingOutput)
{
_outputCache.Clear();
return;
}
SetReadOnlyRegionType(ReadOnlyRegionType.None);
ITextBuffer textBuffer = WpfTextView.TextBuffer;
textBuffer.Delete(new Span(0, textBuffer.CurrentSnapshot.Length));
// Dispose existing incompleted input line
_inputLineStart = null;
// Raise event
ConsoleCleared.Raise(this);
}
public void ClearConsole()
{
if (_inputLineStart != null)
{
Dispatcher.ClearConsole();
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Usage",
"CA2213:DisposableFieldsShouldBeDisposed",
MessageId = "_marshaler",
Justification = "The Dispose() method on _marshaler is called when the tool window is closed."),
System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Design",
"CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "We don't want to crash VS when it exits.")]
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (_bufferAdapter != null)
{
var docData = _bufferAdapter as IVsPersistDocData;
if (docData != null)
{
try
{
docData.Close();
}
catch (Exception exception)
{
ExceptionHelper.WriteToActivityLog(exception);
}
_bufferAdapter = null;
}
}
var disposable = _dispatcher as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
}
}
~WpfConsole()
{
Dispose(false);
}
#region Nested type: PrivateMarshaler
private class PrivateMarshaler : Marshaler<WpfConsole>, IWpfConsole, IPrivateWpfConsole
{
public PrivateMarshaler(WpfConsole impl)
: base(impl)
{
}
#region IPrivateWpfConsole Members
public SnapshotPoint? InputLineStart
{
get { return Invoke(() => _impl.InputLineStart); }
}
public void BeginInputLine()
{
Invoke(() => _impl.BeginInputLine());
}
public SnapshotSpan? EndInputLine(bool isEcho)
{
return Invoke(() => _impl.EndInputLine(isEcho));
}
public InputHistory InputHistory
{
get { return Invoke(() => _impl.InputHistory); }
}
#endregion
#region IWpfConsole Members
public IHost Host
{
get { return Invoke(() => _impl.Host); }
set { Invoke(() => { _impl.Host = value; }); }
}
public IConsoleDispatcher Dispatcher
{
get { return Invoke(() => _impl.Dispatcher); }
}
public int ConsoleWidth
{
get { return Invoke(() => _impl.ConsoleWidth); }
}
public void Write(string text)
{
Invoke(() => _impl.Write(text));
}
public void WriteLine(string text)
{
Invoke(() => _impl.WriteLine(text));
}
public void WriteBackspace()
{
Invoke(_impl.WriteBackspace);
}
public void Write(string text, Color? foreground, Color? background)
{
Invoke(() => _impl.Write(text, foreground, background));
}
public void Clear()
{
Invoke(_impl.Clear);
}
public void SetExecutionMode(bool isExecuting)
{
Invoke(() => _impl.SetExecutionMode(isExecuting));
}
public object Content
{
get { return Invoke(() => _impl.Content); }
}
public void WriteProgress(string operation, int percentComplete)
{
Invoke(() => _impl.WriteProgress(operation, percentComplete));
}
public object VsTextView
{
get { return Invoke(() => _impl.VsTextView); }
}
public bool ShowDisclaimerHeader
{
get { return true; }
}
public void StartWritingOutput()
{
Invoke(_impl.StartWritingOutput);
}
#endregion
public void Dispose()
{
_impl.Dispose(disposing: true);
}
}
#endregion
#region Nested type: ReadOnlyRegionType
private enum ReadOnlyRegionType
{
/// <summary>
/// No ReadOnly region. The whole text buffer allows edit.
/// </summary>
None,
/// <summary>
/// Begin and body are ReadOnly. Only allows edit at the end.
/// </summary>
BeginAndBody,
/// <summary>
/// The whole text buffer is ReadOnly. Does not allow any edit.
/// </summary>
All
};
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
using System.Diagnostics;
namespace System.Threading.Tasks.Tests
{
public class TaskContinueWhenAnyTests
{
#region TaskFactory.ContinueWhenAny tests
[Fact]
public static void RunContinueWhenAnyTests()
{
TaskCompletionSource<int> tcs = null;
ManualResetEvent mre1 = null;
ManualResetEvent mre2 = null;
Task[] antecedents;
Task continuation = null;
for (int i = 0; i < 2; i++)
{
bool antecedentsAreFutures = (i == 0);
for (int j = 0; j < 2; j++)
{
bool continuationIsFuture = (j == 0);
for (int k = 0; k < 2; k++)
{
bool preCanceledToken = (k == 0);
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken ct = cts.Token;
if (preCanceledToken)
cts.Cancel();
for (int x = 0; x < 2; x++)
{
bool longRunning = (x == 0);
TaskContinuationOptions tco = longRunning ? TaskContinuationOptions.LongRunning : TaskContinuationOptions.None;
for (int y = 0; y < 2; y++)
{
bool preCompletedTask = (y == 0);
for (int z = 0; z < 2; z++)
{
bool useFutureFactory = (z == 0);
// This would be a nonsensical combination
if (useFutureFactory && !continuationIsFuture)
continue;
//Assert.True(false, string.Format(" - Test Task{5}.Factory.ContinueWhenAny(Task{0}[]({1} completed), {2}, ct({3}), {4}, ts.Default)",
// antecedentsAreFutures ? "<int>" : "",
// preCompletedTask ? 1 : 0,
// continuationIsFuture ? "func" : "action",
// preCanceledToken ? "signaled" : "unsignaled",
// tco,
// useFutureFactory ? "<int>" : ""));
TaskScheduler ts = TaskScheduler.Default;
if (antecedentsAreFutures)
antecedents = new Task<int>[3];
else
antecedents = new Task[3];
tcs = new TaskCompletionSource<int>();
mre1 = new ManualResetEvent(false);
mre2 = new ManualResetEvent(false);
continuation = null;
if (antecedentsAreFutures)
{
antecedents[0] = new Task<int>(() => { mre2.WaitOne(); return 0; });
antecedents[1] = new Task<int>(() => { mre1.WaitOne(); return 1; });
antecedents[2] = new Task<int>(() => { mre2.WaitOne(); return 2; });
}
else
{
antecedents[0] = new Task(() => { mre2.WaitOne(); tcs.TrySetResult(0); });
antecedents[1] = new Task(() => { mre1.WaitOne(); tcs.TrySetResult(1); });
antecedents[2] = new Task(() => { mre2.WaitOne(); tcs.TrySetResult(2); });
}
if (preCompletedTask)
{
mre1.Set();
antecedents[1].Start();
antecedents[1].Wait();
}
if (continuationIsFuture)
{
if (antecedentsAreFutures)
{
if (useFutureFactory)
{
continuation = Task<int>.Factory.ContinueWhenAny<int>((Task<int>[])antecedents, t => { tcs.TrySetResult(t.Result); return 10; }, ct, tco, ts);
}
else
{
continuation = Task.Factory.ContinueWhenAny<int, int>((Task<int>[])antecedents, t => { tcs.TrySetResult(t.Result); return 10; }, ct, tco, ts);
}
}
else // antecedents are tasks
{
if (useFutureFactory)
{
continuation = Task<int>.Factory.ContinueWhenAny(antecedents, _ => 10, ct, tco, ts);
}
else
{
continuation = Task.Factory.ContinueWhenAny<int>(antecedents, _ => 10, ct, tco, ts);
}
}
}
else // continuation is task
{
if (antecedentsAreFutures)
{
continuation = Task.Factory.ContinueWhenAny<int>((Task<int>[])antecedents, t => tcs.TrySetResult(t.Result), ct, tco, ts);
}
else
{
continuation = Task.Factory.ContinueWhenAny(antecedents, _ => { }, ct, tco, ts);
}
}
// If we have a pre-canceled token, the continuation should have completed by now
Assert.False(preCanceledToken && !continuation.IsCompleted, " > FAILED. Continuation should complete early on pre-canceled ct");
// Slightly different than the previous assert:
// We should only have completed by now if we have a preCanceledToken or a preCompletedTask
Assert.True(!continuation.IsCompleted || preCompletedTask || preCanceledToken, " > FAILED! Continuation should fire early only if (preCanceledToken or preCompletedTask)(1).");
// Kick off our antecedents array
startTaskArray(antecedents);
//Thread.Sleep(50);
// re-assert that the only way that the continuation should have completed by now is preCompletedTask or preCanceledToken
Assert.True(!continuation.IsCompleted || preCompletedTask || preCanceledToken, " > FAILED! Continuation should fire early only if (preCanceledToken or preCompletedTask)(2).");
// signal mre1 if we have not done so already
if (!preCompletedTask)
mre1.Set();
Exception ex = null;
int result = 0;
try
{
if (continuationIsFuture)
result = ((Task<int>)continuation).Result;
else
continuation.Wait();
}
catch (Exception e)
{
ex = e;
}
Assert.True((ex == null) == !preCanceledToken,
"RunContinueWhenAnyTests: > FAILED! continuation.Wait() should throw exception iff preCanceledToken");
if (preCanceledToken)
{
if (ex == null)
{
Assert.True(false, string.Format("RunContinueWhenAnyTests: > FAILED! Expected AE<TCE> from continuation.Wait() (no exception thrown)"));
;
}
else if (ex.GetType() != typeof(AggregateException))
{
Assert.True(false, string.Format("RunContinueWhenAnyTests: > FAILED! Expected AE<TCE> from continuation.Wait() (didn't throw aggregate exception)"));
}
else if (((AggregateException)ex).InnerException.GetType() != typeof(TaskCanceledException))
{
ex = ((AggregateException)ex).InnerException;
Assert.True(false, string.Format("RunContinueWhenAnyTests: > FAILED! Expected AE<TCE> from continuation.Wait() (threw " + ex.GetType().Name + " instead of TaskCanceledException)"));
}
}
Assert.True(preCanceledToken || (tcs.Task.Result == 1),
"RunContinueWhenAnyTests: > FAILED! Wrong task was recorded as completed.");
Assert.True((result == 10) || !continuationIsFuture || preCanceledToken,
"RunContinueWhenAnyTests:> FAILED! continuation yielded wrong result");
Assert.Equal((continuation.CreationOptions & TaskCreationOptions.LongRunning) != 0, longRunning);
Assert.True((continuation.CreationOptions == TaskCreationOptions.None) || longRunning, "continuation CreationOptions should be None unless longRunning is true");
// Allow remaining antecedents to finish
mre2.Set();
// Make sure that you wait for the antecedents to complete.
// When this line wasn't here, antecedent completion could sneak into
// the next loop iteration, causing tcs to be set to 0 or 2 instead of 1,
// resulting in intermittent test failures.
Task.WaitAll(antecedents);
// We don't need to call this for every combination of i/j/k/x/y/z. So only
// call under these conditions.
if (preCanceledToken && longRunning && preCompletedTask)
{
TestContinueWhenAnyException(antecedents, useFutureFactory, continuationIsFuture);
}
} //end z-loop (useFutureFactory)
} // end y-loop (preCompletedTask)
} // end x-loop (longRunning)
} // end k-loop (preCanceledToken)
} // end j-loop (continuationIsFuture)
} // end i-loop (antecedentsAreFutures)
}
public static void TestContinueWhenAnyException(Task[] antecedents, bool FutureFactory, bool continuationIsFuture)
{
bool antecedentsAreFutures = (antecedents as Task<int>[]) != null;
Debug.WriteLine(" * Test Exceptions in TaskFactory{0}.ContinueWhenAny(Task{1}[],Task{2})",
FutureFactory ? "<TResult>" : "",
antecedentsAreFutures ? "<TResult>" : "",
continuationIsFuture ? "<TResult>" : "");
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken ct = cts.Token;
cts.Cancel();
Task t1 = Task.Factory.StartNew(() => { });
Task<int> f1 = Task<int>.Factory.StartNew(() => 10);
Task[] dummyTasks = new Task[] { t1 };
Task<int>[] dummyFutures = new Task<int>[] { f1 };
if (FutureFactory) //TaskFactory<TResult> methods
{
if (antecedentsAreFutures)
{
Assert.Throws<ArgumentNullException>(
() => { Task<int>.Factory.ContinueWhenAny<int>((Task<int>[])antecedents, t => 0, CancellationToken.None, TaskContinuationOptions.None, (TaskScheduler)null); });
Assert.Throws<ArgumentOutOfRangeException>(
() => { Task<int>.Factory.ContinueWhenAny<int>((Task<int>[])antecedents, t => 0, TaskContinuationOptions.NotOnFaulted); });
Assert.Throws<ArgumentNullException>(
() => { Task<int>.Factory.ContinueWhenAny<int>(null, t => 0); });
var cFuture = Task.Factory.ContinueWhenAny<int, int>((Task<int>[])antecedents, t => 0, ct);
CheckForCorrectCT(cFuture, ct);
antecedents[0] = null;
Assert.Throws<ArgumentException>(
() => { Task<int>.Factory.ContinueWhenAny<int>((Task<int>[])antecedents, t => 0); });
AssertExtensions.Throws<ArgumentException>("tasks", () => Task<int>.Factory.ContinueWhenAny(new Task<int>[0], t => 0));
//
// Test for exception on null continuation function
//
Assert.Throws<ArgumentNullException>(
() => { Task<int>.Factory.ContinueWhenAny<int>(dummyFutures, (Func<Task<int>, int>)null); });
Assert.Throws<ArgumentNullException>(
() => { Task<int>.Factory.ContinueWhenAny<int>(dummyFutures, (Func<Task<int>, int>)null, CancellationToken.None); });
Assert.Throws<ArgumentNullException>(
() => { Task<int>.Factory.ContinueWhenAny<int>(dummyFutures, (Func<Task<int>, int>)null, TaskContinuationOptions.None); });
Assert.Throws<ArgumentNullException>(
() => { Task<int>.Factory.ContinueWhenAny<int>(dummyFutures, (Func<Task<int>, int>)null, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); });
}
else //antecedents are tasks
{
var dummy = Task.Factory.StartNew(delegate { });
Assert.Throws<ArgumentOutOfRangeException>(
() => { Task<int>.Factory.ContinueWhenAny(new Task[] { dummy }, t => 0, TaskContinuationOptions.LongRunning | TaskContinuationOptions.ExecuteSynchronously); });
dummy.Wait();
Assert.Throws<ArgumentNullException>(
() => { Task<int>.Factory.ContinueWhenAny(antecedents, t => 0, CancellationToken.None, TaskContinuationOptions.None, (TaskScheduler)null); });
Assert.Throws<ArgumentOutOfRangeException>(
() => { Task<int>.Factory.ContinueWhenAny(antecedents, t => 0, TaskContinuationOptions.NotOnFaulted); });
Assert.Throws<ArgumentNullException>(
() => { Task<int>.Factory.ContinueWhenAny(null, t => 0); });
var cTask = Task.Factory.ContinueWhenAny(antecedents, t => 0, ct);
CheckForCorrectCT(cTask, ct);
antecedents[0] = null;
Assert.Throws<ArgumentException>(
() => { Task<int>.Factory.ContinueWhenAny(antecedents, (t) => 0); });
AssertExtensions.Throws<ArgumentException>("tasks", () => Task<int>.Factory.ContinueWhenAny(new Task[0], t => 0));
//
// Test for exception on null continuation function
//
Assert.Throws<ArgumentNullException>(
() => { Task<int>.Factory.ContinueWhenAny(dummyTasks, (Func<Task, int>)null); });
Assert.Throws<ArgumentNullException>(
() => { Task<int>.Factory.ContinueWhenAny(dummyTasks, (Func<Task, int>)null, CancellationToken.None); });
Assert.Throws<ArgumentNullException>(
() => { Task<int>.Factory.ContinueWhenAny(dummyTasks, (Func<Task, int>)null, TaskContinuationOptions.None); });
Assert.Throws<ArgumentNullException>(
() => { Task<int>.Factory.ContinueWhenAny(dummyTasks, (Func<Task, int>)null, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); });
}
}
else //TaskFactory methods
{
//test exceptions
if (continuationIsFuture)
{
if (antecedentsAreFutures)
{
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny<int, int>((Task<int>[])antecedents, t => 0, CancellationToken.None, TaskContinuationOptions.None, (TaskScheduler)null); });
Assert.Throws<ArgumentOutOfRangeException>(
() => { Task.Factory.ContinueWhenAny<int, int>((Task<int>[])antecedents, t => 0, TaskContinuationOptions.NotOnFaulted); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny<int, int>(null, t => 0); });
var cTask = Task.Factory.ContinueWhenAny<int, int>((Task<int>[])antecedents, t => 0, ct);
CheckForCorrectCT(cTask, ct);
antecedents[0] = null;
Assert.Throws<ArgumentException>(
() => { Task.Factory.ContinueWhenAny<int, int>((Task<int>[])antecedents, t => 0); });
AssertExtensions.Throws<ArgumentException>("tasks", () => Task.Factory.ContinueWhenAny(new Task<int>[0], t => 0));
//
// Test for exception on null continuation function
//
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny<int, int>(dummyFutures, (Func<Task<int>, int>)null); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny<int, int>(dummyFutures, (Func<Task<int>, int>)null, CancellationToken.None); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny<int, int>(dummyFutures, (Func<Task<int>, int>)null, TaskContinuationOptions.None); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny<int, int>(dummyFutures, (Func<Task<int>, int>)null, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); });
}
else // antecedents are tasks
{
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny<int>(antecedents, t => 0, CancellationToken.None, TaskContinuationOptions.None, (TaskScheduler)null); });
Assert.Throws<ArgumentOutOfRangeException>(
() => { Task.Factory.ContinueWhenAny<int>(antecedents, t => 0, TaskContinuationOptions.NotOnFaulted); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny<int>(null, t => 0); });
var cTask = Task.Factory.ContinueWhenAny(antecedents, delegate (Task t) { }, ct);
CheckForCorrectCT(cTask, ct);
antecedents[0] = null;
Assert.Throws<ArgumentException>(
() => { Task.Factory.ContinueWhenAny<int>(antecedents, t => 0); });
AssertExtensions.Throws<ArgumentException>("tasks", () => Task.Factory.ContinueWhenAny(new Task[0], t => 0));
//
// Test for exception on null continuation function
//
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny<int>(dummyTasks, (Func<Task, int>)null); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny<int>(dummyTasks, (Func<Task, int>)null, CancellationToken.None); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny<int>(dummyTasks, (Func<Task, int>)null, TaskContinuationOptions.None); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny<int>(dummyTasks, (Func<Task, int>)null, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); });
}
}
else //Continuation is task
{
if (antecedentsAreFutures)
{
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny<int>((Task<int>[])antecedents, t => { }, CancellationToken.None, TaskContinuationOptions.None, (TaskScheduler)null); });
Assert.Throws<ArgumentOutOfRangeException>(
() => { Task.Factory.ContinueWhenAny<int>((Task<int>[])antecedents, t => { }, TaskContinuationOptions.NotOnFaulted); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny<int>(null, t => { }); });
var cTask = Task.Factory.ContinueWhenAny<int>((Task<int>[])antecedents, t => { }, ct);
CheckForCorrectCT(cTask, ct);
antecedents[0] = null;
Assert.Throws<ArgumentException>(
() => { Task.Factory.ContinueWhenAny<int>((Task<int>[])antecedents, t => { }); });
AssertExtensions.Throws<ArgumentException>("tasks", () => Task.Factory.ContinueWhenAny(new Task<int>[] { }, t => { }));
//
// Test for exception on null continuation action
//
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny<int>(dummyFutures, (Action<Task<int>>)null); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny<int>(dummyFutures, (Action<Task<int>>)null, CancellationToken.None); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny<int>(dummyFutures, (Action<Task<int>>)null, TaskContinuationOptions.None); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny<int>(dummyFutures, (Action<Task<int>>)null, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); });
}
else // antecedents are tasks
{
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny(antecedents, t => { }, CancellationToken.None, TaskContinuationOptions.None, (TaskScheduler)null); });
Assert.Throws<ArgumentOutOfRangeException>(
() => { Task.Factory.ContinueWhenAny(antecedents, t => { }, TaskContinuationOptions.NotOnFaulted); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny(null, t => { }); });
var task = Task.Factory.ContinueWhenAny(antecedents, t => { }, ct);
CheckForCorrectCT(task, ct);
antecedents[0] = null;
Assert.Throws<ArgumentException>(
() => { Task.Factory.ContinueWhenAny(antecedents, t => { }); });
AssertExtensions.Throws<ArgumentException>("tasks",() => Task.Factory.ContinueWhenAny(new Task[0], t => { }));
//
// Test for exception on null continuation action
//
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny(dummyTasks, (Action<Task>)null); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny(dummyTasks, (Action<Task>)null, CancellationToken.None); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny(dummyTasks, (Action<Task>)null, TaskContinuationOptions.None); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAny(dummyTasks, (Action<Task>)null, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); });
}
}
}
}
#endregion
#region Helper Methods
// used in ContinueWhenAll/ContinueWhenAny tests
public static void startTaskArray(Task[] tasks)
{
for (int i = 0; i < tasks.Length; i++)
{
if (tasks[i].Status == TaskStatus.Created)
tasks[i].Start();
}
}
public static void CheckForCorrectCT(Task canceledTask, CancellationToken correctToken)
{
try
{
canceledTask.Wait();
Assert.True(false, string.Format(" > FAILED! Pre-canceled result did not throw from Wait()"));
}
catch (AggregateException ae)
{
ae.Flatten().Handle(e =>
{
var tce = e as TaskCanceledException;
if (tce == null)
{
Assert.True(false, string.Format(" > FAILED! Pre-canceled result threw non-TCE from Wait()"));
}
else if (tce.CancellationToken != correctToken)
{
Assert.True(false, string.Format(" > FAILED! Pre-canceled result threw TCE w/ wrong token"));
}
return true;
});
}
}
#endregion
}
}
| |
// 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.
using UnityEngine;
using System.Linq;
/// Class that can perform gaze-based selection, as a simple alternative to the
/// more complicated path of using _GazeInputModule_ and the rest of **uGUI**.
[RequireComponent(typeof(Camera))]
public class GvrGaze : MonoBehaviour {
/// The active Gaze Pointer for this camera. Must have IGvrPointer.
/// The IGvrPointer responds to events from this class.
public GameObject PointerObject {
get {
return pointerObject;
}
set {
if (value != null) {
// Retrieve the IGvrPointer component.
var ptr = value.GetComponents<MonoBehaviour>()
.Select(c => c as IGvrPointer)
.Where(c => c != null)
.FirstOrDefault();
if (ptr != null) {
if (pointer != null) {
if (isTriggered) {
pointer.OnPointerClickUp();
}
if (currentGazeObject != null) {
pointer.OnPointerExit(currentGazeObject);
}
pointer.OnInputModuleDisabled();
}
pointerObject = value;
pointer = ptr;
pointer.OnInputModuleEnabled();
if (currentGazeObject != null) {
pointer.OnPointerEnter(currentGazeObject, lastIntersectPosition,
lastIntersectionRay, currentTarget != null);
}
if (isTriggered) {
pointer.OnPointerClickDown();
}
} else {
Debug.LogError("Object must have component which implements IGvrPointer.");
}
} else {
if (pointer != null) {
if (isTriggered) {
pointer.OnPointerClickUp();
}
if (currentTarget != null) {
pointer.OnPointerExit(currentGazeObject);
}
}
pointer = null;
pointerObject = null;
}
}
}
[SerializeField][HideInInspector]
private GameObject pointerObject;
private IGvrPointer pointer;
// Convenient accessor to the camera component used throughout this script.
public Camera cam { get; private set; }
/// The layers to use for finding objects which intersect the user's gaze.
public LayerMask mask = -1;
// Current target detected the user is "gazing" at.
private IGvrGazeResponder currentTarget;
private GameObject currentGazeObject;
private Vector3 lastIntersectPosition;
private Ray lastIntersectionRay;
// Trigger state.
private bool isTriggered;
void Awake() {
cam = GetComponent<Camera>();
PointerObject = pointerObject;
}
void OnEnable() {
if (pointer != null) {
pointer.OnInputModuleEnabled();
}
}
void OnDisable() {
// Is there a current target?
if (currentTarget != null) {
currentTarget.OnGazeExit();
}
// Tell pointer to exit target.
if (pointer != null) {
// Is there a pending trigger?
if (isTriggered) {
pointer.OnPointerClickUp();
}
if (currentGazeObject != null) {
pointer.OnPointerExit(currentGazeObject);
}
pointer.OnInputModuleDisabled();
}
currentGazeObject = null;
currentTarget = null;
isTriggered = false;
}
void LateUpdate () {
GvrViewer.Instance.UpdateState();
HandleGaze();
HandleTrigger();
}
private void HandleGaze() {
// Retrieve GazePointer radius.
float innerRadius = 0.0f;
float outerRadius = 0.0f;
if (pointer != null) {
pointer.GetPointerRadius(out innerRadius, out outerRadius);
}
// Find what object the user is looking at.
Vector3 intersectPosition;
IGvrGazeResponder target = null;
Ray intersectionRay;
GameObject targetObject = FindGazeTarget(innerRadius, out target, out intersectPosition, out intersectionRay);
// Found a target?
if (targetObject != null) {
lastIntersectPosition = intersectPosition;
lastIntersectionRay = intersectionRay;
// Is the object new?
if (targetObject != currentGazeObject) {
if (pointer != null) {
pointer.OnPointerExit(currentGazeObject);
}
if (currentTarget != null) {
// Replace with current object.
currentTarget.OnGazeExit();
}
// Save new object.
currentTarget = target;
currentGazeObject = targetObject;
// Inform pointer and target of gaze.
if (pointer != null) {
pointer.OnPointerEnter(currentGazeObject, intersectPosition,
intersectionRay, currentTarget != null);
}
if (currentTarget != null) {
currentTarget.OnGazeEnter();
}
} else {
// Same object, inform pointer of new intersection.
if (pointer != null) {
pointer.OnPointerHover(currentGazeObject, intersectPosition,
intersectionRay, currentTarget != null);
}
}
} else {
// Failed to find an object by inner radius.
if (currentGazeObject != null) {
// Already gazing an object? Check against outer radius.
if (IsGazeNearObject(outerRadius, currentGazeObject, out intersectPosition)) {
// Still gazing.
if (pointer != null) {
pointer.OnPointerHover(currentGazeObject, intersectPosition,
intersectionRay, currentTarget != null);
}
} else {
// No longer gazing any object.
if (pointer != null) {
pointer.OnPointerExit(currentGazeObject);
}
if (currentTarget != null) {
currentTarget.OnGazeExit();
}
currentTarget = null;
currentGazeObject = null;
}
}
}
}
private GameObject FindGazeTarget(float radius, out IGvrGazeResponder responder,
out Vector3 intersectPosition, out Ray intersectionRay) {
RaycastHit hit;
GameObject targetObject = null;
bool hitResult = false;
intersectionRay = GetRay();
// Use Raycast or SphereCast?
if (radius > 0.0f) {
// Cast a sphere against the scene.
hitResult = Physics.SphereCast(intersectionRay.origin,
radius, intersectionRay.direction, out hit, cam.farClipPlane, mask);
} else {
// Cast a Ray against the scene.
hitResult = Physics.Raycast(intersectionRay, out hit, cam.farClipPlane, mask);
}
// Found anything?
if (hitResult) {
// Set object and IGvrGazeResponder if any.
targetObject = hit.collider.gameObject;
responder = targetObject.GetComponent(typeof(IGvrGazeResponder))
as IGvrGazeResponder;
intersectPosition = transform.position + transform.forward * hit.distance;
} else {
// Nothing? Reset variables.
intersectPosition = Vector3.zero;
responder = null;
}
return targetObject;
}
private bool IsGazeNearObject(float radius, GameObject target, out Vector3 intersectPosition) {
RaycastHit[] hits;
// Use Raycast or SphereCast?
if (radius > 0.0f) {
// Cast a sphere against the scene.
hits = Physics.SphereCastAll(transform.position,
radius, transform.forward, cam.farClipPlane, mask);
} else {
// Cast a Ray against the object.
RaycastHit hitInfo;
Ray ray = new Ray(transform.position, transform.forward);
if (target.GetComponent<Collider>().Raycast(ray, out hitInfo, cam.farClipPlane)) {
hits = new RaycastHit[1];
hits[0] = hitInfo;
} else {
hits = new RaycastHit[0];
}
}
// Iterate all intersected objects to find the object we are looking for.
foreach (RaycastHit hit in hits) {
if (hit.collider.gameObject == target) {
// Found our object, save intersection position.
intersectPosition = transform.position + transform.forward * hit.distance;
return true;
}
}
// Desired object was not intersected.
intersectPosition = Vector3.zero;
return false;
}
private void HandleTrigger() {
// If trigger isn't already held.
if (!isTriggered) {
if (GvrViewer.Instance.Triggered || Input.GetMouseButtonDown(0)) {
// Trigger started.
isTriggered = true;
if (pointer != null) {
pointer.OnPointerClickDown();
}
}
} else if (!GvrViewer.Instance.Triggered && !Input.GetMouseButton(0)) {
// Trigger ended.
if (pointer != null) {
pointer.OnPointerClickUp();
}
if (currentTarget != null) {
currentTarget.OnGazeTrigger();
}
isTriggered = false;
}
}
private Ray GetRay() {
return new Ray(transform.position, transform.forward);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
namespace System.Security
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security.Util;
using System.Text;
using System.Globalization;
using System.IO;
using System.Security.Permissions;
using System.Diagnostics;
using System.Diagnostics.Contracts;
internal enum SecurityElementType
{
Regular = 0,
Format = 1,
Comment = 2
}
internal interface ISecurityElementFactory
{
SecurityElement CreateSecurityElement();
Object Copy();
String GetTag();
String Attribute( String attributeName );
}
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
sealed public class SecurityElement : ISecurityElementFactory
{
internal String m_strTag;
internal String m_strText;
private ArrayList m_lChildren;
internal ArrayList m_lAttributes;
internal SecurityElementType m_type = SecurityElementType.Regular;
private static readonly char[] s_tagIllegalCharacters = new char[] { ' ', '<', '>' };
private static readonly char[] s_textIllegalCharacters = new char[] { '<', '>' };
private static readonly char[] s_valueIllegalCharacters = new char[] { '<', '>', '\"' };
private const String s_strIndent = " ";
private const int c_AttributesTypical = 4 * 2; // 4 attributes, times 2 strings per attribute
private const int c_ChildrenTypical = 1;
private static readonly String[] s_escapeStringPairs = new String[]
{
// these must be all once character escape sequences or a new escaping algorithm is needed
"<", "<",
">", ">",
"\"", """,
"\'", "'",
"&", "&"
};
private static readonly char[] s_escapeChars = new char[] { '<', '>', '\"', '\'', '&' };
//-------------------------- Constructors ---------------------------
internal SecurityElement()
{
}
////// ISecurityElementFactory implementation
SecurityElement ISecurityElementFactory.CreateSecurityElement()
{
return this;
}
String ISecurityElementFactory.GetTag()
{
return ((SecurityElement)this).Tag;
}
Object ISecurityElementFactory.Copy()
{
return ((SecurityElement)this).Copy();
}
String ISecurityElementFactory.Attribute( String attributeName )
{
return ((SecurityElement)this).Attribute( attributeName );
}
public SecurityElement( String tag )
{
if (tag == null)
throw new ArgumentNullException( nameof(tag) );
if (!IsValidTag( tag ))
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementTag" ), tag ) );
Contract.EndContractBlock();
m_strTag = tag;
m_strText = null;
}
public SecurityElement( String tag, String text )
{
if (tag == null)
throw new ArgumentNullException( nameof(tag) );
if (!IsValidTag( tag ))
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementTag" ), tag ) );
if (text != null && !IsValidText( text ))
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementText" ), text ) );
Contract.EndContractBlock();
m_strTag = tag;
m_strText = text;
}
//-------------------------- Properties -----------------------------
public String Tag
{
[Pure]
get
{
return m_strTag;
}
set
{
if (value == null)
throw new ArgumentNullException( nameof(Tag) );
if (!IsValidTag( value ))
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementTag" ), value ) );
Contract.EndContractBlock();
m_strTag = value;
}
}
public Hashtable Attributes
{
get
{
if (m_lAttributes == null || m_lAttributes.Count == 0)
{
return null;
}
else
{
Hashtable hashtable = new Hashtable( m_lAttributes.Count/2 );
int iMax = m_lAttributes.Count;
Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
for (int i = 0; i < iMax; i += 2)
{
hashtable.Add( m_lAttributes[i], m_lAttributes[i+1]);
}
return hashtable;
}
}
set
{
if (value == null || value.Count == 0)
{
m_lAttributes = null;
}
else
{
ArrayList list = new ArrayList(value.Count);
System.Collections.IDictionaryEnumerator enumerator = (System.Collections.IDictionaryEnumerator)value.GetEnumerator();
while (enumerator.MoveNext())
{
String attrName = (String)enumerator.Key;
String attrValue = (String)enumerator.Value;
if (!IsValidAttributeName( attrName ))
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementName" ), (String)enumerator.Current ) );
if (!IsValidAttributeValue( attrValue ))
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementValue" ), (String)enumerator.Value ) );
list.Add(attrName);
list.Add(attrValue);
}
m_lAttributes = list;
}
}
}
public String Text
{
get
{
return Unescape( m_strText );
}
set
{
if (value == null)
{
m_strText = null;
}
else
{
if (!IsValidText( value ))
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementTag" ), value ) );
m_strText = value;
}
}
}
public ArrayList Children
{
get
{
ConvertSecurityElementFactories();
return m_lChildren;
}
set
{
if (value != null)
{
IEnumerator enumerator = value.GetEnumerator();
while (enumerator.MoveNext())
{
if (enumerator.Current == null)
throw new ArgumentException( Environment.GetResourceString( "ArgumentNull_Child" ) );
}
}
m_lChildren = value;
}
}
internal void ConvertSecurityElementFactories()
{
if (m_lChildren == null)
return;
for (int i = 0; i < m_lChildren.Count; ++i)
{
ISecurityElementFactory iseFactory = m_lChildren[i] as ISecurityElementFactory;
if (iseFactory != null && !(m_lChildren[i] is SecurityElement))
m_lChildren[i] = iseFactory.CreateSecurityElement();
}
}
internal ArrayList InternalChildren
{
get
{
// Beware! This array list can contain SecurityElements and other ISecurityElementFactories.
// If you want to get a consistent SecurityElement view, call get_Children.
return m_lChildren;
}
}
//-------------------------- Public Methods -----------------------------
internal void AddAttributeSafe( String name, String value )
{
if (m_lAttributes == null)
{
m_lAttributes = new ArrayList( c_AttributesTypical );
}
else
{
int iMax = m_lAttributes.Count;
Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
for (int i = 0; i < iMax; i += 2)
{
String strAttrName = (String)m_lAttributes[i];
if (String.Equals(strAttrName, name))
throw new ArgumentException( Environment.GetResourceString( "Argument_AttributeNamesMustBeUnique" ) );
}
}
m_lAttributes.Add(name);
m_lAttributes.Add(value);
}
public void AddAttribute( String name, String value )
{
if (name == null)
throw new ArgumentNullException( nameof(name) );
if (value == null)
throw new ArgumentNullException( nameof(value) );
if (!IsValidAttributeName( name ))
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementName" ), name ) );
if (!IsValidAttributeValue( value ))
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementValue" ), value ) );
Contract.EndContractBlock();
AddAttributeSafe( name, value );
}
public void AddChild( SecurityElement child )
{
if (child == null)
throw new ArgumentNullException( nameof(child) );
Contract.EndContractBlock();
if (m_lChildren == null)
m_lChildren = new ArrayList( c_ChildrenTypical );
m_lChildren.Add( child );
}
internal void AddChild( ISecurityElementFactory child )
{
if (child == null)
throw new ArgumentNullException( nameof(child) );
Contract.EndContractBlock();
if (m_lChildren == null)
m_lChildren = new ArrayList( c_ChildrenTypical );
m_lChildren.Add( child );
}
internal void AddChildNoDuplicates( ISecurityElementFactory child )
{
if (child == null)
throw new ArgumentNullException( nameof(child) );
Contract.EndContractBlock();
if (m_lChildren == null)
{
m_lChildren = new ArrayList( c_ChildrenTypical );
m_lChildren.Add( child );
}
else
{
for (int i = 0; i < m_lChildren.Count; ++i)
{
if (m_lChildren[i] == child)
return;
}
m_lChildren.Add( child );
}
}
public bool Equal( SecurityElement other )
{
if (other == null)
return false;
// Check if the tags are the same
if (!String.Equals(m_strTag, other.m_strTag))
return false;
// Check if the text is the same
if (!String.Equals(m_strText, other.m_strText))
return false;
// Check if the attributes are the same and appear in the same
// order.
// Maybe we can get away by only checking the number of attributes
if (m_lAttributes == null || other.m_lAttributes == null)
{
if (m_lAttributes != other.m_lAttributes)
return false;
}
else
{
int iMax = m_lAttributes.Count;
Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
if (iMax != other.m_lAttributes.Count)
return false;
for (int i = 0; i < iMax; i++)
{
String lhs = (String)m_lAttributes[i];
String rhs = (String)other.m_lAttributes[i];
if (!String.Equals(lhs, rhs))
return false;
}
}
// Finally we must check the child and make sure they are
// equal and in the same order
// Maybe we can get away by only checking the number of children
if (m_lChildren == null || other.m_lChildren == null)
{
if (m_lChildren != other.m_lChildren)
return false;
}
else
{
if (m_lChildren.Count != other.m_lChildren.Count)
return false;
this.ConvertSecurityElementFactories();
other.ConvertSecurityElementFactories();
// Okay, we'll need to go through each one of them
IEnumerator lhs = m_lChildren.GetEnumerator();
IEnumerator rhs = other.m_lChildren.GetEnumerator();
SecurityElement e1, e2;
while (lhs.MoveNext())
{
rhs.MoveNext();
e1 = (SecurityElement)lhs.Current;
e2 = (SecurityElement)rhs.Current;
if (e1 == null || !e1.Equal(e2))
return false;
}
}
return true;
}
[System.Runtime.InteropServices.ComVisible(false)]
public SecurityElement Copy()
{
SecurityElement element = new SecurityElement( this.m_strTag, this.m_strText );
element.m_lChildren = this.m_lChildren == null ? null : new ArrayList( this.m_lChildren );
element.m_lAttributes = this.m_lAttributes == null ? null : new ArrayList(this.m_lAttributes);
return element;
}
[Pure]
public static bool IsValidTag( String tag )
{
if (tag == null)
return false;
return tag.IndexOfAny( s_tagIllegalCharacters ) == -1;
}
[Pure]
public static bool IsValidText( String text )
{
if (text == null)
return false;
return text.IndexOfAny( s_textIllegalCharacters ) == -1;
}
[Pure]
public static bool IsValidAttributeName( String name )
{
return IsValidTag( name );
}
[Pure]
public static bool IsValidAttributeValue( String value )
{
if (value == null)
return false;
return value.IndexOfAny( s_valueIllegalCharacters ) == -1;
}
private static String GetEscapeSequence( char c )
{
int iMax = s_escapeStringPairs.Length;
Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
for (int i = 0; i < iMax; i += 2)
{
String strEscSeq = s_escapeStringPairs[i];
String strEscValue = s_escapeStringPairs[i+1];
if (strEscSeq[0] == c)
return strEscValue;
}
Debug.Assert( false, "Unable to find escape sequence for this character" );
return c.ToString();
}
public static String Escape( String str )
{
if (str == null)
return null;
StringBuilder sb = null;
int strLen = str.Length;
int index; // Pointer into the string that indicates the location of the current '&' character
int newIndex = 0; // Pointer into the string that indicates the start index of the "remaining" string (that still needs to be processed).
do
{
index = str.IndexOfAny( s_escapeChars, newIndex );
if (index == -1)
{
if (sb == null)
return str;
else
{
sb.Append( str, newIndex, strLen - newIndex );
return sb.ToString();
}
}
else
{
if (sb == null)
sb = new StringBuilder();
sb.Append( str, newIndex, index - newIndex );
sb.Append( GetEscapeSequence( str[index] ) );
newIndex = ( index + 1 );
}
}
while (true);
// no normal exit is possible
}
private static String GetUnescapeSequence( String str, int index, out int newIndex )
{
int maxCompareLength = str.Length - index;
int iMax = s_escapeStringPairs.Length;
Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
for (int i = 0; i < iMax; i += 2)
{
String strEscSeq = s_escapeStringPairs[i];
String strEscValue = s_escapeStringPairs[i+1];
int length = strEscValue.Length;
if (length <= maxCompareLength && String.Compare( strEscValue, 0, str, index, length, StringComparison.Ordinal) == 0)
{
newIndex = index + strEscValue.Length;
return strEscSeq;
}
}
newIndex = index + 1;
return str[index].ToString();
}
private static String Unescape( String str )
{
if (str == null)
return null;
StringBuilder sb = null;
int strLen = str.Length;
int index; // Pointer into the string that indicates the location of the current '&' character
int newIndex = 0; // Pointer into the string that indicates the start index of the "remainging" string (that still needs to be processed).
do
{
index = str.IndexOf( '&', newIndex );
if (index == -1)
{
if (sb == null)
return str;
else
{
sb.Append( str, newIndex, strLen - newIndex );
return sb.ToString();
}
}
else
{
if (sb == null)
sb = new StringBuilder();
sb.Append(str, newIndex, index - newIndex);
sb.Append( GetUnescapeSequence( str, index, out newIndex ) ); // updates the newIndex too
}
}
while (true);
// C# reports a warning if I leave this in, but I still kinda want to just in case.
// Debug.Assert( false, "If you got here, the execution engine or compiler is really confused" );
// return str;
}
private delegate void ToStringHelperFunc( Object obj, String str );
private static void ToStringHelperStringBuilder( Object obj, String str )
{
((StringBuilder)obj).Append( str );
}
public override String ToString ()
{
StringBuilder sb = new StringBuilder();
ToString( "", sb, new ToStringHelperFunc( ToStringHelperStringBuilder ) );
return sb.ToString();
}
private void ToString( String indent, Object obj, ToStringHelperFunc func )
{
// First add the indent
// func( obj, indent );
// Add in the opening bracket and the tag.
func( obj, "<" );
switch (m_type)
{
case SecurityElementType.Format:
func( obj, "?" );
break;
case SecurityElementType.Comment:
func( obj, "!" );
break;
default:
break;
}
func( obj, m_strTag );
// If there are any attributes, plop those in.
if (m_lAttributes != null && m_lAttributes.Count > 0)
{
func( obj, " " );
int iMax = m_lAttributes.Count;
Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
for (int i = 0; i < iMax; i += 2)
{
String strAttrName = (String)m_lAttributes[i];
String strAttrValue = (String)m_lAttributes[i+1];
func( obj, strAttrName );
func( obj, "=\"" );
func( obj, strAttrValue );
func( obj, "\"" );
if (i != m_lAttributes.Count - 2)
{
if (m_type == SecurityElementType.Regular)
{
func( obj, Environment.NewLine );
}
else
{
func( obj, " " );
}
}
}
}
if (m_strText == null && (m_lChildren == null || m_lChildren.Count == 0))
{
// If we are a single tag with no children, just add the end of tag text.
switch (m_type)
{
case SecurityElementType.Comment:
func( obj, ">" );
break;
case SecurityElementType.Format:
func( obj, " ?>" );
break;
default:
func( obj, "/>" );
break;
}
func( obj, Environment.NewLine );
}
else
{
// Close the current tag.
func( obj, ">" );
// Output the text
func( obj, m_strText );
// Output any children.
if (m_lChildren != null)
{
this.ConvertSecurityElementFactories();
func( obj, Environment.NewLine );
// String childIndent = indent + s_strIndent;
for (int i = 0; i < m_lChildren.Count; ++i)
{
((SecurityElement)m_lChildren[i]).ToString( "", obj, func );
}
// In the case where we have children, the close tag will not be on the same line as the
// opening tag, so we need to indent.
// func( obj, indent );
}
// Output the closing tag
func( obj, "</" );
func( obj, m_strTag );
func( obj, ">" );
func( obj, Environment.NewLine );
}
}
public String Attribute( String name )
{
if (name == null)
throw new ArgumentNullException( nameof(name) );
Contract.EndContractBlock();
// Note: we don't check for validity here because an
// if an invalid name is passed we simply won't find it.
if (m_lAttributes == null)
return null;
// Go through all the attribute and see if we know about
// the one we are asked for
int iMax = m_lAttributes.Count;
Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
for (int i = 0; i < iMax; i += 2)
{
String strAttrName = (String)m_lAttributes[i];
if (String.Equals(strAttrName, name))
{
String strAttrValue = (String)m_lAttributes[i+1];
return Unescape(strAttrValue);
}
}
// In the case where we didn't find it, we are expected to
// return null
return null;
}
public SecurityElement SearchForChildByTag( String tag )
{
// Go through all the children and see if we can
// find the one are are asked for (matching tags)
if (tag == null)
throw new ArgumentNullException( nameof(tag) );
Contract.EndContractBlock();
// Note: we don't check for a valid tag here because
// an invalid tag simply won't be found.
if (m_lChildren == null)
return null;
IEnumerator enumerator = m_lChildren.GetEnumerator();
while (enumerator.MoveNext())
{
SecurityElement current = (SecurityElement)enumerator.Current;
if (current != null && String.Equals(current.Tag, tag))
return current;
}
return null;
}
internal String SearchForTextOfLocalName(String strLocalName)
{
// Search on each child in order and each
// child's child, depth-first
if (strLocalName == null)
throw new ArgumentNullException( nameof(strLocalName) );
Contract.EndContractBlock();
// Note: we don't check for a valid tag here because
// an invalid tag simply won't be found.
// First we check this.
if (m_strTag == null) return null;
if (m_strTag.Equals( strLocalName ) || m_strTag.EndsWith( ":" + strLocalName, StringComparison.Ordinal ))
return Unescape( m_strText );
if (m_lChildren == null)
return null;
IEnumerator enumerator = m_lChildren.GetEnumerator();
while (enumerator.MoveNext())
{
String current = ((SecurityElement)enumerator.Current).SearchForTextOfLocalName( strLocalName );
if (current != null)
return current;
}
return null;
}
public String SearchForTextOfTag( String tag )
{
// Search on each child in order and each
// child's child, depth-first
if (tag == null)
throw new ArgumentNullException( nameof(tag) );
Contract.EndContractBlock();
// Note: we don't check for a valid tag here because
// an invalid tag simply won't be found.
// First we check this.
if (String.Equals(m_strTag, tag))
return Unescape( m_strText );
if (m_lChildren == null)
return null;
IEnumerator enumerator = m_lChildren.GetEnumerator();
this.ConvertSecurityElementFactories();
while (enumerator.MoveNext())
{
String current = ((SecurityElement)enumerator.Current).SearchForTextOfTag( tag );
if (current != null)
return current;
}
return null;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="TransferItem.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
//------------------------------------------------------------------------------
namespace DMLibTest
{
using System;
using System.Globalization;
using System.IO;
using System.Threading;
using DMLibTestCodeGen;
using Microsoft.Azure.Storage.Blob;
using Microsoft.Azure.Storage.DataMovement;
using Microsoft.Azure.Storage.File;
public class TransferItem
{
public object SourceObject
{
get;
set;
}
public object DestObject
{
get;
set;
}
public DMLibDataType SourceType
{
get;
set;
}
public DMLibDataType DestType
{
get;
set;
}
public CopyMethod CopyMethod
{
get;
set;
}
public bool IsDirectoryTransfer
{
get;
set;
}
public object Options
{
get;
set;
}
public TransferContext TransferContext
{
get;
set;
}
public CancellationToken CancellationToken
{
get;
set;
}
public Action BeforeStarted
{
get;
set;
}
public Action AfterStarted
{
get;
set;
}
public TransferStatus FinalStatus
{
get;
set;
}
public bool DisableStreamDispose
{
get;
set;
}
public Exception Exception
{
get;
set;
}
public void CloseStreamIfNecessary()
{
if (!DisableStreamDispose)
{
Stream sourceStream = this.SourceObject as Stream;
Stream destStream = this.DestObject as Stream;
if (sourceStream != null)
{
#if DNXCORE50
sourceStream.Dispose();
#else
sourceStream.Close();
#endif
}
if (destStream != null)
{
#if DNXCORE50
destStream.Dispose();
#else
destStream.Close();
#endif
}
}
}
public TransferItem Clone()
{
TransferItem newTransferItem = new TransferItem()
{
SourceObject = NewLocationObject(this.SourceObject),
DestObject = NewLocationObject(this.DestObject),
SourceType = this.SourceType,
DestType = this.DestType,
IsDirectoryTransfer = this.IsDirectoryTransfer,
CopyMethod = this.CopyMethod,
Options = this.Options,
};
return newTransferItem;
}
private static object NewLocationObject(object locationObject)
{
if (locationObject is CloudBlob)
{
CloudBlob cloudBlob = locationObject as CloudBlob;
if (cloudBlob is CloudPageBlob)
{
return new CloudPageBlob(cloudBlob.SnapshotQualifiedUri, cloudBlob.ServiceClient.Credentials);
}
else if (cloudBlob is CloudBlockBlob)
{
return new CloudBlockBlob(cloudBlob.SnapshotQualifiedUri, cloudBlob.ServiceClient.Credentials);
}
else if (cloudBlob is CloudAppendBlob)
{
return new CloudAppendBlob(cloudBlob.SnapshotQualifiedUri, cloudBlob.ServiceClient.Credentials);
}
else
{
throw new ArgumentException(string.Format("Unsupported blob type: {0}", cloudBlob.BlobType), "locationObject");
}
}
else if (locationObject is CloudFile)
{
CloudFile cloudFile = locationObject as CloudFile;
CloudFile newCloudFile = new CloudFile(cloudFile.Uri, cloudFile.ServiceClient.Credentials);
return newCloudFile;
}
else
{
return locationObject;
}
}
public override string ToString()
{
return string.Format(
CultureInfo.InvariantCulture,
"{0} -> {1}",
this.GetDataObjectString(this.SourceObject),
this.GetDataObjectString(this.DestObject));
}
private string GetDataObjectString(object dataObject)
{
if (dataObject is CloudBlob)
{
return (dataObject as CloudBlob).SnapshotQualifiedUri.ToString();
}
else if (dataObject is CloudFile)
{
return (dataObject as CloudFile).Uri.ToString();
}
else if (dataObject is CloudBlobDirectory)
{
return (dataObject as CloudBlobDirectory).Uri.ToString();
}
else if (dataObject is CloudFileDirectory)
{
return (dataObject as CloudFileDirectory).Uri.ToString();
}
return dataObject.ToString();
}
}
}
| |
// ----------------------------------------------------------------------------
// <copyright file="Scenario.cs" company="HIVacSim">
// Copyright (c) 2014 HIVacSim Contributors
// </copyright>
// <author>Israel Vieira</author>
// ----------------------------------------------------------------------------
namespace HIVacSim
{
using System;
using System.ComponentModel;
using System.Drawing.Design;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Schema;
using HIVacSim.Utility;
/// <summary>
/// Defines the simulation scenario class, the manager of the
/// simulation data and file I/O.
/// </summary>
public class Scenario
{
#region Local variables
//===========================================
//Scenario data
//===========================================
/// <summary>
/// The scenario population
/// </summary>
protected Population _pop;
/// <summary>
/// The scenario disease of interest
/// </summary>
protected Disease _info;
/// <summary>
/// The scenario preventive vaccine
/// </summary>
protected Vaccines _vaccine;
/// <summary>
/// The scenario intervention strategy
/// </summary>
protected Strategies _inteven;
/// <summary>
/// The scenario random number generator
/// </summary>
protected RandomDeviate _rnd;
/// <summary>
/// The scenario random number generator seed
/// </summary>
protected bool _seedAuto;
/// <summary>
/// The scenario random number generator seed
/// </summary>
protected int _seedUser;
/// <summary>
/// Uniform / Clustered initial distribution of infection
/// </summary>
protected bool _uinfect;
//===========================================
//Simulation configuration
//===========================================
/// <summary>
/// Simulation's external clock
/// </summary>
protected ESimClock _simClock;
/// <summary>
/// Simulation's start date
/// </summary>
protected DateTime _simDate;
/// <summary>
/// Duration of each simulation
/// </summary>
protected int _simDuration;
/// <summary>
/// Number of simulation runs
/// </summary>
protected int _simRuns;
/// <summary>
/// Simulation warm-up type
/// </summary>
protected EWarmup _simWarmType;
/// <summary>
/// Simulation warm-up duration
/// </summary>
protected int _simWarmupLen;
/// <summary>
/// Simulation warm-up minimum # of concurrent partners
/// </summary>
protected int _simWMaxConc;
/// <summary>
/// Simulation warm-up probability of concurrent partners
/// </summary>
protected double _simWPrConc;
/// <summary>
/// Simulation warm-up # of initial infected people
/// </summary>
protected Stochastic _simWInfected;
/// <summary>
/// Simulation's speed [1,100]
/// </summary>
protected int _simSpeed;
/// <summary>
/// Simulation's maximum delay for animation
/// </summary>
protected int _simMaxDelay;
/// <summary>
/// Current simulation sleep time
/// </summary>
protected int _simDelay;
/// <summary>
/// Simulation animation flag
/// </summary>
protected bool _simAnimate;
//===========================================
//File I/O Control variables
//===========================================
/// <summary>
/// Indicates a that a file is open
/// </summary>
protected bool _fileOpen;
/// <summary>
/// Scenario file name
/// </summary>
protected string _fileName;
/// <summary>
/// New file, never saved before
/// </summary>
protected bool _fileNew;
/// <summary>
/// The current file has unsaved changes
/// </summary>
protected bool _fileChanged;
/// <summary>
/// Description of the scenario
/// </summary>
protected string _fileInfo;
//===========================================
//Path Length calculation
//===========================================
/// <summary>
/// The maximum population size to calculate numerically
/// </summary>
protected int _plnumeric;
/// <summary>
/// The sample size for estimation
/// </summary>
protected int _plsample;
/// <summary>
/// The SWN p-value to switch algorithm
/// </summary>
protected double _plalgo;
//===========================================
//Control
//===========================================
/// <summary>
/// Scenario validation error log
/// </summary>
protected string _errLog;
#endregion
#region Constructor
/// <summary>
/// Default constructor
/// </summary>
public Scenario()
{
//Random number generator setup
this._rnd = new RandomDeviate();
this._seedAuto = true; //Initialise the generator with a automatic seed
this._seedUser = 19650218; //Default custom seed
this._simWMaxConc = 2; //Default number of concurrent partners
this._simWPrConc = 0.5; //Default probability of concurrent partners
this._simWInfected = new Stochastic(DeviateFunction.Average, 1.0);
this._errLog = "No validation errors were reported.";
}
#endregion
#region Public properties
/// <summary>
/// Returns the current population defined within the scenario.
/// </summary>
[CategoryAttribute("Configuration"),
BrowsableAttribute(false),
DescriptionAttribute("Returns the current population defined within the scenario.")]
public Population Data
{
get { return this._pop; }
}
/// <summary>
/// Gets the scenario's information to transmit (disease) definition.
/// </summary>
[CategoryAttribute("Configuration"),
BrowsableAttribute(false),
DescriptionAttribute("Gets the scenario's information to transmit (disease) definition.")]
public Disease Info
{
get { return this._info; }
}
/// <summary>
/// Gets the scenario's preventive vaccine definition.
/// </summary>
[CategoryAttribute("Configuration"),
BrowsableAttribute(false),
DescriptionAttribute("Gets the scenario's preventive vaccine definition.")]
public Vaccines Vaccine
{
get { return this._vaccine; }
}
/// <summary>
/// Gets the scenario's intervention strategies definition.
/// </summary>
[CategoryAttribute("Configuration"),
BrowsableAttribute(false),
DescriptionAttribute("Gets the scenario's intervention strategies definition.")]
public Strategies Strategy
{
get { return this._inteven; }
}
/// <summary>
/// Gets the scenario's random number generator.
/// </summary>
[CategoryAttribute("Configuration"),
BrowsableAttribute(false),
DescriptionAttribute("Gets the scenario's random number generator.")]
public RandomDeviate Rnd
{
get { return this._rnd; }
}
/// <summary>
/// Gets or sets the random number generator seeding behaviour.
/// </summary>
/// <remarks>
/// The default option (<c>true</c>) initialise the random number generator once
/// on start up with a internal generated seed using the system data/time, this
/// option will cause every simulation trial to generate a different results.
/// <p></p>
/// Alternatively, the user can disable the auto seeding option and use define
/// a custom seed, which reset the random number generator to its initial status
/// before start a new trial. This means that a second run of the same simulation
/// trial will produce the same results.
/// </remarks>
[CategoryAttribute("Random Number"),
DefaultValueAttribute(true),
DescriptionAttribute("Gets or Sets the random number generator seeding behaviour.")]
public bool AutoSeed
{
get
{
return this._seedAuto;
}
set
{
this._seedAuto = value;
if (this._seedAuto)
{
this._rnd.ReSeed(Environment.TickCount);
}
}
}
/// <summary>
/// Gets or sets the random number generator custom seed.
/// </summary>
/// <remarks>
/// This seed is used only when the scenario AutoSeed option is disabled
/// </remarks>
[CategoryAttribute("Random Number"),
DefaultValueAttribute(19650218U),
DescriptionAttribute("Gets or Sets the random number generator custom seed.")]
public int CustomSeed
{
get { return this._seedUser; }
set { this._seedUser = value; }
}
/// <summary>
/// Gets or sets the uniform spread of the initial STD infection.
/// </summary>
[CategoryAttribute("WarmUp"),
DefaultValueAttribute(false),
DescriptionAttribute("Gets or sets the uniform spread of the initial STD infection.")]
public bool UInfection
{
get { return this._uinfect; }
set { this._uinfect = value; }
}
/// <summary>
/// Gets or sets the external simulation clock.
/// </summary>
[CategoryAttribute("Configuration"),
DefaultValueAttribute(ESimClock.Month),
DescriptionAttribute("Gets or Sets the external simulation clock.")]
public ESimClock UserClock
{
get { return this._simClock; }
set { this._simClock = value; }
}
/// <summary>
/// Gets or sets the simulation starting date.
/// </summary>
[CategoryAttribute("Configuration"),
DescriptionAttribute("Gets or Sets the simulation starting date.")]
public DateTime StartDate
{
get { return this._simDate; }
set { this._simDate = value; }
}
/// <summary>
/// Gets or sets the duration of each simulation run.
/// </summary>
[CategoryAttribute("Configuration"),
DefaultValueAttribute(144),
DescriptionAttribute("Gets or Sets the duration of each simulation run.")]
public int Duration
{
get
{
return this._simDuration;
}
set
{
if (value >= 1)
{
this._simDuration = value;
}
}
}
/// <summary>
/// Gets or sets the number of simulation runs
/// </summary>
[CategoryAttribute("Configuration"),
DefaultValueAttribute(10),
DescriptionAttribute("Gets or Sets the duration of each simulation run.")]
public int Runs
{
get
{
return this._simRuns;
}
set
{
if (value >= 1)
{
this._simRuns = value;
}
}
}
/// <summary>
/// Gets or sets the simulation warm-up configuration.
/// </summary>
[CategoryAttribute("WarmUp"),
DefaultValueAttribute(EWarmup.Traditional),
DescriptionAttribute("Gets or Sets the simulation warm-up configuration.")]
public EWarmup WarmUpType
{
get { return this._simWarmType; }
set { this._simWarmType = value; }
}
/// <summary>
/// Gets or sets the duration of the warm-up for Traditional and Temporal
/// warm-up types. For Conditional warm-p, it defines the maximum
/// number of interactions without convergence.
/// </summary>
[CategoryAttribute("WarmUp"),
DefaultValueAttribute(24),
DescriptionAttribute("Gets or sets the duration of the warm-up for " +
"Traditional and Temporal types. For Conditional warm-up, it " +
"defines the maximum number of interactions without convergence.")]
public int WarmUpTime
{
get
{
return this._simWarmupLen;
}
set
{
if (value >= 0)
{
this._simWarmupLen = value;
}
}
}
/// <summary>
/// Gets or sets the minimum number of concurrent partnerships
/// allowed during the simulation warm-up.
/// </summary>
/// <remarks>
/// After completing the warm-up this number switches back to the
/// original concurrency value defined within each group.
/// </remarks>
[CategoryAttribute("WarmUp"),
DefaultValueAttribute(2),
DescriptionAttribute("Gets or sets the minimum number of concurrent " +
"partnerships allowed during the simulation warm-up.")]
public int WMaxConcurrent
{
get
{
return this._simWMaxConc;
}
set
{
if (value >= 1)
{
this._simWMaxConc = value;
}
else
{
throw new SimulationException(
"Invalid maximum number of concurrent partners during warm-up [x < 1]");
}
}
}
/// <summary>
/// Gets or sets the probability of concurrent partnerships
/// during the simulation warm-up.
/// </summary>
/// <remarks>
/// After completing the warm-up this number switches back to the
/// original concurrency value defined within each group.
/// </remarks>
[CategoryAttribute("WarmUp"),
DefaultValueAttribute(0.5),
DescriptionAttribute("Gets or sets the probability of concurrent " +
"partnerships during the simulation warm-up.")]
public double WPrConcurrent
{
get { return this._simWPrConc; }
set
{
if (Group.IsProbability(value) && value > 0.0)
{
this._simWPrConc = value;
}
else
{
throw new SimulationException(
"Invalid probability of concurrent partnerships during warm-up [x <= 0.0]");
}
}
}
/// <summary>
/// Gets or sets the number of initial infected individuals for
/// temporal and conditional warm-up.
/// </summary>
[CategoryAttribute("WarmUp"),
DescriptionAttribute("Gets or sets the number of initial infected " +
"individuals for Temporal and Conditional warm-up."),
Editor(typeof(DistributionValueEditor), typeof(UITypeEditor))]
public Stochastic WarmUpInfected
{
get { return this._simWInfected; }
set { this._simWInfected = value; }
}
/// <summary>
/// Gets or sets the simulation speed.
/// </summary>
[CategoryAttribute("Configuration"),
DefaultValueAttribute(100),
DescriptionAttribute("Get or Set the simulation speed.")]
public int Speed
{
get
{
return this._simSpeed;
}
set
{
if (value >= 0 && value <= 100)
{
this._simSpeed = value;
this._simDelay = (int)(this._simMaxDelay - ((this._simMaxDelay * 0.5) * (value * 0.02)));
}
}
}
/// <summary>
/// Get or set the maximum delay for animation.
/// </summary>
[CategoryAttribute("Configuration"),
DefaultValueAttribute(2000),
DescriptionAttribute("Get or Set the maximum delay for animation.")]
public int MaximumDelay
{
get { return this._simMaxDelay; }
set
{
if (value > 0)
{
this._simMaxDelay = value;
this._simDelay = (int)(value - ((value * 0.5) * (this._simSpeed * 0.02)));
}
}
}
/// <summary>
/// Gets the simulation current delay for animation.
/// </summary>
[CategoryAttribute("Configuration"),
DefaultValueAttribute(0),
BrowsableAttribute(false),
DescriptionAttribute("Gets the simulation current delay for animation.")]
public int Delay
{
get { return this._simDelay; }
}
/// <summary>
/// Gets or sets the simulation animation status.
/// </summary>
[CategoryAttribute("Configuration"),
DefaultValueAttribute(false),
DescriptionAttribute("Gets or Sets the simulation animation status.")]
public bool Animation
{
get { return this._simAnimate; }
set { this._simAnimate = value; }
}
/// <summary>
/// Gets the scenario validation erro log.
/// </summary>
[CategoryAttribute("Validation"),
DefaultValueAttribute("No validation errors were reported."),
BrowsableAttribute(false),
DescriptionAttribute("Gets the scenario validation erro log.")]
public string ErrorLog
{
get { return this._errLog; }
}
/// <summary>
/// Gets or sets the maximum size for numerical calculation of the
/// network efficiency (path length)
/// </summary>
[CategoryAttribute("Path Length"),
DefaultValueAttribute(500),
DescriptionAttribute("Gets or sets the maximum size for numerical " +
"calculation of the network efficiency (path length)")]
public int PLNumerical
{
get
{
return this._plnumeric;
}
set
{
if (value >= 0)
{
this._plnumeric = value;
}
}
}
/// <summary>
/// Gets or sets the sample size for estimating the network
/// efficiency (path length)
/// </summary>
[CategoryAttribute("Path Length"),
DefaultValueAttribute(400),
DescriptionAttribute("Gets or sets the sample size for estimating " +
"the network efficiency (path length)")]
public int PLEstimate
{
get
{
return this._plsample;
}
set
{
if (value > 5)
{
this._plsample = value;
}
}
}
/// <summary>
/// Gets or sets the SWN p value (probability of casual) for
/// switching algorithm (Floyd 0--p--1 BFS)
/// </summary>
[CategoryAttribute("Path Length"),
DefaultValueAttribute(0.13),
DescriptionAttribute("Gets or sets the SWN p value (probability " +
"of casual) for switching algorithm (Floyd 0--p--1 BFS)")]
public double PLAlgorithm
{
get
{
return this._plalgo;
}
set
{
if (Group.IsProbability(value))
{
this._plalgo = value;
}
}
}
#endregion
#region Public Methods
/// <summary>
/// Creates a new simulation scenario
/// </summary>
/// <returns>True if successful, false otherwise</returns>
public bool NewScenario()
{
//Reset the scenario and std definition
if (CloseScenario())
{
this._info = new Disease("HIV/AIDS");
this._pop = new Population();
this._vaccine = new Vaccines();
this._inteven = new Strategies();
this._fileOpen = true;
this._fileNew = true;
this._fileName = "Untitled.xml";
this.SimDefault();
return true;
}
else
{
return false;
}
}
/// <summary>
/// Close current simulation scenario
/// </summary>
/// <returns>True if successful, false otherwise</returns>
public bool CloseScenario()
{
if (!this._fileOpen)
{
return true;
}
this._fileOpen = false;
this._fileNew = false;
this._fileName = "";
this._fileChanged = false;
this._fileInfo = "";
this._info = null;
this._pop.Clear();
this._pop = null;
this._vaccine.Clear();
this._vaccine = null;
this._inteven.Clear();
this._inteven = null;
this._errLog = "No validation errors were reported.";
System.GC.Collect();
return true;
}
/// <summary>
/// Sets the default simulation parameters
/// </summary>
public void SimDefault()
{
//Default values
this._simDate = DateTime.Now;
this._simClock = ESimClock.Month;
this._simDuration = 144;
this._simRuns = 10;
this._uinfect = false;
this._simWarmType = EWarmup.Traditional;
this._simWarmupLen = 24;
this.MaximumDelay = 2000; //(2 Seconds)
this._simSpeed = 100;
this._seedAuto = true;
this._seedUser = 19650218;
this._simWMaxConc = 2;
this._simWPrConc = 0.5;
this._errLog = "No validation errors were reported.";
this._plnumeric = 500;
this._plsample = 400;
this._plalgo = 0.13;
}
/// <summary>
/// Validate the scenario data
/// </summary>
/// <remarks>
/// The cause of the scenario invalidation can be found in the
/// <see cref="ErrorLog"/> property, immediately after the return.
/// </remarks>
/// <returns>
/// <c>true</c> if valid, otherwise <c>false</c>
/// </returns>
public bool ValidateScenario()
{
//Local variables
int g, gCount, p;
double rsum;
Group grp;
bool valid;
string nl = Environment.NewLine;
//Setup
this._errLog = "";
valid = true;
gCount = this._pop.Count;
//Checks for a valid file
if (this._fileOpen == false)
{
this._errLog += "No file open!" + nl;
valid = false;
}
//Validate the Population Size
for (g = 0; g < gCount; g++)
{
grp = this._pop[g];
if (grp.Size < 2)
{
this._errLog += "Invalid population size for Group [" +
grp.Name + "]." + nl;
valid = false;
}
}
//Validate spherical search distance definition
for (g = 0; g < gCount; g++)
{
grp = this._pop[g];
if (grp.Topology == ETopology.Sphere)
{
if (Math.Cos(grp.Distance / grp.Radius) > (Math.PI * grp.Radius))
{
this._errLog += "Invalid sphere searching distance " +
"for population group [" + grp.Name + "]" + nl;
valid = false;
}
}
}
//Validate adjMatrix
for (g = 0; g < gCount; g++)
{
rsum = 0.0;
for (p = 0; p < gCount; p++)
{
if (g == p) //Diagonal
{
if (this._pop.AdjMatrix[g, p] != 0.0)
{
this._errLog += "Adj. Matrix invalid diagonal at [" +
g.ToString() + "," + p.ToString() + "] = " +
this._pop.AdjMatrix[g, p] + nl;
valid = false;
}
}
else
{
if (this._pop.AdjMatrix[g, p] < 0.0 || this._pop.AdjMatrix[g, p] > 1.0)
{
this._errLog += "Adj. Matrix invalid value at [" +
g.ToString() + "," + p.ToString() + "] = " +
this._pop.AdjMatrix[g, p] + nl;
valid = false;
}
rsum += this._pop.AdjMatrix[g, p];
}
}
if (rsum != 0.0 && rsum != 1.0)
{
this._errLog += "Adj. Matrix invalid sum at row [" +
g.ToString() + "] = " + rsum.ToString() + nl;
valid = false;
}
}
//######### TODO ##########
//Validate vaccines
//Validate interventions
//#########################
//reset the error log
if (valid)
{
this._errLog = "No validation errors were reported.";
}
//Returns the result
return valid;
}
#endregion
#region File I/O Methods
/// <summary>
/// Gets the current scenario file status
/// </summary>
[CategoryAttribute("File I/O"),
BrowsableAttribute(false),
DescriptionAttribute("Gets the current scenario file status")]
public bool IsFileOpen
{
get { return this._fileOpen; }
}
/// <summary>
/// Gets the current scenario full file name
/// </summary>
[CategoryAttribute("File I/O"),
BrowsableAttribute(false),
DescriptionAttribute("Gets the current scenario full file name")]
public string FileName
{
get { return this._fileName; }
}
/// <summary>
/// Gets the current scenario short file name
/// </summary>
[CategoryAttribute("File I/O"),
BrowsableAttribute(false),
DescriptionAttribute("Gets the current scenario short file name")]
public string ShortFileName
{
get
{
return this._fileName.Substring(this._fileName.LastIndexOf("\\") + 1);
}
}
/// <summary>
/// Gets the current scenario file creation status
/// </summary>
[CategoryAttribute("File I/O"),
BrowsableAttribute(false),
DescriptionAttribute("Gets the current scenario file creation status")]
public bool IsFileNew
{
get { return this._fileNew; }
}
/// <summary>
/// Gets or sets the current scenario file saving status
/// </summary>
[CategoryAttribute("File I/O"),
BrowsableAttribute(false),
DescriptionAttribute("Gets or sets the current scenario file saving status")]
public bool HasFileChanged
{
get { return this._fileChanged; }
set { this._fileChanged = value; }
}
/// <summary>
/// Gets or sets the scenario file description
/// </summary>
[CategoryAttribute("File I/O"),
BrowsableAttribute(false),
DescriptionAttribute("Gets or sets the scenario file description")]
public string Description
{
get { return this._fileInfo; }
set { this._fileInfo = value; }
}
/// <summary>
/// Save the current scenarion data to a Xml file
/// </summary>
/// <param name="inFileName">
/// The path and name of the file to save the scenario
/// </param>
/// <returns>True if successful, False otherwise</returns>
public bool SaveScenario(string inFileName)
{
XmlTextWriter xmlWrite = new XmlTextWriter(
inFileName,
System.Text.Encoding.UTF8);
xmlWrite.Formatting = Formatting.Indented;
xmlWrite.Indentation = 4;
//Start the XML Document
xmlWrite.WriteStartDocument();
//Write root element
xmlWrite.WriteStartElement("HIVacSim");
xmlWrite.WriteAttributeString("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
xmlWrite.WriteAttributeString("xmlns", "urn:HIVacSim");
xmlWrite.WriteAttributeString("xsi:schemaLocation", "urn:HIVacSim HIVacSimData.xsd");
xmlWrite.WriteAttributeString("Title",
"Simulation Models for the Control of the Dynamics of HIV Infection Through Vaccination");
xmlWrite.WriteAttributeString("by", "Israel Vieira");
xmlWrite.WriteAttributeString("Version", "1.7");
//Scenarion Settings
xmlWrite.WriteComment("Scenario's simulation settings definition.");
xmlWrite.WriteStartElement("Scenario");
xmlWrite.WriteElementString("Description", this._fileInfo);
xmlWrite.WriteElementString("SimClock", this._simClock.ToString());
xmlWrite.WriteElementString("RunDuration", this._simDuration.ToString());
xmlWrite.WriteElementString("NumberOfRuns", this._simRuns.ToString());
xmlWrite.WriteElementString("WarmUpType", this._simWarmType.ToString());
xmlWrite.WriteElementString("WarmUp", this._simWarmupLen.ToString());
xmlWrite.WriteElementString("WarmUpMaxConcurrent", this._simWMaxConc.ToString());
xmlWrite.WriteElementString("WarmUpPrConcurrent", this._simWPrConc.ToString("R"));
this.Stochastic2Xml("WarmUpInfected", xmlWrite, this._simWInfected);
xmlWrite.WriteElementString("Speed", this._simSpeed.ToString());
xmlWrite.WriteElementString("MaxDelay", this._simMaxDelay.ToString());
xmlWrite.WriteElementString("Animation", this._simAnimate.ToString().ToLower());
xmlWrite.WriteElementString("AutoSeed", this._seedAuto.ToString().ToLower());
xmlWrite.WriteElementString("CustomSeed", this._seedUser.ToString());
xmlWrite.WriteElementString("PLNumerical", this._plnumeric.ToString());
xmlWrite.WriteElementString("PLEstimate", this._plsample.ToString());
xmlWrite.WriteElementString("PLAlgorithm", this._plalgo.ToString("R"));
xmlWrite.WriteEndElement();//HIVacSim
//STD Definition
xmlWrite.WriteComment("Define the disease of interest to be simulated");
xmlWrite.WriteStartElement("Disease");
xmlWrite.WriteElementString("Name", this._info.Name);
xmlWrite.WriteElementString("Male2Female", this._info.Male2Female.ToString("R"));
xmlWrite.WriteElementString("Female2Male", this._info.Female2Male.ToString("R"));
xmlWrite.WriteElementString("Male2Male", this._info.Male2Male.ToString("R"));
xmlWrite.WriteElementString("LifeInfection", this._info.LifeInfection.ToString().ToLower());
this.Stochastic2Xml("STDDuration", xmlWrite, this._info.STDDuration);
xmlWrite.WriteElementString("AllowReinfection", this._info.AllowReinfection.ToString().ToLower());
xmlWrite.WriteElementString("Mortality", this._info.Mortality.ToString("R"));
this.Stochastic2Xml("LifeExpectancy", xmlWrite, this._info.LifeExpectancy);
xmlWrite.WriteEndElement();//Disease
//Save population and core Groups definitions
xmlWrite.WriteComment("Population Core Groups Definition");
xmlWrite.WriteStartElement("Population");
xmlWrite.WriteAttributeString("Count", this._pop.Count.ToString());
Group cGroup;
int idx, i, j, grpCount;
grpCount = this._pop.Count;
for (idx = 0; idx < grpCount; idx++)
{
cGroup = this._pop[idx];
xmlWrite.WriteStartElement("Group");
xmlWrite.WriteAttributeString("Name", cGroup.Name);
xmlWrite.WriteElementString("Id", cGroup.Id.ToString());
xmlWrite.WriteElementString("Topology", cGroup.Topology.ToString());
xmlWrite.WriteElementString("Alpha", cGroup.Alpha.ToString("R"));
xmlWrite.WriteElementString("Beta", cGroup.Beta.ToString("R"));
xmlWrite.WriteElementString("Radius", cGroup.Radius.ToString("R"));
xmlWrite.WriteElementString("Distance", cGroup.Distance.ToString("R"));
xmlWrite.WriteElementString("Degrees", cGroup.Degrees.ToString());
xmlWrite.WriteElementString("Size", cGroup.Size.ToString());
this.Stochastic2Xml("Age", xmlWrite, cGroup.Age);
this.Stochastic2Xml("LifeExpectancy", xmlWrite, cGroup.LifeExpectancy);
xmlWrite.WriteElementString("STDPrevalence", cGroup.STDPrevalence.ToString("R"));
this.Stochastic2Xml("STDAge", xmlWrite, cGroup.STDAge);
xmlWrite.WriteElementString("STDTest", cGroup.STDTest.ToString("R"));
xmlWrite.WriteElementString("Female", cGroup.Female.ToString("R"));
xmlWrite.WriteElementString("Male", cGroup.Male.ToString("R"));
xmlWrite.WriteElementString("Homosexual", cGroup.Homosexual.ToString("R"));
xmlWrite.WriteElementString("MaxConcurrent", cGroup.MaxConcurrent.ToString());
xmlWrite.WriteElementString("PrConcurrent", cGroup.PrConcurrent.ToString("R"));
xmlWrite.WriteElementString("PrNewPartner", cGroup.PrNewPartner.ToString("R"));
xmlWrite.WriteElementString("PrCasual", cGroup.PrCasual.ToString("R"));
xmlWrite.WriteElementString("PrInternal", cGroup.PrInternal.ToString("R"));
this.Stochastic2Xml("StbDuration", xmlWrite, cGroup.StbDuration);
this.Stochastic2Xml("StbTransitory", xmlWrite, cGroup.StbTransitory);
this.Stochastic2Xml("StbContacts", xmlWrite, cGroup.StbContacts);
xmlWrite.WriteElementString("StbSafeSex", cGroup.StbSafeSex.ToString("R"));
this.Stochastic2Xml("CslDuration", xmlWrite, cGroup.CslDuration);
this.Stochastic2Xml("CslContacts", xmlWrite, cGroup.CslContacts);
xmlWrite.WriteElementString("CslSafeSex", cGroup.CslSafeSex.ToString("R"));
xmlWrite.WriteEndElement();//Group
}
//Population
xmlWrite.WriteEndElement();
//Save population digraph adjacency matrix
xmlWrite.WriteComment("Population interaction, digraph adjacency matrix");
xmlWrite.WriteStartElement("AdjMatrix");
xmlWrite.WriteAttributeString("Rows", grpCount.ToString());
xmlWrite.WriteAttributeString("Columns", grpCount.ToString());
for (i = 0; i < grpCount; i++)
{
for (j = 0; j < grpCount; j++)
{
xmlWrite.WriteStartElement("Cell");
xmlWrite.WriteAttributeString("Row", i.ToString());
xmlWrite.WriteAttributeString("Column", j.ToString());
xmlWrite.WriteAttributeString("Data", this._pop.AdjMatrix[i, j].ToString("R"));
xmlWrite.WriteEndElement();
}
}
//AdjMatrix
xmlWrite.WriteEndElement();
//Save vaccines
xmlWrite.WriteComment("Preventive vaccine interventions");
xmlWrite.WriteStartElement("Vaccines");
xmlWrite.WriteAttributeString("Count", this._vaccine.Count.ToString());
if (this._vaccine.Count > 0)
{
Vaccine cVac;
grpCount = this._vaccine.Count;
for (idx = 0; idx < grpCount; idx++)
{
cVac = this._vaccine[idx];
xmlWrite.WriteStartElement("Vaccine");
xmlWrite.WriteAttributeString("Name", cVac.Name);
xmlWrite.WriteElementString("Id", cVac.Id.ToString());
xmlWrite.WriteElementString("Effectiveness", cVac.Effectiveness.ToString("R"));
xmlWrite.WriteElementString("Lifetime", cVac.Lifetime.ToString().ToLower());
xmlWrite.WriteElementString("Length", cVac.Length.ToString());
xmlWrite.WriteElementString("UsedBy", cVac.UsedBy.ToString());
xmlWrite.WriteEndElement();
}
}
//Vaccines
xmlWrite.WriteEndElement();
//Save intervention strategies
xmlWrite.WriteComment("Intervention strategies");
xmlWrite.WriteStartElement("Interventions");
xmlWrite.WriteAttributeString("Count", this._inteven.Count.ToString());
if (this._inteven.Count > 0)
{
Strategy cStrat;
grpCount = this._inteven.Count;
for (idx = 0; idx < grpCount; idx++)
{
cStrat = this._inteven[idx];
xmlWrite.WriteStartElement("Strategy");
xmlWrite.WriteAttributeString("Name", cStrat.Name);
xmlWrite.WriteElementString("Id", cStrat.Id.ToString());
xmlWrite.WriteElementString("Active", cStrat.Active.ToString().ToLower());
xmlWrite.WriteElementString("Strategy", cStrat.Intevention.ToString());
xmlWrite.WriteElementString("Groups", cStrat.Groups.ToString());
xmlWrite.WriteElementString("Clock", cStrat.Clock.ToString());
xmlWrite.WriteElementString("Population", cStrat.Population.ToString());
xmlWrite.WriteElementString("Vaccine", cStrat.UseVaccine.Id.ToString());
xmlWrite.WriteElementString("HIVTested", cStrat.HIVTested.ToString().ToLower());
xmlWrite.WriteElementString("HIVResult", cStrat.HIVResult.ToString());
xmlWrite.WriteEndElement();
}
}
//Strategy
xmlWrite.WriteEndElement();
//End HIVacSim Element
xmlWrite.WriteEndElement();
//End the XML Document
xmlWrite.WriteEndDocument();
xmlWrite.Flush();
xmlWrite.Close();
//Reset Flags
this._fileNew = false;
this._fileName = inFileName;
this._fileChanged = false;
return true;
}
/// <summary>
/// Writes a stochastic data structure to a Xml file
/// </summary>
/// <param name="label">The XML element header</param>
/// <param name="file">The <see cref="XmlTextWriter"/>file handler to write the data</param>
/// <param name="data">The <see cref="System.Xml"/> data to write to file</param>
private void Stochastic2Xml(string label, XmlTextWriter file, Stochastic data)
{
file.WriteStartElement(label);
file.WriteElementString("Distribution", data.Distribution.ToString());
file.WriteElementString("ParamOne", data.Parameter1.ToString("R"));
file.WriteElementString("ParamTwo", data.Parameter2.ToString("R"));
file.WriteElementString("ParamThree", data.Parameter3.ToString("R"));
file.WriteElementString("ParamFour", data.Parameter4.ToString("R"));
file.WriteEndElement();
}
/// <summary>
/// Open a scenario from a Xml file
/// </summary>
/// <param name="inFileName">
/// The path and name of the scenario file to open
/// </param>
/// <param name="xsdPath">The path of the XML validation schema</param>
/// <returns>True if successful, False otherwise</returns>
public bool OpenScenario(string xsdPath, string inFileName)
{
//Validate the input file
if (!XMLValidator(xsdPath, inFileName))
{
return false;
}
//Create a new scenario
this.NewScenario();
//Read xml file
XmlTextReader xmlfile = new XmlTextReader(inFileName);
XPathDocument xpnDoc = new XPathDocument(xmlfile);
XPathNavigator xpnNav = xpnDoc.CreateNavigator();
//Move to root and first children - HIVacSim
xpnNav.MoveToRoot(); //Root node
xpnNav.MoveToFirstChild(); //HIVacSim
if (!xpnNav.MoveToFirstChild())
{
return false;
}
do
{
if (xpnNav.NodeType == XPathNodeType.Element)
{
switch (xpnNav.Name)
{
case "Scenario":
{
xpnNav.MoveToFirstChild();
this._fileInfo = xpnNav.Value;
xpnNav.MoveToNext();
this._simClock = (ESimClock)Enum.Parse(typeof(ESimClock), xpnNav.Value);
xpnNav.MoveToNext();
this._simDuration = int.Parse(xpnNav.Value);
xpnNav.MoveToNext();
this._simRuns = int.Parse(xpnNav.Value);
xpnNav.MoveToNext();
this._simWarmType = (EWarmup)Enum.Parse(typeof(EWarmup), xpnNav.Value);
xpnNav.MoveToNext();
this._simWarmupLen = int.Parse(xpnNav.Value);
xpnNav.MoveToNext();
this._simWMaxConc = int.Parse(xpnNav.Value);
xpnNav.MoveToNext();
this._simWPrConc = double.Parse(xpnNav.Value);
xpnNav.MoveToNext();
this._simWInfected = Xml2Stochastic(xpnNav);
xpnNav.MoveToNext();
this._simSpeed = int.Parse(xpnNav.Value);
xpnNav.MoveToNext();
this.MaximumDelay = int.Parse(xpnNav.Value);
xpnNav.MoveToNext();
this._simAnimate = bool.Parse(xpnNav.Value);
xpnNav.MoveToNext();
this._seedAuto = bool.Parse(xpnNav.Value);
xpnNav.MoveToNext();
this._seedUser = int.Parse(xpnNav.Value);
xpnNav.MoveToNext();
this._plnumeric = int.Parse(xpnNav.Value);
xpnNav.MoveToNext();
this._plsample = int.Parse(xpnNav.Value);
xpnNav.MoveToNext();
this._plalgo = double.Parse(xpnNav.Value);
xpnNav.MoveToParent();
break;
}
case "Disease":
{
xpnNav.MoveToFirstChild();
this._info.Name = xpnNav.Value;
xpnNav.MoveToNext();
this._info.Male2Female = double.Parse(xpnNav.Value);
xpnNav.MoveToNext();
this._info.Female2Male = double.Parse(xpnNav.Value);
xpnNav.MoveToNext();
this._info.Male2Male = double.Parse(xpnNav.Value);
xpnNav.MoveToNext();
this._info.LifeInfection = bool.Parse(xpnNav.Value);
xpnNav.MoveToNext();
this._info.STDDuration = Xml2Stochastic(xpnNav);
xpnNav.MoveToNext();
this._info.AllowReinfection = bool.Parse(xpnNav.Value);
xpnNav.MoveToNext();
this._info.Mortality = double.Parse(xpnNav.Value);
xpnNav.MoveToNext();
this._info.LifeExpectancy = Xml2Stochastic(xpnNav);
xpnNav.MoveToParent();
break;
}
case "Population":
{
if (xpnNav.HasChildren)
{
xpnNav.MoveToFirstChild(); //Group 1
do
{
Group core = new Group(this._rnd);
core.Name = xpnNav.GetAttribute("Name", String.Empty);
//Mode to the first element of the group
xpnNav.MoveToFirstChild();
core.Id = int.Parse(xpnNav.Value);
xpnNav.MoveToNext();
core.Topology = (ETopology)Enum.Parse(typeof(ETopology), xpnNav.Value);
xpnNav.MoveToNext();
core.Alpha = double.Parse(xpnNav.Value);
xpnNav.MoveToNext();
core.Beta = double.Parse(xpnNav.Value);
xpnNav.MoveToNext();
core.Radius = double.Parse(xpnNav.Value);
xpnNav.MoveToNext();
core.Distance = double.Parse(xpnNav.Value);
xpnNav.MoveToNext();
core.Degrees = int.Parse(xpnNav.Value);
xpnNav.MoveToNext();
core.Size = int.Parse(xpnNav.Value);
xpnNav.MoveToNext();
core.Age = Xml2Stochastic(xpnNav);
xpnNav.MoveToNext();
core.LifeExpectancy = Xml2Stochastic(xpnNav);
xpnNav.MoveToNext();
core.STDPrevalence = double.Parse(xpnNav.Value);
xpnNav.MoveToNext();
core.STDAge = Xml2Stochastic(xpnNav);
xpnNav.MoveToNext();
core.STDTest = double.Parse(xpnNav.Value);
xpnNav.MoveToNext();
core.Female = double.Parse(xpnNav.Value);
xpnNav.MoveToNext();
core.Male = double.Parse(xpnNav.Value);
xpnNav.MoveToNext();
core.Homosexual = double.Parse(xpnNav.Value);
xpnNav.MoveToNext();
core.MaxConcurrent = int.Parse(xpnNav.Value);
xpnNav.MoveToNext();
core.PrConcurrent = double.Parse(xpnNav.Value);
xpnNav.MoveToNext();
core.PrNewPartner = double.Parse(xpnNav.Value);
xpnNav.MoveToNext();
core.PrCasual = double.Parse(xpnNav.Value);
xpnNav.MoveToNext();
core.PrInternal = double.Parse(xpnNav.Value);
xpnNav.MoveToNext();
core.StbDuration = Xml2Stochastic(xpnNav);
xpnNav.MoveToNext();
core.StbTransitory = Xml2Stochastic(xpnNav);
xpnNav.MoveToNext();
core.StbContacts = Xml2Stochastic(xpnNav);
xpnNav.MoveToNext();
core.StbSafeSex = double.Parse(xpnNav.Value);
xpnNav.MoveToNext();
core.CslDuration = Xml2Stochastic(xpnNav);
xpnNav.MoveToNext();
core.CslContacts = Xml2Stochastic(xpnNav);
xpnNav.MoveToNext();
core.CslSafeSex = double.Parse(xpnNav.Value);
xpnNav.MoveToParent();
this._pop.AddGroup(core);
}
while (xpnNav.MoveToNext());
xpnNav.MoveToParent();
}
break;
}
case "AdjMatrix":
{
double d;
int idx, i, j, count;
count = int.Parse(xpnNav.GetAttribute("Rows", String.Empty));
if (count > 0)
{
count *= count;
xpnNav.MoveToFirstChild(); //First cell
for (idx = 0; idx < count; idx++)
{
i = int.Parse(xpnNav.GetAttribute("Row", String.Empty));
j = int.Parse(xpnNav.GetAttribute("Column", String.Empty));
d = double.Parse(xpnNav.GetAttribute("Data", String.Empty));
this._pop.AdjMatrix[i, j] = d;
xpnNav.MoveToNext();
}
xpnNav.MoveToParent();
}
break;
}
case "Vaccines":
{
if (xpnNav.HasChildren)
{
xpnNav.MoveToFirstChild(); //Vaccine 1
do
{
Vaccine cVac = new Vaccine();
cVac.Name = xpnNav.GetAttribute("Name", String.Empty);
//Mode to the first element of the vaccine
xpnNav.MoveToFirstChild();
cVac.Id = int.Parse(xpnNav.Value);
xpnNav.MoveToNext();
cVac.Effectiveness = double.Parse(xpnNav.Value);
xpnNav.MoveToNext();
cVac.Lifetime = bool.Parse(xpnNav.Value);
xpnNav.MoveToNext();
cVac.Length = int.Parse(xpnNav.Value);
xpnNav.MoveToNext();
if (xpnNav.Value.Length > 0)
{
cVac.UsedBy.Add(xpnNav.Value);
}
this._vaccine.Add(cVac);
xpnNav.MoveToParent();
} while (xpnNav.MoveToNext());
xpnNav.MoveToParent();
}
break;
}
case "Interventions":
{
if (xpnNav.HasChildren)
{
xpnNav.MoveToFirstChild(); //Strategy 1
do
{
Strategy cStrat = new Strategy();
cStrat.Name = xpnNav.GetAttribute("Name", String.Empty);
//Mode to the first element of the strategy
xpnNav.MoveToFirstChild();
cStrat.Id = int.Parse(xpnNav.Value);
xpnNav.MoveToNext();
cStrat.Active = bool.Parse(xpnNav.Value);
xpnNav.MoveToNext();
cStrat.Intevention = (EStrategy)Enum.Parse(typeof(EStrategy), xpnNav.Value);
xpnNav.MoveToNext();
if (cStrat.Intevention == EStrategy.Custom && xpnNav.Value.Length > 0)
{
cStrat.Groups.Add(xpnNav.Value);
}
xpnNav.MoveToNext();
cStrat.Clock = int.Parse(xpnNav.Value);
xpnNav.MoveToNext();
cStrat.Population = double.Parse(xpnNav.Value);
xpnNav.MoveToNext();
cStrat.UseVaccine = this._vaccine[this._vaccine.IndexOf(int.Parse(xpnNav.Value))];
xpnNav.MoveToNext();
cStrat.HIVTested = bool.Parse(xpnNav.Value);
xpnNav.MoveToNext();
cStrat.HIVResult = (EHIVTest)Enum.Parse(typeof(EHIVTest), xpnNav.Value); ;
this._inteven.Add(cStrat);
xpnNav.MoveToParent();
} while (xpnNav.MoveToNext());
xpnNav.MoveToParent();
}
break;
}
}
}
} while (xpnNav.MoveToNext());
//Update file I/O flags
this._fileOpen = true;
this._fileNew = false;
this._fileName = inFileName;
this._fileChanged = false;
//Close the files
xpnNav = null;
xpnDoc = null; xmlfile.Close();
GC.Collect();
//Everything fine.
return true;
}
/// <summary>
/// Read a Xml file as a stochastic data structure
/// </summary>
/// <param name="xpnTNav">The Xml file <see cref="XPathNavigator" /></param>
/// <returns>The <see cref="Stochastic"/> data read from file</returns>
private Stochastic Xml2Stochastic(XPathNavigator xpnTNav)
{
Stochastic temp = new Stochastic();
xpnTNav.MoveToFirstChild();
temp.Distribution = (DeviateFunction)Enum.Parse(typeof(DeviateFunction), xpnTNav.Value);
xpnTNav.MoveToNext();
temp.Parameter1 = double.Parse(xpnTNav.Value);
xpnTNav.MoveToNext();
temp.Parameter2 = double.Parse(xpnTNav.Value);
xpnTNav.MoveToNext();
temp.Parameter3 = double.Parse(xpnTNav.Value);
xpnTNav.MoveToNext();
temp.Parameter4 = double.Parse(xpnTNav.Value);
xpnTNav.MoveToParent();
return temp;
}
/// <summary>
/// HIVacSim data file validation
/// </summary>
/// <param name="xmlFile">The HIVacSim data file to be validated</param>
/// <param name="xsdPath">The path of the XML validation schema</param>
/// <returns>True for a valid data file, false otherwise.</returns>
public bool XMLValidator(string xsdPath, string xmlFile)
{
try
{
//Clear the error log
this._errLog = string.Empty;
// Create the XmlSchemaSet class.
XmlSchemaSet sc = new XmlSchemaSet();
// Add the schema to the collection.
sc.Add("urn:HIVacSim", xsdPath + "\\HIVacSimData.xsd");
// Set the validation settings.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas = sc;
settings.ValidationEventHandler += new ValidationEventHandler(XMLValidationHandler);
// Create the XmlReader object.
XmlReader reader = XmlReader.Create(xmlFile, settings);
// Parse the file.
while (reader.Read()) ;
if (this._errLog.Length > 0)
{
return false;
}
else
{
this._errLog = "No validation errors were reported.";
return true;
}
}
catch (Exception err)
{
this._errLog += err.Message + Environment.NewLine;
return false;
}
}
/// <summary>
/// HIVacSim data file validator event handler, which creates
/// the validation error log
/// </summary>
/// <param name="sender">The sender object</param>
/// <param name="args">The event argument data</param>
private void XMLValidationHandler(object sender, ValidationEventArgs args)
{
this._errLog += args.Message + Environment.NewLine;
}
#endregion
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagve = Google.Ads.GoogleAds.V9.Enums;
using gagvr = Google.Ads.GoogleAds.V9.Resources;
using gaxgrpc = Google.Api.Gax.Grpc;
using gr = Google.Rpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using NUnit.Framework;
using Google.Ads.GoogleAds.V9.Services;
namespace Google.Ads.GoogleAds.Tests.V9.Services
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedFeedServiceClientTest
{
[Category("Autogenerated")][Test]
public void GetFeedRequestObject()
{
moq::Mock<FeedService.FeedServiceClient> mockGrpcClient = new moq::Mock<FeedService.FeedServiceClient>(moq::MockBehavior.Strict);
GetFeedRequest request = new GetFeedRequest
{
ResourceNameAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"),
};
gagvr::Feed expectedResponse = new gagvr::Feed
{
ResourceNameAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"),
Attributes =
{
new gagvr::FeedAttribute(),
},
Origin = gagve::FeedOriginEnum.Types.FeedOrigin.Unspecified,
PlacesLocationFeedData = new gagvr::Feed.Types.PlacesLocationFeedData(),
AffiliateLocationFeedData = new gagvr::Feed.Types.AffiliateLocationFeedData(),
Status = gagve::FeedStatusEnum.Types.FeedStatus.Enabled,
AttributeOperations =
{
new gagvr::FeedAttributeOperation(),
},
Id = -6774108720365892680L,
FeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"),
};
mockGrpcClient.Setup(x => x.GetFeed(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FeedServiceClient client = new FeedServiceClientImpl(mockGrpcClient.Object, null);
gagvr::Feed response = client.GetFeed(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetFeedRequestObjectAsync()
{
moq::Mock<FeedService.FeedServiceClient> mockGrpcClient = new moq::Mock<FeedService.FeedServiceClient>(moq::MockBehavior.Strict);
GetFeedRequest request = new GetFeedRequest
{
ResourceNameAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"),
};
gagvr::Feed expectedResponse = new gagvr::Feed
{
ResourceNameAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"),
Attributes =
{
new gagvr::FeedAttribute(),
},
Origin = gagve::FeedOriginEnum.Types.FeedOrigin.Unspecified,
PlacesLocationFeedData = new gagvr::Feed.Types.PlacesLocationFeedData(),
AffiliateLocationFeedData = new gagvr::Feed.Types.AffiliateLocationFeedData(),
Status = gagve::FeedStatusEnum.Types.FeedStatus.Enabled,
AttributeOperations =
{
new gagvr::FeedAttributeOperation(),
},
Id = -6774108720365892680L,
FeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"),
};
mockGrpcClient.Setup(x => x.GetFeedAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::Feed>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FeedServiceClient client = new FeedServiceClientImpl(mockGrpcClient.Object, null);
gagvr::Feed responseCallSettings = await client.GetFeedAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::Feed responseCancellationToken = await client.GetFeedAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetFeed()
{
moq::Mock<FeedService.FeedServiceClient> mockGrpcClient = new moq::Mock<FeedService.FeedServiceClient>(moq::MockBehavior.Strict);
GetFeedRequest request = new GetFeedRequest
{
ResourceNameAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"),
};
gagvr::Feed expectedResponse = new gagvr::Feed
{
ResourceNameAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"),
Attributes =
{
new gagvr::FeedAttribute(),
},
Origin = gagve::FeedOriginEnum.Types.FeedOrigin.Unspecified,
PlacesLocationFeedData = new gagvr::Feed.Types.PlacesLocationFeedData(),
AffiliateLocationFeedData = new gagvr::Feed.Types.AffiliateLocationFeedData(),
Status = gagve::FeedStatusEnum.Types.FeedStatus.Enabled,
AttributeOperations =
{
new gagvr::FeedAttributeOperation(),
},
Id = -6774108720365892680L,
FeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"),
};
mockGrpcClient.Setup(x => x.GetFeed(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FeedServiceClient client = new FeedServiceClientImpl(mockGrpcClient.Object, null);
gagvr::Feed response = client.GetFeed(request.ResourceName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetFeedAsync()
{
moq::Mock<FeedService.FeedServiceClient> mockGrpcClient = new moq::Mock<FeedService.FeedServiceClient>(moq::MockBehavior.Strict);
GetFeedRequest request = new GetFeedRequest
{
ResourceNameAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"),
};
gagvr::Feed expectedResponse = new gagvr::Feed
{
ResourceNameAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"),
Attributes =
{
new gagvr::FeedAttribute(),
},
Origin = gagve::FeedOriginEnum.Types.FeedOrigin.Unspecified,
PlacesLocationFeedData = new gagvr::Feed.Types.PlacesLocationFeedData(),
AffiliateLocationFeedData = new gagvr::Feed.Types.AffiliateLocationFeedData(),
Status = gagve::FeedStatusEnum.Types.FeedStatus.Enabled,
AttributeOperations =
{
new gagvr::FeedAttributeOperation(),
},
Id = -6774108720365892680L,
FeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"),
};
mockGrpcClient.Setup(x => x.GetFeedAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::Feed>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FeedServiceClient client = new FeedServiceClientImpl(mockGrpcClient.Object, null);
gagvr::Feed responseCallSettings = await client.GetFeedAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::Feed responseCancellationToken = await client.GetFeedAsync(request.ResourceName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetFeedResourceNames()
{
moq::Mock<FeedService.FeedServiceClient> mockGrpcClient = new moq::Mock<FeedService.FeedServiceClient>(moq::MockBehavior.Strict);
GetFeedRequest request = new GetFeedRequest
{
ResourceNameAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"),
};
gagvr::Feed expectedResponse = new gagvr::Feed
{
ResourceNameAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"),
Attributes =
{
new gagvr::FeedAttribute(),
},
Origin = gagve::FeedOriginEnum.Types.FeedOrigin.Unspecified,
PlacesLocationFeedData = new gagvr::Feed.Types.PlacesLocationFeedData(),
AffiliateLocationFeedData = new gagvr::Feed.Types.AffiliateLocationFeedData(),
Status = gagve::FeedStatusEnum.Types.FeedStatus.Enabled,
AttributeOperations =
{
new gagvr::FeedAttributeOperation(),
},
Id = -6774108720365892680L,
FeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"),
};
mockGrpcClient.Setup(x => x.GetFeed(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FeedServiceClient client = new FeedServiceClientImpl(mockGrpcClient.Object, null);
gagvr::Feed response = client.GetFeed(request.ResourceNameAsFeedName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetFeedResourceNamesAsync()
{
moq::Mock<FeedService.FeedServiceClient> mockGrpcClient = new moq::Mock<FeedService.FeedServiceClient>(moq::MockBehavior.Strict);
GetFeedRequest request = new GetFeedRequest
{
ResourceNameAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"),
};
gagvr::Feed expectedResponse = new gagvr::Feed
{
ResourceNameAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"),
Attributes =
{
new gagvr::FeedAttribute(),
},
Origin = gagve::FeedOriginEnum.Types.FeedOrigin.Unspecified,
PlacesLocationFeedData = new gagvr::Feed.Types.PlacesLocationFeedData(),
AffiliateLocationFeedData = new gagvr::Feed.Types.AffiliateLocationFeedData(),
Status = gagve::FeedStatusEnum.Types.FeedStatus.Enabled,
AttributeOperations =
{
new gagvr::FeedAttributeOperation(),
},
Id = -6774108720365892680L,
FeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"),
};
mockGrpcClient.Setup(x => x.GetFeedAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::Feed>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FeedServiceClient client = new FeedServiceClientImpl(mockGrpcClient.Object, null);
gagvr::Feed responseCallSettings = await client.GetFeedAsync(request.ResourceNameAsFeedName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::Feed responseCancellationToken = await client.GetFeedAsync(request.ResourceNameAsFeedName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateFeedsRequestObject()
{
moq::Mock<FeedService.FeedServiceClient> mockGrpcClient = new moq::Mock<FeedService.FeedServiceClient>(moq::MockBehavior.Strict);
MutateFeedsRequest request = new MutateFeedsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new FeedOperation(),
},
PartialFailure = false,
ValidateOnly = true,
ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly,
};
MutateFeedsResponse expectedResponse = new MutateFeedsResponse
{
Results =
{
new MutateFeedResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateFeeds(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FeedServiceClient client = new FeedServiceClientImpl(mockGrpcClient.Object, null);
MutateFeedsResponse response = client.MutateFeeds(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateFeedsRequestObjectAsync()
{
moq::Mock<FeedService.FeedServiceClient> mockGrpcClient = new moq::Mock<FeedService.FeedServiceClient>(moq::MockBehavior.Strict);
MutateFeedsRequest request = new MutateFeedsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new FeedOperation(),
},
PartialFailure = false,
ValidateOnly = true,
ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly,
};
MutateFeedsResponse expectedResponse = new MutateFeedsResponse
{
Results =
{
new MutateFeedResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateFeedsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateFeedsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FeedServiceClient client = new FeedServiceClientImpl(mockGrpcClient.Object, null);
MutateFeedsResponse responseCallSettings = await client.MutateFeedsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateFeedsResponse responseCancellationToken = await client.MutateFeedsAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateFeeds()
{
moq::Mock<FeedService.FeedServiceClient> mockGrpcClient = new moq::Mock<FeedService.FeedServiceClient>(moq::MockBehavior.Strict);
MutateFeedsRequest request = new MutateFeedsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new FeedOperation(),
},
};
MutateFeedsResponse expectedResponse = new MutateFeedsResponse
{
Results =
{
new MutateFeedResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateFeeds(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FeedServiceClient client = new FeedServiceClientImpl(mockGrpcClient.Object, null);
MutateFeedsResponse response = client.MutateFeeds(request.CustomerId, request.Operations);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateFeedsAsync()
{
moq::Mock<FeedService.FeedServiceClient> mockGrpcClient = new moq::Mock<FeedService.FeedServiceClient>(moq::MockBehavior.Strict);
MutateFeedsRequest request = new MutateFeedsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new FeedOperation(),
},
};
MutateFeedsResponse expectedResponse = new MutateFeedsResponse
{
Results =
{
new MutateFeedResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateFeedsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateFeedsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FeedServiceClient client = new FeedServiceClientImpl(mockGrpcClient.Object, null);
MutateFeedsResponse responseCallSettings = await client.MutateFeedsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateFeedsResponse responseCancellationToken = await client.MutateFeedsAsync(request.CustomerId, request.Operations, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using UnityEngine;
using UnityEditor;
using System;
namespace AmplifyShaderEditor
{
public enum TexturePropertyValues
{
white,
black,
gray,
bump
}
public enum TextureType
{
Texture1D,
Texture2D,
Texture3D,
Cube
}
public enum AutoCastType
{
Auto,
LockedToTexture1D,
LockedToTexture2D,
LockedToTexture3D,
LockedToCube
}
[Serializable]
[NodeAttributes( "Texture Object", "Textures", "Represents a Texture Asset. Can only be used alongside Texture Sample node by connecting to its Tex Input Port", null, KeyCode.None, true, false, null, null, false, null, 1 )]
public class TexturePropertyNode : PropertyNode
{
protected readonly string[] AvailablePropertyTypeLabels = { PropertyType.Property.ToString() , PropertyType.Global.ToString() };
protected readonly int[] AvailablePropertyTypeValues = { (int)PropertyType.Property, (int)PropertyType.Global };
protected const int OriginalFontSizeUpper = 9;
protected const int OriginalFontSizeLower = 9;
protected const string DefaultTextureStr = "Default value";
protected const string AutoCastModeStr = "Auto-Cast Mode";
protected const string AutoUnpackNormalsStr = "Normal";
[SerializeField]
protected Texture m_defaultValue;
[SerializeField]
protected Texture m_materialValue;
[SerializeField]
protected TexturePropertyValues m_defaultTextureValue;
[SerializeField]
protected bool m_isNormalMap;
[SerializeField]
protected System.Type m_textureType;
[SerializeField]
protected bool m_isTextureFetched;
[SerializeField]
protected string m_textureFetchedValue;
[SerializeField]
protected TextureType m_currentType = TextureType.Texture2D;
[SerializeField]
protected AutoCastType m_autocastMode = AutoCastType.Auto;
private GUIStyle m_titleOverlay;
//private GUIStyle m_buttonOverlay;
int m_titleOverlayIndex = -1;
//int m_buttonOverlayIndex = -1;
protected int PreviewSizeX = 128;
protected int PreviewSizeY = 128;
protected bool m_linearTexture;
[SerializeField]
protected TexturePropertyNode m_textureProperty = null;
protected bool m_drawPicker;
protected bool m_forceNodeUpdate = false;
protected bool m_drawAutocast = true;
protected int m_cachedSamplerId = -1;
public TexturePropertyNode() : base() { }
public TexturePropertyNode( int uniqueId, float x, float y, float width, float height ) : base( uniqueId, x, y, width, height ) { }
protected override void CommonInit( int uniqueId )
{
base.CommonInit( uniqueId );
m_defaultTextureValue = TexturePropertyValues.white;
m_insideSize.Set( PreviewSizeX, PreviewSizeY + 5 );
AddOutputPort( WirePortDataType.SAMPLER2D, Constants.EmptyPortValue );
m_outputPorts[ 0 ].CreatePortRestrictions( WirePortDataType.SAMPLER1D, WirePortDataType.SAMPLER2D, WirePortDataType.SAMPLER3D, WirePortDataType.SAMPLERCUBE, WirePortDataType.OBJECT );
m_currentParameterType = PropertyType.Property;
// m_useCustomPrefix = true;
m_customPrefix = "Texture ";
m_drawPrecisionUI = false;
m_freeType = false;
m_drawPicker = true;
m_textLabelWidth = 115;
m_availableAttribs.Add( new PropertyAttributes( "No Scale Offset", "[NoScaleOffset]" ));
m_availableAttribs.Add( new PropertyAttributes( "Normal", "[Normal]" ) );
m_availableAttribs.Add( new PropertyAttributes( "Per Renderer Data", "[PerRendererData]" ) );
ConfigTextureData( TextureType.Texture2D );
m_showPreview = true;
m_drawPreviewExpander = false;
m_drawPreview = false;
m_drawPreviewMaskButtons = false;
m_previewShaderGUID = "e53988745ec6e034694ee2640cd3d372";
}
public override void SetPreviewInputs()
{
base.SetPreviewInputs();
if ( m_cachedSamplerId == -1 )
m_cachedSamplerId = Shader.PropertyToID( "_Sampler" );
PreviewMaterial.SetTexture( m_cachedSamplerId, Value );
}
protected override void OnUniqueIDAssigned()
{
base.OnUniqueIDAssigned();
m_textureProperty = this;
UIUtils.RegisterPropertyNode( this );
UIUtils.RegisterTexturePropertyNode( this );
}
protected void ConfigTextureData( TextureType type )
{
switch ( m_autocastMode )
{
case AutoCastType.Auto:
{
m_currentType = type;
}
break;
case AutoCastType.LockedToTexture1D:
{
m_currentType = TextureType.Texture1D;
}
break;
case AutoCastType.LockedToTexture2D:
{
m_currentType = TextureType.Texture2D;
}
break;
case AutoCastType.LockedToTexture3D:
{
m_currentType = TextureType.Texture3D;
}
break;
case AutoCastType.LockedToCube:
{
m_currentType = TextureType.Cube;
}
break;
}
switch ( m_currentType )
{
case TextureType.Texture1D:
{
m_textureType = typeof( Texture );
}
break;
case TextureType.Texture2D:
{
m_textureType = typeof( Texture2D );
}
break;
case TextureType.Texture3D:
{
m_textureType = typeof( Texture3D );
}
break;
case TextureType.Cube:
{
m_textureType = typeof( Cubemap );
}
break;
}
}
protected void DrawTexturePropertyType()
{
PropertyType parameterType = ( PropertyType ) EditorGUILayoutIntPopup( ParameterTypeStr, (int)m_currentParameterType, AvailablePropertyTypeLabels, AvailablePropertyTypeValues );
if ( parameterType != m_currentParameterType )
{
ChangeParameterType( parameterType );
}
}
// Texture1D
public string GetTexture1DPropertyValue()
{
return PropertyName + "(\"" + m_propertyInspectorName + "\", 2D) = \"" + m_defaultTextureValue + "\" {}";
}
public string GetTexture1DUniformValue()
{
return "uniform sampler1D " + PropertyName + ";";
}
// Texture2D
public string GetTexture2DPropertyValue()
{
return PropertyName + "(\"" + m_propertyInspectorName + "\", 2D) = \"" + m_defaultTextureValue + "\" {}";
}
public string GetTexture2DUniformValue()
{
return "uniform sampler2D " + PropertyName + ";";
}
//Texture3D
public string GetTexture3DPropertyValue()
{
return PropertyName + "(\"" + m_propertyInspectorName + "\", 3D) = \"" + m_defaultTextureValue + "\" {}";
}
public string GetTexture3DUniformValue()
{
return "uniform sampler3D " + PropertyName + ";";
}
// Cube
public string GetCubePropertyValue()
{
return PropertyName + "(\"" + m_propertyInspectorName + "\", CUBE) = \"" + m_defaultTextureValue + "\" {}";
}
public string GetCubeUniformValue()
{
return "uniform samplerCUBE " + PropertyName + ";";
}
//
public override void DrawMainPropertyBlock()
{
DrawTexturePropertyType();
base.DrawMainPropertyBlock();
}
public override void DrawSubProperties()
{
ShowDefaults();
EditorGUI.BeginChangeCheck();
m_defaultValue = EditorGUILayoutObjectField( Constants.DefaultValueLabel, m_defaultValue, m_textureType, false ) as Texture;
if ( EditorGUI.EndChangeCheck() )
{
CheckTextureImporter( true );
SetAdditonalTitleText( string.Format( Constants.PropertyValueLabel, GetPropertyValStr() ) );
}
}
public override void DrawMaterialProperties()
{
ShowDefaults();
EditorGUI.BeginChangeCheck();
m_materialValue = EditorGUILayoutObjectField( Constants.MaterialValueLabel, m_materialValue, m_textureType, false ) as Texture;
if ( EditorGUI.EndChangeCheck() )
{
CheckTextureImporter( true );
SetAdditonalTitleText( string.Format( Constants.PropertyValueLabel, GetPropertyValStr() ) );
}
}
new void ShowDefaults()
{
m_defaultTextureValue = ( TexturePropertyValues ) EditorGUILayoutEnumPopup( DefaultTextureStr, m_defaultTextureValue );
if ( !m_drawAutocast )
return;
AutoCastType newAutoCast = ( AutoCastType ) EditorGUILayoutEnumPopup( AutoCastModeStr, m_autocastMode );
if ( newAutoCast != m_autocastMode )
{
m_autocastMode = newAutoCast;
if ( m_autocastMode != AutoCastType.Auto )
{
ConfigTextureData( m_currentType );
ConfigureInputPorts();
ConfigureOutputPorts();
ResizeNodeToPreview();
}
}
}
private void ConfigurePortsFromReference()
{
m_sizeIsDirty = true;
}
public virtual void ConfigureOutputPorts()
{
switch ( m_currentType )
{
case TextureType.Texture1D:
m_outputPorts[ 0 ].ChangeType( WirePortDataType.SAMPLER1D, false );
break;
case TextureType.Texture2D:
m_outputPorts[ 0 ].ChangeType( WirePortDataType.SAMPLER2D, false );
break;
case TextureType.Texture3D:
m_outputPorts[ 0 ].ChangeType( WirePortDataType.SAMPLER3D, false );
break;
case TextureType.Cube:
m_outputPorts[ 0 ].ChangeType( WirePortDataType.SAMPLERCUBE, false );
break;
}
m_sizeIsDirty = true;
}
public virtual void ConfigureInputPorts()
{
}
public virtual void AdditionalCheck()
{
}
public virtual void CheckTextureImporter( bool additionalCheck )
{
m_requireMaterialUpdate = true;
Texture texture = m_materialMode ? m_materialValue : m_defaultValue;
TextureImporter importer = AssetImporter.GetAtPath( AssetDatabase.GetAssetPath( texture ) ) as TextureImporter;
if ( importer != null )
{
#if UNITY_5_5_OR_NEWER
m_isNormalMap = importer.textureType == TextureImporterType.NormalMap;
#else
m_isNormalMap = importer.normalmap;
#endif
if ( m_defaultTextureValue == TexturePropertyValues.bump && !m_isNormalMap )
m_defaultTextureValue = TexturePropertyValues.white;
else if ( m_isNormalMap )
m_defaultTextureValue = TexturePropertyValues.bump;
if ( additionalCheck )
AdditionalCheck();
#if UNITY_5_5_OR_NEWER
m_linearTexture = !importer.sRGBTexture;
#else
m_linearTexture = importer.linearTexture;
#endif
}
if ( ( texture as Texture2D ) != null )
{
ConfigTextureData( TextureType.Texture2D );
}
else if ( ( texture as Texture3D ) != null )
{
ConfigTextureData( TextureType.Texture3D );
}
else if ( ( texture as Cubemap ) != null )
{
ConfigTextureData( TextureType.Cube );
}
//ConfigureInputPorts();
//ConfigureOutputPorts();
//ResizeNodeToPreview();
}
public override void OnObjectDropped( UnityEngine.Object obj )
{
base.OnObjectDropped( obj );
ConfigFromObject( obj );
}
public override void SetupFromCastObject( UnityEngine.Object obj )
{
base.SetupFromCastObject( obj );
ConfigFromObject( obj );
}
protected void ConfigFromObject( UnityEngine.Object obj )
{
Texture texture = obj as Texture;
if ( texture )
{
m_materialValue = texture;
m_defaultValue = texture;
CheckTextureImporter( true );
}
}
public override void Draw( DrawInfo drawInfo )
{
EditorGUI.BeginChangeCheck();
base.Draw( drawInfo );
if ( EditorGUI.EndChangeCheck() )
{
OnPropertyNameChanged();
}
if ( m_forceNodeUpdate )
{
m_forceNodeUpdate = false;
ResizeNodeToPreview();
}
if ( m_isVisible && m_drawPicker )
{
DrawTexturePicker( drawInfo );
}
//GUI.Box( m_remainingBox, string.Empty, UIUtils.CustomStyle( CustomStyle.MainCanvasTitle ) );
}
protected void DrawTexturePicker( DrawInfo drawInfo )
{
if ( m_titleOverlayIndex == -1 )
m_titleOverlayIndex = Array.IndexOf<GUIStyle>( GUI.skin.customStyles, GUI.skin.GetStyle( "ObjectFieldThumbOverlay" ) );
m_titleOverlay = GUI.skin.customStyles[ m_titleOverlayIndex ];
int fontSizeUpper = m_titleOverlay.fontSize;
//UIUtils.MainSkin.customStyles[ ( int )CustomStyle.ObjectPicker ] = GUI.skin.customStyles[ 272 ];
Rect newRect = m_globalPosition;
newRect.width = (PreviewSizeX) * drawInfo.InvertedZoom; //PreviewSizeX * drawInfo.InvertedZoom;
newRect.height = (PreviewSizeY) * drawInfo.InvertedZoom; //PreviewSizeY * drawInfo.InvertedZoom;
newRect.x = m_previewRect.x;
newRect.y = m_previewRect.y;
m_titleOverlay.fontSize = ( int )( OriginalFontSizeUpper * drawInfo.InvertedZoom );
EditorGUI.BeginChangeCheck();
Rect smallButton = newRect;
smallButton.height = 14 * drawInfo.InvertedZoom;
smallButton.y = newRect.yMax - smallButton.height - 2;
smallButton.width = 40 * drawInfo.InvertedZoom;
smallButton.x = newRect.xMax - smallButton.width - 2;
m_showPreview = true;
if ( m_materialMode )
{
if ( m_materialValue == null )
{
GUI.Box( newRect, "", UIUtils.ObjectFieldThumb );
Color temp = GUI.color;
GUI.color = Color.clear;
m_materialValue = EditorGUIObjectField( newRect, m_materialValue, m_textureType, false ) as Texture;
GUI.color = temp;
GUI.Button( smallButton, "Select", UIUtils.GetCustomStyle(CustomStyle.SamplerButton) );
if( ContainerGraph.LodLevel <= ParentGraph.NodeLOD.LOD2 )
GUI.Label( newRect, "None (" + m_currentType.ToString() + ")", UIUtils.ObjectFieldThumbOverlay );
}
else
{
Rect butRect = m_previewRect;
butRect.y -= 1;
butRect.x += 1;
Rect hitRect = butRect;
hitRect.height = 14 * drawInfo.InvertedZoom;
hitRect.y = butRect.yMax - hitRect.height;
hitRect.width = 4 * 14 * drawInfo.InvertedZoom;
Color temp = GUI.color;
GUI.color = Color.clear;
bool restoreMouse = false;
if ( Event.current.type == EventType.mouseDown && hitRect.Contains( Event.current.mousePosition ) )
{
restoreMouse = true;
Event.current.type = EventType.ignore;
}
m_materialValue = EditorGUIObjectField( newRect, m_materialValue, m_textureType, false ) as Texture;
if ( restoreMouse )
{
Event.current.type = EventType.mouseDown;
}
GUI.color = temp;
DrawPreview( drawInfo, m_previewRect );
DrawPreviewMaskButtons( drawInfo, butRect );
GUI.Box( newRect, string.Empty, UIUtils.GetCustomStyle( CustomStyle.SamplerFrame ) );
GUI.Box( smallButton, "Select", UIUtils.GetCustomStyle( CustomStyle.SamplerButton ) );
}
}
else
{
if ( m_defaultValue == null )
{
GUI.Box( newRect, "", UIUtils.ObjectFieldThumb );
Color temp = GUI.color;
GUI.color = Color.clear;
m_defaultValue = EditorGUIObjectField( newRect, m_defaultValue, m_textureType, false ) as Texture;
GUI.color = temp;
GUI.Button( smallButton, "Select", UIUtils.GetCustomStyle( CustomStyle.SamplerButton ) );
if ( ContainerGraph.LodLevel <= ParentGraph.NodeLOD.LOD2 )
GUI.Label( newRect, "None ("+m_currentType.ToString()+")", UIUtils.ObjectFieldThumbOverlay );
}
else
{
Rect butRect = m_previewRect;
butRect.y -= 1;
butRect.x += 1;
Rect hitRect = butRect;
hitRect.height = 14 * drawInfo.InvertedZoom;
hitRect.y = butRect.yMax - hitRect.height;
hitRect.width = 4 * 14 * drawInfo.InvertedZoom;
Color temp = GUI.color;
GUI.color = Color.clear;
bool restoreMouse = false;
if ( Event.current.type == EventType.mouseDown && hitRect.Contains( Event.current.mousePosition ) )
{
restoreMouse = true;
Event.current.type = EventType.ignore;
}
m_defaultValue = EditorGUIObjectField( newRect, m_defaultValue, m_textureType, false ) as Texture;
if ( restoreMouse )
{
Event.current.type = EventType.mouseDown;
}
GUI.color = temp;
DrawPreview( drawInfo, m_previewRect );
DrawPreviewMaskButtons( drawInfo, butRect );
GUI.Box( newRect, string.Empty, UIUtils.GetCustomStyle( CustomStyle.SamplerFrame ) );
GUI.Box( smallButton, "Select", UIUtils.GetCustomStyle( CustomStyle.SamplerButton ) );
}
}
if ( EditorGUI.EndChangeCheck() )
{
CheckTextureImporter( true );
SetAdditonalTitleText( string.Format( Constants.PropertyValueLabel, GetPropertyValStr() ) );
ConfigureInputPorts();
ConfigureOutputPorts();
ResizeNodeToPreview();
BeginDelayedDirtyProperty();
}
m_titleOverlay.fontSize = fontSizeUpper;
}
public virtual void ResizeNodeToPreview()
{
}
public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalVar )
{
base.GenerateShaderForOutput( outputId, ref dataCollector, ignoreLocalVar );
return PropertyName;
}
public override void ResetOutputLocals()
{
base.ResetOutputLocals();
m_isTextureFetched = false;
m_textureFetchedValue = string.Empty;
}
public override void ResetOutputLocalsIfNot( MasterNodePortCategory category )
{
base.ResetOutputLocalsIfNot( category );
m_isTextureFetched = false;
m_textureFetchedValue = string.Empty;
}
public override void UpdateMaterial( Material mat )
{
base.UpdateMaterial( mat );
if ( UIUtils.IsProperty( m_currentParameterType ) )
{
OnPropertyNameChanged();
if ( mat.HasProperty( PropertyName ) )
{
mat.SetTexture( PropertyName, m_materialValue );
}
}
}
public override void SetMaterialMode( Material mat , bool fetchMaterialValues )
{
base.SetMaterialMode( mat , fetchMaterialValues );
if ( fetchMaterialValues && m_materialMode && UIUtils.IsProperty( m_currentParameterType ) )
{
if ( mat.HasProperty( PropertyName ) )
{
m_materialValue = mat.GetTexture( PropertyName );
CheckTextureImporter( false );
}
}
}
public override void ForceUpdateFromMaterial( Material material )
{
if ( UIUtils.IsProperty( m_currentParameterType ) && material.HasProperty( PropertyName ) )
{
m_materialValue = material.GetTexture( PropertyName );
CheckTextureImporter( false );
}
}
public override bool UpdateShaderDefaults( ref Shader shader, ref TextureDefaultsDataColector defaultCol/* ref string metaStr */)
{
if ( m_defaultValue != null )
{
defaultCol.AddValue( PropertyName, m_defaultValue );
}
return true;
}
public override void ReadFromString( ref string[] nodeParams )
{
base.ReadFromString( ref nodeParams );
ReadAdditionalData( ref nodeParams );
}
public virtual void ReadAdditionalData( ref string[] nodeParams )
{
string textureName = GetCurrentParam( ref nodeParams );
m_defaultValue = AssetDatabase.LoadAssetAtPath<Texture>( textureName );
m_isNormalMap = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) );
m_defaultTextureValue = ( TexturePropertyValues ) Enum.Parse( typeof( TexturePropertyValues ), GetCurrentParam( ref nodeParams ) );
m_autocastMode = ( AutoCastType ) Enum.Parse( typeof( AutoCastType ), GetCurrentParam( ref nodeParams ) );
m_forceNodeUpdate = true;
ConfigFromObject( m_defaultValue );
ConfigureInputPorts();
ConfigureOutputPorts();
}
public override void ReadAdditionalClipboardData( ref string[] nodeParams )
{
base.ReadAdditionalClipboardData( ref nodeParams );
string textureName = GetCurrentParam( ref nodeParams );
m_materialValue = AssetDatabase.LoadAssetAtPath<Texture>( textureName );
}
public override void WriteToString( ref string nodeInfo, ref string connectionsInfo )
{
base.WriteToString( ref nodeInfo, ref connectionsInfo );
WriteAdditionalToString( ref nodeInfo, ref connectionsInfo );
}
public virtual void WriteAdditionalToString( ref string nodeInfo, ref string connectionsInfo )
{
IOUtils.AddFieldValueToString( ref nodeInfo, ( m_defaultValue != null ) ? AssetDatabase.GetAssetPath( m_defaultValue ) : Constants.NoStringValue );
IOUtils.AddFieldValueToString( ref nodeInfo, m_isNormalMap.ToString() );
IOUtils.AddFieldValueToString( ref nodeInfo, m_defaultTextureValue );
IOUtils.AddFieldValueToString( ref nodeInfo, m_autocastMode );
}
public override void WriteAdditionalClipboardData( ref string nodeInfo )
{
base.WriteAdditionalClipboardData( ref nodeInfo );
IOUtils.AddFieldValueToString( ref nodeInfo, ( m_materialValue != null ) ? AssetDatabase.GetAssetPath( m_materialValue ) : Constants.NoStringValue );
}
public override void Destroy()
{
base.Destroy();
m_defaultValue = null;
m_materialValue = null;
m_textureProperty = null;
UIUtils.UnregisterPropertyNode( this );
UIUtils.UnregisterTexturePropertyNode( this );
}
public override string GetPropertyValStr()
{
return m_materialMode ? ( m_materialValue != null ? m_materialValue.name : IOUtils.NO_TEXTURES ) : ( m_defaultValue != null ? m_defaultValue.name : IOUtils.NO_TEXTURES );
}
public override string GetPropertyValue()
{
switch ( m_currentType )
{
case TextureType.Texture1D:
{
return PropertyAttributes + GetTexture1DPropertyValue();
}
case TextureType.Texture2D:
{
return PropertyAttributes + GetTexture2DPropertyValue();
}
case TextureType.Texture3D:
{
return PropertyAttributes + GetTexture3DPropertyValue();
}
case TextureType.Cube:
{
return PropertyAttributes + GetCubePropertyValue();
}
}
return string.Empty;
}
public override string GetUniformValue()
{
switch ( m_currentType )
{
case TextureType.Texture1D:
{
return GetTexture1DUniformValue();
}
case TextureType.Texture2D:
{
return GetTexture2DUniformValue();
}
case TextureType.Texture3D:
{
return GetTexture3DUniformValue();
}
case TextureType.Cube:
{
return GetCubeUniformValue();
}
}
return string.Empty;
}
public override bool GetUniformData( out string dataType, out string dataName )
{
dataType = UIUtils.TextureTypeToCgType( m_currentType );
dataName = m_propertyName;
return true;
}
public virtual string CurrentPropertyReference
{
get
{
string propertyName = string.Empty;
propertyName = PropertyName;
return propertyName;
}
}
public Texture Value
{
get { return m_materialMode ? m_materialValue : m_defaultValue; }
set
{
if ( m_materialMode )
{
m_materialValue = value;
}
else
{
m_defaultValue = value;
}
}
}
public Texture MaterialValue
{
get { return m_materialValue; }
set
{
m_materialValue = value;
}
}
public Texture DefaultValue
{
get { return m_defaultValue; }
set
{
m_defaultValue = value;
}
}
public void SetInspectorName( string newName )
{
m_propertyInspectorName = newName;
}
public void SetPropertyName(string newName)
{
m_propertyName = newName;
}
public bool IsNormalMap
{
get
{
return m_isNormalMap;
}
}
public bool IsLinearTexture
{
get
{
return m_linearTexture;
}
}
public override void OnPropertyNameChanged()
{
base.OnPropertyNameChanged();
UIUtils.UpdateTexturePropertyDataNode( UniqueId, PropertyInspectorName );
}
public override string DataToArray { get { return PropertyInspectorName; } }
public TextureType CurrentType
{
get { return m_currentType; }
}
public bool DrawAutocast
{
get { return m_drawAutocast; }
set { m_drawAutocast = value; }
}
public TexturePropertyValues DefaultTextureValue
{
get { return m_defaultTextureValue; }
set { m_defaultTextureValue = value; }
}
}
}
| |
/* ====================================================================
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.Util;
using System;
using System.IO;
using Ionic.Zip;
using Ionic.Zlib;
using NPOI.HWPF.Model;
namespace NPOI.HWPF.UserModel
{
/**
* Represents embedded picture extracted from Word Document
* @author Dmitry Romanov
*/
public partial class Picture: PictureDescriptor
{
//private static POILogger log = POILogFactory.GetLogger(Picture.class);
// public static int FILENAME_OFFSET = 0x7C;
// public static int FILENAME_SIZE_OFFSET = 0x6C;
internal const int PICF_OFFSET = 0x0;
internal const int PICT_HEADER_OFFSET = 0x4;
internal const int MFPMM_OFFSET = 0x6;
internal const int PICF_SHAPE_OFFSET = 0xE;
internal const int PICMD_OFFSET = 0x1C;
internal const int UNKNOWN_HEADER_SIZE = 0x49;
public static byte[] IHDR = new byte[] { (byte)'I', (byte)'H', (byte)'D', (byte)'R' };
public static byte[] COMPRESSED1 = { (byte) 0xFE, 0x78, (byte) 0xDA };
public static byte[] COMPRESSED2 = { (byte) 0xFE, 0x78, (byte) 0x9C };
private int dataBlockStartOfsset;
private int pictureBytesStartOffset;
private int dataBlockSize;
private int size;
// private String fileName;
private byte[] rawContent;
private byte[] content;
private byte[] _dataStream;
private int height = -1;
private int width = -1;
public Picture(int dataBlockStartOfsset, byte[] _dataStream, bool fillBytes)
:base(_dataStream, dataBlockStartOfsset)
//: base(_dataStream, dataBlockStartOfsset)
{
this._dataStream = _dataStream;
this.dataBlockStartOfsset = dataBlockStartOfsset;
this.dataBlockSize = LittleEndian.GetInt(_dataStream, dataBlockStartOfsset);
this.pictureBytesStartOffset = GetPictureBytesStartOffset(dataBlockStartOfsset, _dataStream, dataBlockSize);
this.size = dataBlockSize - (pictureBytesStartOffset - dataBlockStartOfsset);
if (fillBytes)
{
FillImageContent();
}
}
public Picture(byte[] _dataStream) : base()
{
this._dataStream = _dataStream;
this.dataBlockStartOfsset = 0;
this.dataBlockSize = _dataStream.Length;
this.pictureBytesStartOffset = 0;
this.size = _dataStream.Length;
}
private void FillWidthHeight()
{
PictureType pictureType = SuggestPictureType();
// trying to extract width and height from pictures content:
if (pictureType == PictureType.JPEG)
{
FillJPGWidthHeight();
}
else if (pictureType == PictureType.PNG)
{
FillPNGWidthHeight();
}
}
/**
* Tries to suggest a filename: hex representation of picture structure offset in "Data" stream plus extension that
* is tried to determine from first byte of picture's content.
*
* @return suggested file name
*/
public String SuggestFullFileName()
{
String fileExt = SuggestFileExtension();
return StringUtil.ToHexString(dataBlockStartOfsset) + (fileExt.Length > 0 ? "." + fileExt : "");
}
/**
* Writes Picture's content bytes to specified OutputStream.
* Is useful when there is need to write picture bytes directly to stream, omitting its representation in
* memory as distinct byte array.
*
* @param out a stream to write to
* @throws IOException if some exception is occured while writing to specified out
*/
public void WriteImageContent(Stream out1)
{
if (rawContent != null && rawContent.Length > 0)
{
out1.Write(rawContent, 0, size);
}
else
{
out1.Write(_dataStream, dataBlockStartOfsset, size);
}
}
/**
* @return The offset of this picture in the picture bytes, used when
* matching up with {@link CharacterRun#getPicOffset()}
*/
public int getStartOffset()
{
return dataBlockStartOfsset;
}
/**
* @return picture's content as byte array
*/
public byte[] GetContent()
{
if (content == null || content.Length <= 0)
{
FillImageContent();
}
return content;
}
/**
* Returns picture's content as it stored in Word file, i.e. possibly in
* compressed form.
*
* @return picture's content as it stored in Word file
*/
public byte[] GetRawContent()
{
FillRawImageContent();
return rawContent;
}
/**
*
* @return size in bytes of the picture
*/
public int Size
{
get
{
return size;
}
}
/**
* returns horizontal aspect ratio for picture provided by user
*/
public int AspectRatioX
{
get
{
return mx/10;
}
}
/**
* @return Horizontal scaling factor supplied by user expressed in .001%
* units
*/
public int HorizontalScalingFactor
{
get{
return mx;
}
}
/**
* returns vertical aspect ratio for picture provided by user
*/
public int AspectRatioY
{
get
{
return my/10;
}
}
/**
* @return Vertical scaling factor supplied by user expressed in .001% units
*/
public int VerticalScalingFactor
{
get{
return my;
}
}
/**
* Gets the initial width of the picture, in twips, prior to cropping or
* scaling.
*
* @return the initial width of the picture in twips
*/
public int DxaGoal
{
get
{
return dxaGoal;
}
}
/**
* Gets the initial height of the picture, in twips, prior to cropping or
* scaling.
*
* @return the initial width of the picture in twips
*/
public int DyaGoal
{
get
{
return dyaGoal;
}
}
/**
* @return The amount the picture has been cropped on the left in twips
*/
public int DxaCropLeft
{
get
{
return dxaCropLeft;
}
}
/**
* @return The amount the picture has been cropped on the top in twips
*/
public int DyaCropTop
{
get
{
return dyaCropTop;
}
}
/**
* @return The amount the picture has been cropped on the right in twips
*/
public int DxaCropRight
{
get
{
return dxaCropRight;
}
}
/**
* @return The amount the picture has been cropped on the bottom in twips
*/
public int DyaCropBottom
{
get
{
return dyaCropBottom;
}
}
/**
* tries to suggest extension for picture's file by matching signatures of popular image formats to first bytes
* of picture's contents
* @return suggested file extension
*/
public String SuggestFileExtension()
{
return SuggestPictureType().Extension;
}
public PictureType SuggestPictureType()
{
return PictureType.FindMatchingType(GetContent());
}
/**
* Returns the mime type for the image
*/
public String MimeType
{
get
{
return SuggestPictureType().Mime;
}
}
private static bool MatchSignature(byte[] dataStream, byte[] signature, int pictureBytesOffset)
{
bool matched = pictureBytesOffset < dataStream.Length;
for (int i = 0; (i + pictureBytesOffset) < dataStream.Length && i < signature.Length; i++)
{
if (dataStream[i + pictureBytesOffset] != signature[i])
{
matched = false;
break;
}
}
return matched;
}
// public String GetFileName()
// {
// return fileName;
// }
// private static String extractFileName(int blockStartIndex, byte[] dataStream) {
// int fileNameStartOffset = blockStartIndex + 0x7C;
// int fileNameSizeOffset = blockStartIndex + FILENAME_SIZE_OFFSET;
// int fileNameSize = LittleEndian.GetShort(dataStream, fileNameSizeOffSet);
//
// int fileNameIndex = fileNameStartOffSet;
// char[] fileNameChars = new char[(fileNameSize-1)/2];
// int charIndex = 0;
// while(charIndex<fileNameChars.Length) {
// short aChar = LittleEndian.GetShort(dataStream, fileNameIndex);
// fileNameChars[charIndex] = (char)aChar;
// charIndex++;
// fileNameIndex += 2;
// }
// String fileName = new String(fileNameChars);
// return fileName.Trim();
// }
private void FillRawImageContent()
{
this.rawContent = new byte[size];
Array.Copy(_dataStream, pictureBytesStartOffset, rawContent, 0, size);
}
private void FillImageContent()
{
byte[] rawContent = GetRawContent();
// HACK: Detect compressed images. In reality there should be some way to determine
// this from the first 32 bytes, but I can't see any similarity between all the
// samples I have obtained, nor any similarity in the data block contents.
if (MatchSignature(rawContent, COMPRESSED1, 32) || MatchSignature(rawContent, COMPRESSED2, 32))
{
try
{
ZlibStream gzip = new ZlibStream(new MemoryStream(rawContent, 33, rawContent.Length - 33), CompressionMode.Decompress);
MemoryStream out1 = new MemoryStream();
byte[] buf = new byte[4096];
int readBytes;
while ((readBytes = gzip.Read(buf,0,4096)) > 0)
{
out1.Write(buf, 0, readBytes);
}
content = out1.ToArray();
}
catch (IOException)
{
// Problems Reading from the actual MemoryStream should never happen
// so this will only ever be a ZipException.
//log.log(POILogger.INFO, "Possibly corrupt compression or non-compressed data", e);
}
} else {
// Raw data is not compressed.
content = rawContent;
}
}
private static int GetPictureBytesStartOffset(int dataBlockStartOffset, byte[] _dataStream, int dataBlockSize)
{
int realPicoffset = dataBlockStartOffset;
int dataBlockEndOffset = dataBlockSize + dataBlockStartOffset;
// Skip over the PICT block
int PICTFBlockSize = LittleEndian.GetShort(_dataStream, dataBlockStartOffset + PICT_HEADER_OFFSET); // Should be 68 bytes
// Now the PICTF1
int PICTF1BlockOffset = PICTFBlockSize + PICT_HEADER_OFFSET;
short MM_TYPE = LittleEndian.GetShort(_dataStream, dataBlockStartOffset + PICT_HEADER_OFFSET + 2);
if (MM_TYPE == 0x66)
{
// Skip the stPicName
int cchPicName = LittleEndian.GetUByte(_dataStream, PICTF1BlockOffset);
PICTF1BlockOffset += 1 + cchPicName;
}
int PICTF1BlockSize = LittleEndian.GetShort(_dataStream, dataBlockStartOffset + PICTF1BlockOffset);
int unknownHeaderOffset = (PICTF1BlockSize + PICTF1BlockOffset) < dataBlockEndOffset ? (PICTF1BlockSize + PICTF1BlockOffset) : PICTF1BlockOffset;
realPicoffset += (unknownHeaderOffset + UNKNOWN_HEADER_SIZE);
if (realPicoffset >= dataBlockEndOffset)
{
realPicoffset -= UNKNOWN_HEADER_SIZE;
}
return realPicoffset;
}
private void FillJPGWidthHeight()
{
/*
* http://www.codecomments.com/archive281-2004-3-158083.html
*
* Algorhitm proposed by Patrick TJ McPhee:
*
* read 2 bytes make sure they are 'ffd8'x repeatedly: read 2 bytes make
* sure the first one is 'ff'x if the second one is 'd9'x stop else if
* the second one is c0 or c2 (or possibly other values ...) skip 2
* bytes read one byte into depth read two bytes into height read two
* bytes into width else read two bytes into length skip forward
* length-2 bytes
*
* Also used Ruby code snippet from:
* http://www.bigbold.com/snippets/posts/show/805 for reference
*/
int pointer = pictureBytesStartOffset + 2;
int firstByte = _dataStream[pointer];
int secondByte = _dataStream[pointer + 1];
int endOfPicture = pictureBytesStartOffset + size;
while (pointer < endOfPicture - 1)
{
do
{
firstByte = _dataStream[pointer];
secondByte = _dataStream[pointer + 1];
pointer += 2;
} while (!(firstByte == (byte)0xFF) && pointer < endOfPicture - 1);
if (firstByte == ((byte)0xFF) && pointer < endOfPicture - 1)
{
if (secondByte == (byte)0xD9 || secondByte == (byte)0xDA)
{
break;
}
else if ((secondByte & 0xF0) == 0xC0 && secondByte != (byte)0xC4 && secondByte != (byte)0xC8 && secondByte != (byte)0xCC)
{
pointer += 5;
this.height = GetBigEndianShort(_dataStream, pointer);
this.width = GetBigEndianShort(_dataStream, pointer + 2);
break;
}
else
{
pointer++;
pointer++;
int length = GetBigEndianShort(_dataStream, pointer);
pointer += length;
}
}
else
{
pointer++;
}
}
}
private void FillPNGWidthHeight()
{
/*
Used PNG file format description from http://www.wotsit.org/download.asp?f=png
*/
int HEADER_START = pictureBytesStartOffset + PictureType.PNG.Signatures[0].Length + 4;
if (MatchSignature(_dataStream, IHDR, HEADER_START))
{
int IHDR_CHUNK_WIDTH = HEADER_START + 4;
this.width = GetBigEndianInt(_dataStream, IHDR_CHUNK_WIDTH);
this.height = GetBigEndianInt(_dataStream, IHDR_CHUNK_WIDTH + 4);
}
}
/**
* returns pixel width of the picture or -1 if dimensions determining was failed
*/
public int Width
{
get
{
if (width == -1)
{
FillWidthHeight();
}
return width;
}
}
/**
* returns pixel height of the picture or -1 if dimensions determining was failed
*/
public int Height
{
get
{
if (height == -1)
{
FillWidthHeight();
}
return height;
}
}
private static int GetBigEndianInt(byte[] data, int offset)
{
return (((data[offset] & 0xFF) << 24) + ((data[offset + 1] & 0xFF) << 16) + ((data[offset + 2] & 0xFF) << 8) + (data[offset + 3] & 0xFF));
}
private static int GetBigEndianShort(byte[] data, int offset)
{
return (((data[offset] & 0xFF) << 8) + (data[offset + 1] & 0xFF));
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
using FluentAssertions;
using IotHub.Tests.Helpers;
using Microsoft.Azure.Management.IotHub;
using Microsoft.Azure.Management.IotHub.Models;
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Management.ResourceManager.Models;
using Microsoft.Rest.Azure;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace IotHub.Tests.ScenarioTests
{
public class IotHubClientTests : IotHubTestBase
{
[Fact]
public async Task IotHubClient_HubCreate()
{
try
{
using var context = MockContext.Start(GetType());
Initialize(context);
// Create resource group
ResourceGroup resourceGroup = await CreateResourceGroupAsync(IotHubTestUtilities.DefaultResourceGroupName)
.ConfigureAwait(false);
// Check if hub exists and delete
IotHubNameAvailabilityInfo iotHubNameAvailabilityInfo = await _iotHubClient.IotHubResource
.CheckNameAvailabilityAsync(IotHubTestUtilities.DefaultIotHubName)
.ConfigureAwait(false);
if (!iotHubNameAvailabilityInfo.NameAvailable.Value)
{
_ = await _iotHubClient.IotHubResource
.DeleteAsync(
IotHubTestUtilities.DefaultResourceGroupName,
IotHubTestUtilities.DefaultIotHubName)
.ConfigureAwait(false);
iotHubNameAvailabilityInfo = await _iotHubClient.IotHubResource
.CheckNameAvailabilityAsync(IotHubTestUtilities.DefaultIotHubName)
.ConfigureAwait(false);
iotHubNameAvailabilityInfo.NameAvailable.Should().BeTrue();
}
// Create EH and AuthRule
var properties = new IotHubProperties
{
Routing = await GetIotHubRoutingPropertiesAsync(resourceGroup).ConfigureAwait(false)
};
IotHubDescription iotHub = await _iotHubClient.IotHubResource
.CreateOrUpdateAsync(
resourceGroup.Name,
IotHubTestUtilities.DefaultIotHubName,
new IotHubDescription
{
Location = IotHubTestUtilities.DefaultLocation,
Sku = new IotHubSkuInfo
{
Name = IotHubSku.S1,
Capacity = 1,
},
Properties = properties,
})
.ConfigureAwait(false);
iotHub.Should().NotBeNull();
iotHub.Name.Should().Be(IotHubTestUtilities.DefaultIotHubName);
iotHub.Location.Should().Be(IotHubTestUtilities.DefaultLocation);
iotHub.Sku.Name.Should().Be(IotHubSku.S1);
iotHub.Sku.Capacity.Should().Be(1);
// Add and get tags
var tags = new Dictionary<string, string>
{
{ "key1", "value1" },
{ "key2", "value2" }
};
iotHub = await _iotHubClient.IotHubResource
.UpdateAsync(IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultIotHubName, tags)
.ConfigureAwait(false);
iotHub.Should().NotBeNull();
iotHub.Tags.Count().Should().Be(tags.Count);
iotHub.Tags.Should().BeEquivalentTo(tags);
UserSubscriptionQuotaListResult subscriptionQuota = await _iotHubClient.ResourceProviderCommon
.GetSubscriptionQuotaAsync()
.ConfigureAwait(false);
subscriptionQuota.Value.Count.Should().Be(2);
subscriptionQuota.Value.FirstOrDefault(x => x.Name.Value.Equals("freeIotHubCount")).Limit.Should().BeGreaterThan(0);
subscriptionQuota.Value.FirstOrDefault(x => x.Name.Value.Equals("paidIotHubCount")).Limit.Should().BeGreaterThan(0);
IPage<EndpointHealthData> endpointHealth = await _iotHubClient
.IotHubResource
.GetEndpointHealthAsync(IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultIotHubName);
endpointHealth.Count().Should().Be(4);
Assert.Contains(endpointHealth, q => q.EndpointId.Equals("events", StringComparison.OrdinalIgnoreCase));
var testAllRoutesInput = new TestAllRoutesInput(RoutingSource.DeviceMessages, new RoutingMessage(), new RoutingTwin());
TestAllRoutesResult testAllRoutesResult = await _iotHubClient.IotHubResource
.TestAllRoutesAsync(testAllRoutesInput, IotHubTestUtilities.DefaultIotHubName, IotHubTestUtilities.DefaultResourceGroupName)
.ConfigureAwait(false);
testAllRoutesResult.Routes.Count.Should().Be(4);
var testRouteInput = new TestRouteInput(properties.Routing.Routes[0], new RoutingMessage(), new RoutingTwin());
TestRouteResult testRouteResult = await _iotHubClient.IotHubResource
.TestRouteAsync(testRouteInput, IotHubTestUtilities.DefaultIotHubName, IotHubTestUtilities.DefaultResourceGroupName)
.ConfigureAwait(false);
testRouteResult.Result.Should().Be("true");
// Get quota metrics
var quotaMetrics = await _iotHubClient.IotHubResource
.GetQuotaMetricsAsync(
IotHubTestUtilities.DefaultResourceGroupName,
IotHubTestUtilities.DefaultIotHubName)
.ConfigureAwait(false);
quotaMetrics.Count().Should().BeGreaterThan(0);
Assert.Contains(quotaMetrics, q => q.Name.Equals("TotalMessages", StringComparison.OrdinalIgnoreCase)
&& q.CurrentValue == 0
&& q.MaxValue == 400000);
Assert.Contains(quotaMetrics, q => q.Name.Equals("TotalDeviceCount", StringComparison.OrdinalIgnoreCase)
&& q.CurrentValue == 0
&& q.MaxValue == 1000000);
// Get all IoT hubs in a resource group
IPage<IotHubDescription> iotHubs = await _iotHubClient.IotHubResource
.ListByResourceGroupAsync(IotHubTestUtilities.DefaultResourceGroupName)
.ConfigureAwait(false);
iotHubs.Count().Should().BeGreaterThan(0);
// Get all IoT hubs in a subscription
IPage<IotHubDescription> iotHubBySubscription = await _iotHubClient.IotHubResource
.ListBySubscriptionAsync()
.ConfigureAwait(false);
iotHubBySubscription.Count().Should().BeGreaterThan(0);
// Get registry stats on newly created hub
RegistryStatistics regStats = await _iotHubClient.IotHubResource
.GetStatsAsync(IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultIotHubName)
.ConfigureAwait(false);
regStats.TotalDeviceCount.Value.Should().Be(0);
regStats.EnabledDeviceCount.Value.Should().Be(0);
regStats.DisabledDeviceCount.Value.Should().Be(0);
// Get valid skus
IPage<IotHubSkuDescription> skus = await _iotHubClient.IotHubResource
.GetValidSkusAsync(
IotHubTestUtilities.DefaultResourceGroupName,
IotHubTestUtilities.DefaultIotHubName)
.ConfigureAwait(false);
skus.Count().Should().Be(3);
// Get all IoT hub keys
const string hubOwnerRole = "iothubowner";
IPage<SharedAccessSignatureAuthorizationRule> keys = await _iotHubClient.IotHubResource
.ListKeysAsync(
IotHubTestUtilities.DefaultResourceGroupName,
IotHubTestUtilities.DefaultIotHubName)
.ConfigureAwait(false);
keys.Count().Should().BeGreaterThan(0);
Assert.Contains(keys, k => k.KeyName.Equals(hubOwnerRole, StringComparison.OrdinalIgnoreCase));
// Get specific IoT Hub key
SharedAccessSignatureAuthorizationRule key = await _iotHubClient.IotHubResource
.GetKeysForKeyNameAsync(
IotHubTestUtilities.DefaultResourceGroupName,
IotHubTestUtilities.DefaultIotHubName,
hubOwnerRole)
.ConfigureAwait(false);
key.KeyName.Should().Be(hubOwnerRole);
// Get all EH consumer groups
IPage<EventHubConsumerGroupInfo> ehConsumerGroups = await _iotHubClient.IotHubResource
.ListEventHubConsumerGroupsAsync(
IotHubTestUtilities.DefaultResourceGroupName,
IotHubTestUtilities.DefaultIotHubName,
IotHubTestUtilities.EventsEndpointName)
.ConfigureAwait(false);
ehConsumerGroups.Count().Should().BeGreaterThan(0);
Assert.Contains(ehConsumerGroups, e => e.Name.Equals("$Default", StringComparison.OrdinalIgnoreCase));
// Add EH consumer group
const string ehCgName = "testConsumerGroup";
var ehConsumerGroup = await _iotHubClient.IotHubResource
.CreateEventHubConsumerGroupAsync(
IotHubTestUtilities.DefaultResourceGroupName,
IotHubTestUtilities.DefaultIotHubName,
IotHubTestUtilities.EventsEndpointName,
ehCgName,
new EventHubConsumerGroupName(ehCgName))
.ConfigureAwait(false);
ehConsumerGroup.Name.Should().Be(ehCgName);
// Get EH consumer group
ehConsumerGroup = await _iotHubClient.IotHubResource
.GetEventHubConsumerGroupAsync(
IotHubTestUtilities.DefaultResourceGroupName,
IotHubTestUtilities.DefaultIotHubName,
IotHubTestUtilities.EventsEndpointName,
ehCgName)
.ConfigureAwait(false);
ehConsumerGroup.Name.Should().Be(ehCgName);
// Delete EH consumer group
await _iotHubClient.IotHubResource.DeleteEventHubConsumerGroupAsync(
IotHubTestUtilities.DefaultResourceGroupName,
IotHubTestUtilities.DefaultIotHubName,
IotHubTestUtilities.EventsEndpointName,
ehCgName)
.ConfigureAwait(false);
// Get all of the available IoT Hub REST API operations
IPage<Operation> operationList = _iotHubClient.Operations.List();
operationList.Count().Should().BeGreaterThan(0);
Assert.Contains(operationList, e => e.Name.Equals("Microsoft.Devices/iotHubs/Read", StringComparison.OrdinalIgnoreCase));
// Get IoT Hub REST API read operation
IEnumerable<Operation> hubReadOperation = operationList.Where(e => e.Name.Equals("Microsoft.Devices/iotHubs/Read", StringComparison.OrdinalIgnoreCase));
hubReadOperation.Count().Should().Be(1);
hubReadOperation.First().Display.Provider.Should().Be("Microsoft Devices");
hubReadOperation.First().Display.Operation.Should().Be("Get IotHub(s)");
// Initiate manual failover
IotHubDescription iotHubBeforeFailover = await _iotHubClient.IotHubResource
.GetAsync(
IotHubTestUtilities.DefaultResourceGroupName,
IotHubTestUtilities.DefaultIotHubName)
.ConfigureAwait(false);
await _iotHubClient.IotHub
.ManualFailoverAsync(
IotHubTestUtilities.DefaultIotHubName,
IotHubTestUtilities.DefaultResourceGroupName,
IotHubTestUtilities.DefaultFailoverLocation)
.ConfigureAwait(false);
var iotHubAfterFailover = await _iotHubClient.IotHubResource
.GetAsync(
IotHubTestUtilities.DefaultResourceGroupName,
IotHubTestUtilities.DefaultIotHubName)
.ConfigureAwait(false);
iotHubBeforeFailover.Properties.Locations[0].Role.ToLower().Should().Be("primary");
iotHubBeforeFailover.Properties.Locations[0].Location.Replace(" ", "").ToLower().Should().Be(IotHubTestUtilities.DefaultLocation.ToLower());
iotHubBeforeFailover.Properties.Locations[1].Role.ToLower().Should().Be("secondary");
iotHubBeforeFailover.Properties.Locations[1].Location.Replace(" ", "").ToLower().Should().Be(IotHubTestUtilities.DefaultFailoverLocation.ToLower());
iotHubAfterFailover.Properties.Locations[0].Role.ToLower().Should().Be("primary");
iotHubAfterFailover.Properties.Locations[0].Location.Replace(" ", "").ToLower().Should().Be(IotHubTestUtilities.DefaultFailoverLocation.ToLower());
iotHubAfterFailover.Properties.Locations[1].Role.ToLower().Should().Be("secondary");
iotHubAfterFailover.Properties.Locations[1].Location.Replace(" ", "").ToLower().Should().Be(IotHubTestUtilities.DefaultLocation.ToLower());
}
catch (ErrorDetailsException ex)
{
Console.WriteLine(ex.ToString());
Console.WriteLine($"{ex.Body.Message}: {ex.Body.Details}");
throw;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
throw;
}
}
[Fact]
public async Task IotHubClient_HubUpdate()
{
try
{
using MockContext context = MockContext.Start(GetType());
Initialize(context);
// Create resource group
ResourceGroup resourceGroup = await CreateResourceGroupAsync(IotHubTestUtilities.DefaultUpdateResourceGroupName);
// Check if hub exists and delete
var iotHubNameAvailabilityInfo = await _iotHubClient.IotHubResource
.CheckNameAvailabilityAsync(IotHubTestUtilities.DefaultUpdateIotHubName)
.ConfigureAwait(false);
if (!iotHubNameAvailabilityInfo.NameAvailable.Value)
{
_ = await _iotHubClient.IotHubResource
.DeleteAsync(
IotHubTestUtilities.DefaultResourceGroupName,
IotHubTestUtilities.DefaultUpdateIotHubName)
.ConfigureAwait(false);
}
var iotHub = await CreateIotHubAsync(resourceGroup, IotHubTestUtilities.DefaultLocation, IotHubTestUtilities.DefaultUpdateIotHubName, null)
.ConfigureAwait(false);
iotHub.Should().NotBeNull();
iotHub.Sku.Name.Should().Be(IotHubSku.S1);
iotHub.Name.Should().Be(IotHubTestUtilities.DefaultUpdateIotHubName);
// Update capacity
iotHub.Sku.Capacity += 1;
var retIotHub = await UpdateIotHubAsync(resourceGroup, iotHub, IotHubTestUtilities.DefaultUpdateIotHubName)
.ConfigureAwait(false);
// Update Iot Hub with routing rules
iotHub.Properties.Routing = await GetIotHubRoutingPropertiesAsync(resourceGroup).ConfigureAwait(false);
retIotHub = await UpdateIotHubAsync(resourceGroup, iotHub, IotHubTestUtilities.DefaultUpdateIotHubName).ConfigureAwait(false);
retIotHub.Should().NotBeNull();
retIotHub.Name.Should().Be(IotHubTestUtilities.DefaultUpdateIotHubName);
retIotHub.Properties.Routing.Routes.Count.Should().Be(4);
retIotHub.Properties.Routing.Endpoints.EventHubs.Count.Should().Be(1);
retIotHub.Properties.Routing.Endpoints.ServiceBusTopics.Count.Should().Be(1);
retIotHub.Properties.Routing.Endpoints.ServiceBusQueues.Count.Should().Be(1);
retIotHub.Properties.Routing.Routes[0].Name.Should().Be("route1");
// Get an IoT Hub
var iotHubDesc = await _iotHubClient.IotHubResource
.GetAsync(
IotHubTestUtilities.DefaultUpdateResourceGroupName,
IotHubTestUtilities.DefaultUpdateIotHubName)
.ConfigureAwait(false);
iotHubDesc.Should().NotBeNull();
iotHubDesc.Sku.Name.Should().Be(IotHubSku.S1);
iotHubDesc.Sku.Capacity.Should().Be(iotHub.Sku.Capacity);
iotHubDesc.Name.Should().Be(IotHubTestUtilities.DefaultUpdateIotHubName);
// Update again
// Perform a fake update
iotHubDesc.Properties.Routing.Endpoints.EventHubs[0].ResourceGroup = "1";
retIotHub = await UpdateIotHubAsync(resourceGroup, iotHubDesc, IotHubTestUtilities.DefaultUpdateIotHubName).ConfigureAwait(false);
retIotHub.Should().NotBeNull();
retIotHub.Name.Should().Be(IotHubTestUtilities.DefaultUpdateIotHubName);
retIotHub.Properties.Routing.Routes.Count.Should().Be(4);
retIotHub.Properties.Routing.Endpoints.EventHubs.Count.Should().Be(1);
retIotHub.Properties.Routing.Endpoints.ServiceBusTopics.Count.Should().Be(1);
retIotHub.Properties.Routing.Endpoints.ServiceBusQueues.Count.Should().Be(1);
retIotHub.Properties.Routing.Routes[0].Name.Should().Be("route1");
}
catch (ErrorDetailsException ex)
{
Console.WriteLine(ex.ToString());
Console.WriteLine($"{ex.Body.Message}: {ex.Body.Details}");
throw;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
throw;
}
}
[Fact]
public async Task IotHubClient_HubCertificate()
{
try
{
using var context = MockContext.Start(GetType());
Initialize(context);
// Create resource group
ResourceGroup resourceGroup = await CreateResourceGroupAsync(IotHubTestUtilities.DefaultCertificateResourceGroupName).ConfigureAwait(false);
// Check if hub exists and delete
IotHubNameAvailabilityInfo iotHubNameAvailabilityInfo = await _iotHubClient.IotHubResource
.CheckNameAvailabilityAsync(IotHubTestUtilities.DefaultCertificateIotHubName)
.ConfigureAwait(false);
if (!iotHubNameAvailabilityInfo.NameAvailable.Value)
{
_ = await _iotHubClient.IotHubResource
.DeleteAsync(
IotHubTestUtilities.DefaultCertificateResourceGroupName,
IotHubTestUtilities.DefaultCertificateIotHubName)
.ConfigureAwait(false);
}
// Create hub
IotHubDescription iotHub = await CreateIotHubAsync(resourceGroup, IotHubTestUtilities.DefaultLocation, IotHubTestUtilities.DefaultCertificateIotHubName, null)
.ConfigureAwait(false);
// Upload certificate to the hub
CertificateDescription newCertificateDescription = await CreateCertificateAsync(
resourceGroup,
IotHubTestUtilities.DefaultCertificateIotHubName,
IotHubTestUtilities.DefaultIotHubCertificateName)
.ConfigureAwait(false);
newCertificateDescription.Name.Should().Be(IotHubTestUtilities.DefaultIotHubCertificateName);
newCertificateDescription.Properties.Subject.Should().Be(IotHubTestUtilities.DefaultIotHubCertificateSubject);
newCertificateDescription.Properties.Thumbprint.Should().Be(IotHubTestUtilities.DefaultIotHubCertificateThumbprint);
newCertificateDescription.Type.Should().Be(IotHubTestUtilities.DefaultIotHubCertificateType);
newCertificateDescription.Properties.IsVerified.Should().BeFalse();
// Get all certificates
var certificateList = await GetCertificatesAsync(resourceGroup, IotHubTestUtilities.DefaultCertificateIotHubName).ConfigureAwait(false);
certificateList.Value.Count().Should().Be(1);
// Get certificate
CertificateDescription certificate = await GetCertificateAsync(resourceGroup, IotHubTestUtilities.DefaultCertificateIotHubName, IotHubTestUtilities.DefaultIotHubCertificateName)
.ConfigureAwait(false);
certificate.Name.Should().Be(IotHubTestUtilities.DefaultIotHubCertificateName);
certificate.Properties.Subject.Should().Be(IotHubTestUtilities.DefaultIotHubCertificateSubject);
certificate.Properties.Thumbprint.Should().Be(IotHubTestUtilities.DefaultIotHubCertificateThumbprint);
certificate.Type.Should().Be(IotHubTestUtilities.DefaultIotHubCertificateType);
certificate.Properties.IsVerified.Should().BeFalse();
CertificateWithNonceDescription certificateWithNonceDescription = await GenerateVerificationCodeAsync(
resourceGroup,
IotHubTestUtilities.DefaultCertificateIotHubName,
IotHubTestUtilities.DefaultIotHubCertificateName,
certificate.Etag)
.ConfigureAwait(false);
certificateWithNonceDescription.Name.Should().Be(IotHubTestUtilities.DefaultIotHubCertificateName);
certificateWithNonceDescription.Properties.Subject.Should().Be(IotHubTestUtilities.DefaultIotHubCertificateSubject);
certificateWithNonceDescription.Properties.Thumbprint.Should().Be(IotHubTestUtilities.DefaultIotHubCertificateThumbprint);
certificateWithNonceDescription.Type.Should().Be(IotHubTestUtilities.DefaultIotHubCertificateType);
certificateWithNonceDescription.Properties.IsVerified.Should().BeFalse();
certificateWithNonceDescription.Properties.VerificationCode.Should().NotBeNull();
// Delete certificate
await DeleteCertificateAsync(
resourceGroup,
IotHubTestUtilities.DefaultCertificateIotHubName,
IotHubTestUtilities.DefaultIotHubCertificateName,
certificateWithNonceDescription.Etag)
.ConfigureAwait(false);
// Get all certificate after delete
var certificateListAfterDelete = await GetCertificatesAsync(resourceGroup, IotHubTestUtilities.DefaultCertificateIotHubName)
.ConfigureAwait(false);
certificateListAfterDelete.Value.Count().Should().Be(0);
}
catch (ErrorDetailsException ex)
{
Console.WriteLine(ex.ToString());
Console.WriteLine($"{ex.Body.Message}: {ex.Body.Details}");
throw;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
throw;
}
}
private async Task<RoutingProperties> GetIotHubRoutingPropertiesAsync(ResourceGroup resourceGroup)
{
string ehConnectionString = await CreateExternalEhAsync(resourceGroup, _location);
Tuple<string, string> sbTopicConnectionString = await CreateExternalQueueAndTopicAsync(resourceGroup, _location);
string sbConnectionString = sbTopicConnectionString.Item1;
string topicConnectionString = sbTopicConnectionString.Item2;
// Create hub
var routingProperties = new RoutingProperties
{
Endpoints = new RoutingEndpoints
{
EventHubs = new List<RoutingEventHubProperties>
{
new RoutingEventHubProperties
{
Name = "eh1",
ConnectionString = ehConnectionString
}
},
ServiceBusQueues = new List<RoutingServiceBusQueueEndpointProperties>
{
new RoutingServiceBusQueueEndpointProperties
{
Name = "sb1",
ConnectionString = sbConnectionString
}
},
ServiceBusTopics = new List<RoutingServiceBusTopicEndpointProperties>
{
new RoutingServiceBusTopicEndpointProperties
{
Name = "tp1",
ConnectionString = topicConnectionString
}
}
},
Routes = new List<RouteProperties>
{
new RouteProperties
{
Condition = "true",
EndpointNames = new List<string> {"events"},
IsEnabled = true,
Name = "route1",
Source = "DeviceMessages"
},
new RouteProperties
{
Condition = "true",
EndpointNames = new List<string> {"eh1"},
IsEnabled = true,
Name = "route2",
Source = "DeviceMessages"
},
new RouteProperties
{
Condition = "true",
EndpointNames = new List<string> {"sb1"},
IsEnabled = true,
Name = "route3",
Source = "DeviceMessages"
},
new RouteProperties
{
Condition = "true",
EndpointNames = new List<string> {"tp1"},
IsEnabled = true,
Name = "route4",
Source = "DeviceMessages"
},
}
};
return routingProperties;
}
}
}
| |
// Created by Paul Gonzalez Becerra
using System;
using GDToolkit.Core;
using GDToolkit.Design;
using GDToolkit.Mathematics;
using GDToolkit.Mathematics.Geometry;
using OpenTK.Graphics.OpenGL;
namespace GDToolkit.Design.GUI
{
public class Border
{
#region --- Field Variables ---
// Variables
public Rectangle bounds;
public GUIColorPacket colors;
public GUIColorPacket secondSetColors; // Used for inset, outset, grove, yada yada
public float borderSize;
public BorderStyle style;
#endregion // Field Variables
#region --- Constructors ---
public Border()
{
bounds= Rectangle.EMPTY;
colors= new GUIColorPacket
(
new Color(0, 0, 0),
new Color(0, 0, 0),
new Color(0, 0, 0),
new Color(0, 0, 0)
);
secondSetColors= new GUIColorPacket
(
new Color(255, 255, 255),
new Color(255, 255, 255),
new Color(255, 255, 255),
new Color(255, 255, 255)
);
borderSize= 1f;
style= BorderStyle.SOLID;
}
#endregion // Constructors
#region --- Properties ---
// Gets the x value of the border location
public float x
{
get { return bounds.x; }
}
// Gets the y value of the border location
public float y
{
get { return bounds.y; }
}
// Gets the width value of the border size
public float width
{
get { return bounds.width; }
}
// Gets the height value of the border size
public float height
{
get { return bounds.height; }
}
#endregion // Properties
#region --- Methods ---
// Sets the border size of the border
public void setBorderSize(float pmBorderSize)
{
borderSize= pmBorderSize;
}
public void setBorderStyle(BorderStyle pmStyle)
{
style= pmStyle;
}
// Renders the border given the game to render it on, state 0 is normal, state 1 is disabled, state 2 is hovered, and state 3 is pressed
public void render(Game game, Rectangle prevClipRegion, byte state)
{
game.graphics.endClip();
switch((int)(style))
{
case 0: return;
case 1: renderSolid(ref game, state); break;
case 2: renderDashed(ref game, state); break;
case 3: renderDotted(ref game, state); break;
case 4: renderDouble(ref game, state); break;
case 5: renderGroove(ref game, state); break;
case 6: renderRidge(ref game, state); break;
case 7: renderInset(ref game, state); break;
case 8: renderOutset(ref game, state); break;
}
game.graphics.beginClip(prevClipRegion);
}
// Renders the border as a solid border
protected virtual void renderSolid(ref Game game, byte state)
{
// Variables
Color colorUsed= colors.normal;
if(state== 1)
colorUsed= colors.disabled;
if(state== 2)
colorUsed= colors.hovered;
if(state== 3)
colorUsed= colors.pressed;
game.graphics.outlineRect(new Rectangle(x-borderSize, y-borderSize, width+borderSize*2f, height+borderSize*2f), colorUsed, borderSize);
game.graphics.renderRectEndpoints(new Rectangle(x-borderSize, y-borderSize, width+borderSize*2f, height+borderSize*2f), colorUsed, borderSize);
}
// Renders the border as a dashed border
protected virtual void renderDashed(ref Game game, byte state)
{
// Variables
Color colorUsed= colors.normal;
if(state== 1)
colorUsed= colors.disabled;
if(state== 2)
colorUsed= colors.hovered;
if(state== 3)
colorUsed= colors.pressed;
GL.LineStipple(1, ushort.MaxValue-255);
GL.Enable(EnableCap.LineStipple);
game.graphics.outlineRect(new Rectangle(x-borderSize, y-borderSize, width+borderSize*2f, height+borderSize*2f), colorUsed, borderSize);
GL.Disable(EnableCap.LineStipple);
game.graphics.renderRectEndpoints(new Rectangle(x-borderSize, y-borderSize, width+borderSize*2f, height+borderSize*2f), colorUsed, borderSize);
}
// Renders the border as a dotted border
protected virtual void renderDotted(ref Game game, byte state)
{
// Variables
Color colorUsed= colors.normal;
if(state== 1)
colorUsed= colors.disabled;
if(state== 2)
colorUsed= colors.hovered;
if(state== 3)
colorUsed= colors.pressed;
GL.LineStipple(1, 0xaaaa);
GL.Enable(EnableCap.LineStipple);
game.graphics.outlineRect(new Rectangle(x-borderSize, y-borderSize, width+borderSize*2f, height+borderSize*2f), colorUsed, borderSize);
GL.Disable(EnableCap.LineStipple);
game.graphics.renderRectEndpoints(new Rectangle(x-borderSize, y-borderSize, width+borderSize*2f, height+borderSize*2f), colorUsed, borderSize);
}
// Renders the border as a double border
protected virtual void renderDouble(ref Game game, byte state)
{
// Variables
Color colorUsed= colors.normal;
renderSolid(ref game, state);
if(state== 1)
colorUsed= colors.disabled;
if(state== 2)
colorUsed= colors.hovered;
if(state== 3)
colorUsed= colors.pressed;
game.graphics.outlineRect(new Rectangle(x+2f, y+2f, width-4f, height-4f), colorUsed, borderSize);
game.graphics.renderRectEndpoints(new Rectangle(x+2f, y+2f, width-4f, height-4f), colorUsed, borderSize);
}
// Renders the border as a groove border
protected virtual void renderGroove(ref Game game, byte state)
{
// Variables
Color colorUsed= colors.normal;
Color colorBUsed= secondSetColors.normal;
if(state== 1)
{
colorUsed= colors.disabled;
colorBUsed= secondSetColors.disabled;
}
if(state== 2)
{
colorUsed= colors.hovered;
colorBUsed= secondSetColors.hovered;
}
if(state== 3)
{
colorUsed= colors.pressed;
colorBUsed= secondSetColors.pressed;
}
game.graphics.outlineRect(new Rectangle(x-borderSize, y-borderSize, width+borderSize*2f, height+borderSize*2f), colorUsed, borderSize);
game.graphics.renderRectEndpoints(new Rectangle(x-borderSize, y-borderSize, width+borderSize*2f, height+borderSize*2f), colorUsed, borderSize);
game.graphics.outlineRect(bounds, colorBUsed, 1f);
game.graphics.renderRectEndpoints(bounds, colorBUsed, 1f);
}
// Renders the border as a ridge border
protected virtual void renderRidge(ref Game game, byte state)
{
// Variables
Color colorUsed= colors.normal;
Color colorBUsed= secondSetColors.normal;
if(state== 1)
{
colorUsed= colors.disabled;
colorBUsed= secondSetColors.disabled;
}
if(state== 2)
{
colorUsed= colors.hovered;
colorBUsed= secondSetColors.hovered;
}
if(state== 3)
{
colorUsed= colors.pressed;
colorBUsed= secondSetColors.pressed;
}
game.graphics.outlineRect(new Rectangle(x-borderSize, y-borderSize, width+borderSize*2f, height+borderSize*2f), colorBUsed, borderSize);
game.graphics.renderRectEndpoints(new Rectangle(x-borderSize, y-borderSize, width+borderSize*2f, height+borderSize*2f), colorBUsed, borderSize);
game.graphics.outlineRect(bounds, colorUsed, 1f);
game.graphics.renderRectEndpoints(bounds, colorUsed, 1f);
}
// Renders the border as a inset border
protected virtual void renderInset(ref Game game, byte state)
{
// Variables
Color colorUsed= colors.normal;
Color colorBUsed= secondSetColors.normal;
if(state== 1)
{
colorUsed= colors.disabled;
colorBUsed= secondSetColors.disabled;
}
if(state== 2)
{
colorUsed= colors.hovered;
colorBUsed= secondSetColors.hovered;
}
if(state== 3)
{
colorUsed= colors.pressed;
colorBUsed= secondSetColors.pressed;
}
game.graphics.renderLine(new Point2(x, y), new Point2(x, y+height), colorUsed, borderSize);
game.graphics.renderLine(new Point2(x, y), new Point2(x+width, y), colorUsed, borderSize);
game.graphics.renderLine(new Point2(x+width, y+height), new Point2(x, y+height), colorBUsed, borderSize);
game.graphics.renderLine(new Point2(x+width, y+height), new Point2(x+width, y), colorBUsed, borderSize);
}
// Renders the border as a outset border
protected virtual void renderOutset(ref Game game, byte state)
{
// Variables
Color colorUsed= colors.normal;
Color colorBUsed= secondSetColors.normal;
if(state== 1)
{
colorUsed= colors.disabled;
colorBUsed= secondSetColors.disabled;
}
if(state== 2)
{
colorUsed= colors.hovered;
colorBUsed= secondSetColors.hovered;
}
if(state== 3)
{
colorUsed= colors.pressed;
colorBUsed= secondSetColors.pressed;
}
game.graphics.renderLine(new Point2(x, y), new Point2(x, y+height), colorBUsed, borderSize);
game.graphics.renderLine(new Point2(x, y), new Point2(x+width, y), colorBUsed, borderSize);
game.graphics.renderLine(new Point2(x+width, y+height), new Point2(x, y+height), colorUsed, borderSize);
game.graphics.renderLine(new Point2(x+width, y+height), new Point2(x+width, y), colorUsed, borderSize);
}
#endregion // Methods
}
}
// End of File
| |
// 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.Threading;
using System.Threading.Tasks;
using IEnumerable = System.Collections.IEnumerable;
using SuppressMessageAttribute = System.Diagnostics.CodeAnalysis.SuppressMessageAttribute;
namespace System.Xml.Linq
{
internal struct Inserter
{
private readonly XContainer _parent;
private XNode _previous;
private string _text;
public Inserter(XContainer parent, XNode anchor)
{
_parent = parent;
_previous = anchor;
_text = null;
}
public void Add(object content)
{
AddContent(content);
if (_text != null)
{
if (_parent.content == null)
{
if (_parent.SkipNotify())
{
_parent.content = _text;
}
else
{
if (_text.Length > 0)
{
InsertNode(new XText(_text));
}
else
{
if (_parent is XElement)
{
// Change in the serialization of an empty element:
// from empty tag to start/end tag pair
_parent.NotifyChanging(_parent, XObjectChangeEventArgs.Value);
if (_parent.content != null) throw new InvalidOperationException(SR.InvalidOperation_ExternalCode);
_parent.content = _text;
_parent.NotifyChanged(_parent, XObjectChangeEventArgs.Value);
}
else
{
_parent.content = _text;
}
}
}
}
else if (_text.Length > 0)
{
XText prevXText = _previous as XText;
if (prevXText != null && !(_previous is XCData))
{
prevXText.Value += _text;
}
else
{
_parent.ConvertTextToNode();
InsertNode(new XText(_text));
}
}
}
}
private void AddContent(object content)
{
if (content == null) return;
XNode n = content as XNode;
if (n != null)
{
AddNode(n);
return;
}
string s = content as string;
if (s != null)
{
AddString(s);
return;
}
XStreamingElement x = content as XStreamingElement;
if (x != null)
{
AddNode(new XElement(x));
return;
}
object[] o = content as object[];
if (o != null)
{
foreach (object obj in o) AddContent(obj);
return;
}
IEnumerable e = content as IEnumerable;
if (e != null)
{
foreach (object obj in e) AddContent(obj);
return;
}
if (content is XAttribute) throw new ArgumentException(SR.Argument_AddAttribute);
AddString(XContainer.GetStringValue(content));
}
private void AddNode(XNode n)
{
_parent.ValidateNode(n, _previous);
if (n.parent != null)
{
n = n.CloneNode();
}
else
{
XNode p = _parent;
while (p.parent != null) p = p.parent;
if (n == p) n = n.CloneNode();
}
_parent.ConvertTextToNode();
if (_text != null)
{
if (_text.Length > 0)
{
XText prevXText = _previous as XText;
if (prevXText != null && !(_previous is XCData))
{
prevXText.Value += _text;
}
else
{
InsertNode(new XText(_text));
}
}
_text = null;
}
InsertNode(n);
}
private void AddString(string s)
{
_parent.ValidateString(s);
_text += s;
}
// Prepends if previous == null, otherwise inserts after previous
private void InsertNode(XNode n)
{
bool notify = _parent.NotifyChanging(n, XObjectChangeEventArgs.Add);
if (n.parent != null) throw new InvalidOperationException(SR.InvalidOperation_ExternalCode);
n.parent = _parent;
if (_parent.content == null || _parent.content is string)
{
n.next = n;
_parent.content = n;
}
else if (_previous == null)
{
XNode last = (XNode)_parent.content;
n.next = last.next;
last.next = n;
}
else
{
n.next = _previous.next;
_previous.next = n;
if (_parent.content == _previous) _parent.content = n;
}
_previous = n;
if (notify) _parent.NotifyChanged(n, XObjectChangeEventArgs.Add);
}
}
internal struct NamespaceCache
{
private XNamespace _ns;
private string _namespaceName;
public XNamespace Get(string namespaceName)
{
if ((object)namespaceName == (object)_namespaceName) return _ns;
_namespaceName = namespaceName;
_ns = XNamespace.Get(namespaceName);
return _ns;
}
}
internal struct ElementWriter
{
private readonly XmlWriter _writer;
private NamespaceResolver _resolver;
public ElementWriter(XmlWriter writer)
{
_writer = writer;
_resolver = new NamespaceResolver();
}
public void WriteElement(XElement e)
{
PushAncestors(e);
XElement root = e;
XNode n = e;
while (true)
{
e = n as XElement;
if (e != null)
{
WriteStartElement(e);
if (e.content == null)
{
WriteEndElement();
}
else
{
string s = e.content as string;
if (s != null)
{
_writer.WriteString(s);
WriteFullEndElement();
}
else
{
n = ((XNode)e.content).next;
continue;
}
}
}
else
{
n.WriteTo(_writer);
}
while (n != root && n == n.parent.content)
{
n = n.parent;
WriteFullEndElement();
}
if (n == root) break;
n = n.next;
}
}
public async Task WriteElementAsync(XElement e, CancellationToken cancellationToken)
{
PushAncestors(e);
XElement root = e;
XNode n = e;
while (true)
{
e = n as XElement;
if (e != null)
{
await WriteStartElementAsync(e, cancellationToken).ConfigureAwait(false);
if (e.content == null)
{
await WriteEndElementAsync(cancellationToken).ConfigureAwait(false);
}
else
{
string s = e.content as string;
if (s != null)
{
cancellationToken.ThrowIfCancellationRequested();
await _writer.WriteStringAsync(s).ConfigureAwait(false);
await WriteFullEndElementAsync(cancellationToken).ConfigureAwait(false);
}
else
{
n = ((XNode)e.content).next;
continue;
}
}
}
else
{
await n.WriteToAsync(_writer, cancellationToken).ConfigureAwait(false);
}
while (n != root && n == n.parent.content)
{
n = n.parent;
await WriteFullEndElementAsync(cancellationToken).ConfigureAwait(false);
}
if (n == root) break;
n = n.next;
}
}
private string GetPrefixOfNamespace(XNamespace ns, bool allowDefaultNamespace)
{
string namespaceName = ns.NamespaceName;
if (namespaceName.Length == 0) return string.Empty;
string prefix = _resolver.GetPrefixOfNamespace(ns, allowDefaultNamespace);
if (prefix != null) return prefix;
if ((object)namespaceName == (object)XNamespace.xmlPrefixNamespace) return "xml";
if ((object)namespaceName == (object)XNamespace.xmlnsPrefixNamespace) return "xmlns";
return null;
}
private void PushAncestors(XElement e)
{
while (true)
{
e = e.parent as XElement;
if (e == null) break;
XAttribute a = e.lastAttr;
if (a != null)
{
do
{
a = a.next;
if (a.IsNamespaceDeclaration)
{
_resolver.AddFirst(a.Name.NamespaceName.Length == 0 ? string.Empty : a.Name.LocalName, XNamespace.Get(a.Value));
}
} while (a != e.lastAttr);
}
}
}
private void PushElement(XElement e)
{
_resolver.PushScope();
XAttribute a = e.lastAttr;
if (a != null)
{
do
{
a = a.next;
if (a.IsNamespaceDeclaration)
{
_resolver.Add(a.Name.NamespaceName.Length == 0 ? string.Empty : a.Name.LocalName, XNamespace.Get(a.Value));
}
} while (a != e.lastAttr);
}
}
private void WriteEndElement()
{
_writer.WriteEndElement();
_resolver.PopScope();
}
private async Task WriteEndElementAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
await _writer.WriteEndElementAsync().ConfigureAwait(false);
_resolver.PopScope();
}
private void WriteFullEndElement()
{
_writer.WriteFullEndElement();
_resolver.PopScope();
}
private async Task WriteFullEndElementAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
await _writer.WriteFullEndElementAsync().ConfigureAwait(false);
_resolver.PopScope();
}
private void WriteStartElement(XElement e)
{
PushElement(e);
XNamespace ns = e.Name.Namespace;
_writer.WriteStartElement(GetPrefixOfNamespace(ns, true), e.Name.LocalName, ns.NamespaceName);
XAttribute a = e.lastAttr;
if (a != null)
{
do
{
a = a.next;
ns = a.Name.Namespace;
string localName = a.Name.LocalName;
string namespaceName = ns.NamespaceName;
_writer.WriteAttributeString(GetPrefixOfNamespace(ns, false), localName, namespaceName.Length == 0 && localName == "xmlns" ? XNamespace.xmlnsPrefixNamespace : namespaceName, a.Value);
} while (a != e.lastAttr);
}
}
private async Task WriteStartElementAsync(XElement e, CancellationToken cancellationToken)
{
PushElement(e);
XNamespace ns = e.Name.Namespace;
await _writer.WriteStartElementAsync(GetPrefixOfNamespace(ns, true), e.Name.LocalName, ns.NamespaceName).ConfigureAwait(false);
XAttribute a = e.lastAttr;
if (a != null)
{
do
{
a = a.next;
ns = a.Name.Namespace;
string localName = a.Name.LocalName;
string namespaceName = ns.NamespaceName;
await _writer.WriteAttributeStringAsync(GetPrefixOfNamespace(ns, false), localName, namespaceName.Length == 0 && localName == "xmlns" ? XNamespace.xmlnsPrefixNamespace : namespaceName, a.Value).ConfigureAwait(false);
} while (a != e.lastAttr);
}
}
}
internal struct NamespaceResolver
{
private class NamespaceDeclaration
{
public string prefix;
public XNamespace ns;
public int scope;
public NamespaceDeclaration prev;
}
private int _scope;
private NamespaceDeclaration _declaration;
private NamespaceDeclaration _rover;
public void PushScope()
{
_scope++;
}
public void PopScope()
{
NamespaceDeclaration d = _declaration;
if (d != null)
{
do
{
d = d.prev;
if (d.scope != _scope) break;
if (d == _declaration)
{
_declaration = null;
}
else
{
_declaration.prev = d.prev;
}
_rover = null;
} while (d != _declaration && _declaration != null);
}
_scope--;
}
public void Add(string prefix, XNamespace ns)
{
NamespaceDeclaration d = new NamespaceDeclaration();
d.prefix = prefix;
d.ns = ns;
d.scope = _scope;
if (_declaration == null)
{
_declaration = d;
}
else
{
d.prev = _declaration.prev;
}
_declaration.prev = d;
_rover = null;
}
public void AddFirst(string prefix, XNamespace ns)
{
NamespaceDeclaration d = new NamespaceDeclaration();
d.prefix = prefix;
d.ns = ns;
d.scope = _scope;
if (_declaration == null)
{
d.prev = d;
}
else
{
d.prev = _declaration.prev;
_declaration.prev = d;
}
_declaration = d;
_rover = null;
}
// Only elements allow default namespace declarations. The rover
// caches the last namespace declaration used by an element.
public string GetPrefixOfNamespace(XNamespace ns, bool allowDefaultNamespace)
{
if (_rover != null && _rover.ns == ns && (allowDefaultNamespace || _rover.prefix.Length > 0)) return _rover.prefix;
NamespaceDeclaration d = _declaration;
if (d != null)
{
do
{
d = d.prev;
if (d.ns == ns)
{
NamespaceDeclaration x = _declaration.prev;
while (x != d && x.prefix != d.prefix)
{
x = x.prev;
}
if (x == d)
{
if (allowDefaultNamespace)
{
_rover = d;
return d.prefix;
}
else if (d.prefix.Length > 0)
{
return d.prefix;
}
}
}
} while (d != _declaration);
}
return null;
}
}
internal struct StreamingElementWriter
{
private readonly XmlWriter _writer;
private XStreamingElement _element;
private readonly List<XAttribute> _attributes;
private NamespaceResolver _resolver;
public StreamingElementWriter(XmlWriter w)
{
_writer = w;
_element = null;
_attributes = new List<XAttribute>();
_resolver = new NamespaceResolver();
}
private void FlushElement()
{
if (_element != null)
{
PushElement();
XNamespace ns = _element.Name.Namespace;
_writer.WriteStartElement(GetPrefixOfNamespace(ns, true), _element.Name.LocalName, ns.NamespaceName);
foreach (XAttribute a in _attributes)
{
ns = a.Name.Namespace;
string localName = a.Name.LocalName;
string namespaceName = ns.NamespaceName;
_writer.WriteAttributeString(GetPrefixOfNamespace(ns, false), localName, namespaceName.Length == 0 && localName == "xmlns" ? XNamespace.xmlnsPrefixNamespace : namespaceName, a.Value);
}
_element = null;
_attributes.Clear();
}
}
private string GetPrefixOfNamespace(XNamespace ns, bool allowDefaultNamespace)
{
string namespaceName = ns.NamespaceName;
if (namespaceName.Length == 0) return string.Empty;
string prefix = _resolver.GetPrefixOfNamespace(ns, allowDefaultNamespace);
if (prefix != null) return prefix;
if ((object)namespaceName == (object)XNamespace.xmlPrefixNamespace) return "xml";
if ((object)namespaceName == (object)XNamespace.xmlnsPrefixNamespace) return "xmlns";
return null;
}
private void PushElement()
{
_resolver.PushScope();
foreach (XAttribute a in _attributes)
{
if (a.IsNamespaceDeclaration)
{
_resolver.Add(a.Name.NamespaceName.Length == 0 ? string.Empty : a.Name.LocalName, XNamespace.Get(a.Value));
}
}
}
private void Write(object content)
{
if (content == null) return;
XNode n = content as XNode;
if (n != null)
{
WriteNode(n);
return;
}
string s = content as string;
if (s != null)
{
WriteString(s);
return;
}
XAttribute a = content as XAttribute;
if (a != null)
{
WriteAttribute(a);
return;
}
XStreamingElement x = content as XStreamingElement;
if (x != null)
{
WriteStreamingElement(x);
return;
}
object[] o = content as object[];
if (o != null)
{
foreach (object obj in o) Write(obj);
return;
}
IEnumerable e = content as IEnumerable;
if (e != null)
{
foreach (object obj in e) Write(obj);
return;
}
WriteString(XContainer.GetStringValue(content));
}
private void WriteAttribute(XAttribute a)
{
if (_element == null) throw new InvalidOperationException(SR.InvalidOperation_WriteAttribute);
_attributes.Add(a);
}
private void WriteNode(XNode n)
{
FlushElement();
n.WriteTo(_writer);
}
internal void WriteStreamingElement(XStreamingElement e)
{
FlushElement();
_element = e;
Write(e.content);
FlushElement();
_writer.WriteEndElement();
_resolver.PopScope();
}
private void WriteString(string s)
{
FlushElement();
_writer.WriteString(s);
}
}
/// <summary>
/// Specifies the event type when an event is raised for an <see cref="XObject"/>.
/// </summary>
public enum XObjectChange
{
/// <summary>
/// An <see cref="XObject"/> has been or will be added to an <see cref="XContainer"/>.
/// </summary>
Add,
/// <summary>
/// An <see cref="XObject"/> has been or will be removed from an <see cref="XContainer"/>.
/// </summary>
Remove,
/// <summary>
/// An <see cref="XObject"/> has been or will be renamed.
/// </summary>
Name,
/// <summary>
/// The value of an <see cref="XObject"/> has been or will be changed.
/// There is a special case for elements. Change in the serialization
/// of an empty element (either from an empty tag to start/end tag
/// pair or vice versa) raises this event.
/// </summary>
Value,
}
/// <summary>
/// Specifies a set of options for Load().
/// </summary>
[Flags]
public enum LoadOptions
{
/// <summary>Default options.</summary>
None = 0x00000000,
/// <summary>Preserve whitespace.</summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Back-compat with System.Xml.")]
PreserveWhitespace = 0x00000001,
/// <summary>Set the BaseUri property.</summary>
SetBaseUri = 0x00000002,
/// <summary>Set the IXmlLineInfo.</summary>
SetLineInfo = 0x00000004,
}
/// <summary>
/// Specifies a set of options for Save().
/// </summary>
[Flags]
public enum SaveOptions
{
/// <summary>Default options.</summary>
None = 0x00000000,
/// <summary>Disable formatting.</summary>
DisableFormatting = 0x00000001,
/// <summary>Remove duplicate namespace declarations.</summary>
OmitDuplicateNamespaces = 0x00000002,
}
/// <summary>
/// Specifies a set of options for CreateReader().
/// </summary>
[Flags]
public enum ReaderOptions
{
/// <summary>Default options.</summary>
None = 0x00000000,
/// <summary>Remove duplicate namespace declarations.</summary>
OmitDuplicateNamespaces = 0x00000001,
}
}
| |
namespace MDIRibbon
{
partial class Form1
{
/// <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();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.ribbon = new ComponentFactory.Krypton.Ribbon.KryptonRibbon();
this.buttonSpecHelp = new ComponentFactory.Krypton.Toolkit.ButtonSpecAny();
this.kryptonContextMenuItem1 = new ComponentFactory.Krypton.Toolkit.KryptonContextMenuItem();
this.tabHome = new ComponentFactory.Krypton.Ribbon.KryptonRibbonTab();
this.kryptonRibbonGroup2 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup();
this.kryptonRibbonGroupTriple2 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple();
this.buttonNewWindow = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton();
this.kryptonRibbonGroupSeparator1 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupSeparator();
this.kryptonRibbonGroupTriple3 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple();
this.buttonCloseWindow = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton();
this.buttonCloseAllWindows = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton();
this.kryptonRibbonGroup1 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup();
this.kryptonRibbonGroupTriple4 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple();
this.buttonCascade = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton();
this.buttonTileHorizontal = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton();
this.buttonTileVertical = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton();
this.kryptonManager1 = new ComponentFactory.Krypton.Toolkit.KryptonManager(this.components);
((System.ComponentModel.ISupportInitialize)(this.ribbon)).BeginInit();
this.SuspendLayout();
//
// ribbon
//
this.ribbon.ButtonSpecs.AddRange(new ComponentFactory.Krypton.Toolkit.ButtonSpecAny[] {
this.buttonSpecHelp});
this.ribbon.Name = "ribbon";
this.ribbon.QATLocation = ComponentFactory.Krypton.Ribbon.QATLocation.Hidden;
this.ribbon.RibbonAppButton.AppButtonMenuItems.AddRange(new ComponentFactory.Krypton.Toolkit.KryptonContextMenuItemBase[] {
this.kryptonContextMenuItem1});
this.ribbon.RibbonAppButton.AppButtonShowRecentDocs = false;
this.ribbon.RibbonTabs.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonTab[] {
this.tabHome});
this.ribbon.SelectedTab = this.tabHome;
this.ribbon.Size = new System.Drawing.Size(692, 114);
this.ribbon.TabIndex = 0;
//
// buttonSpecHelp
//
this.buttonSpecHelp.Image = ((System.Drawing.Image)(resources.GetObject("buttonSpecHelp.Image")));
this.buttonSpecHelp.Style = ComponentFactory.Krypton.Toolkit.PaletteButtonStyle.ButtonSpec;
this.buttonSpecHelp.UniqueName = "06E98F3735BC4B1106E98F3735BC4B11";
this.buttonSpecHelp.Click += new System.EventHandler(this.buttonSpecHelp_Click);
//
// kryptonContextMenuItem1
//
this.kryptonContextMenuItem1.Image = ((System.Drawing.Image)(resources.GetObject("kryptonContextMenuItem1.Image")));
this.kryptonContextMenuItem1.Text = "E&xit";
this.kryptonContextMenuItem1.Click += new System.EventHandler(this.appMenu_Click);
//
// tabHome
//
this.tabHome.Groups.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup[] {
this.kryptonRibbonGroup2,
this.kryptonRibbonGroup1});
this.tabHome.KeyTip = "H";
this.tabHome.Text = "Home";
//
// kryptonRibbonGroup2
//
this.kryptonRibbonGroup2.DialogBoxLauncher = false;
this.kryptonRibbonGroup2.Image = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroup2.Image")));
this.kryptonRibbonGroup2.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupContainer[] {
this.kryptonRibbonGroupTriple2,
this.kryptonRibbonGroupSeparator1,
this.kryptonRibbonGroupTriple3});
this.kryptonRibbonGroup2.KeyTipGroup = "O";
this.kryptonRibbonGroup2.TextLine1 = "Operations";
//
// kryptonRibbonGroupTriple2
//
this.kryptonRibbonGroupTriple2.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] {
this.buttonNewWindow});
//
// buttonNewWindow
//
this.buttonNewWindow.ImageLarge = ((System.Drawing.Image)(resources.GetObject("buttonNewWindow.ImageLarge")));
this.buttonNewWindow.ImageSmall = ((System.Drawing.Image)(resources.GetObject("buttonNewWindow.ImageSmall")));
this.buttonNewWindow.KeyTip = "N";
this.buttonNewWindow.TextLine1 = "New";
this.buttonNewWindow.TextLine2 = "Window";
this.buttonNewWindow.Click += new System.EventHandler(this.buttonNewWindow_Click);
//
// kryptonRibbonGroupTriple3
//
this.kryptonRibbonGroupTriple3.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] {
this.buttonCloseWindow,
this.buttonCloseAllWindows});
//
// buttonCloseWindow
//
this.buttonCloseWindow.ImageLarge = ((System.Drawing.Image)(resources.GetObject("buttonCloseWindow.ImageLarge")));
this.buttonCloseWindow.ImageSmall = ((System.Drawing.Image)(resources.GetObject("buttonCloseWindow.ImageSmall")));
this.buttonCloseWindow.KeyTip = "X";
this.buttonCloseWindow.TextLine1 = "Close";
this.buttonCloseWindow.TextLine2 = "Window";
this.buttonCloseWindow.Click += new System.EventHandler(this.buttonCloseWindow_Click);
//
// buttonCloseAllWindows
//
this.buttonCloseAllWindows.ImageLarge = ((System.Drawing.Image)(resources.GetObject("buttonCloseAllWindows.ImageLarge")));
this.buttonCloseAllWindows.ImageSmall = ((System.Drawing.Image)(resources.GetObject("buttonCloseAllWindows.ImageSmall")));
this.buttonCloseAllWindows.KeyTip = "A";
this.buttonCloseAllWindows.TextLine1 = "Close All";
this.buttonCloseAllWindows.TextLine2 = "Windows";
this.buttonCloseAllWindows.Click += new System.EventHandler(this.buttonCloseAllWindows_Click);
//
// kryptonRibbonGroup1
//
this.kryptonRibbonGroup1.DialogBoxLauncher = false;
this.kryptonRibbonGroup1.Image = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroup1.Image")));
this.kryptonRibbonGroup1.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupContainer[] {
this.kryptonRibbonGroupTriple4});
this.kryptonRibbonGroup1.KeyTipGroup = "A";
this.kryptonRibbonGroup1.TextLine1 = "Arrange";
//
// kryptonRibbonGroupTriple4
//
this.kryptonRibbonGroupTriple4.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] {
this.buttonCascade,
this.buttonTileHorizontal,
this.buttonTileVertical});
//
// buttonCascade
//
this.buttonCascade.ImageLarge = ((System.Drawing.Image)(resources.GetObject("buttonCascade.ImageLarge")));
this.buttonCascade.ImageSmall = ((System.Drawing.Image)(resources.GetObject("buttonCascade.ImageSmall")));
this.buttonCascade.KeyTip = "C";
this.buttonCascade.TextLine1 = "Cascade";
this.buttonCascade.Click += new System.EventHandler(this.buttonCascade_Click);
//
// buttonTileHorizontal
//
this.buttonTileHorizontal.ImageLarge = ((System.Drawing.Image)(resources.GetObject("buttonTileHorizontal.ImageLarge")));
this.buttonTileHorizontal.ImageSmall = ((System.Drawing.Image)(resources.GetObject("buttonTileHorizontal.ImageSmall")));
this.buttonTileHorizontal.KeyTip = "H";
this.buttonTileHorizontal.TextLine1 = "Tile";
this.buttonTileHorizontal.TextLine2 = "Horizontal";
this.buttonTileHorizontal.Click += new System.EventHandler(this.buttonTileHorizontal_Click);
//
// buttonTileVertical
//
this.buttonTileVertical.ImageLarge = ((System.Drawing.Image)(resources.GetObject("buttonTileVertical.ImageLarge")));
this.buttonTileVertical.ImageSmall = ((System.Drawing.Image)(resources.GetObject("buttonTileVertical.ImageSmall")));
this.buttonTileVertical.KeyTip = "V";
this.buttonTileVertical.TextLine1 = "Tile";
this.buttonTileVertical.TextLine2 = "Vertical";
this.buttonTileVertical.Click += new System.EventHandler(this.buttonTileVertical_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(692, 516);
this.Controls.Add(this.ribbon);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.IsMdiContainer = true;
this.MinimumSize = new System.Drawing.Size(350, 350);
this.Name = "Form1";
this.Text = "MDI Ribbon";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.ribbon)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private ComponentFactory.Krypton.Ribbon.KryptonRibbon ribbon;
private ComponentFactory.Krypton.Ribbon.KryptonRibbonTab tabHome;
private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup kryptonRibbonGroup2;
private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple kryptonRibbonGroupTriple2;
private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton buttonNewWindow;
private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupSeparator kryptonRibbonGroupSeparator1;
private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple kryptonRibbonGroupTriple3;
private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton buttonCloseWindow;
private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton buttonCloseAllWindows;
private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup kryptonRibbonGroup1;
private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple kryptonRibbonGroupTriple4;
private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton buttonCascade;
private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton buttonTileHorizontal;
private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton buttonTileVertical;
private ComponentFactory.Krypton.Toolkit.ButtonSpecAny buttonSpecHelp;
private ComponentFactory.Krypton.Toolkit.KryptonContextMenuItem kryptonContextMenuItem1;
private ComponentFactory.Krypton.Toolkit.KryptonManager kryptonManager1;
}
}
| |
/*
Copyright 2010 Google Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
namespace Google.Apis.Util
{
/// <summary>
/// Provides the base class for a generic read-only dictionary.
/// </summary>
/// <typeparam name="TKey">
/// The type of keys in the dictionary.
/// </typeparam>
/// <typeparam name="TValue">
/// The type of values in the dictionary.
/// </typeparam>
/// <remarks>
/// <para>
/// An instance of the <b>ReadOnlyDictionary</b> generic class is
/// always read-only. A dictionary that is read-only is simply a
/// dictionary with a wrapper that prevents modifying the
/// dictionary; therefore, if changes are made to the underlying
/// dictionary, the read-only dictionary reflects those changes.
/// See <see cref="Dictionary{TKey,TValue}"/> for a modifiable version of
/// this class.
/// </para>
/// <para>
/// <b>Notes to Implementers</b> This base class is provided to
/// make it easier for implementers to create a generic read-only
/// custom dictionary. Implementers are encouraged to extend this
/// base class instead of creating their own.
/// </para>
/// </remarks>
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(ReadOnlyDictionaryDebugView<,>))]
#if !SILVERLIGHT
[Serializable]
#endif
public class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary
{
private readonly IDictionary<TKey, TValue> source;
/// <summary>
/// Initializes a new instance of the
/// <see cref="T:ReadOnlyDictionary`2" /> class that wraps
/// the supplied <paramref name="dictionaryToWrap"/>.
/// </summary>
/// <param name="dictionaryToWrap">The <see cref="T:IDictionary`2" />
/// that will be wrapped.</param>
/// <exception cref="T:System.ArgumentNullException">
/// Thrown when the dictionary is null.
/// </exception>
public ReadOnlyDictionary(IDictionary<TKey, TValue> dictionaryToWrap)
{
if (dictionaryToWrap == null)
{
throw new ArgumentNullException("dictionaryToWrap");
}
source = dictionaryToWrap;
}
#region IDictionary Members
/// <summary>Gets a value indicating whether the
/// dictionary has a fixed size. This property will
/// always return true.</summary>
bool IDictionary.IsFixedSize
{
get { return true; }
}
/// <summary>Gets a value indicating whether the
/// dictionary is read-only.This property will
/// always return true.</summary>
bool IDictionary.IsReadOnly
{
get { return true; }
}
/// <summary>Gets an <see cref="ICollection"/> object
/// containing the keys of the dictionary object.</summary>
ICollection IDictionary.Keys
{
get { return ((IDictionary) source).Keys; }
}
/// <summary>
/// Gets an ICollection object containing the values in the DictionaryBase object.
/// </summary>
ICollection IDictionary.Values
{
get { return ((IDictionary) source).Values; }
}
/// <summary>
/// Gets a value indicating whether access to the dictionary
/// is synchronized (thread safe).
/// </summary>
bool ICollection.IsSynchronized
{
get { return ((ICollection) source).IsSynchronized; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to dictionary.
/// </summary>
object ICollection.SyncRoot
{
get { return ((ICollection) source).SyncRoot; }
}
/// <summary>
/// Gets or sets the element with the specified key.
/// </summary>
/// <param name="key">The key of the element to get or set.</param>
/// <returns>The element with the specified key. </returns>
/// <exception cref="NotSupportedException">
/// Thrown when a value is set.
/// </exception>
/// <exception cref="ArgumentNullException">
/// Thrown when the key is a null reference (<b>Nothing</b> in Visual Basic).
/// </exception>
object IDictionary.this[object key]
{
get { return ((IDictionary) source)[key]; }
set { ThrowNotSupportedException(); }
}
/// <summary>
/// This method is not supported by the <see cref="T:ReadOnlyDictionary`2"/>.
/// </summary>
/// <param name="key">
/// The System.Object to use as the key of the element to add.
/// </param>
/// <param name="value">
/// The System.Object to use as the value of the element to add.
/// </param>
void IDictionary.Add(object key, object value)
{
ThrowNotSupportedException();
}
/// <summary>
/// This method is not supported by the <see cref="T:ReadOnlyDictionary`2"/>.
/// </summary>
void IDictionary.Clear()
{
ThrowNotSupportedException();
}
/// <summary>
/// Determines whether the IDictionary object contains an element
/// with the specified key.
/// </summary>
/// <param name="key">
/// The key to locate in the IDictionary object.
/// </param>
/// <returns>
/// <b>true</b> if the IDictionary contains an element with the key;
/// otherwise, <b>false</b>.
/// </returns>
bool IDictionary.Contains(object key)
{
return ((IDictionary) source).Contains(key);
}
/// <summary>
/// Returns an <see cref="IDictionaryEnumerator"/> for the
/// <see cref="IDictionary"/>.
/// </summary>
/// <returns>
/// An IDictionaryEnumerator for the IDictionary.
/// </returns>
IDictionaryEnumerator IDictionary.GetEnumerator()
{
return ((IDictionary) source).GetEnumerator();
}
/// <summary>
/// This method is not supported by the <see cref="T:ReadOnlyDictionary`2"/>.
/// </summary>
/// <param name="key">
/// Gets an <see cref="ICollection"/> object containing the keys of the
/// <see cref="IDictionary"/> object.
/// </param>
void IDictionary.Remove(object key)
{
ThrowNotSupportedException();
}
/// <summary>
/// For a description of this member, see <see cref="ICollection.CopyTo"/>.
/// </summary>
/// <param name="array">
/// The one-dimensional Array that is the destination of the elements copied from
/// ICollection. The Array must have zero-based indexing.
/// </param>
/// <param name="index">
/// The zero-based index in Array at which copying begins.
/// </param>
void ICollection.CopyTo(Array array, int index)
{
((ICollection) source).CopyTo(array, index);
}
#endregion
#region IDictionary<TKey,TValue> Members
/// <summary>
/// Gets the number of key/value pairs contained in the
/// <see cref="T:ReadOnlyDictionary`2"></see>.
/// </summary>
/// <value>The number of key/value pairs.</value>
/// <returns>The number of key/value pairs contained in the
/// <see cref="T:ReadOnlyDictionary`2"></see>.</returns>
public int Count
{
get { return source.Count; }
}
/// <summary>Gets a collection containing the keys in the
/// <see cref="T:ReadOnlyDictionary{TKey,TValue}"></see>.</summary>
/// <value>A <see cref="Dictionary{TKey,TValue}.KeyCollection"/>
/// containing the keys.</value>
/// <returns>A
/// <see cref="Dictionary{TKey,TValue}.KeyCollection"/>
/// containing the keys in the
/// <see cref="Dictionary{TKey,TValue}"></see>.
/// </returns>
public ICollection<TKey> Keys
{
get { return source.Keys; }
}
/// <summary>
/// Gets a collection containing the values of the
/// <see cref="T:ReadOnlyDictionary`2"/>.
/// </summary>
/// <value>The collection of values.</value>
public ICollection<TValue> Values
{
get { return source.Values; }
}
/// <summary>Gets a value indicating whether the dictionary is read-only.
/// This value will always be true.</summary>
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get { return true; }
}
/// <summary>
/// Gets or sets the value associated with the specified key.
/// </summary>
/// <returns>
/// The value associated with the specified key. If the specified key
/// is not found, a get operation throws a
/// <see cref="T:System.Collections.Generic.KeyNotFoundException" />,
/// and a set operation creates a new element with the specified key.
/// </returns>
/// <param name="key">The key of the value to get or set.</param>
/// <exception cref="T:System.ArgumentNullException">
/// Thrown when the key is null.
/// </exception>
/// <exception cref="T:System.Collections.Generic.KeyNotFoundException">
/// The property is retrieved and key does not exist in the collection.
/// </exception>
public TValue this[TKey key]
{
get { return source[key]; }
set { ThrowNotSupportedException(); }
}
/// <summary>This method is not supported by the
/// <see cref="T:ReadOnlyDictionary`2"/>.</summary>
/// <param name="key">
/// The object to use as the key of the element to add.</param>
/// <param name="value">
/// The object to use as the value of the element to add.</param>
void IDictionary<TKey, TValue>.Add(TKey key, TValue value)
{
ThrowNotSupportedException();
}
/// <summary>Determines whether the <see cref="T:ReadOnlyDictionary`2" />
/// contains the specified key.</summary>
/// <returns>
/// True if the <see cref="T:ReadOnlyDictionary`2" /> contains
/// an element with the specified key; otherwise, false.
/// </returns>
/// <param name="key">The key to locate in the
/// <see cref="T:ReadOnlyDictionary`2"></see>.</param>
/// <exception cref="T:System.ArgumentNullException">
/// Thrown when the key is null.
/// </exception>
public bool ContainsKey(TKey key)
{
return source.ContainsKey(key);
}
/// <summary>
/// This method is not supported by the <see cref="T:ReadOnlyDictionary`2"/>.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
/// <returns>
/// True if the element is successfully removed; otherwise, false.
/// </returns>
bool IDictionary<TKey, TValue>.Remove(TKey key)
{
ThrowNotSupportedException();
return false;
}
/// <summary>
/// Gets the value associated with the specified key.
/// </summary>
/// <param name="key">The key of the value to get.</param>
/// <param name="value">When this method returns, contains the value
/// associated with the specified key, if the key is found;
/// otherwise, the default value for the type of the value parameter.
/// This parameter is passed uninitialized.</param>
/// <returns>
/// <b>true</b> if the <see cref="T:ReadOnlyDictionary`2" /> contains
/// an element with the specified key; otherwise, <b>false</b>.
/// </returns>
public bool TryGetValue(TKey key, out TValue value)
{
return source.TryGetValue(key, out value);
}
/// <summary>This method is not supported by the
/// <see cref="T:ReadOnlyDictionary`2"/>.</summary>
/// <param name="item">
/// The object to add to the <see cref="T:ICollection`1"/>.
/// </param>
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
{
ThrowNotSupportedException();
}
/// <summary>This method is not supported by the
/// <see cref="T:ReadOnlyDictionary`2"/>.</summary>
void ICollection<KeyValuePair<TKey, TValue>>.Clear()
{
ThrowNotSupportedException();
}
/// <summary>
/// Determines whether the <see cref="T:ICollection`1"/> contains a
/// specific value.
/// </summary>
/// <param name="item">
/// The object to locate in the <see cref="T:ICollection`1"/>.
/// </param>
/// <returns>
/// <b>true</b> if item is found in the <b>ICollection</b>;
/// otherwise, <b>false</b>.
/// </returns>
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
{
return (source).Contains(item);
}
/// <summary>
/// Copies the elements of the ICollection to an Array, starting at a
/// particular Array index.
/// </summary>
/// <param name="array">The one-dimensional Array that is the
/// destination of the elements copied from ICollection.
/// The Array must have zero-based indexing.
/// </param>
/// <param name="arrayIndex">
/// The zero-based index in array at which copying begins.
/// </param>
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
(source).CopyTo(array, arrayIndex);
}
/// <summary>This method is not supported by the
/// <see cref="T:ReadOnlyDictionary`2"/>.</summary>
/// <param name="item">
/// The object to remove from the ICollection.
/// </param>
/// <returns>Will never return a value.</returns>
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
{
ThrowNotSupportedException();
return false;
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A IEnumerator that can be used to iterate through the collection.
/// </returns>
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return (source).GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An IEnumerator that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable) source).GetEnumerator();
}
#endregion
private static void ThrowNotSupportedException()
{
throw new NotSupportedException("This Dictionary is read-only");
}
}
internal sealed class ReadOnlyDictionaryDebugView<TKey, TValue>
{
private readonly IDictionary<TKey, TValue> dict;
public ReadOnlyDictionaryDebugView(ReadOnlyDictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
{
throw new ArgumentNullException("dictionary");
}
dict = dictionary;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public KeyValuePair<TKey, TValue>[] Items
{
get
{
KeyValuePair<TKey, TValue>[] array = new KeyValuePair<TKey, TValue>[dict.Count];
dict.CopyTo(array, 0);
return array;
}
}
}
}
| |
// 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.Runtime.CompilerServices;
namespace System.Buffers.Text
{
// All the helper methods in this class assume that the by-ref is valid and that there is
// enough space to fit the items that will be written into the underlying memory. The calling
// code must have already done all the necessary validation.
internal static partial class FormattingHelpers
{
// A simple lookup table for converting numbers to hex.
internal const string HexTableLower = "0123456789abcdef";
internal const string HexTableUpper = "0123456789ABCDEF";
/// <summary>
/// Returns the symbol contained within the standard format. If the standard format
/// has not been initialized, returns the provided fallback symbol.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static char GetSymbolOrDefault(in StandardFormat format, char defaultSymbol)
{
// This is equivalent to the line below, but it is written in such a way
// that the JIT is able to perform more optimizations.
//
// return (format.IsDefault) ? defaultSymbol : format.Symbol;
var symbol = format.Symbol;
if (symbol == default && format.Precision == default)
{
symbol = defaultSymbol;
}
return symbol;
}
#region UTF-8 Helper methods
/// <summary>
/// Fills a buffer with the ASCII character '0' (0x30).
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void FillWithAsciiZeros(Span<byte> buffer)
{
// This is a faster implementation of Span<T>.Fill().
for (int i = 0; i < buffer.Length; i++)
{
buffer[i] = (byte)'0';
}
}
public enum HexCasing : uint
{
// Output [ '0' .. '9' ] and [ 'A' .. 'F' ].
Uppercase = 0,
// Output [ '0' .. '9' ] and [ 'a' .. 'f' ].
// This works because values in the range [ 0x30 .. 0x39 ] ([ '0' .. '9' ])
// already have the 0x20 bit set, so ORing them with 0x20 is a no-op,
// while outputs in the range [ 0x41 .. 0x46 ] ([ 'A' .. 'F' ])
// don't have the 0x20 bit set, so ORing them maps to
// [ 0x61 .. 0x66 ] ([ 'a' .. 'f' ]), which is what we want.
Lowercase = 0x2020U,
}
// The JIT can elide bounds checks if 'startingIndex' is constant and if the caller is
// writing to a span of known length (or the caller has already checked the bounds of the
// furthest access).
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteHexByte(byte value, Span<byte> buffer, int startingIndex = 0, HexCasing casing = HexCasing.Uppercase)
{
// We want to pack the incoming byte into a single integer [ 0000 HHHH 0000 LLLL ],
// where HHHH and LLLL are the high and low nibbles of the incoming byte. Then
// subtract this integer from a constant minuend as shown below.
//
// [ 1000 1001 1000 1001 ]
// - [ 0000 HHHH 0000 LLLL ]
// =========================
// [ *YYY **** *ZZZ **** ]
//
// The end result of this is that YYY is 0b000 if HHHH <= 9, and YYY is 0b111 if HHHH >= 10.
// Similarly, ZZZ is 0b000 if LLLL <= 9, and ZZZ is 0b111 if LLLL >= 10.
// (We don't care about the value of asterisked bits.)
//
// To turn a nibble in the range [ 0 .. 9 ] into hex, we calculate hex := nibble + 48 (ascii '0').
// To turn a nibble in the range [ 10 .. 15 ] into hex, we calculate hex := nibble - 10 + 65 (ascii 'A').
// => hex := nibble + 55.
// The difference in the starting ASCII offset is (55 - 48) = 7, depending on whether the nibble is <= 9 or >= 10.
// Since 7 is 0b111, this conveniently matches the YYY or ZZZ value computed during the earlier subtraction.
// The commented out code below is code that directly implements the logic described above.
//uint packedOriginalValues = (((uint)value & 0xF0U) << 4) + ((uint)value & 0x0FU);
//uint difference = 0x8989U - packedOriginalValues;
//uint add7Mask = (difference & 0x7070U) >> 4; // line YYY and ZZZ back up with the packed values
//uint packedResult = packedOriginalValues + add7Mask + 0x3030U /* ascii '0' */;
// The code below is equivalent to the commented out code above but has been tweaked
// to allow codegen to make some extra optimizations.
uint difference = (((uint)value & 0xF0U) << 4) + ((uint)value & 0x0FU) - 0x8989U;
uint packedResult = ((((uint)(-(int)difference) & 0x7070U) >> 4) + difference + 0xB9B9U) | (uint)casing;
// The low byte of the packed result contains the hex representation of the incoming byte's low nibble.
// The adjacent byte of the packed result contains the hex representation of the incoming byte's high nibble.
// Finally, write to the output buffer starting with the *highest* index so that codegen can
// elide all but the first bounds check. (This only works if 'startingIndex' is a compile-time constant.)
buffer[startingIndex + 1] = (byte)(packedResult);
buffer[startingIndex] = (byte)(packedResult >> 8);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteDigits(ulong value, Span<byte> buffer)
{
// We can mutate the 'value' parameter since it's a copy-by-value local.
// It'll be used to represent the value left over after each division by 10.
for (int i = buffer.Length - 1; i >= 1; i--)
{
ulong temp = '0' + value;
value /= 10;
buffer[i] = (byte)(temp - (value * 10));
}
Debug.Assert(value < 10);
buffer[0] = (byte)('0' + value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteDigitsWithGroupSeparator(ulong value, Span<byte> buffer)
{
// We can mutate the 'value' parameter since it's a copy-by-value local.
// It'll be used to represent the value left over after each division by 10.
int digitsWritten = 0;
for (int i = buffer.Length - 1; i >= 1; i--)
{
ulong temp = '0' + value;
value /= 10;
buffer[i] = (byte)(temp - (value * 10));
if (digitsWritten == Utf8Constants.GroupSize - 1)
{
buffer[--i] = Utf8Constants.Comma;
digitsWritten = 0;
}
else
{
digitsWritten++;
}
}
Debug.Assert(value < 10);
buffer[0] = (byte)('0' + value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteDigits(uint value, Span<byte> buffer)
{
// We can mutate the 'value' parameter since it's a copy-by-value local.
// It'll be used to represent the value left over after each division by 10.
for (int i = buffer.Length - 1; i >= 1; i--)
{
uint temp = '0' + value;
value /= 10;
buffer[i] = (byte)(temp - (value * 10));
}
Debug.Assert(value < 10);
buffer[0] = (byte)('0' + value);
}
/// <summary>
/// Writes a value [ 0000 .. 9999 ] to the buffer starting at the specified offset.
/// This method performs best when the starting index is a constant literal.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteFourDecimalDigits(uint value, Span<byte> buffer, int startingIndex = 0)
{
Debug.Assert(0 <= value && value <= 9999);
uint temp = '0' + value;
value /= 10;
buffer[startingIndex + 3] = (byte)(temp - (value * 10));
temp = '0' + value;
value /= 10;
buffer[startingIndex + 2] = (byte)(temp - (value * 10));
temp = '0' + value;
value /= 10;
buffer[startingIndex + 1] = (byte)(temp - (value * 10));
buffer[startingIndex] = (byte)('0' + value);
}
/// <summary>
/// Writes a value [ 00 .. 99 ] to the buffer starting at the specified offset.
/// This method performs best when the starting index is a constant literal.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteTwoDecimalDigits(uint value, Span<byte> buffer, int startingIndex = 0)
{
Debug.Assert(0 <= value && value <= 99);
uint temp = '0' + value;
value /= 10;
buffer[startingIndex + 1] = (byte)(temp - (value * 10));
buffer[startingIndex] = (byte)('0' + value);
}
#endregion UTF-8 Helper methods
#region Math Helper methods
/// <summary>
/// We don't have access to Math.DivRem, so this is a copy of the implementation.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ulong DivMod(ulong numerator, ulong denominator, out ulong modulo)
{
ulong div = numerator / denominator;
modulo = numerator - (div * denominator);
return div;
}
/// <summary>
/// We don't have access to Math.DivRem, so this is a copy of the implementation.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static uint DivMod(uint numerator, uint denominator, out uint modulo)
{
uint div = numerator / denominator;
modulo = numerator - (div * denominator);
return div;
}
#endregion Math Helper methods
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
#if (UNITY_WSA || UNITY_WP8)
using TestLibraryInterface;
#endif
namespace com.adjust.sdk.test
{
#if (UNITY_WSA || UNITY_WP8)
public class CommandExecutor : IAdjustCommandExecutor
#else
public class CommandExecutor
#endif
{
public string ExtraPath { get; set; }
private Dictionary<int, AdjustConfig> _savedConfigs = new Dictionary<int, AdjustConfig>();
private Dictionary<int, AdjustEvent> _savedEvents = new Dictionary<int, AdjustEvent>();
private string _baseUrl;
private string _gdprUrl;
private string _subscriptionUrl;
private Command _command;
private ITestLibrary _testLibrary;
public CommandExecutor(ITestLibrary testLibrary, string baseUrl, string gdprUrl, string subscriptionUrl)
{
_baseUrl = baseUrl;
_gdprUrl = gdprUrl;
_subscriptionUrl = subscriptionUrl;
_testLibrary = testLibrary;
}
public void ExecuteCommand(string className, string methodName, Dictionary<string, List<string>> parameters)
{
this.ExecuteCommand(new Command(className, methodName, parameters));
}
public void ExecuteCommand(Command command)
{
_command = command;
TestApp.Log(string.Format("\tEXECUTING METHOD: [{0}.{1}]", _command.ClassName, _command.MethodName));
try
{
switch (_command.MethodName)
{
case "testOptions": TestOptions(); break;
case "config": Config(); break;
case "start": Start(); break;
case "event": Event(); break;
case "trackEvent": TrackEvent(); break;
case "resume": Resume(); break;
case "pause": Pause(); break;
case "setEnabled": SetEnabled(); break;
case "setReferrer": SetReferrer(); break;
case "setOfflineMode": SetOfflineMode(); break;
case "sendFirstPackages": SendFirstPackages(); break;
case "addSessionCallbackParameter": AddSessionCallbackParameter(); break;
case "addSessionPartnerParameter": AddSessionPartnerParameter(); break;
case "removeSessionCallbackParameter": RemoveSessionCallbackParameter(); break;
case "removeSessionPartnerParameter": RemoveSessionPartnerParameter(); break;
case "resetSessionCallbackParameters": ResetSessionCallbackParameters(); break;
case "resetSessionPartnerParameters": ResetSessionPartnerParameters(); break;
case "setPushToken": SetPushToken(); break;
case "openDeeplink": OpenDeepLink(); break;
case "sendReferrer": SetReferrer(); break;
case "gdprForgetMe": GdprForgetMe(); break;
case "trackAdRevenue": TrackAdRevenue(); break;
case "disableThirdPartySharing": DisableThirdPartySharing(); break;
case "trackSubscription": TrackSubscription(); break;
case "thirdPartySharing": ThirdPartySharing(); break;
case "measurementConsent": MeasurementConsent(); break;
case "trackAdRevenueV2": TrackAdRevenueV2(); break;
default: CommandNotFound(_command.ClassName, _command.MethodName); break;
}
}
catch (Exception ex)
{
TestApp.LogError(string.Format("{0} -- {1}",
"executeCommand: failed to parse command. Check commands' syntax", ex.ToString()));
}
}
private void TestOptions()
{
Dictionary<string, string> testOptions = new Dictionary<string, string>();
testOptions[AdjustUtils.KeyTestOptionsBaseUrl] = _baseUrl;
testOptions[AdjustUtils.KeyTestOptionsGdprUrl] = _gdprUrl;
testOptions[AdjustUtils.KeyTestOptionsSubscriptionUrl] = _subscriptionUrl;
if (_command.ContainsParameter("basePath"))
{
ExtraPath = _command.GetFirstParameterValue("basePath");
}
if (_command.ContainsParameter("timerInterval"))
{
testOptions[AdjustUtils.KeyTestOptionsTimerIntervalInMilliseconds] = _command.GetFirstParameterValue("timerInterval");
}
if (_command.ContainsParameter("timerStart"))
{
testOptions[AdjustUtils.KeyTestOptionsTimerStartInMilliseconds] = _command.GetFirstParameterValue("timerStart");
}
if (_command.ContainsParameter("sessionInterval"))
{
testOptions[AdjustUtils.KeyTestOptionsSessionIntervalInMilliseconds] = _command.GetFirstParameterValue("sessionInterval");
}
if (_command.ContainsParameter("subsessionInterval"))
{
testOptions[AdjustUtils.KeyTestOptionsSubsessionIntervalInMilliseconds] = _command.GetFirstParameterValue("subsessionInterval");
}
if (_command.ContainsParameter("noBackoffWait"))
{
testOptions[AdjustUtils.KeyTestOptionsNoBackoffWait] = _command.GetFirstParameterValue("noBackoffWait");
}
// iAd.framework will not be used in test app by default
testOptions [AdjustUtils.KeyTestOptionsiAdFrameworkEnabled] = "false";
if (_command.ContainsParameter("iAdFrameworkEnabled"))
{
testOptions[AdjustUtils.KeyTestOptionsiAdFrameworkEnabled] = _command.GetFirstParameterValue("iAdFrameworkEnabled");
}
// AdServices.framework will not be used in test app by default
testOptions [AdjustUtils.KeyTestOptionsAdServicesFrameworkEnabled] = "false";
if (_command.ContainsParameter("adServicesFrameworkEnabled"))
{
testOptions[AdjustUtils.KeyTestOptionsAdServicesFrameworkEnabled] = _command.GetFirstParameterValue("adServicesFrameworkEnabled");
}
#if UNITY_ANDROID
bool useTestConnectionOptions = false;
#endif
if (_command.ContainsParameter("teardown"))
{
List<string> teardownOptions = _command.Parameters["teardown"];
foreach (string teardownOption in teardownOptions)
{
if (teardownOption == "resetSdk")
{
testOptions[AdjustUtils.KeyTestOptionsTeardown] = "true";
testOptions[AdjustUtils.KeyTestOptionsExtraPath] = ExtraPath;
#if UNITY_IOS
testOptions[AdjustUtils.KeyTestOptionsUseTestConnectionOptions] = "true";
#endif
#if UNITY_ANDROID
useTestConnectionOptions = true;
#endif
}
if (teardownOption == "deleteState")
{
testOptions[AdjustUtils.KeyTestOptionsDeleteState] = "true";
}
if (teardownOption == "resetTest")
{
_savedEvents = new Dictionary<int, AdjustEvent>();
_savedConfigs = new Dictionary<int, AdjustConfig>();
testOptions[AdjustUtils.KeyTestOptionsTimerIntervalInMilliseconds] = "-1";
testOptions[AdjustUtils.KeyTestOptionsSessionIntervalInMilliseconds] = "-1";
testOptions[AdjustUtils.KeyTestOptionsTimerStartInMilliseconds] = "-1";
testOptions[AdjustUtils.KeyTestOptionsSubsessionIntervalInMilliseconds] = "-1";
}
if (teardownOption == "sdk")
{
testOptions[AdjustUtils.KeyTestOptionsTeardown] = "true";
testOptions[AdjustUtils.KeyTestOptionsExtraPath] = null;
#if UNITY_IOS
testOptions[AdjustUtils.KeyTestOptionsUseTestConnectionOptions] = "false";
#endif
}
if (teardownOption == "test")
{
_savedEvents = null;
_savedConfigs = null;
testOptions[AdjustUtils.KeyTestOptionsTimerIntervalInMilliseconds] = "-1";
testOptions[AdjustUtils.KeyTestOptionsTimerStartInMilliseconds] = "-1";
testOptions[AdjustUtils.KeyTestOptionsSessionIntervalInMilliseconds] = "-1";
testOptions[AdjustUtils.KeyTestOptionsSubsessionIntervalInMilliseconds] = "-1";
}
}
}
Adjust.SetTestOptions(testOptions);
#if UNITY_ANDROID
if (useTestConnectionOptions)
{
TestConnectionOptions.SetTestConnectionOptions();
}
#endif
}
private void Config()
{
var configNumber = 0;
if (_command.ContainsParameter("configName"))
{
var configName = _command.GetFirstParameterValue("configName");
configNumber = int.Parse(configName.Substring(configName.Length - 1));
}
AdjustConfig adjustConfig;
AdjustLogLevel? logLevel = null;
if (_command.ContainsParameter("logLevel"))
{
var logLevelString = _command.GetFirstParameterValue("logLevel");
switch (logLevelString)
{
case "verbose":
logLevel = AdjustLogLevel.Verbose;
break;
case "debug":
logLevel = AdjustLogLevel.Debug;
break;
case "info":
logLevel = AdjustLogLevel.Info;
break;
case "warn":
logLevel = AdjustLogLevel.Warn;
break;
case "error":
logLevel = AdjustLogLevel.Error;
break;
case "assert":
logLevel = AdjustLogLevel.Assert;
break;
case "suppress":
logLevel = AdjustLogLevel.Suppress;
break;
}
TestApp.Log(string.Format("TestApp LogLevel = {0}", logLevel));
}
if (_savedConfigs.ContainsKey(configNumber))
{
adjustConfig = _savedConfigs[configNumber];
}
else
{
var environmentString = _command.GetFirstParameterValue("environment");
var environment = environmentString == "sandbox" ? AdjustEnvironment.Sandbox : AdjustEnvironment.Production;
var appToken = _command.GetFirstParameterValue("appToken");
if (!string.IsNullOrEmpty(appToken))
{
if (appToken == "null")
{
adjustConfig = new AdjustConfig(null, environment);
}
else
{
adjustConfig = new AdjustConfig(appToken, environment);
}
}
else
{
adjustConfig = new AdjustConfig(null, environment);
}
if (logLevel.HasValue)
{
adjustConfig.setLogLevel(logLevel.Value);
}
#if (UNITY_WSA || UNITY_WP8)
adjustConfig.logDelegate = msg => Debug.Log(msg);
#endif
_savedConfigs.Add(configNumber, adjustConfig);
}
if (_command.ContainsParameter("sdkPrefix"))
{
// SDK prefix not tested for non natives.
}
if (_command.ContainsParameter("defaultTracker"))
{
adjustConfig.setDefaultTracker(_command.GetFirstParameterValue("defaultTracker"));
}
if (_command.ContainsParameter("externalDeviceId"))
{
adjustConfig.setExternalDeviceId(_command.GetFirstParameterValue("externalDeviceId"));
}
if (_command.ContainsParameter("delayStart"))
{
var delayStartStr = _command.GetFirstParameterValue("delayStart");
var delayStart = double.Parse(delayStartStr);
adjustConfig.setDelayStart(delayStart);
}
if (_command.ContainsParameter("appSecret"))
{
var appSecretList = _command.Parameters["appSecret"];
if (!string.IsNullOrEmpty(appSecretList[0]) && appSecretList.Count == 5)
{
long secretId, info1, info2, info3, info4;
long.TryParse(appSecretList[0], out secretId);
long.TryParse(appSecretList[1], out info1);
long.TryParse(appSecretList[2], out info2);
long.TryParse(appSecretList[3], out info3);
long.TryParse(appSecretList[4], out info4);
adjustConfig.setAppSecret(secretId, info1, info2, info3, info4);
}
}
if (_command.ContainsParameter("deviceKnown"))
{
var deviceKnownS = _command.GetFirstParameterValue("deviceKnown");
var deviceKnown = deviceKnownS.ToLower() == "true";
adjustConfig.setIsDeviceKnown(deviceKnown);
}
if (_command.ContainsParameter("eventBufferingEnabled"))
{
var eventBufferingEnabledS = _command.GetFirstParameterValue("eventBufferingEnabled");
var eventBufferingEnabled = eventBufferingEnabledS.ToLower() == "true";
adjustConfig.setEventBufferingEnabled(eventBufferingEnabled);
}
if (_command.ContainsParameter("sendInBackground"))
{
var sendInBackgroundS = _command.GetFirstParameterValue("sendInBackground");
var sendInBackground = sendInBackgroundS.ToLower() == "true";
adjustConfig.sendInBackground = sendInBackground;
}
if (_command.ContainsParameter("allowiAdInfoReading"))
{
var allowiAdInfoReadingS = _command.GetFirstParameterValue("allowiAdInfoReading");
var allowiAdInfoReading = allowiAdInfoReadingS.ToLower() == "true";
adjustConfig.allowiAdInfoReading = allowiAdInfoReading;
}
if (_command.ContainsParameter("allowAdServicesInfoReading"))
{
var allowAdServicesInfoReadingS = _command.GetFirstParameterValue("allowAdServicesInfoReading");
var allowAdServicesInfoReading = allowAdServicesInfoReadingS.ToLower() == "true";
adjustConfig.allowAdServicesInfoReading = allowAdServicesInfoReading;
}
if (_command.ContainsParameter("allowIdfaReading"))
{
var allowIdfaReadingS = _command.GetFirstParameterValue("allowIdfaReading");
var allowIdfaReading = allowIdfaReadingS.ToLower() == "true";
adjustConfig.allowIdfaReading = allowIdfaReading;
}
if (_command.ContainsParameter("allowSkAdNetworkHandling"))
{
var allowSkAdNetworkHandlingS = _command.GetFirstParameterValue("allowSkAdNetworkHandling");
var allowSkAdNetworkHandling = allowSkAdNetworkHandlingS.ToLower() == "true";
if (allowSkAdNetworkHandling == false)
{
adjustConfig.deactivateSKAdNetworkHandling();
}
}
if (_command.ContainsParameter("userAgent"))
{
var userAgent = _command.GetFirstParameterValue("userAgent");
if (userAgent.Equals("null"))
{
adjustConfig.setUserAgent(null);
}
else
{
adjustConfig.setUserAgent(userAgent);
}
}
if (_command.ContainsParameter("deferredDeeplinkCallback"))
{
bool launchDeferredDeeplink = _command.GetFirstParameterValue("deferredDeeplinkCallback") == "true";
adjustConfig.setLaunchDeferredDeeplink(launchDeferredDeeplink);
string localExtraPath = ExtraPath;
adjustConfig.setDeferredDeeplinkDelegate(uri =>
{
_testLibrary.AddInfoToSend("deeplink", uri);
_testLibrary.SendInfoToServer(localExtraPath);
});
}
if (_command.ContainsParameter("attributionCallbackSendAll"))
{
string localExtraPath = ExtraPath;
adjustConfig.setAttributionChangedDelegate(attribution =>
{
_testLibrary.AddInfoToSend("trackerToken", attribution.trackerToken);
_testLibrary.AddInfoToSend("trackerName", attribution.trackerName);
_testLibrary.AddInfoToSend("network", attribution.network);
_testLibrary.AddInfoToSend("campaign", attribution.campaign);
_testLibrary.AddInfoToSend("adgroup", attribution.adgroup);
_testLibrary.AddInfoToSend("creative", attribution.creative);
_testLibrary.AddInfoToSend("clickLabel", attribution.clickLabel);
_testLibrary.AddInfoToSend("adid", attribution.adid);
_testLibrary.AddInfoToSend("costType", attribution.costType);
_testLibrary.AddInfoToSend("costAmount", attribution.costAmount.ToString());
_testLibrary.AddInfoToSend("costCurrency", attribution.costCurrency);
_testLibrary.SendInfoToServer(localExtraPath);
});
}
if (_command.ContainsParameter("sessionCallbackSendSuccess"))
{
string localExtraPath = ExtraPath;
adjustConfig.setSessionSuccessDelegate(sessionSuccessResponseData =>
{
_testLibrary.AddInfoToSend("message", sessionSuccessResponseData.Message);
_testLibrary.AddInfoToSend("timestamp", sessionSuccessResponseData.Timestamp);
_testLibrary.AddInfoToSend("adid", sessionSuccessResponseData.Adid);
if (sessionSuccessResponseData.JsonResponse != null)
{
_testLibrary.AddInfoToSend("jsonResponse", sessionSuccessResponseData.GetJsonResponse());
}
_testLibrary.SendInfoToServer(localExtraPath);
});
}
if (_command.ContainsParameter("sessionCallbackSendFailure"))
{
string localExtraPath = ExtraPath;
adjustConfig.setSessionFailureDelegate(sessionFailureResponseData =>
{
_testLibrary.AddInfoToSend("message", sessionFailureResponseData.Message);
_testLibrary.AddInfoToSend("timestamp", sessionFailureResponseData.Timestamp);
_testLibrary.AddInfoToSend("adid", sessionFailureResponseData.Adid);
_testLibrary.AddInfoToSend("willRetry", sessionFailureResponseData.WillRetry.ToString().ToLower());
if (sessionFailureResponseData.JsonResponse != null)
{
_testLibrary.AddInfoToSend("jsonResponse", sessionFailureResponseData.GetJsonResponse());
}
_testLibrary.SendInfoToServer(localExtraPath);
});
}
if (_command.ContainsParameter("eventCallbackSendSuccess"))
{
string localExtraPath = ExtraPath;
adjustConfig.setEventSuccessDelegate(eventSuccessResponseData =>
{
_testLibrary.AddInfoToSend("message", eventSuccessResponseData.Message);
_testLibrary.AddInfoToSend("timestamp", eventSuccessResponseData.Timestamp);
_testLibrary.AddInfoToSend("adid", eventSuccessResponseData.Adid);
_testLibrary.AddInfoToSend("eventToken", eventSuccessResponseData.EventToken);
_testLibrary.AddInfoToSend("callbackId", eventSuccessResponseData.CallbackId);
if (eventSuccessResponseData.JsonResponse != null)
{
_testLibrary.AddInfoToSend("jsonResponse", eventSuccessResponseData.GetJsonResponse());
}
_testLibrary.SendInfoToServer(localExtraPath);
});
}
if (_command.ContainsParameter("eventCallbackSendFailure"))
{
string localExtraPath = ExtraPath;
adjustConfig.setEventFailureDelegate(eventFailureResponseData =>
{
_testLibrary.AddInfoToSend("message", eventFailureResponseData.Message);
_testLibrary.AddInfoToSend("timestamp", eventFailureResponseData.Timestamp);
_testLibrary.AddInfoToSend("adid", eventFailureResponseData.Adid);
_testLibrary.AddInfoToSend("eventToken", eventFailureResponseData.EventToken);
_testLibrary.AddInfoToSend("callbackId", eventFailureResponseData.CallbackId);
_testLibrary.AddInfoToSend("willRetry", eventFailureResponseData.WillRetry.ToString().ToLower());
if (eventFailureResponseData.JsonResponse != null)
{
_testLibrary.AddInfoToSend("jsonResponse", eventFailureResponseData.GetJsonResponse());
}
_testLibrary.SendInfoToServer(localExtraPath);
});
}
}
private void Start()
{
Config();
var configNumber = 0;
if (_command.ContainsParameter("configName"))
{
var configName = _command.GetFirstParameterValue("configName");
configNumber = int.Parse(configName.Substring(configName.Length - 1));
}
var adjustConfig = _savedConfigs[configNumber];
Adjust.start(adjustConfig);
_savedConfigs.Remove(0);
}
private void Event()
{
var eventNumber = 0;
if (_command.ContainsParameter("eventName"))
{
var eventName = _command.GetFirstParameterValue("eventName");
eventNumber = int.Parse(eventName.Substring(eventName.Length - 1));
}
AdjustEvent adjustEvent = null;
if (_savedEvents.ContainsKey(eventNumber))
{
adjustEvent = _savedEvents[eventNumber];
}
else
{
var eventToken = _command.GetFirstParameterValue("eventToken");
adjustEvent = new AdjustEvent(eventToken);
_savedEvents.Add(eventNumber, adjustEvent);
}
if (_command.ContainsParameter("revenue"))
{
var revenueParams = _command.Parameters["revenue"];
var currency = revenueParams[0];
var revenue = double.Parse(revenueParams[1]);
adjustEvent.setRevenue(revenue, currency);
}
if (_command.ContainsParameter("callbackParams"))
{
var callbackParams = _command.Parameters["callbackParams"];
for (var i = 0; i < callbackParams.Count; i = i + 2)
{
var key = callbackParams[i];
var value = callbackParams[i + 1];
adjustEvent.addCallbackParameter(key, value);
}
}
if (_command.ContainsParameter("partnerParams"))
{
var partnerParams = _command.Parameters["partnerParams"];
for (var i = 0; i < partnerParams.Count; i = i + 2)
{
var key = partnerParams[i];
var value = partnerParams[i + 1];
adjustEvent.addPartnerParameter(key, value);
}
}
if (_command.ContainsParameter("orderId"))
{
var orderId = _command.GetFirstParameterValue("orderId");
adjustEvent.setTransactionId(orderId);
}
if (_command.ContainsParameter("callbackId"))
{
var callbackId = _command.GetFirstParameterValue("callbackId");
adjustEvent.setCallbackId(callbackId);
}
}
private void TrackEvent()
{
Event();
var eventNumber = 0;
if (_command.ContainsParameter("eventName"))
{
var eventName = _command.GetFirstParameterValue("eventName");
eventNumber = int.Parse(eventName.Substring(eventName.Length - 1));
}
var adjustEvent = _savedEvents[eventNumber];
Adjust.trackEvent(adjustEvent);
_savedEvents.Remove(0);
}
private void Resume()
{
#if UNITY_IOS
AdjustiOS.TrackSubsessionStart("test");
#elif UNITY_ANDROID
AdjustAndroid.OnResume();
#elif (UNITY_WSA || UNITY_WP8)
AdjustWindows.OnResume();
#else
Debug.Log("TestApp - Command Executor - Error! Cannot Resume. None of the supported platforms selected.");
#endif
}
private void Pause()
{
#if UNITY_IOS
AdjustiOS.TrackSubsessionEnd("test");
#elif UNITY_ANDROID
AdjustAndroid.OnPause();
#elif (UNITY_WSA || UNITY_WP8)
AdjustWindows.OnPause();
#else
Debug.Log("TestApp - Command Executor - Error! Cannot Pause. None of the supported platforms selected.");
#endif
}
private void SetEnabled()
{
var enabled = bool.Parse(_command.GetFirstParameterValue("enabled"));
Adjust.setEnabled(enabled);
}
public void GdprForgetMe()
{
Adjust.gdprForgetMe();
}
public void DisableThirdPartySharing()
{
Adjust.disableThirdPartySharing();
}
private void SetOfflineMode()
{
var enabled = bool.Parse(_command.GetFirstParameterValue("enabled"));
Adjust.setOfflineMode(enabled);
}
private void SetReferrer()
{
string referrer = _command.GetFirstParameterValue("referrer");
#pragma warning disable CS0618
Adjust.setReferrer(referrer);
#pragma warning restore CS0618
}
private void AddSessionCallbackParameter()
{
if (!_command.ContainsParameter("KeyValue"))
{
return;
}
var keyValuePairs = _command.Parameters["KeyValue"];
for (var i = 0; i < keyValuePairs.Count; i = i + 2)
{
var key = keyValuePairs[i];
var value = keyValuePairs[i + 1];
Adjust.addSessionCallbackParameter(key, value);
}
}
private void SendFirstPackages()
{
Adjust.sendFirstPackages();
}
private void AddSessionPartnerParameter()
{
if (!_command.ContainsParameter("KeyValue"))
{
return;
}
var keyValuePairs = _command.Parameters["KeyValue"];
for (var i = 0; i < keyValuePairs.Count; i = i + 2)
{
var key = keyValuePairs[i];
var value = keyValuePairs[i + 1];
Adjust.addSessionPartnerParameter(key, value);
}
}
private void RemoveSessionCallbackParameter()
{
if (!_command.ContainsParameter("key"))
{
return;
}
var keys = _command.Parameters["key"];
for (var i = 0; i < keys.Count; i = i + 1)
{
var key = keys[i];
Adjust.removeSessionCallbackParameter(key);
}
}
private void RemoveSessionPartnerParameter()
{
if (!_command.ContainsParameter("key"))
{
return;
}
var keys = _command.Parameters["key"];
for (var i = 0; i < keys.Count; i = i + 1)
{
var key = keys[i];
Adjust.removeSessionPartnerParameter(key);
}
}
private void ResetSessionCallbackParameters()
{
Adjust.resetSessionCallbackParameters();
}
private void ResetSessionPartnerParameters()
{
Adjust.resetSessionPartnerParameters();
}
private void ResetSessionCallbackParameters(JSONNode parameters)
{
Adjust.resetSessionCallbackParameters();
}
private void ResetSessionPartnerParameters(JSONNode parameters)
{
Adjust.resetSessionPartnerParameters();
}
private void SetPushToken()
{
var pushToken = _command.GetFirstParameterValue("pushToken");
if (!string.IsNullOrEmpty(pushToken))
{
if (pushToken.Equals("null"))
{
Adjust.setDeviceToken(null);
}
else
{
Adjust.setDeviceToken(pushToken);
}
}
}
private void OpenDeepLink()
{
var deeplink = _command.GetFirstParameterValue("deeplink");
Adjust.appWillOpenUrl(deeplink);
}
private void TrackAdRevenue()
{
string source = _command.GetFirstParameterValue("adRevenueSource");
string payload = _command.GetFirstParameterValue("adRevenueJsonString");
Adjust.trackAdRevenue(source, payload);
}
private void TrackSubscription()
{
#if UNITY_IOS
string price = _command.GetFirstParameterValue("revenue");
string currency = _command.GetFirstParameterValue("currency");
string transactionId = _command.GetFirstParameterValue("transactionId");
string receipt = _command.GetFirstParameterValue("receipt");
string transactionDate = _command.GetFirstParameterValue("transactionDate");
string salesRegion = _command.GetFirstParameterValue("salesRegion");
AdjustAppStoreSubscription subscription = new AdjustAppStoreSubscription(
price,
currency,
transactionId,
receipt);
subscription.setTransactionDate(transactionDate);
subscription.setSalesRegion(salesRegion);
if (_command.ContainsParameter("callbackParams"))
{
var callbackParams = _command.Parameters["callbackParams"];
for (var i = 0; i < callbackParams.Count; i = i + 2)
{
var key = callbackParams[i];
var value = callbackParams[i + 1];
subscription.addCallbackParameter(key, value);
}
}
if (_command.ContainsParameter("partnerParams"))
{
var partnerParams = _command.Parameters["partnerParams"];
for (var i = 0; i < partnerParams.Count; i = i + 2)
{
var key = partnerParams[i];
var value = partnerParams[i + 1];
subscription.addPartnerParameter(key, value);
}
}
Adjust.trackAppStoreSubscription(subscription);
#elif UNITY_ANDROID
string price = _command.GetFirstParameterValue("revenue");
string currency = _command.GetFirstParameterValue("currency");
string purchaseTime = _command.GetFirstParameterValue("transactionDate");
string sku = _command.GetFirstParameterValue("productId");
string signature = _command.GetFirstParameterValue("receipt");
string purchaseToken = _command.GetFirstParameterValue("purchaseToken");
string orderId = _command.GetFirstParameterValue("transactionId");
AdjustPlayStoreSubscription subscription = new AdjustPlayStoreSubscription(
price,
currency,
sku,
orderId,
signature,
purchaseToken);
subscription.setPurchaseTime(purchaseTime);
if (_command.ContainsParameter("callbackParams"))
{
var callbackParams = _command.Parameters["callbackParams"];
for (var i = 0; i < callbackParams.Count; i = i + 2)
{
var key = callbackParams[i];
var value = callbackParams[i + 1];
subscription.addCallbackParameter(key, value);
}
}
if (_command.ContainsParameter("partnerParams"))
{
var partnerParams = _command.Parameters["partnerParams"];
for (var i = 0; i < partnerParams.Count; i = i + 2)
{
var key = partnerParams[i];
var value = partnerParams[i + 1];
subscription.addPartnerParameter(key, value);
}
}
Adjust.trackPlayStoreSubscription(subscription);
#endif
}
private void ThirdPartySharing()
{
string enabled = _command.GetFirstParameterValue("isEnabled");
bool? isEnabled = null;
if (enabled != null)
{
isEnabled = bool.Parse(enabled);
}
AdjustThirdPartySharing adjustThirdPartySharing = new AdjustThirdPartySharing(isEnabled);
if (_command.ContainsParameter("granularOptions"))
{
var granularOptions = _command.Parameters["granularOptions"];
for (var i = 0; i < granularOptions.Count; i += 3)
{
var partnerName = granularOptions[i];
var key = granularOptions[i+1];
var value = granularOptions[i+2];
adjustThirdPartySharing.addGranularOption(partnerName, key, value);
}
}
Adjust.trackThirdPartySharing(adjustThirdPartySharing);
}
private void MeasurementConsent()
{
var enabled = bool.Parse(_command.GetFirstParameterValue("isEnabled"));
Adjust.trackMeasurementConsent(enabled);
}
private void TrackAdRevenueV2()
{
string source = _command.GetFirstParameterValue("adRevenueSource");
AdjustAdRevenue adRevenue = new AdjustAdRevenue(source);
if (_command.ContainsParameter("revenue"))
{
var revenueParams = _command.Parameters["revenue"];
var currency = revenueParams[0];
var revenue = double.Parse(revenueParams[1]);
adRevenue.setRevenue(revenue, currency);
}
if (_command.ContainsParameter("adImpressionsCount"))
{
int adImpressionsCount = int.Parse(_command.GetFirstParameterValue("adImpressionsCount"));
adRevenue.setAdImpressionsCount(adImpressionsCount);
}
if (_command.ContainsParameter("adRevenueUnit"))
{
string adRevenueUnit = _command.GetFirstParameterValue("adRevenueUnit");
adRevenue.setAdRevenueUnit(adRevenueUnit);
}
if (_command.ContainsParameter("adRevenuePlacement"))
{
string adRevenuePlacement = _command.GetFirstParameterValue("adRevenuePlacement");
adRevenue.setAdRevenuePlacement(adRevenuePlacement);
}
if (_command.ContainsParameter("adRevenueNetwork"))
{
string adRevenueNetwork = _command.GetFirstParameterValue("adRevenueNetwork");
adRevenue.setAdRevenueNetwork(adRevenueNetwork);
}
if (_command.ContainsParameter("callbackParams"))
{
var callbackParams = _command.Parameters["callbackParams"];
for (var i = 0; i < callbackParams.Count; i = i + 2)
{
var key = callbackParams[i];
var value = callbackParams[i + 1];
adRevenue.addCallbackParameter(key, value);
}
}
if (_command.ContainsParameter("partnerParams"))
{
var partnerParams = _command.Parameters["partnerParams"];
for (var i = 0; i < partnerParams.Count; i = i + 2)
{
var key = partnerParams[i];
var value = partnerParams[i + 1];
adRevenue.addPartnerParameter(key, value);
}
}
Adjust.trackAdRevenue(adRevenue);
}
private void CommandNotFound(string className, string methodName)
{
TestApp.Log("Adjust Test: Method '" + methodName + "' not found for class '" + className + "'");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Reactive.Linq;
using System.Text;
using Avalonia;
using Avalonia.Animation;
using Avalonia.Collections;
using Avalonia.Controls;
using Avalonia.Controls.Html;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Controls.Templates;
using Avalonia.Data;
using Avalonia.Diagnostics;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using Avalonia.Platform;
using Avalonia.Threading;
using TestApplication;
namespace TestApplication
{
class MainWindow
{
private static readonly AvaloniaList<Node> s_treeData = new AvaloniaList<Node>
{
new Node
{
Name = "Root 1",
Children = new AvaloniaList<Node>
{
new Node
{
Name = "Child 1",
},
new Node
{
Name = "Child 2",
Children = new AvaloniaList<Node>
{
new Node
{
Name = "Grandchild 1",
},
new Node
{
Name = "Grandmaster Flash",
},
}
},
new Node
{
Name = "Child 3",
},
}
},
new Node
{
Name = "Root 2",
},
};
private static readonly AvaloniaList<Item> s_listBoxData = new AvaloniaList<Item>
{
new Item { Name = "Item 1", Value = "Item 1 Value" },
new Item { Name = "Item 2", Value = "Item 2 Value" },
new Item { Name = "Item 3", Value = "Item 3 Value" },
new Item { Name = "Item 4", Value = "Item 4 Value" },
new Item { Name = "Item 5", Value = "Item 5 Value" },
new Item { Name = "Item 6", Value = "Item 6 Value" },
new Item { Name = "Item 7", Value = "Item 7 Value" },
new Item { Name = "Item 8", Value = "Item 8 Value" },
};
public static Window Create()
{
TabControl container;
Window window = new Window
{
Title = "Avalonia Test Application",
//Width = 900,
//Height = 480,
Content = (container = new TabControl
{
Padding = new Thickness(5),
Items = new[]
{
ButtonsTab(),
TextTab(),
HtmlTab(),
ImagesTab(),
ListsTab(),
LayoutTab(),
AnimationsTab(),
},
Transition = new CrossFade(TimeSpan.FromSeconds(0.25)),
[Grid.RowProperty] = 1,
[Grid.ColumnSpanProperty] = 2,
})
};
container.Classes.Add("container");
window.Show();
return window;
}
private static TabItem ButtonsTab()
{
var result = new TabItem
{
Header = "Button",
Content = new ScrollViewer()
{
CanScrollHorizontally = false,
Content = new StackPanel
{
Margin = new Thickness(10),
Orientation = Orientation.Vertical,
Gap = 4,
Children = new Controls
{
new TextBlock
{
Text = "Button",
FontWeight = FontWeight.Medium,
FontSize = 20,
Foreground = Brush.Parse("#212121"),
},
new TextBlock
{
Text = "A button control",
FontSize = 13,
Foreground = Brush.Parse("#727272"),
Margin = new Thickness(0, 0, 0, 10)
},
new Button
{
Width = 150,
Content = "Button"
},
new Button
{
Width = 150,
Content = "Disabled",
IsEnabled = false,
},
new TextBlock
{
Margin = new Thickness(0, 40, 0, 0),
Text = "ToggleButton",
FontWeight = FontWeight.Medium,
FontSize = 20,
Foreground = Brush.Parse("#212121"),
},
new TextBlock
{
Text = "A toggle button control",
FontSize = 13,
Foreground = Brush.Parse("#727272"),
Margin = new Thickness(0, 0, 0, 10)
},
new ToggleButton
{
Width = 150,
IsChecked = true,
Content = "On"
},
new ToggleButton
{
Width = 150,
IsChecked = false,
Content = "Off"
},
}
}
},
};
return result;
}
private static TabItem HtmlTab()
{
return new TabItem
{
Header = "Text",
Content = new ScrollViewer()
{
CanScrollHorizontally = false,
Content = new StackPanel()
{
Margin = new Thickness(10),
Orientation = Orientation.Vertical,
Gap = 4,
Children = new Controls
{
new TextBlock
{
Text = "TextBlock",
FontWeight = FontWeight.Medium,
FontSize = 20,
Foreground = Brush.Parse("#212121"),
},
new TextBlock
{
Text = "A control for displaying text.",
FontSize = 13,
Foreground = Brush.Parse("#727272"),
Margin = new Thickness(0, 0, 0, 10)
},
new TextBlock
{
Text = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit.",
FontSize = 11
},
new TextBlock
{
Text = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit.",
FontSize = 11,
FontWeight = FontWeight.Medium
},
new TextBlock
{
Text = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit.",
FontSize = 11,
FontWeight = FontWeight.Bold
},
new TextBlock
{
Text = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit.",
FontSize = 11,
FontStyle = FontStyle.Italic,
},
new TextBlock
{
Margin = new Thickness(0, 40, 0, 0),
Text = "HtmlLabel",
FontWeight = FontWeight.Medium,
FontSize = 20,
Foreground = Brush.Parse("#212121"),
},
new TextBlock
{
Text = "A label capable of displaying HTML content",
FontSize = 13,
Foreground = Brush.Parse("#727272"),
Margin = new Thickness(0, 0, 0, 10)
},
new HtmlLabel
{
Background = Brush.Parse("#CCCCCC"),
Padding = new Thickness(5),
Text = @"<p><strong>Pellentesque habitant morbi tristique</strong> senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. <em>Aenean ultricies mi vitae est.</em> Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, <code>commodo vitae</code>, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. <a href=""#"">Donec non enim</a> in turpis pulvinar facilisis. Ut felis.</p>
<h2>Header Level 2</h2>
<ol>
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
<li>Aliquam tincidunt mauris eu risus.</li>
</ol>
<blockquote><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus magna. Cras in mi at felis aliquet congue. Ut a est eget ligula molestie gravida. Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis elit sit amet quam. Vivamus pretium ornare est.</p></blockquote>
<h3>Header Level 3</h3>
<ul>
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
<li>Aliquam tincidunt mauris eu risus.</li>
</ul>"
}
}
}
}
};
}
private static TabItem TextTab()
{
return new TabItem
{
Header = "Input",
Content = new ScrollViewer()
{
Content = new StackPanel
{
Margin = new Thickness(10),
Orientation = Orientation.Vertical,
Gap = 4,
Children = new Controls
{
new TextBlock
{
Text = "TextBox",
FontWeight = FontWeight.Medium,
FontSize = 20,
Foreground = Brush.Parse("#212121"),
},
new TextBlock
{
Text = "A text box control",
FontSize = 13,
Foreground = Brush.Parse("#727272"),
Margin = new Thickness(0, 0, 0, 10)
},
new TextBox { Text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", Width = 200},
new TextBox { Width = 200, Watermark="Watermark"},
new TextBox { Width = 200, Watermark="Floating Watermark", UseFloatingWatermark = true },
new TextBox { AcceptsReturn = true, TextWrapping = TextWrapping.Wrap, Width = 200, Height = 150, Text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus magna. Cras in mi at felis aliquet congue. Ut a est eget ligula molestie gravida. Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis elit sit amet quam. Vivamus pretium ornare est." },
new TextBlock
{
Margin = new Thickness(0, 40, 0, 0),
Text = "CheckBox",
FontWeight = FontWeight.Medium,
FontSize = 20,
Foreground = Brush.Parse("#212121"),
},
new TextBlock
{
Text = "A check box control",
FontSize = 13,
Foreground = Brush.Parse("#727272"),
Margin = new Thickness(0, 0, 0, 10)
},
new CheckBox { IsChecked = true, Margin = new Thickness(0, 0, 0, 5), Content = "Checked" },
new CheckBox { IsChecked = false, Content = "Unchecked" },
new TextBlock
{
Margin = new Thickness(0, 40, 0, 0),
Text = "RadioButton",
FontWeight = FontWeight.Medium,
FontSize = 20,
Foreground = Brush.Parse("#212121"),
},
new TextBlock
{
Text = "A radio button control",
FontSize = 13,
Foreground = Brush.Parse("#727272"),
Margin = new Thickness(0, 0, 0, 10)
},
new RadioButton { IsChecked = true, Content = "Option 1" },
new RadioButton { IsChecked = false, Content = "Option 2" },
new RadioButton { IsChecked = false, Content = "Option 3" },
}
}
}
};
}
public static string RootNamespace;
static Stream GetImage(string path)
{
return AvaloniaLocator.Current.GetService<IAssetLoader>().Open(new Uri("resm:" + RootNamespace + "." + path));
}
private static TabItem ListsTab()
{
return new TabItem
{
Header = "Lists",
Content = new ScrollViewer()
{
CanScrollHorizontally = false,
Content = new StackPanel
{
HorizontalAlignment = HorizontalAlignment.Left,
Orientation = Orientation.Vertical,
VerticalAlignment = VerticalAlignment.Top,
Gap = 4,
Margin = new Thickness(10),
DataTemplates = new DataTemplates
{
new FuncDataTemplate<Item>(x =>
new StackPanel
{
Gap = 4,
Orientation = Orientation.Horizontal,
Children = new Controls
{
new Image { Width = 50, Height = 50, Source = new Bitmap(GetImage("github_icon.png")) },
new TextBlock { Text = x.Name, FontSize = 18 }
}
})
},
Children = new Controls
{
new TextBlock
{
Text = "ListBox",
FontWeight = FontWeight.Medium,
FontSize = 20,
Foreground = Brush.Parse("#212121"),
},
new TextBlock
{
Text = "A list box control.",
FontSize = 13,
Foreground = Brush.Parse("#727272"),
Margin = new Thickness(0, 0, 0, 10)
},
new ListBox
{
BorderThickness = 2,
Items = s_listBoxData,
Height = 300,
Width = 300,
},
new TextBlock
{
Margin = new Thickness(0, 40, 0, 0),
Text = "TreeView",
FontWeight = FontWeight.Medium,
FontSize = 20,
Foreground = Brush.Parse("#212121"),
},
new TextBlock
{
Text = "A tree view control.",
FontSize = 13,
Foreground = Brush.Parse("#727272"),
Margin = new Thickness(0, 0, 0, 10)
},
new TreeView
{
Name = "treeView",
Items = s_treeData,
Height = 300,
BorderThickness = 2,
Width = 300,
}
}
},
}
};
}
private static TabItem ImagesTab()
{
var imageCarousel = new Carousel
{
Width = 400,
Height = 400,
Transition = new PageSlide(TimeSpan.FromSeconds(0.25)),
Items = new[]
{
new Image { Source = new Bitmap(GetImage("github_icon.png")), Width = 400, Height = 400 },
new Image { Source = new Bitmap(GetImage("pattern.jpg")), Width = 400, Height = 400 },
}
};
var next = new Button
{
VerticalAlignment = VerticalAlignment.Center,
Padding = new Thickness(20),
Content = new Avalonia.Controls.Shapes.Path
{
Data = StreamGeometry.Parse("M4,11V13H16L10.5,18.5L11.92,19.92L19.84,12L11.92,4.08L10.5,5.5L16,11H4Z"),
Fill = Brushes.Black
}
};
var prev = new Button
{
VerticalAlignment = VerticalAlignment.Center,
Padding = new Thickness(20),
Content = new Avalonia.Controls.Shapes.Path
{
Data = StreamGeometry.Parse("M20,11V13H8L13.5,18.5L12.08,19.92L4.16,12L12.08,4.08L13.5,5.5L8,11H20Z"),
Fill = Brushes.Black
}
};
prev.Click += (s, e) =>
{
if (imageCarousel.SelectedIndex == 0)
imageCarousel.SelectedIndex = 1;
else
imageCarousel.SelectedIndex--;
};
next.Click += (s, e) =>
{
if (imageCarousel.SelectedIndex == 1)
imageCarousel.SelectedIndex = 0;
else
imageCarousel.SelectedIndex++;
};
return new TabItem
{
Header = "Images",
Content = new ScrollViewer
{
Content = new StackPanel
{
HorizontalAlignment = HorizontalAlignment.Left,
Orientation = Orientation.Vertical,
VerticalAlignment = VerticalAlignment.Top,
Gap = 4,
Margin = new Thickness(10),
Children = new Controls
{
new TextBlock
{
Text = "Carousel",
FontWeight = FontWeight.Medium,
FontSize = 20,
Foreground = Brush.Parse("#212121"),
},
new TextBlock
{
Text = "An items control that displays its items as pages that fill the controls.",
FontSize = 13,
Foreground = Brush.Parse("#727272"),
Margin = new Thickness(0, 0, 0, 10)
},
new StackPanel
{
Name = "carouselVisual",
Orientation = Orientation.Horizontal,
Gap = 4,
Children = new Controls
{
prev,
imageCarousel,
next
}
}
}
}
}
};
}
private static TabItem LayoutTab()
{
var polylinePoints = new Point[] { new Point(0, 0), new Point(5, 0), new Point(6, -2), new Point(7, 3), new Point(8, -3),
new Point(9, 1), new Point(10, 0), new Point(15, 0) };
var polygonPoints = new Point[] { new Point(5, 0), new Point(8, 8), new Point(0, 3), new Point(10, 3), new Point(2, 8) };
for (int i = 0; i < polylinePoints.Length; i++)
{
polylinePoints[i] = polylinePoints[i] * 13;
}
for (int i = 0; i < polygonPoints.Length; i++)
{
polygonPoints[i] = polygonPoints[i] * 15;
}
return new TabItem
{
Header = "Layout",
Content = new ScrollViewer
{
Content = new StackPanel
{
HorizontalAlignment = HorizontalAlignment.Left,
Orientation = Orientation.Vertical,
VerticalAlignment = VerticalAlignment.Top,
Gap = 4,
Margin = new Thickness(10),
Children = new Controls
{
new TextBlock
{
Text = "Grid",
FontWeight = FontWeight.Medium,
FontSize = 20,
Foreground = Brush.Parse("#212121"),
},
new TextBlock
{
Text = "Lays out child controls according to a grid.",
FontSize = 13,
Foreground = Brush.Parse("#727272"),
Margin = new Thickness(0, 0, 0, 10)
},
new Grid
{
Width = 600,
ColumnDefinitions = new ColumnDefinitions
{
new ColumnDefinition(1, GridUnitType.Star),
new ColumnDefinition(1, GridUnitType.Star),
},
RowDefinitions = new RowDefinitions
{
new RowDefinition(1, GridUnitType.Auto),
new RowDefinition(1, GridUnitType.Auto)
},
Children = new Controls
{
new Rectangle
{
Fill = Brush.Parse("#FF5722"),
[Grid.ColumnSpanProperty] = 2,
Height = 200,
Margin = new Thickness(2.5)
},
new Rectangle
{
Fill = Brush.Parse("#FF5722"),
[Grid.RowProperty] = 1,
Height = 100,
Margin = new Thickness(2.5)
},
new Rectangle
{
Fill = Brush.Parse("#FF5722"),
[Grid.RowProperty] = 1,
[Grid.ColumnProperty] = 1,
Height = 100,
Margin = new Thickness(2.5)
},
},
},
new TextBlock
{
Margin = new Thickness(0, 40, 0, 0),
Text = "StackPanel",
FontWeight = FontWeight.Medium,
FontSize = 20,
Foreground = Brush.Parse("#212121"),
},
new TextBlock
{
Text = "A panel which lays out its children horizontally or vertically.",
FontSize = 13,
Foreground = Brush.Parse("#727272"),
Margin = new Thickness(0, 0, 0, 10)
},
new StackPanel
{
Orientation = Orientation.Vertical,
Gap = 4,
Width = 300,
Children = new Controls
{
new Rectangle
{
Fill = Brush.Parse("#FFC107"),
Height = 50,
},
new Rectangle
{
Fill = Brush.Parse("#FFC107"),
Height = 50,
},
new Rectangle
{
Fill = Brush.Parse("#FFC107"),
Height = 50,
},
}
},
new TextBlock
{
Margin = new Thickness(0, 40, 0, 0),
Text = "Canvas",
FontWeight = FontWeight.Medium,
FontSize = 20,
Foreground = Brush.Parse("#212121"),
},
new TextBlock
{
Text = "A panel which lays out its children by explicit coordinates.",
FontSize = 13,
Foreground = Brush.Parse("#727272"),
Margin = new Thickness(0, 0, 0, 10)
},
new Canvas
{
Background = Brushes.Yellow,
Width = 300,
Height = 400,
Children = new Controls
{
new Rectangle
{
Fill = Brushes.Blue,
Width = 63,
Height = 41,
[Canvas.LeftProperty] = 40,
[Canvas.TopProperty] = 31,
},
new Ellipse
{
Fill = Brushes.Green,
Width = 58,
Height = 58,
[Canvas.LeftProperty] = 130,
[Canvas.TopProperty] = 79,
},
new Line
{
Stroke = Brushes.Red,
StrokeThickness = 2,
StartPoint = new Point(120, 185),
EndPoint = new Point(30, 115)
},
new Avalonia.Controls.Shapes.Path
{
Fill = Brushes.Orange,
Data = StreamGeometry.Parse("M 30,250 c 50,0 50,-50 c 50,0 50,50 h -50 v 50 l -50,-50 Z"),
},
new Polygon
{
Stroke = Brushes.DarkBlue,
Fill = Brushes.Violet,
Points = polygonPoints,
StrokeThickness = 1,
[Canvas.LeftProperty] = 150,
[Canvas.TopProperty] = 180,
},
new Polyline
{
Stroke = Brushes.Brown,
Points = polylinePoints,
StrokeThickness = 5,
StrokeJoin = PenLineJoin.Round,
StrokeStartLineCap = PenLineCap.Triangle,
StrokeEndLineCap = PenLineCap.Triangle,
[Canvas.LeftProperty] = 30,
[Canvas.TopProperty] = 350,
},
}
},
}
}
}
};
}
private static TabItem AnimationsTab()
{
Border border1;
Border border2;
RotateTransform rotate;
Button button1;
var result = new TabItem
{
Header = "Animations",
Content = new StackPanel
{
Orientation = Orientation.Vertical,
Gap = 4,
Margin = new Thickness(10),
Children = new Controls
{
new TextBlock
{
Text = "Animations",
FontWeight = FontWeight.Medium,
FontSize = 20,
Foreground = Brush.Parse("#212121"),
},
new TextBlock
{
Text = "A few animations showcased below",
FontSize = 13,
Foreground = Brush.Parse("#727272"),
Margin = new Thickness(0, 0, 0, 10)
},
(button1 = new Button
{
Content = "Animate",
Width = 120,
[Grid.ColumnProperty] = 1,
[Grid.RowProperty] = 1,
}),
new Canvas
{
ClipToBounds = false,
Children = new Controls
{
(border1 = new Border
{
Width = 100,
Height = 100,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
Background = Brushes.Crimson,
RenderTransform = new RotateTransform(),
Child = new Grid
{
Children = new Controls
{
new Ellipse()
{
Width = 100,
Height = 100,
Fill =
new RadialGradientBrush()
{
GradientStops =
{
new GradientStop(Colors.Blue, 0),
new GradientStop(Colors.Green, 1)
},
Radius = 75
}
},
new Avalonia.Controls.Shapes.Path
{
Data =
StreamGeometry.Parse(
"F1 M 16.6309,18.6563C 17.1309,8.15625 29.8809,14.1563 29.8809,14.1563C 30.8809,11.1563 34.1308,11.4063 34.1308,11.4063C 33.5,12 34.6309,13.1563 34.6309,13.1563C 32.1309,13.1562 31.1309,14.9062 31.1309,14.9062C 41.1309,23.9062 32.6309,27.9063 32.6309,27.9062C 24.6309,24.9063 21.1309,22.1562 16.6309,18.6563 Z M 16.6309,19.9063C 21.6309,24.1563 25.1309,26.1562 31.6309,28.6562C 31.6309,28.6562 26.3809,39.1562 18.3809,36.1563C 18.3809,36.1563 18,38 16.3809,36.9063C 15,36 16.3809,34.9063 16.3809,34.9063C 16.3809,34.9063 10.1309,30.9062 16.6309,19.9063 Z"),
Fill =
new LinearGradientBrush()
{
GradientStops =
{
new GradientStop(Colors.Green, 0),
new GradientStop(Colors.LightSeaGreen, 1)
}
},
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
RenderTransform = new MatrixTransform(Matrix.CreateScale(2, 2))
}
}
},
[Canvas.LeftProperty] = 100,
[Canvas.TopProperty] = 100,
}),
(border2 = new Border
{
Width = 100,
Height = 100,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
Background = Brushes.Coral,
Child = new Image
{
Source = new Bitmap(GetImage("github_icon.png")),
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
},
RenderTransform = (rotate = new RotateTransform
{
PropertyTransitions = new PropertyTransitions
{
RotateTransform.AngleProperty.Transition(500),
}
}),
PropertyTransitions = new PropertyTransitions
{
Layoutable.WidthProperty.Transition(300),
Layoutable.HeightProperty.Transition(1000),
},
[Canvas.LeftProperty] = 400,
[Canvas.TopProperty] = 100,
}),
}
}
},
},
};
button1.Click += (s, e) =>
{
if (border2.Width == 100)
{
border2.Width = border2.Height = 400;
rotate.Angle = 180;
}
else
{
border2.Width = border2.Height = 100;
rotate.Angle = 0;
}
};
var start = Animate.Stopwatch.Elapsed;
var degrees = Animate.Timer
.Select(x =>
{
var elapsed = (x - start).TotalSeconds;
var cycles = elapsed / 4;
var progress = cycles % 1;
return 360.0 * progress;
});
border1.RenderTransform.Bind(
RotateTransform.AngleProperty,
degrees,
BindingPriority.Animation);
return result;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace WebApiSample.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
//
// Encog(tm) Core v3.2 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using Encog.MathUtil.Matrices;
using Encog.ML;
using Encog.ML.Data;
using Encog.ML.Data.Specific;
namespace Encog.Neural.ART
{
/// <summary>
/// Implements an ART1 neural network. An ART1 neural network is trained to
/// recognize bipolar patterns as it is presented data. There is no distinct
/// learning phase, like there is with other neural network types.
/// The ART1 neural network is a type of Adaptive Resonance Theory (ART) neural
/// network. ART1 was developed by Stephen Grossberg and Gail Carpenter.
/// This neural network type supports only bipolar input. The ART1 neural
/// network is trained as it is used. New patterns are presented to the ART1
/// network, and they are classified into either new, or existing, classes.
/// Once the maximum number of classes have been used the network will report
/// that it is out of classes. ART1 neural networks are used for classification.
/// There are essentially 2 layers in an ART1 network. The first, named the
/// F1 layer, acts as the input. The F1 layer receives bipolar patterns that
/// the network is to classify. The F2 layer specifies the maximum number
/// classes that the ART1 network can recognize.
/// Plasticity is an important part for all Adaptive Resonance Theory (ART)
/// neural networks. Unlike most neural networks, ART1 does not have a
/// distinct training and usage stage. The ART1 network will learn as it is
/// used.
/// </summary>
[Serializable]
public class ART1 : BasicART, IMLResettable, IMLClassification
{
/// <summary>
/// A parameter for F1 layer.
/// </summary>
///
private double _a1;
/// <summary>
/// B parameter for F1 layer.
/// </summary>
///
private double _b1;
/// <summary>
/// C parameter for F1 layer.
/// </summary>
///
private double _c1;
/// <summary>
/// D parameter for F1 layer.
/// </summary>
///
private double _d1;
/// <summary>
/// The F1 layer neuron count.
/// </summary>
///
private int _f1Count;
/// <summary>
/// The F2 layer neuron count.
/// </summary>
///
private int _f2Count;
/// <summary>
/// Allows members of the F2 layer to be inhibited.
/// </summary>
[NonSerialized]
private bool[] _inhibitF2;
/// <summary>
/// L parameter for net.
/// </summary>
///
private double _l;
/// <summary>
/// This is the value that is returned if there is no winner.
/// This value is generally set to the number of classes, plus 1.
/// </summary>
///
private int _noWinner;
/// <summary>
/// The output from the F1 layer.
/// </summary>
///
private BiPolarMLData _outputF1;
/// <summary>
/// The output from the F2 layer.
/// </summary>
///
private BiPolarMLData _outputF2;
/// <summary>
/// The vigilance parameter.
/// </summary>
///
private double _vigilance;
/// <summary>
/// Weights from f1 to f2.
/// </summary>
///
private Matrix _weightsF1ToF2;
/// <summary>
/// Weights from f2 to f1.
/// </summary>
///
private Matrix _weightsF2ToF1;
/// <summary>
/// Default constructor, used mainly for persistence.
/// </summary>
///
public ART1()
{
_a1 = 1;
_b1 = 1.5d;
_c1 = 5;
_d1 = 0.9d;
_l = 3;
_vigilance = 0.9d;
}
/// <summary>
/// Construct the ART1 network.
/// </summary>
///
/// <param name="theF1Count">The neuron count for the f1 layer.</param>
/// <param name="theF2Count">The neuron count for the f2 layer.</param>
public ART1(int theF1Count, int theF2Count)
{
_a1 = 1;
_b1 = 1.5d;
_c1 = 5;
_d1 = 0.9d;
_l = 3;
_vigilance = 0.9d;
_f1Count = theF1Count;
_f2Count = theF2Count;
_weightsF1ToF2 = new Matrix(_f1Count, _f2Count);
_weightsF2ToF1 = new Matrix(_f2Count, _f1Count);
_inhibitF2 = new bool[_f2Count];
_outputF1 = new BiPolarMLData(_f1Count);
_outputF2 = new BiPolarMLData(_f2Count);
_noWinner = _f2Count;
Reset();
}
/// <summary>
/// Set the A1 parameter.
/// </summary>
///
/// <value>The new value.</value>
public double A1
{
get { return _a1; }
set { _a1 = value; }
}
/// <summary>
/// Set the B1 parameter.
/// </summary>
public double B1
{
get { return _b1; }
set { _b1 = value; }
}
/// <summary>
/// Set the C1 parameter.
/// </summary>
///
/// <value>The new value.</value>
public double C1
{
get { return _c1; }
set { _c1 = value; }
}
/// <summary>
/// Set the D1 parameter.
/// </summary>
///
/// <value>The new value.</value>
public double D1
{
get { return _d1; }
set { _d1 = value; }
}
/// <summary>
/// Set the F1 count. The F1 layer is the input layer.
/// </summary>
public int F1Count
{
get { return _f1Count; }
set
{
_f1Count = value;
_outputF1 = new BiPolarMLData(_f1Count);
}
}
/// <summary>
/// Set the F2 count. The F2 layer is the output layer.
/// </summary>
///
/// <value>The count.</value>
public int F2Count
{
get { return _f2Count; }
set
{
_f2Count = value;
_inhibitF2 = new bool[_f2Count];
_outputF2 = new BiPolarMLData(_f2Count);
}
}
/// <summary>
/// Set the L parameter.
/// </summary>
///
/// <value>The new value.</value>
public double L
{
get { return _l; }
set { _l = value; }
}
/// <summary>
/// This is the value that is returned if there is no winner.
/// This value is generally set to the index of the last classes, plus 1.
/// For example, if there were 3 classes, the network would return 0-2 to
/// represent what class was found, in this case the no winner property
/// would be set to 3.
/// </summary>
public int NoWinner
{
get { return _noWinner; }
set { _noWinner = value; }
}
/// <summary>
/// Set the vigilance.
/// </summary>
public double Vigilance
{
get { return _vigilance; }
set { _vigilance = value; }
}
/// <summary>
/// Set the f1 to f2 matrix.
/// </summary>
public Matrix WeightsF1ToF2
{
get { return _weightsF1ToF2; }
set { _weightsF1ToF2 = value; }
}
/// <summary>
/// Set the f2 to f1 matrix.
/// </summary>
public Matrix WeightsF2ToF1
{
get { return _weightsF2ToF1; }
set { _weightsF2ToF1 = value; }
}
/// <value>The winning neuron.</value>
public int Winner { get; private set; }
/// <returns>Does this network have a "winner"?</returns>
public bool HasWinner
{
get { return Winner != _noWinner; }
}
/// <summary>
/// Set the input to the neural network.
/// </summary>
private BiPolarMLData Input
{
set
{
for (int i = 0; i < _f1Count; i++)
{
double activation = ((value.GetBoolean(i)) ? 1 : 0)
/(1 + _a1*(((value.GetBoolean(i)) ? 1 : 0) + _b1) + _c1);
_outputF1.SetBoolean(i, (activation > 0));
}
}
}
#region MLClassification Members
/// <summary>
/// Classify the input data to a class number.
/// </summary>
///
/// <param name="input">The input data.</param>
/// <returns>The class that the data belongs to.</returns>
public int Classify(IMLData input)
{
var input2 = new BiPolarMLData(_f1Count);
var output = new BiPolarMLData(_f2Count);
if (input.Count != input2.Count)
{
throw new NeuralNetworkError("Input array size does not match.");
}
for (int i = 0; i < input2.Count; i++)
{
input2.SetBoolean(i, input[i] > 0);
}
Compute(input2, output);
return HasWinner ? Winner : -1;
}
/// <summary>
/// The input count.
/// </summary>
public int InputCount
{
get { return _f1Count; }
}
/// <value>The number of neurons in the output count, which is the f2 layer
/// count.</value>
public int OutputCount
{
get { return _f2Count; }
}
#endregion
#region MLResettable Members
/// <summary>
/// Reset the weight matrix back to starting values.
/// </summary>
///
public void Reset()
{
Reset(0);
}
/// <summary>
/// Reset with a specic seed.
/// </summary>
///
/// <param name="seed">The seed to reset with.</param>
public void Reset(int seed)
{
for (int i = 0; i < _f1Count; i++)
{
for (int j = 0; j < _f2Count; j++)
{
_weightsF1ToF2[i, j] = (_b1 - 1)/_d1 + 0.2d;
_weightsF2ToF1[j, i] = _l
/(_l - 1 + _f1Count) - 0.1d;
}
}
}
#endregion
/// <summary>
/// Adjust the weights for the pattern just presented.
/// </summary>
///
public void AdjustWeights()
{
for (int i = 0; i < _f1Count; i++)
{
if (_outputF1.GetBoolean(i))
{
double magnitudeInput = Magnitude(_outputF1);
_weightsF1ToF2[i, Winner] = 1;
_weightsF2ToF1[Winner, i] = _l
/(_l - 1 + magnitudeInput);
}
else
{
_weightsF1ToF2[i, Winner] = 0;
_weightsF2ToF1[Winner, i] = 0;
}
}
}
/// <summary>
/// Compute the output from the ART1 network. This can be called directly or
/// used by the BasicNetwork class. Both input and output should be bipolar
/// numbers.
/// </summary>
///
/// <param name="input">The input to the network.</param>
/// <param name="output">The output from the network.</param>
public void Compute(BiPolarMLData input,
BiPolarMLData output)
{
int i;
for (i = 0; i < _f2Count; i++)
{
_inhibitF2[i] = false;
}
bool resonance = false;
bool exhausted = false;
do
{
Input = input;
ComputeF2();
GetOutput(output);
if (Winner != _noWinner)
{
ComputeF1(input);
double magnitudeInput1 = Magnitude(input);
double magnitudeInput2 = Magnitude(_outputF1);
if ((magnitudeInput2/magnitudeInput1) < _vigilance)
{
_inhibitF2[Winner] = true;
}
else
{
resonance = true;
}
}
else
{
exhausted = true;
}
} while (!(resonance || exhausted));
if (resonance)
{
AdjustWeights();
}
}
/// <summary>
/// Compute the output for the BasicNetwork class.
/// </summary>
///
/// <param name="input">The input to the network.</param>
/// <returns>The output from the network.</returns>
public IMLData Compute(IMLData input)
{
if (!(input is BiPolarMLData))
{
throw new NeuralNetworkError(
"Input to ART1 logic network must be BiPolarNeuralData.");
}
var output = new BiPolarMLData(_f1Count);
Compute((BiPolarMLData) input, output);
return output;
}
/// <summary>
/// Compute the output from the F1 layer.
/// </summary>
///
/// <param name="input">The input to the F1 layer.</param>
private void ComputeF1(BiPolarMLData input)
{
for (int i = 0; i < _f1Count; i++)
{
double sum = _weightsF1ToF2[i, Winner]
*((_outputF2.GetBoolean(Winner)) ? 1 : 0);
double activation = (((input.GetBoolean(i)) ? 1 : 0) + _d1*sum - _b1)
/(1 + _a1
*(((input.GetBoolean(i)) ? 1 : 0) + _d1*sum) + _c1);
_outputF1.SetBoolean(i, activation > 0);
}
}
/// <summary>
/// Compute the output from the F2 layer.
/// </summary>
///
private void ComputeF2()
{
int i;
double maxOut = Double.NegativeInfinity;
Winner = _noWinner;
for (i = 0; i < _f2Count; i++)
{
if (!_inhibitF2[i])
{
double sum = 0;
int j;
for (j = 0; j < _f1Count; j++)
{
sum += _weightsF2ToF1[i, j]
*((_outputF1.GetBoolean(j)) ? 1 : 0);
}
if (sum > maxOut)
{
maxOut = sum;
Winner = i;
}
}
_outputF2.SetBoolean(i, false);
}
if (Winner != _noWinner)
{
_outputF2.SetBoolean(Winner, true);
}
}
/// <summary>
/// Copy the output from the network to another object.
/// </summary>
///
/// <param name="output">The target object for the output from the network.</param>
private void GetOutput(BiPolarMLData output)
{
for (int i = 0; i < _f2Count; i++)
{
output.SetBoolean(i, _outputF2.GetBoolean(i));
}
}
/// <summary>
/// Get the magnitude of the specified input.
/// </summary>
///
/// <param name="input">The input to calculate the magnitude for.</param>
/// <returns>The magnitude of the specified pattern.</returns>
public double Magnitude(BiPolarMLData input)
{
double result;
result = 0;
for (int i = 0; i < _f1Count; i++)
{
result += (input.GetBoolean(i)) ? 1 : 0;
}
return result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
/*
* 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 Lucene.Net.Randomized.Generators;
using Lucene.Net.Support;
using NUnit.Framework;
namespace Lucene.Net.Util
{
[TestFixture]
public class TestWeakIdentityMap : LuceneTestCase
{
[Test]
public virtual void TestSimpleHashMap()
{
WeakIdentityMap<string, string> map = WeakIdentityMap<string, string>.NewHashMap(Random().NextBoolean());
// we keep strong references to the keys,
// so WeakIdentityMap will not forget about them:
string key1 = "foo";
string key2 = "foo";
string key3 = "foo";
Assert.AreNotSame(key1, key2);
Assert.AreEqual(key1, key2);
Assert.AreNotSame(key1, key3);
Assert.AreEqual(key1, key3);
Assert.AreNotSame(key2, key3);
Assert.AreEqual(key2, key3);
// try null key & check its iterator also return null:
map.Put(null, "null");
{
IEnumerator<string> iter = map.Keys.GetEnumerator();
Assert.IsTrue(iter.MoveNext());
Assert.IsNull(iter.Current);
Assert.IsFalse(iter.MoveNext());
Assert.IsFalse(iter.MoveNext());
}
// 2 more keys:
map.Put(key1, "bar1");
map.Put(key2, "bar2");
Assert.AreEqual(3, map.Size());
Assert.AreEqual("bar1", map.Get(key1));
Assert.AreEqual("bar2", map.Get(key2));
Assert.AreEqual(null, map.Get(key3));
Assert.AreEqual("null", map.Get(null));
Assert.IsTrue(map.ContainsKey(key1));
Assert.IsTrue(map.ContainsKey(key2));
Assert.IsFalse(map.ContainsKey(key3));
Assert.IsTrue(map.ContainsKey(null));
// repeat and check that we have no double entries
map.Put(key1, "bar1");
map.Put(key2, "bar2");
map.Put(null, "null");
Assert.AreEqual(3, map.Size());
Assert.AreEqual("bar1", map.Get(key1));
Assert.AreEqual("bar2", map.Get(key2));
Assert.AreEqual(null, map.Get(key3));
Assert.AreEqual("null", map.Get(null));
Assert.IsTrue(map.ContainsKey(key1));
Assert.IsTrue(map.ContainsKey(key2));
Assert.IsFalse(map.ContainsKey(key3));
Assert.IsTrue(map.ContainsKey(null));
map.Remove(null);
Assert.AreEqual(2, map.Size());
map.Remove(key1);
Assert.AreEqual(1, map.Size());
map.Put(key1, "bar1");
map.Put(key2, "bar2");
map.Put(key3, "bar3");
Assert.AreEqual(3, map.Size());
int c = 0, keysAssigned = 0;
for (IEnumerator<string> iter = map.Keys.GetEnumerator(); iter.MoveNext(); )
{
//Assert.IsTrue(iter.hasNext()); // try again, should return same result!
string k = iter.Current;
Assert.IsTrue(k == key1 || k == key2 | k == key3);
keysAssigned += (k == key1) ? 1 : ((k == key2) ? 2 : 4);
c++;
}
Assert.AreEqual(3, c);
Assert.AreEqual(1 + 2 + 4, keysAssigned, "all keys must have been seen");
c = 0;
for (IEnumerator<string> iter = map.Values.GetEnumerator(); iter.MoveNext(); )
{
string v = iter.Current;
Assert.IsTrue(v.StartsWith("bar"));
c++;
}
Assert.AreEqual(3, c);
// clear strong refs
key1 = key2 = key3 = null;
// check that GC does not cause problems in reap() method, wait 1 second and let GC work:
int size = map.Size();
for (int i = 0; size > 0 && i < 10; i++)
{
try
{
System.RunFinalization();
System.gc();
int newSize = map.Size();
Assert.IsTrue(size >= newSize, "previousSize(" + size + ")>=newSize(" + newSize + ")");
size = newSize;
Thread.Sleep(new TimeSpan(100L));
c = 0;
for (IEnumerator<string> iter = map.Keys.GetEnumerator(); iter.MoveNext(); )
{
Assert.IsNotNull(iter.Current);
c++;
}
newSize = map.Size();
Assert.IsTrue(size >= c, "previousSize(" + size + ")>=iteratorSize(" + c + ")");
Assert.IsTrue(c >= newSize, "iteratorSize(" + c + ")>=newSize(" + newSize + ")");
size = newSize;
}
catch (ThreadInterruptedException ie)
{
}
}
map.Clear();
Assert.AreEqual(0, map.Size());
Assert.IsTrue(map.Empty);
IEnumerator<string> it = map.Keys.GetEnumerator();
Assert.IsFalse(it.MoveNext());
/*try
{
it.Next();
Assert.Fail("Should throw NoSuchElementException");
}
catch (NoSuchElementException nse)
{
}*/
key1 = "foo";
key2 = "foo";
map.Put(key1, "bar1");
map.Put(key2, "bar2");
Assert.AreEqual(2, map.Size());
map.Clear();
Assert.AreEqual(0, map.Size());
Assert.IsTrue(map.Empty);
}
[Test]
public virtual void TestConcurrentHashMap()
{
// don't make threadCount and keyCount random, otherwise easily OOMs or fails otherwise:
const int threadCount = 8, keyCount = 1024;
ExecutorService exec = Executors.newFixedThreadPool(threadCount, new NamedThreadFactory("testConcurrentHashMap"));
WeakIdentityMap<object, int?> map = WeakIdentityMap<object, int?>.NewConcurrentHashMap(Random().NextBoolean());
// we keep strong references to the keys,
// so WeakIdentityMap will not forget about them:
AtomicReferenceArray<object> keys = new AtomicReferenceArray<object>(keyCount);
for (int j = 0; j < keyCount; j++)
{
keys.Set(j, new object());
}
try
{
for (int t = 0; t < threadCount; t++)
{
Random rnd = new Random(Random().Next());
exec.execute(new RunnableAnonymousInnerClassHelper(this, keyCount, map, keys, rnd));
}
}
finally
{
exec.shutdown();
while (!exec.awaitTermination(1000L, TimeUnit.MILLISECONDS)) ;
}
// clear strong refs
for (int j = 0; j < keyCount; j++)
{
keys.Set(j, null);
}
// check that GC does not cause problems in reap() method:
int size = map.Size();
for (int i = 0; size > 0 && i < 10; i++)
{
try
{
System.runFinalization();
System.gc();
int newSize = map.Size();
Assert.IsTrue(size >= newSize, "previousSize(" + size + ")>=newSize(" + newSize + ")");
size = newSize;
Thread.Sleep(new TimeSpan(100L));
int c = 0;
for (IEnumerator<object> it = map.Keys.GetEnumerator(); it.MoveNext(); )
{
Assert.IsNotNull(it.Current);
c++;
}
newSize = map.Size();
Assert.IsTrue(size >= c, "previousSize(" + size + ")>=iteratorSize(" + c + ")");
Assert.IsTrue(c >= newSize, "iteratorSize(" + c + ")>=newSize(" + newSize + ")");
size = newSize;
}
catch (ThreadInterruptedException ie)
{
}
}
}
private class RunnableAnonymousInnerClassHelper : IThreadRunnable
{
private readonly TestWeakIdentityMap OuterInstance;
private int KeyCount;
private WeakIdentityMap<object, int?> Map;
private AtomicReferenceArray<object> Keys;
private Random Rnd;
public RunnableAnonymousInnerClassHelper(TestWeakIdentityMap outerInstance, int keyCount, WeakIdentityMap<object, int?> map, AtomicReferenceArray<object> keys, Random rnd)
{
this.OuterInstance = outerInstance;
this.KeyCount = keyCount;
this.Map = map;
this.Keys = keys;
this.Rnd = rnd;
}
public void Run()
{
int count = AtLeast(Rnd, 10000);
for (int i = 0; i < count; i++)
{
int j = Rnd.Next(KeyCount);
switch (Rnd.Next(5))
{
case 0:
Map.Put(Keys.Get(j), Convert.ToInt32(j));
break;
case 1:
int? v = Map.Get(Keys.Get(j));
if (v != null)
{
Assert.AreEqual(j, (int)v);
}
break;
case 2:
Map.Remove(Keys.Get(j));
break;
case 3:
// renew key, the old one will be GCed at some time:
Keys.Set(j, new object());
break;
case 4:
// check iterator still working
for (IEnumerator<object> it = Map.Keys.GetEnumerator(); it.MoveNext(); )
{
Assert.IsNotNull(it.Current);
}
break;
default:
Assert.Fail("Should not get here.");
break;
}
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace Azure.Data.Tables.Models
{
/// <summary> Error codes returned by the service. </summary>
public readonly partial struct TableErrorCode : IEquatable<TableErrorCode>
{
private readonly string _value;
/// <summary> Determines if two <see cref="TableErrorCode"/> values are the same. </summary>
/// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception>
public TableErrorCode(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
private const string AuthorizationResourceTypeMismatchValue = "AuthorizationResourceTypeMismatch";
private const string AuthorizationPermissionMismatchValue = "AuthorizationPermissionMismatch";
private const string XMethodNotUsingPostValue = "XMethodNotUsingPost";
private const string XMethodIncorrectValueValue = "XMethodIncorrectValue";
private const string XMethodIncorrectCountValue = "XMethodIncorrectCount";
private const string TableHasNoPropertiesValue = "TableHasNoProperties";
private const string DuplicatePropertiesSpecifiedValue = "DuplicatePropertiesSpecified";
private const string TableHasNoSuchPropertyValue = "TableHasNoSuchProperty";
private const string DuplicateKeyPropertySpecifiedValue = "DuplicateKeyPropertySpecified";
private const string TableAlreadyExistsValue = "TableAlreadyExists";
private const string TableNotFoundValue = "TableNotFound";
private const string ResourceNotFoundValue = "ResourceNotFound";
private const string EntityNotFoundValue = "EntityNotFound";
private const string EntityAlreadyExistsValue = "EntityAlreadyExists";
private const string PartitionKeyNotSpecifiedValue = "PartitionKeyNotSpecified";
private const string OperatorInvalidValue = "OperatorInvalid";
private const string UpdateConditionNotSatisfiedValue = "UpdateConditionNotSatisfied";
private const string PropertiesNeedValueValue = "PropertiesNeedValue";
private const string PartitionKeyPropertyCannotBeUpdatedValue = "PartitionKeyPropertyCannotBeUpdated";
private const string TooManyPropertiesValue = "TooManyProperties";
private const string EntityTooLargeValue = "EntityTooLarge";
private const string PropertyValueTooLargeValue = "PropertyValueTooLarge";
private const string KeyValueTooLargeValue = "KeyValueTooLarge";
private const string InvalidValueTypeValue = "InvalidValueType";
private const string TableBeingDeletedValue = "TableBeingDeleted";
private const string PrimaryKeyPropertyIsInvalidTypeValue = "PrimaryKeyPropertyIsInvalidType";
private const string PropertyNameTooLongValue = "PropertyNameTooLong";
private const string PropertyNameInvalidValue = "PropertyNameInvalid";
private const string InvalidDuplicateRowValue = "InvalidDuplicateRow";
private const string CommandsInBatchActOnDifferentPartitionsValue = "CommandsInBatchActOnDifferentPartitions";
private const string JsonFormatNotSupportedValue = "JsonFormatNotSupported";
private const string AtomFormatNotSupportedValue = "AtomFormatNotSupported";
private const string JsonVerboseFormatNotSupportedValue = "JsonVerboseFormatNotSupported";
private const string MediaTypeNotSupportedValue = "MediaTypeNotSupported";
private const string MethodNotAllowedValue = "MethodNotAllowed";
private const string ContentLengthExceededValue = "ContentLengthExceeded";
private const string AccountIOPSLimitExceededValue = "AccountIOPSLimitExceeded";
private const string CannotCreateTableWithIOPSGreaterThanMaxAllowedPerTableValue = "CannotCreateTableWithIOPSGreaterThanMaxAllowedPerTable";
private const string PerTableIOPSIncrementLimitReachedValue = "PerTableIOPSIncrementLimitReached";
private const string PerTableIOPSDecrementLimitReachedValue = "PerTableIOPSDecrementLimitReached";
private const string SettingIOPSForATableInProvisioningNotAllowedValue = "SettingIOPSForATableInProvisioningNotAllowed";
private const string PartitionKeyEqualityComparisonExpectedValue = "PartitionKeyEqualityComparisonExpected";
private const string PartitionKeySpecifiedMoreThanOnceValue = "PartitionKeySpecifiedMoreThanOnce";
private const string InvalidInputValue = "InvalidInput";
private const string NotImplementedValue = "NotImplemented";
private const string OperationTimedOutValue = "OperationTimedOut";
private const string OutOfRangeInputValue = "OutOfRangeInput";
private const string ForbiddenValue = "Forbidden";
/// <summary> AuthorizationResourceTypeMismatch. </summary>
public static TableErrorCode AuthorizationResourceTypeMismatch { get; } = new TableErrorCode(AuthorizationResourceTypeMismatchValue);
/// <summary> XMethodNotUsingPost. </summary>
public static TableErrorCode XMethodNotUsingPost { get; } = new TableErrorCode(XMethodNotUsingPostValue);
/// <summary> XMethodIncorrectValue. </summary>
public static TableErrorCode XMethodIncorrectValue { get; } = new TableErrorCode(XMethodIncorrectValueValue);
/// <summary> XMethodIncorrectCount. </summary>
public static TableErrorCode XMethodIncorrectCount { get; } = new TableErrorCode(XMethodIncorrectCountValue);
/// <summary> TableHasNoProperties. </summary>
public static TableErrorCode TableHasNoProperties { get; } = new TableErrorCode(TableHasNoPropertiesValue);
/// <summary> DuplicatePropertiesSpecified. </summary>
public static TableErrorCode DuplicatePropertiesSpecified { get; } = new TableErrorCode(DuplicatePropertiesSpecifiedValue);
/// <summary> TableHasNoSuchProperty. </summary>
public static TableErrorCode TableHasNoSuchProperty { get; } = new TableErrorCode(TableHasNoSuchPropertyValue);
/// <summary> DuplicateKeyPropertySpecified. </summary>
public static TableErrorCode DuplicateKeyPropertySpecified { get; } = new TableErrorCode(DuplicateKeyPropertySpecifiedValue);
/// <summary> TableAlreadyExists. </summary>
public static TableErrorCode TableAlreadyExists { get; } = new TableErrorCode(TableAlreadyExistsValue);
/// <summary> TableNotFound.</summary>
public static TableErrorCode TableNotFound { get; } = new TableErrorCode(TableNotFoundValue);
/// <summary> TableNotFound. </summary>
public static TableErrorCode ResourceNotFound { get; } = new TableErrorCode(ResourceNotFoundValue);
/// <summary> EntityNotFound. </summary>
public static TableErrorCode EntityNotFound { get; } = new TableErrorCode(EntityNotFoundValue);
/// <summary> EntityAlreadyExists. </summary>
public static TableErrorCode EntityAlreadyExists { get; } = new TableErrorCode(EntityAlreadyExistsValue);
/// <summary> PartitionKeyNotSpecified. </summary>
public static TableErrorCode PartitionKeyNotSpecified { get; } = new TableErrorCode(PartitionKeyNotSpecifiedValue);
/// <summary> OperatorInvalid. </summary>
public static TableErrorCode OperatorInvalid { get; } = new TableErrorCode(OperatorInvalidValue);
/// <summary> UpdateConditionNotSatisfied. </summary>
public static TableErrorCode UpdateConditionNotSatisfied { get; } = new TableErrorCode(UpdateConditionNotSatisfiedValue);
/// <summary> PropertiesNeedValue. </summary>
public static TableErrorCode PropertiesNeedValue { get; } = new TableErrorCode(PropertiesNeedValueValue);
/// <summary> PartitionKeyPropertyCannotBeUpdated. </summary>
public static TableErrorCode PartitionKeyPropertyCannotBeUpdated { get; } = new TableErrorCode(PartitionKeyPropertyCannotBeUpdatedValue);
/// <summary> TooManyProperties. </summary>
public static TableErrorCode TooManyProperties { get; } = new TableErrorCode(TooManyPropertiesValue);
/// <summary> EntityTooLarge. </summary>
public static TableErrorCode EntityTooLarge { get; } = new TableErrorCode(EntityTooLargeValue);
/// <summary> PropertyValueTooLarge. </summary>
public static TableErrorCode PropertyValueTooLarge { get; } = new TableErrorCode(PropertyValueTooLargeValue);
/// <summary> KeyValueTooLarge. </summary>
public static TableErrorCode KeyValueTooLarge { get; } = new TableErrorCode(KeyValueTooLargeValue);
/// <summary> InvalidValueType. </summary>
public static TableErrorCode InvalidValueType { get; } = new TableErrorCode(InvalidValueTypeValue);
/// <summary> TableBeingDeleted. </summary>
public static TableErrorCode TableBeingDeleted { get; } = new TableErrorCode(TableBeingDeletedValue);
/// <summary> PrimaryKeyPropertyIsInvalidType. </summary>
public static TableErrorCode PrimaryKeyPropertyIsInvalidType { get; } = new TableErrorCode(PrimaryKeyPropertyIsInvalidTypeValue);
/// <summary> PropertyNameTooLong. </summary>
public static TableErrorCode PropertyNameTooLong { get; } = new TableErrorCode(PropertyNameTooLongValue);
/// <summary> PropertyNameInvalid. </summary>
public static TableErrorCode PropertyNameInvalid { get; } = new TableErrorCode(PropertyNameInvalidValue);
/// <summary> InvalidDuplicateRow. </summary>
public static TableErrorCode InvalidDuplicateRow { get; } = new TableErrorCode(InvalidDuplicateRowValue);
/// <summary> CommandsInBatchActOnDifferentPartitions. </summary>
public static TableErrorCode CommandsInBatchActOnDifferentPartitions { get; } = new TableErrorCode(CommandsInBatchActOnDifferentPartitionsValue);
/// <summary> JsonFormatNotSupported. </summary>
public static TableErrorCode JsonFormatNotSupported { get; } = new TableErrorCode(JsonFormatNotSupportedValue);
/// <summary> AtomFormatNotSupported. </summary>
public static TableErrorCode AtomFormatNotSupported { get; } = new TableErrorCode(AtomFormatNotSupportedValue);
/// <summary> JsonVerboseFormatNotSupported. </summary>
public static TableErrorCode JsonVerboseFormatNotSupported { get; } = new TableErrorCode(JsonVerboseFormatNotSupportedValue);
/// <summary> MediaTypeNotSupported. </summary>
public static TableErrorCode MediaTypeNotSupported { get; } = new TableErrorCode(MediaTypeNotSupportedValue);
/// <summary> MethodNotAllowed. </summary>
public static TableErrorCode MethodNotAllowed { get; } = new TableErrorCode(MethodNotAllowedValue);
/// <summary> ContentLengthExceeded. </summary>
public static TableErrorCode ContentLengthExceeded { get; } = new TableErrorCode(ContentLengthExceededValue);
/// <summary> AccountIOPSLimitExceeded. </summary>
public static TableErrorCode AccountIOPSLimitExceeded { get; } = new TableErrorCode(AccountIOPSLimitExceededValue);
/// <summary> CannotCreateTableWithIOPSGreaterThanMaxAllowedPerTable. </summary>
public static TableErrorCode CannotCreateTableWithIOPSGreaterThanMaxAllowedPerTable { get; } = new TableErrorCode(CannotCreateTableWithIOPSGreaterThanMaxAllowedPerTableValue);
/// <summary> PerTableIOPSIncrementLimitReached. </summary>
public static TableErrorCode PerTableIOPSIncrementLimitReached { get; } = new TableErrorCode(PerTableIOPSIncrementLimitReachedValue);
/// <summary> PerTableIOPSDecrementLimitReached. </summary>
public static TableErrorCode PerTableIOPSDecrementLimitReached { get; } = new TableErrorCode(PerTableIOPSDecrementLimitReachedValue);
/// <summary> SettingIOPSForATableInProvisioningNotAllowed. </summary>
public static TableErrorCode SettingIOPSForATableInProvisioningNotAllowed { get; } = new TableErrorCode(SettingIOPSForATableInProvisioningNotAllowedValue);
/// <summary> PartitionKeyEqualityComparisonExpected. </summary>
public static TableErrorCode PartitionKeyEqualityComparisonExpected { get; } = new TableErrorCode(PartitionKeyEqualityComparisonExpectedValue);
/// <summary> PartitionKeySpecifiedMoreThanOnce. </summary>
public static TableErrorCode PartitionKeySpecifiedMoreThanOnce { get; } = new TableErrorCode(PartitionKeySpecifiedMoreThanOnceValue);
/// <summary> InvalidInput. </summary>
public static TableErrorCode InvalidInput { get; } = new TableErrorCode(InvalidInputValue);
/// <summary> NotImplemented. </summary>
public static TableErrorCode NotImplemented { get; } = new TableErrorCode(NotImplementedValue);
/// <summary> OperationTimedOut. </summary>
public static TableErrorCode OperationTimedOut { get; } = new TableErrorCode(OperationTimedOutValue);
/// <summary> OutOfRangeInput. </summary>
public static TableErrorCode OutOfRangeInput { get; } = new TableErrorCode(OutOfRangeInputValue);
/// <summary> Forbidden. </summary>
public static TableErrorCode Forbidden { get; } = new TableErrorCode(ForbiddenValue);
/// <summary> AuthorizationPermissionMismatch. </summary>
public static TableErrorCode AuthorizationPermissionMismatch { get; } = new TableErrorCode(AuthorizationPermissionMismatchValue);
/// <summary> Determines if two <see cref="TableErrorCode"/> values are the same. </summary>
public static bool operator ==(TableErrorCode left, TableErrorCode right) => left.Equals(right);
/// <summary> Determines if two <see cref="TableErrorCode"/> values are not the same. </summary>
public static bool operator !=(TableErrorCode left, TableErrorCode right) => !left.Equals(right);
/// <summary> Converts a string to a <see cref="TableErrorCode"/>. </summary>
public static implicit operator TableErrorCode(string value) => new TableErrorCode(value);
/// <inheritdoc />
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj) => obj is TableErrorCode other && Equals(other);
/// <inheritdoc />
public bool Equals(TableErrorCode other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);
/// <inheritdoc />
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
/// <inheritdoc />
public override string ToString() => _value;
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the SysRelFormularioCobertura class.
/// </summary>
[Serializable]
public partial class SysRelFormularioCoberturaCollection : ActiveList<SysRelFormularioCobertura, SysRelFormularioCoberturaCollection>
{
public SysRelFormularioCoberturaCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>SysRelFormularioCoberturaCollection</returns>
public SysRelFormularioCoberturaCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
SysRelFormularioCobertura o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the Sys_RelFormularioCobertura table.
/// </summary>
[Serializable]
public partial class SysRelFormularioCobertura : ActiveRecord<SysRelFormularioCobertura>, IActiveRecord
{
#region .ctors and Default Settings
public SysRelFormularioCobertura()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public SysRelFormularioCobertura(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public SysRelFormularioCobertura(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public SysRelFormularioCobertura(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("Sys_RelFormularioCobertura", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdRelFormularioCobertura = new TableSchema.TableColumn(schema);
colvarIdRelFormularioCobertura.ColumnName = "idRelFormularioCobertura";
colvarIdRelFormularioCobertura.DataType = DbType.Int32;
colvarIdRelFormularioCobertura.MaxLength = 0;
colvarIdRelFormularioCobertura.AutoIncrement = true;
colvarIdRelFormularioCobertura.IsNullable = false;
colvarIdRelFormularioCobertura.IsPrimaryKey = true;
colvarIdRelFormularioCobertura.IsForeignKey = false;
colvarIdRelFormularioCobertura.IsReadOnly = false;
colvarIdRelFormularioCobertura.DefaultSetting = @"";
colvarIdRelFormularioCobertura.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdRelFormularioCobertura);
TableSchema.TableColumn colvarIdFormulario = new TableSchema.TableColumn(schema);
colvarIdFormulario.ColumnName = "idFormulario";
colvarIdFormulario.DataType = DbType.Int32;
colvarIdFormulario.MaxLength = 0;
colvarIdFormulario.AutoIncrement = false;
colvarIdFormulario.IsNullable = false;
colvarIdFormulario.IsPrimaryKey = false;
colvarIdFormulario.IsForeignKey = true;
colvarIdFormulario.IsReadOnly = false;
colvarIdFormulario.DefaultSetting = @"((0))";
colvarIdFormulario.ForeignKeyTableName = "Rem_Formulario";
schema.Columns.Add(colvarIdFormulario);
TableSchema.TableColumn colvarIdTipoCobertura = new TableSchema.TableColumn(schema);
colvarIdTipoCobertura.ColumnName = "idTipoCobertura";
colvarIdTipoCobertura.DataType = DbType.Int32;
colvarIdTipoCobertura.MaxLength = 0;
colvarIdTipoCobertura.AutoIncrement = false;
colvarIdTipoCobertura.IsNullable = false;
colvarIdTipoCobertura.IsPrimaryKey = false;
colvarIdTipoCobertura.IsForeignKey = true;
colvarIdTipoCobertura.IsReadOnly = false;
colvarIdTipoCobertura.DefaultSetting = @"((0))";
colvarIdTipoCobertura.ForeignKeyTableName = "Rem_TipoCobertura";
schema.Columns.Add(colvarIdTipoCobertura);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("Sys_RelFormularioCobertura",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdRelFormularioCobertura")]
[Bindable(true)]
public int IdRelFormularioCobertura
{
get { return GetColumnValue<int>(Columns.IdRelFormularioCobertura); }
set { SetColumnValue(Columns.IdRelFormularioCobertura, value); }
}
[XmlAttribute("IdFormulario")]
[Bindable(true)]
public int IdFormulario
{
get { return GetColumnValue<int>(Columns.IdFormulario); }
set { SetColumnValue(Columns.IdFormulario, value); }
}
[XmlAttribute("IdTipoCobertura")]
[Bindable(true)]
public int IdTipoCobertura
{
get { return GetColumnValue<int>(Columns.IdTipoCobertura); }
set { SetColumnValue(Columns.IdTipoCobertura, value); }
}
#endregion
#region ForeignKey Properties
/// <summary>
/// Returns a RemTipoCobertura ActiveRecord object related to this SysRelFormularioCobertura
///
/// </summary>
public DalSic.RemTipoCobertura RemTipoCobertura
{
get { return DalSic.RemTipoCobertura.FetchByID(this.IdTipoCobertura); }
set { SetColumnValue("idTipoCobertura", value.IdTipoCobertura); }
}
/// <summary>
/// Returns a RemFormulario ActiveRecord object related to this SysRelFormularioCobertura
///
/// </summary>
public DalSic.RemFormulario RemFormulario
{
get { return DalSic.RemFormulario.FetchByID(this.IdFormulario); }
set { SetColumnValue("idFormulario", value.IdFormulario); }
}
#endregion
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int varIdFormulario,int varIdTipoCobertura)
{
SysRelFormularioCobertura item = new SysRelFormularioCobertura();
item.IdFormulario = varIdFormulario;
item.IdTipoCobertura = varIdTipoCobertura;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdRelFormularioCobertura,int varIdFormulario,int varIdTipoCobertura)
{
SysRelFormularioCobertura item = new SysRelFormularioCobertura();
item.IdRelFormularioCobertura = varIdRelFormularioCobertura;
item.IdFormulario = varIdFormulario;
item.IdTipoCobertura = varIdTipoCobertura;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdRelFormularioCoberturaColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdFormularioColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn IdTipoCoberturaColumn
{
get { return Schema.Columns[2]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdRelFormularioCobertura = @"idRelFormularioCobertura";
public static string IdFormulario = @"idFormulario";
public static string IdTipoCobertura = @"idTipoCobertura";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
/*
* CustomFormatter.cs - Implementation of the
* "System.Private.Formatter" class.
*
* Copyright (C) 2001 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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 System.Private.NumberFormat
{
using System;
using System.Collections;
using System.Globalization;
using System.Text;
internal class CustomFormatter : Formatter
{
//
// Constants and read-only
//
private const char zeroPlaceholder = '0';
private const char digitPlaceholder = '#';
private const char decimalSeparator = '.';
private const char groupSeparator = ',';
private const char percentagePlaceholder = '%';
private static readonly char[] engineeringFormat = {'E','e'};
private static readonly char[] sectionSeparator = {';'};
//
// Stored format information
//
private string originalFormat;
private string positiveFormat;
private string negativeFormat;
private string zeroFormat;
bool includeNegSign; // Should a '-' be included?
//
// Constructor - Take custom format string as input.
//
public CustomFormatter(string inFormat)
{
string[] fmts;
this.originalFormat = inFormat;
fmts = originalFormat.Split(sectionSeparator, 3);
if (fmts.Length == 0)
{
this.positiveFormat = null;
this.negativeFormat = null;
this.zeroFormat = null;
this.includeNegSign = true;
}
else if (fmts.Length == 1)
{
this.positiveFormat = inFormat;
this.negativeFormat = inFormat;
this.zeroFormat = inFormat;
this.includeNegSign = true;
}
else if (fmts.Length == 2)
{
this.positiveFormat = fmts[0];
this.negativeFormat = fmts[1];
this.zeroFormat = fmts[0];
this.includeNegSign = false;
}
else
{
this.positiveFormat = fmts[0];
if (this.negativeFormat == String.Empty)
{
this.negativeFormat = fmts[0];
this.includeNegSign=true;
}
else
{
this.negativeFormat = fmts[1];
this.includeNegSign=false;
}
this.zeroFormat = fmts[2];
}
}
private int ScientificStart(string format)
{
int ret, pos;
pos = format.IndexOfAny(engineeringFormat, 0);
while (pos != -1)
{
ret = pos++;
if (format[pos] == '+' || format[pos] == '-')
{
pos++;
}
if (format[pos] == '0')
{
return ret;
}
pos = format.IndexOfAny(engineeringFormat, pos);
}
return -1;
}
private string FormatFromSign(int sign)
{
string ret = null;
switch(sign)
{
case 1:
ret = positiveFormat;
break;
case -1:
ret = negativeFormat;
break;
case 0:
ret = zeroFormat;
break;
}
return ret;
}
//
// FormatRawNumber - Given a string of form 'n*.n*', format it based
// upon the custom format.
//
private string FormatRawNumber(string value, string format, int sign,
IFormatProvider provider)
{
string rawnumber;
int firstzero, lastzero;
int scale = 0;
// Locate the decimal point
int decimalPos = format.IndexOf(decimalSeparator);
if (decimalPos == -1) decimalPos = format.Length;
// Scaling
int formatindex = decimalPos - 1;
while (formatindex >=0 && format[formatindex] == groupSeparator)
{
scale += 3;
--formatindex;
}
// Move the decimal point
StringBuilder temp = new StringBuilder();
if (scale <= value.IndexOf('.'))
{
temp.Append(value.Substring(0, value.IndexOf('.') - scale))
.Append(".")
.Append(value.Substring(value.IndexOf('.') - scale, scale));
}
else
{
temp.Append(".")
.Append(value
.Substring(0, value.IndexOf('.'))
.PadLeft(scale, '0'));
}
temp.Append(value.Substring(value.IndexOf('.') + 1));
if (includeNegSign && sign == -1)
{
temp.Insert(0, NumberFormatInfo(provider).NegativeSign);
}
rawnumber = temp.ToString();
// Formatting
int rawindex = rawnumber.IndexOf('.') - 1;
StringBuilder ret = new StringBuilder();
while (rawindex >= 0 && formatindex >= 0) {
if (format[formatindex] == digitPlaceholder)
{
ret.Insert(0, rawnumber[rawindex--]);
}
else if (format[formatindex] == zeroPlaceholder )
{
// Don't put a negative if a zero should go there.
if ( rawnumber[rawindex] < '0' || rawnumber[rawindex] > '9')
{
int i = formatindex + 1;
while (format[i] == ',') ++i;
if (format[i] == '.')
{
ret.Insert(0,'0');
}
else
{
ret.Insert(0, rawnumber[rawindex--]);
}
}
else
{
ret.Insert(0, rawnumber[rawindex--]);
}
}
else if (format[formatindex] == groupSeparator)
{
ret.Insert(0, NumberFormatInfo(provider).NumberGroupSeparator);
}
else
{
ret.Insert(0, format[formatindex]);
}
--formatindex;
}
if (rawindex >= 0)
{
ret.Insert(0, rawnumber.Substring(0, rawindex+1));
}
// Zero pad
firstzero = format.IndexOf(zeroPlaceholder);
if (firstzero != -1)
{
while (firstzero <= formatindex)
{
if (format[formatindex] == digitPlaceholder
|| format[formatindex] == zeroPlaceholder)
{
ret.Insert(0, '0');
}
else if (format[formatindex] == groupSeparator)
{
ret.Insert(0,
NumberFormatInfo(provider).NumberGroupSeparator);
}
else
{
ret.Insert(0, format[formatindex]);
}
--formatindex;
}
}
// Fill out literal portion
while (formatindex >= 0)
{
if( !( format[formatindex] == digitPlaceholder
|| format[formatindex] == zeroPlaceholder
|| format[formatindex] == groupSeparator ))
{
ret.Insert(0, format[formatindex]);
}
--formatindex;
}
// Decimal point dealings
rawindex = rawnumber.IndexOf('.') + 1;
formatindex = decimalPos + 1;
if(decimalPos < format.Length)
{
ret.Append(NumberFormatInfo(provider).NumberDecimalSeparator);
}
while (rawindex < rawnumber.Length && formatindex < format.Length) {
if (format[formatindex] == digitPlaceholder
|| format[formatindex] == zeroPlaceholder )
{
ret.Append(rawnumber[rawindex++]);
}
else
{
ret.Append(format[formatindex]);
}
++formatindex;
}
// More zero padding
lastzero = format.LastIndexOf(zeroPlaceholder);
while (lastzero >= formatindex)
{
if (format[formatindex] == digitPlaceholder
|| format[formatindex] == zeroPlaceholder)
{
ret.Append('0');
}
else
{
ret.Append(format[formatindex]);
}
formatindex++;
}
while (formatindex < format.Length)
{
if ( !( format[formatindex] == digitPlaceholder
|| format[formatindex] == zeroPlaceholder ))
{
ret.Append(format[formatindex]);
}
++formatindex;
}
return ret.ToString();
}
#if CONFIG_EXTENDED_NUMERICS
private string FormatScientific(double d, string format, int sign,
IFormatProvider provider)
{
//int exponent = (int)Math.Floor(Math.Log10(d));
int exponent = Formatter.GetExponent( d );
double mantissa = d/Math.Pow(10,exponent);
int i = ScientificStart(format);
// Format the mantissa
StringBuilder ret = new StringBuilder(
FormatFloat(mantissa, format.Substring(0, i), sign, provider))
.Append(format[i++]);
// Sign logic
if (format[i] == '+' && exponent >= 0)
{
ret.Append(NumberFormatInfo(provider).PositiveSign);
}
else if (exponent < 0)
{
ret.Append(NumberFormatInfo(provider).NegativeSign);
}
if (format[i] == '+' || format[i] == '-')
{
++i;
}
// Place exponent value into string.
int exponentMin = 0;
while (i<format.Length && format[i] == '0')
{
++i;
++exponentMin;
}
// Format the exponent and append,
string exponentString =
Formatter.FormatInteger((ulong)Math.Abs(exponent));
ret.Append(exponentString.Substring(0, exponentString.Length-1)
.PadLeft(exponentMin,'0'));
// Fill out the string
ret.Append(format.Substring(i));
return ret.ToString();
}
#endif // CONFIG_EXTENDED_NUMERICS
private string FormatInteger(ulong value, string format, int sign,
IFormatProvider provider)
{
return FormatRawNumber(Formatter.FormatInteger(value)
,format, sign, provider);
}
#if CONFIG_EXTENDED_NUMERICS
private string FormatFloat(double d, string format, int sign,
IFormatProvider provider)
{
int formatindex, precision;
formatindex = format.IndexOf('.');
if (formatindex == -1) {
precision = 0;
}
else
{
for (formatindex++, precision = 0;
formatindex < format.Length; formatindex++)
{
if (format[formatindex] == digitPlaceholder ||
format[formatindex] == zeroPlaceholder)
{
++precision;
}
}
}
return FormatRawNumber( Formatter.FormatFloat(d, precision + 2),
format, sign, provider);
}
private string FormatDecimal(decimal value, string format, int sign,
IFormatProvider provider)
{
if (format.IndexOf(percentagePlaceholder) != -1)
{
return FormatRawNumber(Formatter.FormatDecimal(value*100),
format, sign, provider);
}
else
{
return FormatRawNumber(Formatter.FormatDecimal(value),
format, sign, provider);
}
}
#endif // CONFIG_EXTENDED_NUMERICS
//
// Public access method.
//
public override string Format(Object o, IFormatProvider provider)
{
if (IsSignedInt(o))
{
long val = OToLong(o);
int sign;
if(val < 0)
{
sign = -1;
val = -val;
}
else if(val > 0)
{
sign = 1;
}
else
{
sign = 0;
}
string format = FormatFromSign(sign);
#if CONFIG_EXTENDED_NUMERICS
if (ScientificStart(format) == -1)
{
return FormatInteger((ulong)val, format, sign, provider);
}
else
{
return FormatScientific((double)val, format, sign, provider);
}
#else
return FormatInteger((ulong)val, format, sign, provider);
#endif
}
else if (IsUnsignedInt(o))
{
ulong val = OToUlong(o);
string format = ( (val==0) ? zeroFormat : positiveFormat);
#if CONFIG_EXTENDED_NUMERICS
if (ScientificStart(format) == -1)
{
return FormatInteger(val, format, val == 0 ? 0 : 1, provider);
}
else
{
return FormatScientific( (double)val,
format, val == 0 ? 0 : 1, provider);
}
#else
return FormatInteger(val, format, val == 0 ? 0 : 1, provider);
#endif
}
#if CONFIG_EXTENDED_NUMERICS
else if (IsFloat(o))
{
double val = OToDouble(o);
string format = FormatFromSign(Math.Sign(val));
if (ScientificStart(format) == -1)
{
return FormatFloat(Math.Abs(val),
format, Math.Sign(val), provider);
}
else
{
return FormatScientific(Math.Abs(val),
format, Math.Sign(val), provider);
}
}
else if (IsDecimal(o))
{
decimal val = (decimal) o;
string format = FormatFromSign(Math.Sign(val));
if (ScientificStart(format) == -1)
{
return FormatDecimal(Math.Abs(val),
format, Math.Sign(val), provider);
}
else
{
return FormatScientific((double)Math.Abs(val),
format, Math.Sign(val), provider);
}
}
#endif // CONFIG_EXTENDED_NUMERICS
else if (o is IFormattable)
{
return ((IFormattable)o).ToString(originalFormat, provider);
}
else
{
return o.ToString();
}
}
} // class CustomFormatter
} // namespace System.Private.NumberFormat
| |
using System.Diagnostics;
namespace System.Data.SQLite
{
using u8 = System.Byte;
public partial class Sqlite3
{
/*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** An tokenizer for SQL
**
** This file contains C code that implements the sqlite3_complete() API.
** This code used to be part of the tokenizer.c source file. But by
** separating it out, the code will be automatically omitted from
** static links that do not use it.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3
**
*************************************************************************
*/
//#include "sqliteInt.h"
#if !SQLITE_OMIT_COMPLETE
/*
** This is defined in tokenize.c. We just have to import the definition.
*/
#if !SQLITE_AMALGAMATION
#if SQLITE_ASCII
//#define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
static bool IdChar(u8 C)
{
return (sqlite3CtypeMap[(char)C] & 0x46) != 0;
}
#endif
//#if SQLITE_EBCDIC
//extern const char sqlite3IsEbcdicIdChar[];
//#define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
//#endif
#endif // * SQLITE_AMALGAMATION */
/*
** Token types used by the sqlite3_complete() routine. See the header
** comments on that procedure for additional information.
*/
const int tkSEMI = 0;
const int tkWS = 1;
const int tkOTHER = 2;
#if !SQLITE_OMIT_TRIGGER
const int tkEXPLAIN = 3;
const int tkCREATE = 4;
const int tkTEMP = 5;
const int tkTRIGGER = 6;
const int tkEND = 7;
#endif
/*
** Return TRUE if the given SQL string ends in a semicolon.
**
** Special handling is require for CREATE TRIGGER statements.
** Whenever the CREATE TRIGGER keywords are seen, the statement
** must end with ";END;".
**
** This implementation uses a state machine with 8 states:
**
** (0) INVALID We have not yet seen a non-whitespace character.
**
** (1) START At the beginning or end of an SQL statement. This routine
** returns 1 if it ends in the START state and 0 if it ends
** in any other state.
**
** (2) NORMAL We are in the middle of statement which ends with a single
** semicolon.
**
** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
** a statement.
**
** (4) CREATE The keyword CREATE has been seen at the beginning of a
** statement, possibly preceeded by EXPLAIN and/or followed by
** TEMP or TEMPORARY
**
** (5) TRIGGER We are in the middle of a trigger definition that must be
** ended by a semicolon, the keyword END, and another semicolon.
**
** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
** the end of a trigger definition.
**
** (7) END We've seen the ";END" of the ";END;" that occurs at the end
** of a trigger difinition.
**
** Transitions between states above are determined by tokens extracted
** from the input. The following tokens are significant:
**
** (0) tkSEMI A semicolon.
** (1) tkWS Whitespace.
** (2) tkOTHER Any other SQL token.
** (3) tkEXPLAIN The "explain" keyword.
** (4) tkCREATE The "create" keyword.
** (5) tkTEMP The "temp" or "temporary" keyword.
** (6) tkTRIGGER The "trigger" keyword.
** (7) tkEND The "end" keyword.
**
** Whitespace never causes a state transition and is always ignored.
** This means that a SQL string of all whitespace is invalid.
**
** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
** to recognize the end of a trigger can be omitted. All we have to do
** is look for a semicolon that is not part of an string or comment.
*/
static public int sqlite3_complete(string zSql)
{
int state = 0; /* Current state, using numbers defined in header comment */
int token; /* Value of the next token */
#if !SQLITE_OMIT_TRIGGER
/* A complex statement machine used to detect the end of a CREATE TRIGGER
** statement. This is the normal case.
*/
u8[][] trans = new u8[][] {
/* Token: */
/* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
/* 0 INVALID: */ new u8[]{ 1, 0, 2, 3, 4, 2, 2, 2, },
/* 1 START: */ new u8[]{ 1, 1, 2, 3, 4, 2, 2, 2, },
/* 2 NORMAL: */ new u8[]{ 1, 2, 2, 2, 2, 2, 2, 2, },
/* 3 EXPLAIN: */ new u8[]{ 1, 3, 3, 2, 4, 2, 2, 2, },
/* 4 CREATE: */ new u8[]{ 1, 4, 2, 2, 2, 4, 5, 2, },
/* 5 TRIGGER: */ new u8[]{ 6, 5, 5, 5, 5, 5, 5, 5, },
/* 6 SEMI: */ new u8[]{ 6, 6, 5, 5, 5, 5, 5, 7, },
/* 7 END: */ new u8[]{ 1, 7, 5, 5, 5, 5, 5, 5, },
};
#else
/* If triggers are not supported by this compile then the statement machine
** used to detect the end of a statement is much simplier
*/
u8[][] trans = new u8[][] {
/* Token: */
/* State: ** SEMI WS OTHER */
/* 0 INVALID: */new u8[] { 1, 0, 2, },
/* 1 START: */new u8[] { 1, 1, 2, },
/* 2 NORMAL: */new u8[] { 1, 2, 2, },
};
#endif // * SQLITE_OMIT_TRIGGER */
int zIdx = 0;
while (zIdx < zSql.Length)
{
switch (zSql[zIdx])
{
case ';':
{ /* A semicolon */
token = tkSEMI;
break;
}
case ' ':
case '\r':
case '\t':
case '\n':
case '\f':
{ /* White space is ignored */
token = tkWS;
break;
}
case '/':
{ /* C-style comments */
if (zSql[zIdx + 1] != '*')
{
token = tkOTHER;
break;
}
zIdx += 2;
while (zIdx < zSql.Length && zSql[zIdx] != '*' || zIdx < zSql.Length - 1 && zSql[zIdx + 1] != '/')
{
zIdx++;
}
if (zIdx == zSql.Length)
return 0;
zIdx++;
token = tkWS;
break;
}
case '-':
{ /* SQL-style comments from "--" to end of line */
if (zSql[zIdx + 1] != '-')
{
token = tkOTHER;
break;
}
while (zIdx < zSql.Length && zSql[zIdx] != '\n')
{
zIdx++;
}
if (zIdx == zSql.Length)
return state == 1 ? 1 : 0;//if( *zSql==0 ) return state==1;
token = tkWS;
break;
}
case '[':
{ /* Microsoft-style identifiers in [...] */
zIdx++;
while (zIdx < zSql.Length && zSql[zIdx] != ']')
{
zIdx++;
}
if (zIdx == zSql.Length)
return 0;
token = tkOTHER;
break;
}
case '`': /* Grave-accent quoted symbols used by MySQL */
case '"': /* single- and double-quoted strings */
case '\'':
{
int c = zSql[zIdx];
zIdx++;
while (zIdx < zSql.Length && zSql[zIdx] != c)
{
zIdx++;
}
if (zIdx == zSql.Length)
return 0;
token = tkOTHER;
break;
}
default:
{
//#if SQLITE_EBCDIC
// unsigned char c;
//#endif
if (IdChar((u8)zSql[zIdx]))
{
/* Keywords and unquoted identifiers */
int nId;
for (nId = 1; (zIdx + nId) < zSql.Length && IdChar((u8)zSql[zIdx + nId]); nId++)
{
}
#if SQLITE_OMIT_TRIGGER
token = tkOTHER;
#else
switch (zSql[zIdx])
{
case 'c':
case 'C':
{
if (nId == 6 && sqlite3StrNICmp(zSql, zIdx, "create", 6) == 0)
{
token = tkCREATE;
}
else
{
token = tkOTHER;
}
break;
}
case 't':
case 'T':
{
if (nId == 7 && sqlite3StrNICmp(zSql, zIdx, "trigger", 7) == 0)
{
token = tkTRIGGER;
}
else if (nId == 4 && sqlite3StrNICmp(zSql, zIdx, "temp", 4) == 0)
{
token = tkTEMP;
}
else if (nId == 9 && sqlite3StrNICmp(zSql, zIdx, "temporary", 9) == 0)
{
token = tkTEMP;
}
else
{
token = tkOTHER;
}
break;
}
case 'e':
case 'E':
{
if (nId == 3 && sqlite3StrNICmp(zSql, zIdx, "end", 3) == 0)
{
token = tkEND;
}
else
#if !SQLITE_OMIT_EXPLAIN
if (nId == 7 && sqlite3StrNICmp(zSql, zIdx, "explain", 7) == 0)
{
token = tkEXPLAIN;
}
else
#endif
{
token = tkOTHER;
}
break;
}
default:
{
token = tkOTHER;
break;
}
}
#endif // * SQLITE_OMIT_TRIGGER */
zIdx += nId - 1;
}
else
{
/* Operators and special symbols */
token = tkOTHER;
}
break;
}
}
state = trans[state][token];
zIdx++;
}
return (state == 1) ? 1 : 0;//return state==1;
}
#if !SQLITE_OMIT_UTF16
/*
** This routine is the same as the sqlite3_complete() routine described
** above, except that the parameter is required to be UTF-16 encoded, not
** UTF-8.
*/
int sqlite3_complete16(const void *zSql){
sqlite3_value pVal;
char const *zSql8;
int rc = SQLITE_NOMEM;
#if !SQLITE_OMIT_AUTOINIT
rc = sqlite3_initialize();
if( rc !=0) return rc;
#endif
pVal = sqlite3ValueNew(0);
sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
if( zSql8 ){
rc = sqlite3_complete(zSql8);
}else{
rc = SQLITE_NOMEM;
}
sqlite3ValueFree(pVal);
return sqlite3ApiExit(0, rc);
}
#endif // * SQLITE_OMIT_UTF16 */
#endif // * SQLITE_OMIT_COMPLETE */
}
}
| |
// 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.Config.DataAccess
{
/// <summary>
/// Provides simplified data access features to perform SCRUD operation on the database table "config.offices".
/// </summary>
public class Office : DbAccess, IOfficeRepository
{
/// <summary>
/// The schema of this table. Returns literal "config".
/// </summary>
public override string _ObjectNamespace => "config";
/// <summary>
/// The schema unqualified name of this table. Returns literal "offices".
/// </summary>
public override string _ObjectName => "offices";
/// <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 "config.offices".
/// </summary>
/// <returns>Returns the number of rows of the table "config.offices".</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 \"Office\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT COUNT(*) FROM config.offices;";
return Factory.Scalar<long>(this._Catalog, sql);
}
/// <summary>
/// Executes a select query on the table "config.offices" to return all instances of the "Office" class.
/// </summary>
/// <returns>Returns a non-live, non-mapped instances of "Office" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Config.Entities.Office> 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 \"Office\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM config.offices ORDER BY office_id;";
return Factory.Get<Frapid.Config.Entities.Office>(this._Catalog, sql);
}
/// <summary>
/// Executes a select query on the table "config.offices" to return all instances of the "Office" class to export.
/// </summary>
/// <returns>Returns a non-live, non-mapped instances of "Office" 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 \"Office\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM config.offices ORDER BY office_id;";
return Factory.Get<dynamic>(this._Catalog, sql);
}
/// <summary>
/// Executes a select query on the table "config.offices" with a where filter on the column "office_id" to return a single instance of the "Office" class.
/// </summary>
/// <param name="officeId">The column "office_id" parameter used on where filter.</param>
/// <returns>Returns a non-live, non-mapped instance of "Office" 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.Config.Entities.Office Get(int officeId)
{
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 \"Office\" filtered by \"OfficeId\" with value {OfficeId} was denied to the user with Login ID {_LoginId}", officeId, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM config.offices WHERE office_id=@0;";
return Factory.Get<Frapid.Config.Entities.Office>(this._Catalog, sql, officeId).FirstOrDefault();
}
/// <summary>
/// Gets the first record of the table "config.offices".
/// </summary>
/// <returns>Returns a non-live, non-mapped instance of "Office" 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.Config.Entities.Office 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 \"Office\" was denied to the user with Login ID {_LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM config.offices ORDER BY office_id LIMIT 1;";
return Factory.Get<Frapid.Config.Entities.Office>(this._Catalog, sql).FirstOrDefault();
}
/// <summary>
/// Gets the previous record of the table "config.offices" sorted by officeId.
/// </summary>
/// <param name="officeId">The column "office_id" parameter used to find the next record.</param>
/// <returns>Returns a non-live, non-mapped instance of "Office" 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.Config.Entities.Office GetPrevious(int officeId)
{
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 \"Office\" by \"OfficeId\" with value {OfficeId} was denied to the user with Login ID {_LoginId}", officeId, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM config.offices WHERE office_id < @0 ORDER BY office_id DESC LIMIT 1;";
return Factory.Get<Frapid.Config.Entities.Office>(this._Catalog, sql, officeId).FirstOrDefault();
}
/// <summary>
/// Gets the next record of the table "config.offices" sorted by officeId.
/// </summary>
/// <param name="officeId">The column "office_id" parameter used to find the next record.</param>
/// <returns>Returns a non-live, non-mapped instance of "Office" 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.Config.Entities.Office GetNext(int officeId)
{
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 \"Office\" by \"OfficeId\" with value {OfficeId} was denied to the user with Login ID {_LoginId}", officeId, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM config.offices WHERE office_id > @0 ORDER BY office_id LIMIT 1;";
return Factory.Get<Frapid.Config.Entities.Office>(this._Catalog, sql, officeId).FirstOrDefault();
}
/// <summary>
/// Gets the last record of the table "config.offices".
/// </summary>
/// <returns>Returns a non-live, non-mapped instance of "Office" 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.Config.Entities.Office 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 \"Office\" was denied to the user with Login ID {_LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM config.offices ORDER BY office_id DESC LIMIT 1;";
return Factory.Get<Frapid.Config.Entities.Office>(this._Catalog, sql).FirstOrDefault();
}
/// <summary>
/// Executes a select query on the table "config.offices" with a where filter on the column "office_id" to return a multiple instances of the "Office" class.
/// </summary>
/// <param name="officeIds">Array of column "office_id" parameter used on where filter.</param>
/// <returns>Returns a non-live, non-mapped collection of "Office" 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.Config.Entities.Office> Get(int[] officeIds)
{
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 \"Office\" was denied to the user with Login ID {LoginId}. officeIds: {officeIds}.", this._LoginId, officeIds);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM config.offices WHERE office_id IN (@0);";
return Factory.Get<Frapid.Config.Entities.Office>(this._Catalog, sql, officeIds);
}
/// <summary>
/// Custom fields are user defined form elements for config.offices.
/// </summary>
/// <returns>Returns an enumerable custom field collection for the table config.offices</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 \"Office\" 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='config.offices' ORDER BY field_order;";
return Factory.Get<Frapid.DataAccess.Models.CustomField>(this._Catalog, sql);
}
sql = "SELECT * from config.get_custom_field_definition('config.offices'::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 config.offices.
/// </summary>
/// <returns>Returns an enumerable name and value collection for the table config.offices</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 \"Office\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT office_id AS key, office_code || ' (' || office_name || ')' as value FROM config.offices;";
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 Office class on the database table "config.offices".
/// </summary>
/// <param name="office">The instance of "Office" 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 office, List<Frapid.DataAccess.Models.CustomField> customFields)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
office.audit_user_id = this._UserId;
office.audit_ts = System.DateTime.UtcNow;
object primaryKeyValue = office.office_id;
if (Cast.To<int>(primaryKeyValue) > 0)
{
this.Update(office, Cast.To<int>(primaryKeyValue));
}
else
{
primaryKeyValue = this.Add(office);
}
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('config.offices')" +
");";
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('config.offices', @0::character varying(100)), " +
"@1, @2;";
Factory.NonQuery(this._Catalog, sql, field.FieldName, primaryKeyValue, field.Value);
}
return primaryKeyValue;
}
/// <summary>
/// Inserts the instance of Office class on the database table "config.offices".
/// </summary>
/// <param name="office">The instance of "Office" 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 office)
{
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 \"Office\" was denied to the user with Login ID {LoginId}. {Office}", this._LoginId, office);
throw new UnauthorizedException("Access is denied.");
}
}
return Factory.Insert(this._Catalog, office, "config.offices", "office_id");
}
/// <summary>
/// Inserts or updates multiple instances of Office class on the database table "config.offices";
/// </summary>
/// <param name="offices">List of "Office" class to import.</param>
/// <returns></returns>
public List<object> BulkImport(List<ExpandoObject> offices)
{
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.ImportData, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to import entity \"Office\" was denied to the user with Login ID {LoginId}. {offices}", this._LoginId, offices);
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 office in offices)
{
line++;
office.audit_user_id = this._UserId;
office.audit_ts = System.DateTime.UtcNow;
object primaryKeyValue = office.office_id;
if (Cast.To<int>(primaryKeyValue) > 0)
{
result.Add(office.office_id);
db.Update("config.offices", "office_id", office, office.office_id);
}
else
{
result.Add(db.Insert("config.offices", "office_id", office));
}
}
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 "config.offices" with an instance of "Office" class against the primary key value.
/// </summary>
/// <param name="office">The instance of "Office" class to update.</param>
/// <param name="officeId">The value of the column "office_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 office, int officeId)
{
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 \"Office\" with Primary Key {PrimaryKey} was denied to the user with Login ID {LoginId}. {Office}", officeId, this._LoginId, office);
throw new UnauthorizedException("Access is denied.");
}
}
Factory.Update(this._Catalog, office, officeId, "config.offices", "office_id");
}
/// <summary>
/// Deletes the row of the table "config.offices" against the primary key value.
/// </summary>
/// <param name="officeId">The value of the column "office_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 officeId)
{
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 \"Office\" with Primary Key {PrimaryKey} was denied to the user with Login ID {LoginId}.", officeId, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "DELETE FROM config.offices WHERE office_id=@0;";
Factory.NonQuery(this._Catalog, sql, officeId);
}
/// <summary>
/// Performs a select statement on table "config.offices" producing a paginated result of 10.
/// </summary>
/// <returns>Returns the first page of collection of "Office" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Config.Entities.Office> 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 \"Office\" was denied to the user with Login ID {LoginId}.", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM config.offices ORDER BY office_id LIMIT 10 OFFSET 0;";
return Factory.Get<Frapid.Config.Entities.Office>(this._Catalog, sql);
}
/// <summary>
/// Performs a select statement on table "config.offices" producing a paginated result of 10.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the paginated result.</param>
/// <returns>Returns collection of "Office" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Config.Entities.Office> 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 \"Office\" 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 config.offices ORDER BY office_id LIMIT 10 OFFSET @0;";
return Factory.Get<Frapid.Config.Entities.Office>(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='config.offices' AND lower(filter_name)=lower(@0);";
return Factory.Get<Frapid.DataAccess.Models.Filter>(catalog, sql, filterName).ToList();
}
/// <summary>
/// Performs a filtered count on table "config.offices".
/// </summary>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns number of rows of "Office" 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 \"Office\" 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 config.offices WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.Office(), filters);
return Factory.Scalar<long>(this._Catalog, sql);
}
/// <summary>
/// Performs a filtered select statement on table "config.offices" 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 "Office" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Config.Entities.Office> 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 \"Office\" 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 config.offices WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.Office(), filters);
sql.OrderBy("office_id");
if (pageNumber > 0)
{
sql.Append("LIMIT @0", 10);
sql.Append("OFFSET @0", offset);
}
return Factory.Get<Frapid.Config.Entities.Office>(this._Catalog, sql);
}
/// <summary>
/// Performs a filtered count on table "config.offices".
/// </summary>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns number of rows of "Office" 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 \"Office\" 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 config.offices WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.Office(), filters);
return Factory.Scalar<long>(this._Catalog, sql);
}
/// <summary>
/// Performs a filtered select statement on table "config.offices" 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 "Office" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Config.Entities.Office> 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 \"Office\" 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 config.offices WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.Office(), filters);
sql.OrderBy("office_id");
if (pageNumber > 0)
{
sql.Append("LIMIT @0", 10);
sql.Append("OFFSET @0", offset);
}
return Factory.Get<Frapid.Config.Entities.Office>(this._Catalog, sql);
}
}
}
| |
// JsonParser.cs
//
// Copyright (C) 2006 Andy Kernahan
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// 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
using System;
using System.IO;
using System.Text;
using System.Globalization;
namespace NetServ.Net.Json
{
/// <summary>
/// Provided support for parsing JavaScript Object Notation data types from
/// an underlying <see cref="System.IO.TextReader"/>.
/// </summary>
public class JsonParser : Disposable
{
#region Private Fields.
private int _depth;
private int _maxDepth = JsonParser.DEFAULT_MAX_DEPTH;
private readonly bool _ownsReader;
private TextReader _rdr;
private const int DEFAULT_MAX_DEPTH = 20;
#endregion
#region Public Interface.
/// <summary>
///
/// </summary>
[Serializable()]
public enum TokenType
{
/// <summary>
/// Begin array token.
/// </summary>
BeginArray,
/// <summary>
/// End array token.
/// </summary>
EndArray,
/// <summary>
/// Begin object token.
/// </summary>
BeginObject,
/// <summary>
/// End object token.
/// </summary>
EndObject,
/// <summary>
/// Member seperator token
/// </summary>
ValueSeperator,
/// <summary>
/// Object property name / value seperator token.
/// </summary>
NameSeperator,
/// <summary>
/// Start of string token.
/// </summary>
String,
/// <summary>
/// Start of number token.
/// </summary>
Number,
/// <summary>
/// Start of boolean token.
/// </summary>
Boolean,
/// <summary>
/// Start of null token.
/// </summary>
Null,
/// <summary>
/// End of input token.
/// </summary>
EOF,
}
/// <summary>
/// Initialises a new instance of the JsonParser class and specifies the source
/// <see cref="System.IO.TextReader"/> and a value indicating if the instance
/// owns the specified TextReader.
/// </summary>
/// <param name="rdr">The underlying TextReader.</param>
/// <param name="ownsReader">True if this instance owns the TextReader, otherwise;
/// false.</param>
public JsonParser(TextReader rdr, bool ownsReader) {
if(rdr == null)
throw new ArgumentNullException("rdr");
_rdr = rdr;
_ownsReader = ownsReader;
}
/// <summary>
/// Classifies the next token on the underlying stream.
/// </summary>
/// <returns>The classification of the next token from the underlying stream.</returns>
public TokenType NextToken() {
CheckDisposed();
int ch = Peek(true);
if(ch < 0)
return TokenType.EOF;
switch(ch) {
case JsonWriter.BeginArray:
return TokenType.BeginArray;
case JsonWriter.EndArray:
return TokenType.EndArray;
case JsonWriter.BeginObject:
return TokenType.BeginObject;
case JsonWriter.EndObject:
return TokenType.EndObject;
case JsonWriter.NameSeperator:
return TokenType.NameSeperator;
case JsonWriter.ValueSeperator:
return TokenType.ValueSeperator;
case '"':
return TokenType.String;
case 'n':
case 'N':
return TokenType.Null;
case 'f':
case 'F':
case 't':
case 'T':
return TokenType.Boolean;
case '.':
case '-':
case '+':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return TokenType.Number;
default:
throw new FormatException(string.Format(
"The character '{0}' does not start any valid token.",
((char)ch).ToString()));
}
}
/// <summary>
/// Parses a <see cref="NetServ.Net.Json.JsonBoolean"/> from the underlying
/// stream.
/// </summary>
/// <returns>The parsed JsonBoolean.</returns>
public JsonBoolean ParseBoolean() {
AssertNext(TokenType.Boolean);
int ch = Peek();
if(ch == 'f' || ch == 'F') {
if(Match(JsonBoolean.FalseString))
return JsonBoolean.False;
} else if(Match(JsonBoolean.TrueString))
return JsonBoolean.True;
throw new FormatException("The input contains a malformed Json-Boolean.");
}
/// <summary>
/// Parses a <see cref="NetServ.Net.Json.JsonNull"/> from the underlying
/// stream.
/// </summary>
/// <returns>The parsed JsonNull.</returns>
public JsonNull ParseNull() {
AssertNext(TokenType.Null);
if(Match(JsonNull.NullString))
return JsonNull.Null;
throw new FormatException("The input contains a malformed Json-Null.");
}
/// <summary>
/// Parses a <see cref="NetServ.Net.Json.JsonNumber"/> from the underlying
/// stream.
/// </summary>
/// <returns>The parsed JsonNumber.</returns>
public JsonNumber ParseNumber() {
AssertNext(TokenType.Number);
int ch;
double value;
StringBuilder sb = new StringBuilder();
while((ch = Peek()) > -1 && JsonParser.IsNumberComponent(ch))
sb.Append((char)Read());
if(double.TryParse(sb.ToString(), NumberStyles.Float, CultureInfo.InvariantCulture,
out value))
return new JsonNumber(value);
throw new FormatException("The input contains a malformed Json-Number.");
}
/// <summary>
/// Parses a <see cref="NetServ.Net.Json.JsonObject"/> and all contained types
/// from the underlying stream.
/// </summary>
/// <returns>The parsed JsonObject.</returns>
public virtual JsonObject ParseObject() {
AssertNext(TokenType.BeginObject);
AssertDepth(++this.Depth);
string key;
TokenType type;
SpState state = SpState.Initial;
JsonObject obj = new JsonObject();
// Move into the object.
for(Read(); ; ) {
switch(NextToken()) {
case TokenType.String:
key = ParseStringImpl();
if(NextToken() != TokenType.NameSeperator)
goto error;
Read();
break;
case TokenType.ValueSeperator:
if(state != SpState.SepValid)
goto error;
Read();
// Empty members are illegal.
state = SpState.ReqValue;
continue;
case TokenType.EndObject:
if(state == SpState.ReqValue)
goto error;
Read();
--this.Depth;
return obj;
default:
goto error;
}
switch(type = NextToken()) {
case TokenType.EndArray:
case TokenType.EndObject:
case TokenType.NameSeperator:
case TokenType.EOF:
case TokenType.ValueSeperator:
goto error;
default:
obj.Add(key, ParseNext(type));
state = SpState.SepValid;
break;
}
}
error:
throw new FormatException("The input contains a malformed Json-Object.");
}
/// <summary>
/// Parses a <see cref="NetServ.Net.Json.JsonArray"/> and all contained types
/// from the underlying stream.
/// </summary>
/// <returns>The parsed JsonArray.</returns>
public virtual JsonArray ParseArray() {
AssertNext(TokenType.BeginArray);
AssertDepth(++this.Depth);
TokenType type;
SpState state = SpState.Initial;
JsonArray arr = new JsonArray();
// Move into the array.
for(Read(); ; ) {
switch(type = NextToken()) {
case TokenType.EndArray:
if(state == SpState.ReqValue)
goto error;
Read();
--this.Depth;
return arr;
case TokenType.ValueSeperator:
if(state != SpState.SepValid)
goto error;
Read();
// Empty elements are illegal.
state = SpState.ReqValue;
break;
case TokenType.EndObject:
case TokenType.EOF:
case TokenType.NameSeperator:
goto error;
default:
arr.Add(ParseNext(type));
state = SpState.SepValid;
break;
}
}
error:
throw new FormatException("The input contains a malformed Json-Array.");
}
/// <summary>
/// Parses a <see cref="NetServ.Net.Json.JsonString"/> from the underlying stream.
/// </summary>
/// <returns>The parsed JsonString.</returns>
public JsonString ParseString() {
return new JsonString(ParseStringImpl());
}
/// <summary>
/// Parses the next type from the underlying stream.
/// </summary>
/// <returns>The next type from the underlying stream.</returns>
public IJsonType ParseNext() {
return ParseNext(NextToken());
}
/// <summary>
/// Parses the specified <paramref name="type"/> from the underlying stream.
/// </summary>
/// <param name="type">The type to parse.</param>
/// <returns>The type parsed from the underlying stream.</returns>
public virtual IJsonType ParseNext(TokenType type) {
switch(type) {
case TokenType.BeginArray:
return ParseArray();
case TokenType.BeginObject:
return ParseObject();
case TokenType.String:
return ParseString();
case TokenType.Number:
return ParseNumber();
case TokenType.Boolean:
return ParseBoolean();
case TokenType.Null:
return ParseNull();
default:
throw new System.ComponentModel.InvalidEnumArgumentException(
"type", type.GetHashCode(), typeof(TokenType));
}
}
/// <summary>
/// Closes this parser.
/// </summary>
public void Close() {
Dispose(true);
}
/// <summary>
/// Gets the current depth of the parser.
/// </summary>
public int Depth {
get { return _depth; }
protected set { _depth = value; }
}
/// <summary>
/// Gets or sets the maximum depth of structures before a
/// <see cref="System.FormatException"/> is thrown.
/// </summary>
public int MaximumDepth {
get { return _maxDepth; }
set {
if(value < 1)
throw new ArgumentOutOfRangeException("value");
_maxDepth = value;
}
}
#endregion
#region Protected Interface.
/// <summary>
/// Peeks at and returns a single character from the underlying stream.
/// </summary>
/// <returns>The character, otherwise; -1 if the end of the stream has been reached.</returns>
protected int Peek() {
CheckDisposed();
return this.Reader.Peek();
}
/// <summary>
/// Peeks at the next character from the underlying stream and specifies a value
/// which indicates whether white space characters should be advanced over.
/// </summary>
/// <param name="skipWhite">True to skip white space characters, otherwise; false.</param>
/// <returns>The next character from the underlying stream, or -1 if the end
/// has been reached.</returns>
protected int Peek(bool skipWhite) {
CheckDisposed();
if(!skipWhite)
return this.Reader.Peek();
int ch;
while((ch = this.Reader.Peek()) > 0) {
if(!char.IsWhiteSpace((char)ch))
return ch;
this.Reader.Read();
}
return -1;
}
/// <summary>
/// Reads and returns a single character from the underlying stream.
/// </summary>
/// <returns>The character, otherwise; -1 if the end of the stream has been reached.</returns>
protected int Read() {
CheckDisposed();
return this.Reader.Read();
}
/// <summary>
/// Reads the next character from the underlying stream and specified a value
/// which indicates whether white space characters should be skipped.
/// </summary>
/// <param name="skipWhite">True to skip white space characters, otherwise; false.</param>
/// <returns>The next character from the underlying stream, or -1 if the end
/// has been reached.</returns>
protected int Read(bool skipWhite) {
CheckDisposed();
if(!skipWhite)
return this.Reader.Read();
int ch;
while((ch = this.Reader.Read()) > 0) {
if(!char.IsWhiteSpace((char)ch))
return ch;
}
return -1;
}
/// <summary>
/// Asserts that the specified depth does not exceed
/// <see cref="P:NetServ.Net.Json.JsonParser.MaximumDepth"/>. If the depth has been
/// exceeded, a <see cref="System.FormatException"/> is thrown.
/// </summary>
/// <param name="depth">The depth.</param>
protected void AssertDepth(int depth) {
if(depth > this.MaximumDepth)
throw new FormatException(string.Format(
"The maximum depth of {0} has been exceeded.", this.MaximumDepth.ToString()));
}
/// <summary>
/// Disposed of this instance.
/// </summary>
/// <param name="disposing">True if being called explicitly, otherwise; false
/// to indicate being called implicitly by the GC.</param>
protected override void Dispose(bool disposing) {
if(!base.IsDisposed) {
try {
if(this.OwnsReader && disposing)
((IDisposable)this.Reader).Dispose();
} catch {
} finally {
this.Reader = null;
}
}
base.Dispose(disposing);
}
/// <summary>
/// Gets a value indicating if this instance owns it's
/// <see cref="P:NetServ.Net.Json.TextParser.Reader"/>.
/// </summary>
protected bool OwnsReader {
get { return _ownsReader; }
}
/// <summary>
/// Gets the underlying <see cref="System.IO.TextReader"/>.
/// </summary>
protected TextReader Reader {
get { return _rdr; }
private set { _rdr = value; }
}
#endregion
#region Private Impl.
/// <summary>
/// Structure parse state.
/// </summary>
private enum SpState
{
/// <summary>
/// Initial.
/// </summary>
Initial,
/// <summary>
/// A value is required.
/// </summary>
ReqValue,
/// <summary>
/// A seperator is currently valid.
/// </summary>
SepValid,
}
private bool Match(string value) {
// This method assumes that value is in lower case.
int ch;
for(int i = 0; i < value.Length; ++i) {
if((ch = Read()) < 0 || char.ToLowerInvariant((char)ch) != value[i])
return false;
}
return true;
}
private string ParseStringImpl() {
AssertNext(TokenType.String);
int ch;
StringBuilder sb = new StringBuilder();
// Move into the string.
Read();
while((ch = Read()) > -1) {
if(ch == '"')
return sb.ToString();
if(ch != '\\')
sb.Append((char)ch);
else {
if((ch = Read()) < 0)
goto error;
switch(ch) {
case '"':
sb.Append('"');
break;
case '/':
sb.Append('/');
break;
case '\\':
sb.Append('\\');
break;
case 'b':
sb.Append('\b');
break;
case 'f':
sb.Append('\f');
break;
case 'n':
sb.Append('\n');
break;
case 'r':
sb.Append('\r');
break;
case 't':
sb.Append('\t');
break;
case 'u':
sb.Append(ParseUnicode());
break;
default:
goto error;
}
}
}
error:
throw new FormatException("The input contains a malformed Json-String.");
}
private char ParseUnicode() {
int ch1 = Read();
int ch2 = Read();
int ch3 = Read();
int ch4 = Read();
if(ch1 > -1 && ch2 > -1 && ch3 > -1 && ch4 > -1)
return (char)(JsonParser.FromHex(ch1) << 12 | JsonParser.FromHex(ch2) << 8 |
JsonParser.FromHex(ch3) << 4 | JsonParser.FromHex((ch4)));
throw new FormatException("The input contains a malformed character escape.");
}
private static int FromHex(int ch) {
if(ch >= '0' && ch <= '9')
return ch - '0';
if(ch >= 'a' && ch <= 'f')
return (ch - 'a') + 10;
if(ch >= 'A' && ch <= 'F')
return (ch - 'A') + 10;
throw new FormatException("The input contains a malformed hexadecimal character escape.");
}
private static bool IsNumberComponent(int ch) {
return (ch >= '0' && ch <= '9') || ch == '-' || ch == '+' || ch == '.' ||
ch == 'e' || ch == 'E';
}
private void AssertNext(TokenType type) {
if(NextToken() != type)
throw new InvalidOperationException(
string.Format("Method must only be called when {0} is the next token.",
type.ToString()));
}
#endregion
}
}
| |
// <copyright file="GeometricTests.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
//
// Copyright (c) 2009-2014 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace MathNet.Numerics.UnitTests.DistributionTests.Discrete
{
using System;
using System.Linq;
using Distributions;
using NUnit.Framework;
/// <summary>
/// Geometric distribution tests.
/// </summary>
[TestFixture, Category("Distributions")]
public class GeometricTests
{
/// <summary>
/// Can create Geometric.
/// </summary>
/// <param name="p">Probability of generating a one.</param>
[TestCase(0.0)]
[TestCase(0.3)]
[TestCase(1.0)]
public void CanCreateGeometric(double p)
{
var d = new Geometric(p);
Assert.AreEqual(p, d.P);
}
/// <summary>
/// Geometric create fails with bad parameters.
/// </summary>
/// <param name="p">Probability of generating a one.</param>
[TestCase(Double.NaN)]
[TestCase(-1.0)]
[TestCase(2.0)]
public void GeometricCreateFailsWithBadParameters(double p)
{
Assert.That(() => new Geometric(p), Throws.ArgumentException);
}
/// <summary>
/// Validate ToString.
/// </summary>
[Test]
public void ValidateToString()
{
var d = new Geometric(0.3);
Assert.AreEqual("Geometric(p = 0.3)", d.ToString());
}
/// <summary>
/// Validate entropy.
/// </summary>
/// <param name="p">Probability of generating a one.</param>
[TestCase(0.0)]
[TestCase(0.3)]
[TestCase(1.0)]
public void ValidateEntropy(double p)
{
var d = new Geometric(p);
Assert.AreEqual(((-p * Math.Log(p, 2.0)) - ((1.0 - p) * Math.Log(1.0 - p, 2.0))) / p, d.Entropy);
}
/// <summary>
/// Validate skewness.
/// </summary>
/// <param name="p">Probability of generating a one.</param>
[TestCase(0.0)]
[TestCase(0.3)]
[TestCase(1.0)]
public void ValidateSkewness(double p)
{
var d = new Geometric(p);
Assert.AreEqual((2.0 - p) / Math.Sqrt(1.0 - p), d.Skewness);
}
/// <summary>
/// Validate mode.
/// </summary>
/// <param name="p">Probability of generating a one.</param>
[TestCase(0.0)]
[TestCase(0.3)]
[TestCase(1.0)]
public void ValidateMode(double p)
{
var d = new Geometric(p);
Assert.AreEqual(1, d.Mode);
}
[TestCase(0.0, double.PositiveInfinity)]
[TestCase(0.0001, 6932.0)]
[TestCase(0.1, 7.0)]
[TestCase(0.3, 2.0)]
[TestCase(0.9, 1.0)]
[TestCase(1.0, 1.0)]
public void ValidateMedian(double p, double expected)
{
Assert.That(new Geometric(p).Median, Is.EqualTo(expected));
}
/// <summary>
/// Validate minimum.
/// </summary>
[Test]
public void ValidateMinimum()
{
var d = new Geometric(0.3);
Assert.AreEqual(1.0, d.Minimum);
}
/// <summary>
/// Validate maximum.
/// </summary>
[Test]
public void ValidateMaximum()
{
var d = new Geometric(0.3);
Assert.AreEqual(int.MaxValue, d.Maximum);
}
/// <summary>
/// Validate probability.
/// </summary>
/// <param name="p">Probability of generating a one.</param>
/// <param name="x">Input X value.</param>
[TestCase(0.0, -1)]
[TestCase(0.3, 0)]
[TestCase(1.0, 1)]
[TestCase(1.0, 2)]
public void ValidateProbability(double p, int x)
{
var d = new Geometric(p);
if (x > 0)
{
Assert.AreEqual(Math.Pow(1.0 - p, x - 1) * p, d.Probability(x));
}
else
{
Assert.AreEqual(0.0, d.Probability(x));
}
}
/// <summary>
/// Validate probability log.
/// </summary>
/// <param name="p">Probability of generating a one.</param>
/// <param name="x">Input X value.</param>
/// <param name="pln">Expected value.</param>
[TestCase(0.0, -1, Double.NegativeInfinity)]
[TestCase(0.0, 0, 0.0)]
[TestCase(0.0, 1, Double.NegativeInfinity)]
[TestCase(0.0, 2, Double.NegativeInfinity)]
[TestCase(0.3, -1, Double.NegativeInfinity)]
[TestCase(0.3, 0, -0.35667494393873244235395440410727451457180907089949815)]
[TestCase(0.3, 1, -1.2039728043259360296301803719337238685164245381839102)]
[TestCase(0.3, 2, Double.NegativeInfinity)]
[TestCase(1.0, -1, Double.NegativeInfinity)]
[TestCase(1.0, 0, Double.NegativeInfinity)]
[TestCase(1.0, 1, 0.0)]
[TestCase(1.0, 2, Double.NegativeInfinity)]
public void ValidateProbabilityLn(double p, int x, double pln)
{
var d = new Geometric(p);
if (x > 0)
{
Assert.AreEqual(((x - 1) * Math.Log(1.0 - p)) + Math.Log(p), d.ProbabilityLn(x));
}
else
{
Assert.AreEqual(Double.NegativeInfinity, d.ProbabilityLn(x));
}
}
/// <summary>
/// Can sample.
/// </summary>
[Test]
public void CanSample()
{
var d = new Geometric(0.3);
d.Sample();
}
/// <summary>
/// Can sample sequence.
/// </summary>
[Test]
public void CanSampleSequence()
{
var d = new Geometric(0.3);
var ied = d.Samples();
GC.KeepAlive(ied.Take(5).ToArray());
}
/// <summary>
/// Validate cumulative distribution.
/// </summary>
/// <param name="p">Probability of generating a one.</param>
/// <param name="x">Input X value.</param>
[TestCase(0.0, -1)]
[TestCase(0.3, 0)]
[TestCase(1.0, 1)]
[TestCase(1.0, 2)]
public void ValidateCumulativeDistribution(double p, int x)
{
var d = new Geometric(p);
Assert.AreEqual(1.0 - Math.Pow(1.0 - p, x), d.CumulativeDistribution(x));
}
}
}
| |
#region MIT License
/*
* Copyright (c) 2005-2008 Jonathan Mark Porter. http://physics2d.googlepages.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.
*/
#endregion
#if UseDouble
using Scalar = System.Double;
#else
using Scalar = System.Single;
#endif
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Drawing;
using AdvanceMath;
using AdvanceMath.Geometry2D;
using Physics2DDotNet;
using Physics2DDotNet.Shapes;
using Physics2DDotNet.Collections;
using Tao.OpenGl;
using SdlDotNet.Graphics;
using SdlDotNet.Core;
using SdlDotNet.Input;
namespace Graphics2DDotNet
{
/// <summary>
/// This is the window. the actaul window that will appear. It holds the timer that will
/// Draw scenes via viewports.
/// </summary>
public class Window
{
public event EventHandler<CollectionEventArgs<Viewport>> ViewportsAdded
{
add { viewports.ItemsAdded += value; }
remove { viewports.ItemsAdded -= value; }
}
public event EventHandler<CollectionEventArgs<Viewport>> ViewportsRemoved
{
add { viewports.ItemsRemoved += value; }
remove { viewports.ItemsRemoved -= value; }
}
public event EventHandler<SizeEventArgs> Resized;
object syncRoot;
Surface screen;
Size size;
bool isResized;
PendableCollection<Window, Viewport> viewports;
int drawCount;
int refreshCount;
PhysicsTimer drawTimer;
bool isRunning;
[NonSerialized]
AdvReaderWriterLock rwLock;
public Window(Size size)
{
this.size = size;
this.drawTimer = new PhysicsTimer(GraphicsProcess, .01f);
this.viewports = new PendableCollection<Window, Viewport>(this);
this.syncRoot = new object();
this.rwLock = new AdvReaderWriterLock();
}
public string Title
{
get { return Video.WindowCaption; }
set { Video.WindowCaption = value; }
}
public Size Size { get { return size; } }
public Scalar DrawingInterval
{
get { return drawTimer.TargetInterval; }
set { drawTimer.TargetInterval = value; }
}
public bool IsRunning
{
get { return isRunning; }
}
public ReadOnlyThreadSafeCollection<Viewport> Viewports
{
get
{
return new ReadOnlyThreadSafeCollection<Viewport>(rwLock, viewports.Items);
}
}
private void GraphicsProcess(Scalar dt, Scalar trueDt)
{
while (Events.Poll()) { }
if (isResized)
{
Init();
Resize();
isResized = false;
}
GlHelper.DoDelete(refreshCount);
Gl.glClear(Gl.GL_COLOR_BUFFER_BIT | Gl.GL_DEPTH_BUFFER_BIT);
Draw(dt, trueDt);
Video.GLSwapBuffers();
}
void Draw(Scalar dt, Scalar trueDt)
{
rwLock.EnterWrite();
try
{
viewports.RemoveExpired();
lock (syncRoot)
{
viewports.AddPending();
}
viewports.CheckZOrder();
drawCount++;
DrawInfo drawInfo = new DrawInfo(dt, trueDt, drawCount, refreshCount);
foreach (Viewport viewport in viewports.Items)
{
viewport.Draw(drawInfo);
}
}
finally
{
rwLock.ExitWrite();
}
}
void Init()
{
Gl.glShadeModel(Gl.GL_SMOOTH);
Gl.glClearColor(0, 0, 0, 0.5f);
Gl.glClearDepth(1);
Gl.glEnable(Gl.GL_DEPTH_TEST);
Gl.glDepthFunc(Gl.GL_LEQUAL);
Gl.glHint(Gl.GL_PERSPECTIVE_CORRECTION_HINT, Gl.GL_NICEST);
}
void Resize()
{
refreshCount++;
size.Width = screen.Width;
size.Height = screen.Height;
}
bool isIntialized;
public void Intialize()
{
if (!isIntialized)
{
isIntialized = true;
Video.WindowIcon();
screen = Video.SetVideoMode(size.Width, size.Height, true, true);
Events.VideoResize += OnVideoResize;
Events.Quit += OnQuit;
Init();
}
}
/// <summary>
/// Starts the drawing loop.
/// </summary>
public void Run()
{
isRunning = true;
Intialize();
drawTimer.RunOnCurrentThread();
isRunning = false;
Events.Close();
}
void OnQuit(object sender, QuitEventArgs e)
{
Quit();
Events.QuitApplication();
}
void OnVideoResize(object sender, VideoResizeEventArgs e)
{
isResized = e.Height != size.Height || e.Width != size.Width;
if (isResized)
{
screen = Video.SetVideoMode(e.Width, e.Height, true, true);
if (Resized != null) { Resized(this, new SizeEventArgs(e.Width, e.Height)); }
}
}
public void Quit()
{
this.drawTimer.Dispose();
}
public void AddViewport(Viewport item)
{
lock (syncRoot)
{
viewports.Add(item);
}
}
public void AddViewportRange(ICollection<Viewport> collection)
{
lock (syncRoot)
{
viewports.AddRange(collection);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Sql
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ServersOperations operations.
/// </summary>
public partial interface IServersOperations
{
/// <summary>
/// Creates or updates a firewall rule.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can
/// obtain this value from the Azure Resource Manager API or the
/// portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='firewallRuleName'>
/// The name of the firewall rule.
/// </param>
/// <param name='parameters'>
/// The required parameters for creating or updating a firewall rule.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ServerFirewallRule>> CreateOrUpdateFirewallRuleWithHttpMessagesAsync(string resourceGroupName, string serverName, string firewallRuleName, ServerFirewallRule parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a firewall rule.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can
/// obtain this value from the Azure Resource Manager API or the
/// portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='firewallRuleName'>
/// The name of the firewall rule.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteFirewallRuleWithHttpMessagesAsync(string resourceGroupName, string serverName, string firewallRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets a firewall rule.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can
/// obtain this value from the Azure Resource Manager API or the
/// portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='firewallRuleName'>
/// The name of the firewall rule.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ServerFirewallRule>> GetFirewallRuleWithHttpMessagesAsync(string resourceGroupName, string serverName, string firewallRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns a list of firewall rules.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can
/// obtain this value from the Azure Resource Manager API or the
/// portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IEnumerable<ServerFirewallRule>>> ListFirewallRulesWithHttpMessagesAsync(string resourceGroupName, string serverName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Imports a bacpac into a new database.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can
/// obtain this value from the Azure Resource Manager API or the
/// portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='parameters'>
/// The required parameters for importing a Bacpac into a database.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ImportExportOperationResponse>> ImportDatabaseWithHttpMessagesAsync(string resourceGroupName, string serverName, ImportRequestParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns a list of servers.
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IEnumerable<Server>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a new server.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can
/// obtain this value from the Azure Resource Manager API or the
/// portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='parameters'>
/// The required parameters for creating or updating a server.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<Server>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, Server parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a SQL server.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can
/// obtain this value from the Azure Resource Manager API or the
/// portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string serverName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets a server.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can
/// obtain this value from the Azure Resource Manager API or the
/// portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<Server>> GetByResourceGroupWithHttpMessagesAsync(string resourceGroupName, string serverName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns a list of servers in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can
/// obtain this value from the Azure Resource Manager API or the
/// portal.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IEnumerable<Server>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns server usages.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can
/// obtain this value from the Azure Resource Manager API or the
/// portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IEnumerable<ServerMetric>>> ListUsagesWithHttpMessagesAsync(string resourceGroupName, string serverName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets a database service objective.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can
/// obtain this value from the Azure Resource Manager API or the
/// portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='serviceObjectiveName'>
/// The name of the service objective to retrieve.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ServiceObjective>> GetServiceObjectiveWithHttpMessagesAsync(string resourceGroupName, string serverName, string serviceObjectiveName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns database service objectives.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can
/// obtain this value from the Azure Resource Manager API or the
/// portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IEnumerable<ServiceObjective>>> ListServiceObjectivesWithHttpMessagesAsync(string resourceGroupName, string serverName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Imports a bacpac into a new database.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can
/// obtain this value from the Azure Resource Manager API or the
/// portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='parameters'>
/// The required parameters for importing a Bacpac into a database.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ImportExportOperationResponse>> BeginImportDatabaseWithHttpMessagesAsync(string resourceGroupName, string serverName, ImportRequestParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using System.Threading.Tasks;
namespace Bridge.jQuery2
{
public partial class jQuery
{
/// <summary>
/// Display the matched elements by fading them to opaque.
/// </summary>
/// <returns></returns>
public virtual jQuery FadeIn()
{
return null;
}
[Template("Bridge.Task.fromPromise({this}.fadeIn())")]
public virtual Task FadeInTask()
{
return null;
}
[Template("Bridge.Task.fromPromise({this}.fadeIn({0}))")]
public virtual Task FadeInTask(int duration)
{
return null;
}
[Template("Bridge.Task.fromPromise({this}.fadeIn({0}, {1}))")]
public virtual Task FadeInTask(int duration, string easing)
{
return null;
}
[Template("Bridge.Task.fromPromise({this}.fadeIn({0}))")]
public virtual Task FadeInTask(EffectOptions options)
{
return null;
}
[Template("Bridge.Task.fromPromise({this}.fadeOut())")]
public virtual Task FadeOutTask()
{
return null;
}
[Template("Bridge.Task.fromPromise({this}.fadeOut({0}))")]
public virtual Task FadeOutTask(int duration)
{
return null;
}
[Template("Bridge.Task.fromPromise({this}.fadeOut({0}, {1}))")]
public virtual Task FadeOutTask(int duration, string easing)
{
return null;
}
[Template("Bridge.Task.fromPromise({this}.fadeOut({0}))")]
public virtual Task FadeOutTask(EffectOptions options)
{
return null;
}
/// <summary>
/// Display the matched elements by fading them to opaque.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <returns></returns>
public virtual jQuery FadeIn(int duration)
{
return null;
}
/// <summary>
/// Display the matched elements by fading them to opaque.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeIn(int duration, Delegate complete)
{
return null;
}
/// <summary>
/// Display the matched elements by fading them to opaque.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeIn(int duration, Action complete)
{
return null;
}
/// <summary>
/// Display the matched elements by fading them to opaque.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <returns></returns>
public virtual jQuery FadeIn(string duration)
{
return null;
}
/// <summary>
/// Display the matched elements by fading them to opaque.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeIn(string duration, Delegate complete)
{
return null;
}
/// <summary>
/// Display the matched elements by fading them to opaque.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeIn(string duration, Action complete)
{
return null;
}
/// <summary>
/// Display the matched elements by fading them to opaque.
/// </summary>
/// <param name="options">A map of additional options to pass to the method.</param>
/// <returns></returns>
public virtual jQuery FadeIn(EffectOptions options)
{
return null;
}
/// <summary>
/// Display the matched elements by fading them to opaque.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <returns></returns>
public virtual jQuery FadeIn(int duration, string easing)
{
return null;
}
/// <summary>
/// Display the matched elements by fading them to opaque.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <returns></returns>
public virtual jQuery FadeIn(string duration, string easing)
{
return null;
}
/// <summary>
/// Display the matched elements by fading them to opaque.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeIn(int duration, string easing, Delegate complete)
{
return null;
}
/// <summary>
/// Display the matched elements by fading them to opaque.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeIn(int duration, string easing, Action complete)
{
return null;
}
/// <summary>
/// Display the matched elements by fading them to opaque.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeIn(string duration, string easing, Delegate complete)
{
return null;
}
/// <summary>
/// Display the matched elements by fading them to opaque.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeIn(string duration, string easing, Action complete)
{
return null;
}
/// <summary>
/// Hide the matched elements by fading them to transparent.
/// </summary>
/// <returns></returns>
public virtual jQuery FadeOut()
{
return null;
}
/// <summary>
/// Hide the matched elements by fading them to transparent.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <returns></returns>
public virtual jQuery FadeOut(int duration)
{
return null;
}
/// <summary>
/// Hide the matched elements by fading them to transparent.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeOut(int duration, Delegate complete)
{
return null;
}
/// <summary>
/// Hide the matched elements by fading them to transparent.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeOut(int duration, Action complete)
{
return null;
}
/// <summary>
/// Hide the matched elements by fading them to transparent.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <returns></returns>
public virtual jQuery FadeOut(string duration)
{
return null;
}
/// <summary>
/// Hide the matched elements by fading them to transparent.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeOut(string duration, Delegate complete)
{
return null;
}
/// <summary>
/// Hide the matched elements by fading them to transparent.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeOut(string duration, Action complete)
{
return null;
}
/// <summary>
/// Hide the matched elements by fading them to transparent.
/// </summary>
/// <param name="options">A map of additional options to pass to the method.</param>
/// <returns></returns>
public virtual jQuery FadeOut(EffectOptions options)
{
return null;
}
/// <summary>
/// Hide the matched elements by fading them to transparent.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <returns></returns>
public virtual jQuery FadeOut(int duration, string easing)
{
return null;
}
/// <summary>
/// Hide the matched elements by fading them to transparent.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <returns></returns>
public virtual jQuery FadeOut(string duration, string easing)
{
return null;
}
/// <summary>
/// Hide the matched elements by fading them to transparent.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeOut(int duration, string easing, Delegate complete)
{
return null;
}
/// <summary>
/// Hide the matched elements by fading them to transparent.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeOut(int duration, string easing, Action complete)
{
return null;
}
/// <summary>
/// Hide the matched elements by fading them to transparent.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeOut(string duration, string easing, Delegate complete)
{
return null;
}
/// <summary>
/// Hide the matched elements by fading them to transparent.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeOut(string duration, string easing, Action complete)
{
return null;
}
/// <summary>
/// Adjust the opacity of the matched elements.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <returns></returns>
public virtual jQuery FadeTo(int duration)
{
return null;
}
/// <summary>
/// Adjust the opacity of the matched elements.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <returns></returns>
public virtual jQuery FadeTo(string duration)
{
return null;
}
/// <summary>
/// Adjust the opacity of the matched elements.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="opacity">A number between 0 and 1 denoting the target opacity.</param>
/// <returns></returns>
public virtual jQuery FadeTo(int duration, double opacity)
{
return null;
}
/// <summary>
/// Adjust the opacity of the matched elements.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="opacity">A number between 0 and 1 denoting the target opacity.</param>
/// <returns></returns>
public virtual jQuery FadeTo(string duration, double opacity)
{
return null;
}
/// <summary>
/// Adjust the opacity of the matched elements.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="opacity">A number between 0 and 1 denoting the target opacity.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeTo(int duration, double opacity, Delegate complete)
{
return null;
}
/// <summary>
/// Adjust the opacity of the matched elements.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="opacity">A number between 0 and 1 denoting the target opacity.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeTo(int duration, double opacity, Action complete)
{
return null;
}
/// <summary>
/// Adjust the opacity of the matched elements.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="opacity">A number between 0 and 1 denoting the target opacity.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeTo(string duration, double opacity, Delegate complete)
{
return null;
}
/// <summary>
/// Adjust the opacity of the matched elements.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="opacity">A number between 0 and 1 denoting the target opacity.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeTo(string duration, double opacity, Action complete)
{
return null;
}
/// <summary>
/// Adjust the opacity of the matched elements.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="opacity">A number between 0 and 1 denoting the target opacity.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <returns></returns>
public virtual jQuery FadeTo(int duration, double opacity, string easing)
{
return null;
}
/// <summary>
/// Adjust the opacity of the matched elements.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="opacity">A number between 0 and 1 denoting the target opacity.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <returns></returns>
public virtual jQuery FadeTo(string duration, double opacity, string easing)
{
return null;
}
/// <summary>
/// Adjust the opacity of the matched elements.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="opacity">A number between 0 and 1 denoting the target opacity.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeTo(int duration, double opacity, string easing, Delegate complete)
{
return null;
}
/// <summary>
/// Adjust the opacity of the matched elements.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="opacity">A number between 0 and 1 denoting the target opacity.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeTo(int duration, double opacity, string easing, Action complete)
{
return null;
}
/// <summary>
/// Adjust the opacity of the matched elements.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="opacity">A number between 0 and 1 denoting the target opacity.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeTo(string duration, double opacity, string easing, Delegate complete)
{
return null;
}
/// <summary>
/// Adjust the opacity of the matched elements.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="opacity">A number between 0 and 1 denoting the target opacity.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeTo(string duration, double opacity, string easing, Action complete)
{
return null;
}
/// <summary>
/// Display or hide the matched elements by animating their opacity.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <returns></returns>
public virtual jQuery FadeToggle(int duration)
{
return null;
}
/// <summary>
/// Display or hide the matched elements by animating their opacity.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <returns></returns>
public virtual jQuery FadeToggle(string duration)
{
return null;
}
/// <summary>
/// Display or hide the matched elements by animating their opacity.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <returns></returns>
public virtual jQuery FadeToggle(int duration, string easing)
{
return null;
}
/// <summary>
/// Display or hide the matched elements by animating their opacity.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <returns></returns>
public virtual jQuery FadeToggle(string duration, string easing)
{
return null;
}
/// <summary>
/// Display or hide the matched elements by animating their opacity.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeToggle(int duration, string easing, Delegate complete)
{
return null;
}
/// <summary>
/// Display or hide the matched elements by animating their opacity.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeToggle(int duration, string easing, Action complete)
{
return null;
}
/// <summary>
/// Display or hide the matched elements by animating their opacity.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeToggle(string duration, string easing, Delegate complete)
{
return null;
}
/// <summary>
/// Display or hide the matched elements by animating their opacity.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeToggle(string duration, string easing, Action complete)
{
return null;
}
/// <summary>
/// Display or hide the matched elements by animating their opacity.
/// </summary>
/// <param name="options">A map of additional options to pass to the method.</param>
/// <returns></returns>
public virtual jQuery FadeToggle(EffectOptions options)
{
return null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.NetCore.Extensions;
namespace System.Tests
{
public class EnvironmentTests : RemoteExecutorTestBase
{
[Fact]
public void CurrentDirectory_Null_Path_Throws_ArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("value", () => Environment.CurrentDirectory = null);
}
[Fact]
public void CurrentDirectory_Empty_Path_Throws_ArgumentException()
{
AssertExtensions.Throws<ArgumentException>("value", () => Environment.CurrentDirectory = string.Empty);
}
[Fact]
public void CurrentDirectory_SetToNonExistentDirectory_ThrowsDirectoryNotFoundException()
{
Assert.Throws<DirectoryNotFoundException>(() => Environment.CurrentDirectory = GetTestFilePath());
}
[Fact]
public void CurrentDirectory_SetToValidOtherDirectory()
{
RemoteInvoke(() =>
{
Environment.CurrentDirectory = TestDirectory;
Assert.Equal(Directory.GetCurrentDirectory(), Environment.CurrentDirectory);
if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
// On OSX, the temp directory /tmp/ is a symlink to /private/tmp, so setting the current
// directory to a symlinked path will result in GetCurrentDirectory returning the absolute
// path that followed the symlink.
Assert.Equal(TestDirectory, Directory.GetCurrentDirectory());
}
return SuccessExitCode;
}).Dispose();
}
[Fact]
public void CurrentManagedThreadId_Idempotent()
{
Assert.Equal(Environment.CurrentManagedThreadId, Environment.CurrentManagedThreadId);
}
[Fact]
public void CurrentManagedThreadId_DifferentForActiveThreads()
{
var ids = new HashSet<int>();
Barrier b = new Barrier(10);
Task.WaitAll((from i in Enumerable.Range(0, b.ParticipantCount)
select Task.Factory.StartNew(() =>
{
b.SignalAndWait();
lock (ids) ids.Add(Environment.CurrentManagedThreadId);
b.SignalAndWait();
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)).ToArray());
Assert.Equal(b.ParticipantCount, ids.Count);
}
[Fact]
public void HasShutdownStarted_FalseWhileExecuting()
{
Assert.False(Environment.HasShutdownStarted);
}
[Fact]
public void Is64BitProcess_MatchesIntPtrSize()
{
Assert.Equal(IntPtr.Size == 8, Environment.Is64BitProcess);
}
[Fact]
public void Is64BitOperatingSystem_TrueIf64BitProcess()
{
if (Environment.Is64BitProcess)
{
Assert.True(Environment.Is64BitOperatingSystem);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests OS-specific environment
public void Is64BitOperatingSystem_Unix_TrueIff64BitProcess()
{
Assert.Equal(Environment.Is64BitProcess, Environment.Is64BitOperatingSystem);
}
[Fact]
public void OSVersion_Idempotent()
{
Assert.Same(Environment.OSVersion, Environment.OSVersion);
}
[Fact]
public void OSVersion_MatchesPlatform()
{
PlatformID id = Environment.OSVersion.Platform;
Assert.Equal(
RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? PlatformID.Win32NT : PlatformID.Unix,
id);
}
[Fact]
public void OSVersion_ValidVersion()
{
Version version = Environment.OSVersion.Version;
string versionString = Environment.OSVersion.VersionString;
Assert.False(string.IsNullOrWhiteSpace(versionString), "Expected non-empty version string");
Assert.True(version.Major > 0);
Assert.Contains(version.ToString(2), versionString);
Assert.Contains(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "Windows" : "Unix", versionString);
}
[Fact]
public void SystemPageSize_Valid()
{
int pageSize = Environment.SystemPageSize;
Assert.Equal(pageSize, Environment.SystemPageSize);
Assert.True(pageSize > 0, "Expected positive page size");
Assert.True((pageSize & (pageSize - 1)) == 0, "Expected power-of-2 page size");
}
[Fact]
public void UserInteractive_True()
{
Assert.True(Environment.UserInteractive);
}
[Fact]
public void UserName_Valid()
{
Assert.False(string.IsNullOrWhiteSpace(Environment.UserName));
}
[Fact]
public void UserDomainName_Valid()
{
Assert.False(string.IsNullOrWhiteSpace(Environment.UserDomainName));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests OS-specific environment
public void UserDomainName_Unix_MatchesMachineName()
{
Assert.Equal(Environment.MachineName, Environment.UserDomainName);
}
[Fact]
public void Version_MatchesFixedVersion()
{
Assert.Equal(new Version(4, 0, 30319, 42000), Environment.Version);
}
[Fact]
public void WorkingSet_Valid()
{
Assert.True(Environment.WorkingSet > 0, "Expected positive WorkingSet value");
}
[Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // fail fast crashes the process
[OuterLoop]
[Fact]
public void FailFast_ExpectFailureExitCode()
{
using (Process p = RemoteInvoke(() => { Environment.FailFast("message"); return SuccessExitCode; }).Process)
{
p.WaitForExit();
Assert.NotEqual(SuccessExitCode, p.ExitCode);
}
using (Process p = RemoteInvoke(() => { Environment.FailFast("message", new Exception("uh oh")); return SuccessExitCode; }).Process)
{
p.WaitForExit();
Assert.NotEqual(SuccessExitCode, p.ExitCode);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests OS-specific environment
public void GetFolderPath_Unix_PersonalIsHomeAndUserProfile()
{
Assert.Equal(Environment.GetEnvironmentVariable("HOME"), Environment.GetFolderPath(Environment.SpecialFolder.Personal));
Assert.Equal(Environment.GetEnvironmentVariable("HOME"), Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
Assert.Equal(Environment.GetEnvironmentVariable("HOME"), Environment.GetFolderPath(Environment.SpecialFolder.UserProfile));
}
[Fact]
public void GetSystemDirectory()
{
Assert.Equal(Environment.GetFolderPath(Environment.SpecialFolder.System), Environment.SystemDirectory);
}
[Theory]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests OS-specific environment
[InlineData(Environment.SpecialFolder.UserProfile, Environment.SpecialFolderOption.None)]
[InlineData(Environment.SpecialFolder.Personal, Environment.SpecialFolderOption.None)]
[InlineData(Environment.SpecialFolder.MyDocuments, Environment.SpecialFolderOption.None)]
[InlineData(Environment.SpecialFolder.CommonApplicationData, Environment.SpecialFolderOption.None)]
[InlineData(Environment.SpecialFolder.CommonTemplates, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.ApplicationData, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.Desktop, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.DesktopDirectory, Environment.SpecialFolderOption.DoNotVerify)]
// Not set on Unix (amongst others)
//[InlineData(Environment.SpecialFolder.System, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.Templates, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.MyVideos, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.MyMusic, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.MyPictures, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.Fonts, Environment.SpecialFolderOption.DoNotVerify)]
public void GetFolderPath_Unix_NonEmptyFolderPaths(Environment.SpecialFolder folder, Environment.SpecialFolderOption option)
{
Assert.NotEmpty(Environment.GetFolderPath(folder, option));
if (option == Environment.SpecialFolderOption.None)
{
Assert.NotEmpty(Environment.GetFolderPath(folder));
}
}
[Theory]
[PlatformSpecific(TestPlatforms.OSX)] // Tests OS-specific environment
[InlineData(Environment.SpecialFolder.Favorites, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.InternetCache, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.ProgramFiles, Environment.SpecialFolderOption.None)]
[InlineData(Environment.SpecialFolder.System, Environment.SpecialFolderOption.None)]
public void GetFolderPath_OSX_NonEmptyFolderPaths(Environment.SpecialFolder folder, Environment.SpecialFolderOption option)
{
Assert.NotEmpty(Environment.GetFolderPath(folder, option));
if (option == Environment.SpecialFolderOption.None)
{
Assert.NotEmpty(Environment.GetFolderPath(folder));
}
}
// The commented out folders aren't set on all systems.
[Theory]
[InlineData(Environment.SpecialFolder.ApplicationData)]
[InlineData(Environment.SpecialFolder.CommonApplicationData)]
[InlineData(Environment.SpecialFolder.LocalApplicationData)]
[InlineData(Environment.SpecialFolder.Cookies)]
[InlineData(Environment.SpecialFolder.Desktop)]
[InlineData(Environment.SpecialFolder.Favorites)]
[InlineData(Environment.SpecialFolder.History)]
[InlineData(Environment.SpecialFolder.InternetCache)]
[InlineData(Environment.SpecialFolder.Programs)]
// [InlineData(Environment.SpecialFolder.MyComputer)]
[InlineData(Environment.SpecialFolder.MyMusic)]
[InlineData(Environment.SpecialFolder.MyPictures)]
[InlineData(Environment.SpecialFolder.MyVideos)]
[InlineData(Environment.SpecialFolder.Recent)]
[InlineData(Environment.SpecialFolder.SendTo)]
[InlineData(Environment.SpecialFolder.StartMenu)]
[InlineData(Environment.SpecialFolder.Startup)]
[InlineData(Environment.SpecialFolder.System)]
[InlineData(Environment.SpecialFolder.Templates)]
[InlineData(Environment.SpecialFolder.DesktopDirectory)]
[InlineData(Environment.SpecialFolder.Personal)]
[InlineData(Environment.SpecialFolder.ProgramFiles)]
[InlineData(Environment.SpecialFolder.CommonProgramFiles)]
[InlineData(Environment.SpecialFolder.AdminTools)]
[InlineData(Environment.SpecialFolder.CDBurning)]
[InlineData(Environment.SpecialFolder.CommonAdminTools)]
[InlineData(Environment.SpecialFolder.CommonDocuments)]
[InlineData(Environment.SpecialFolder.CommonMusic)]
// [InlineData(Environment.SpecialFolder.CommonOemLinks)]
[InlineData(Environment.SpecialFolder.CommonPictures)]
[InlineData(Environment.SpecialFolder.CommonStartMenu)]
[InlineData(Environment.SpecialFolder.CommonPrograms)]
[InlineData(Environment.SpecialFolder.CommonStartup)]
[InlineData(Environment.SpecialFolder.CommonDesktopDirectory)]
[InlineData(Environment.SpecialFolder.CommonTemplates)]
[InlineData(Environment.SpecialFolder.CommonVideos)]
[InlineData(Environment.SpecialFolder.Fonts)]
[InlineData(Environment.SpecialFolder.NetworkShortcuts)]
// [InlineData(Environment.SpecialFolder.PrinterShortcuts)]
[InlineData(Environment.SpecialFolder.UserProfile)]
[InlineData(Environment.SpecialFolder.CommonProgramFilesX86)]
[InlineData(Environment.SpecialFolder.ProgramFilesX86)]
[InlineData(Environment.SpecialFolder.Resources)]
// [InlineData(Environment.SpecialFolder.LocalizedResources)]
[InlineData(Environment.SpecialFolder.SystemX86)]
[InlineData(Environment.SpecialFolder.Windows)]
[PlatformSpecific(TestPlatforms.Windows)] // Tests OS-specific environment
public unsafe void GetFolderPath_Windows(Environment.SpecialFolder folder)
{
string knownFolder = Environment.GetFolderPath(folder);
Assert.NotEmpty(knownFolder);
// Call the older folder API to compare our results.
char* buffer = stackalloc char[260];
SHGetFolderPathW(IntPtr.Zero, (int)folder, IntPtr.Zero, 0, buffer);
string folderPath = new string(buffer);
Assert.Equal(folderPath, knownFolder);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Uses P/Invokes
public void GetLogicalDrives_Unix_AtLeastOneIsRoot()
{
string[] drives = Environment.GetLogicalDrives();
Assert.NotNull(drives);
Assert.True(drives.Length > 0, "Expected at least one drive");
Assert.All(drives, d => Assert.NotNull(d));
Assert.Contains(drives, d => d == "/");
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes
public void GetLogicalDrives_Windows_MatchesExpectedLetters()
{
string[] drives = Environment.GetLogicalDrives();
uint mask = (uint)GetLogicalDrives();
var bits = new BitArray(new[] { (int)mask });
Assert.Equal(bits.Cast<bool>().Count(b => b), drives.Length);
for (int bit = 0, d = 0; bit < bits.Length; bit++)
{
if (bits[bit])
{
Assert.Contains((char)('A' + bit), drives[d++]);
}
}
}
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern int GetLogicalDrives();
[DllImport("shell32.dll", SetLastError = false, BestFitMapping = false, ExactSpelling = true)]
internal static extern unsafe int SHGetFolderPathW(
IntPtr hwndOwner,
int nFolder,
IntPtr hToken,
uint dwFlags,
char* pszPath);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Security;
using Xunit;
[assembly: System.Reflection.CustomAttributesTests.Data.Attr(77, name = "AttrSimple")]
[assembly: System.Reflection.CustomAttributesTests.Data.Int32Attr(77, name = "Int32AttrSimple"),
System.Reflection.CustomAttributesTests.Data.Int64Attr((Int64)77, name = "Int64AttrSimple"),
System.Reflection.CustomAttributesTests.Data.StringAttr("hello", name = "StringAttrSimple"),
System.Reflection.CustomAttributesTests.Data.EnumAttr(System.Reflection.CustomAttributesTests.Data.MyColorEnum.RED, name = "EnumAttrSimple"),
System.Reflection.CustomAttributesTests.Data.TypeAttr(typeof(Object), name = "TypeAttrSimple")]
[assembly: System.Runtime.CompilerServices.CompilationRelaxationsAttribute((Int32)8)]
[assembly: System.Diagnostics.Debuggable((System.Diagnostics.DebuggableAttribute.DebuggingModes)263)]
[assembly: System.CLSCompliant(false)]
namespace System.Reflection.Tests
{
public class AssemblyTests : FileCleanupTestBase
{
private string SourceTestAssemblyPath { get; } = Path.Combine(Environment.CurrentDirectory, "TestAssembly.dll");
private string DestTestAssemblyPath { get; }
private string LoadFromTestPath { get; }
public AssemblyTests()
{
// Assembly.Location not supported (properly) on uapaot.
DestTestAssemblyPath = Path.Combine(base.TestDirectory, "TestAssembly.dll");
LoadFromTestPath = Path.Combine(base.TestDirectory, "System.Runtime.Tests.dll");
// There is no dll to copy in ILC runs
if (!PlatformDetection.IsNetNative)
{
File.Copy(SourceTestAssemblyPath, DestTestAssemblyPath);
string currAssemblyPath = Path.Combine(Environment.CurrentDirectory, "System.Runtime.Tests.dll");
File.Copy(currAssemblyPath, LoadFromTestPath, true);
}
}
public static IEnumerable<object[]> Equality_TestData()
{
yield return new object[] { Assembly.Load(new AssemblyName(typeof(int).GetTypeInfo().Assembly.FullName)), Assembly.Load(new AssemblyName(typeof(int).GetTypeInfo().Assembly.FullName)), true };
yield return new object[] { Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName)), Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName)), true };
yield return new object[] { Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName)), typeof(AssemblyTests).Assembly, false };
}
[Theory]
[MemberData(nameof(Equality_TestData))]
public void Equality(Assembly assembly1, Assembly assembly2, bool expected)
{
Assert.Equal(expected, assembly1 == assembly2);
Assert.NotEqual(expected, assembly1 != assembly2);
}
[Fact]
public void GetAssembly_Nullery()
{
AssertExtensions.Throws<ArgumentNullException>("type", () => Assembly.GetAssembly(null));
}
public static IEnumerable<object[]> GetAssembly_TestData()
{
yield return new object[] { Assembly.Load(new AssemblyName(typeof(HashSet<int>).GetTypeInfo().Assembly.FullName)), Assembly.GetAssembly(typeof(HashSet<int>)), true };
yield return new object[] { Assembly.Load(new AssemblyName(typeof(int).GetTypeInfo().Assembly.FullName)), Assembly.GetAssembly(typeof(int)), true };
yield return new object[] { typeof(AssemblyTests).Assembly, Assembly.GetAssembly(typeof(AssemblyTests)), true };
}
[Theory]
[MemberData(nameof(GetAssembly_TestData))]
public void GetAssembly(Assembly assembly1, Assembly assembly2, bool expected)
{
Assert.Equal(expected, assembly1.Equals(assembly2));
}
public static IEnumerable<object[]> GetCallingAssembly_TestData()
{
yield return new object[] { typeof(AssemblyTests).Assembly, GetGetCallingAssembly(), true };
yield return new object[] { Assembly.GetCallingAssembly(), GetGetCallingAssembly(), false };
}
[Theory]
[MemberData(nameof(GetCallingAssembly_TestData))]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "GetCallingAssembly() is not supported on UapAot")]
public void GetCallingAssembly(Assembly assembly1, Assembly assembly2, bool expected)
{
Assert.Equal(expected, assembly1.Equals(assembly2));
}
[Fact]
public void GetExecutingAssembly()
{
Assert.True(typeof(AssemblyTests).Assembly.Equals(Assembly.GetExecutingAssembly()));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.GetSatelliteAssembly() not supported on UapAot")]
public void GetSatelliteAssemblyNeg()
{
Assert.Throws<ArgumentNullException>(() => (typeof(AssemblyTests).Assembly.GetSatelliteAssembly(null)));
Assert.Throws<System.IO.FileNotFoundException>(() => (typeof(AssemblyTests).Assembly.GetSatelliteAssembly(CultureInfo.InvariantCulture)));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.Load(String) not supported on UapAot")]
public void AssemblyLoadFromString()
{
AssemblyName an = typeof(AssemblyTests).Assembly.GetName();
string fullName = an.FullName;
string simpleName = an.Name;
Assembly a1 = Assembly.Load(fullName);
Assert.NotNull(a1);
Assert.Equal(fullName, a1.GetName().FullName);
Assembly a2 = Assembly.Load(simpleName);
Assert.NotNull(a2);
Assert.Equal(fullName, a2.GetName().FullName);
}
[Fact]
public void AssemblyLoadFromStringNeg()
{
Assert.Throws<ArgumentNullException>(() => Assembly.Load((string)null));
AssertExtensions.Throws<ArgumentException>(null, () => Assembly.Load(string.Empty));
string emptyCName = new string('\0', 1);
AssertExtensions.Throws<ArgumentException>(null, () => Assembly.Load(emptyCName));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Assembly.Load(byte[]) not supported on UapAot")]
public void AssemblyLoadFromBytes()
{
Assembly assembly = typeof(AssemblyTests).Assembly;
byte[] aBytes = System.IO.File.ReadAllBytes(assembly.Location);
Assembly loadedAssembly = Assembly.Load(aBytes);
Assert.NotNull(loadedAssembly);
Assert.Equal(assembly.FullName, loadedAssembly.FullName);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Assembly.Load(byte[]) not supported on UapAot")]
public void AssemblyLoadFromBytesNeg()
{
Assert.Throws<ArgumentNullException>(() => Assembly.Load((byte[])null));
Assert.Throws<BadImageFormatException>(() => Assembly.Load(new byte[0]));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Assembly.Load(byte[]) not supported on UapAot")]
public void AssemblyLoadFromBytesWithSymbols()
{
Assembly assembly = typeof(AssemblyTests).Assembly;
byte[] aBytes = System.IO.File.ReadAllBytes(assembly.Location);
byte[] symbols = System.IO.File.ReadAllBytes((System.IO.Path.ChangeExtension(assembly.Location, ".pdb")));
Assembly loadedAssembly = Assembly.Load(aBytes, symbols);
Assert.NotNull(loadedAssembly);
Assert.Equal(assembly.FullName, loadedAssembly.FullName);
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Assembly.ReflectionOnlyLoad() not supported on UapAot")]
public void AssemblyReflectionOnlyLoadFromString()
{
AssemblyName an = typeof(AssemblyTests).Assembly.GetName();
Assert.Throws<NotSupportedException>(() => Assembly.ReflectionOnlyLoad(an.FullName));
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Assembly.ReflectionOnlyLoad() not supported on UapAot")]
public void AssemblyReflectionOnlyLoadFromBytes()
{
Assembly assembly = typeof(AssemblyTests).Assembly;
byte[] aBytes = System.IO.File.ReadAllBytes(assembly.Location);
Assert.Throws<NotSupportedException>(() => Assembly.ReflectionOnlyLoad(aBytes));
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Assembly.ReflectionOnlyLoad() not supported on UapAot")]
public void AssemblyReflectionOnlyLoadFromNeg()
{
Assert.Throws<ArgumentNullException>(() => Assembly.ReflectionOnlyLoad((string)null));
AssertExtensions.Throws<ArgumentException>(null, () => Assembly.ReflectionOnlyLoad(string.Empty));
Assert.Throws<ArgumentNullException>(() => Assembly.ReflectionOnlyLoad((byte[])null));
}
public static IEnumerable<object[]> GetModules_TestData()
{
yield return new object[] { LoadSystemCollectionsAssembly() };
yield return new object[] { LoadSystemReflectionAssembly() };
}
[Theory]
[MemberData(nameof(GetModules_TestData))]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.GetModules() is not supported on UapAot.")]
public void GetModules_GetModule(Assembly assembly)
{
Assert.NotEmpty(assembly.GetModules());
foreach (Module module in assembly.GetModules())
{
Assert.Equal(module, assembly.GetModule(module.ToString()));
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.GetLoadedModules() is not supported on UapAot.")]
public void GetLoadedModules()
{
Assembly assembly = typeof(AssemblyTests).Assembly;
Assert.NotEmpty(assembly.GetLoadedModules());
foreach (Module module in assembly.GetLoadedModules())
{
Assert.NotNull(module);
Assert.Equal(module, assembly.GetModule(module.ToString()));
}
}
public static IEnumerable<object[]> CreateInstance_TestData()
{
yield return new object[] { typeof(AssemblyTests).Assembly, typeof(AssemblyPublicClass).FullName, BindingFlags.CreateInstance, typeof(AssemblyPublicClass) };
yield return new object[] { typeof(int).Assembly, typeof(int).FullName, BindingFlags.Default, typeof(int) };
yield return new object[] { typeof(int).Assembly, typeof(Dictionary<int, string>).FullName, BindingFlags.Default, typeof(Dictionary<int, string>) };
}
[Theory]
[MemberData(nameof(CreateInstance_TestData))]
public void CreateInstance(Assembly assembly, string typeName, BindingFlags bindingFlags, Type expectedType)
{
Assert.IsType(expectedType, assembly.CreateInstance(typeName, true, bindingFlags, null, null, null, null));
Assert.IsType(expectedType, assembly.CreateInstance(typeName, false, bindingFlags, null, null, null, null));
}
public static IEnumerable<object[]> CreateInstance_Invalid_TestData()
{
yield return new object[] { "", typeof(ArgumentException) };
yield return new object[] { null, typeof(ArgumentNullException) };
yield return new object[] { typeof(AssemblyClassWithPrivateCtor).FullName, typeof(MissingMethodException) };
}
[Theory]
[MemberData(nameof(CreateInstance_Invalid_TestData))]
public void CreateInstance_Invalid(string typeName, Type exceptionType)
{
Assembly assembly = typeof(AssemblyTests).Assembly;
Assert.Throws(exceptionType, () => assembly.CreateInstance(typeName, true, BindingFlags.Public, null, null, null, null));
Assert.Throws(exceptionType, () => assembly.CreateInstance(typeName, false, BindingFlags.Public, null, null, null, null));
}
[Fact]
public void GetManifestResourceStream()
{
Assert.NotNull(typeof(AssemblyTests).Assembly.GetManifestResourceStream(typeof(AssemblyTests), "EmbeddedImage.png"));
Assert.NotNull(typeof(AssemblyTests).Assembly.GetManifestResourceStream(typeof(AssemblyTests), "EmbeddedTextFile.txt"));
Assert.Null(typeof(AssemblyTests).Assembly.GetManifestResourceStream(typeof(AssemblyTests), "IDontExist"));
}
[Fact]
public void Test_GlobalAssemblyCache()
{
Assert.False(typeof(AssemblyTests).Assembly.GlobalAssemblyCache);
}
[Fact]
public void Test_HostContext()
{
Assert.Equal(0, typeof(AssemblyTests).Assembly.HostContext);
}
[Fact]
public void Test_IsFullyTrusted()
{
Assert.True(typeof(AssemblyTests).Assembly.IsFullyTrusted);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "The full .NET Framework supports SecurityRuleSet")]
public void Test_SecurityRuleSet_Netcore()
{
Assert.Equal(SecurityRuleSet.None, typeof(AssemblyTests).Assembly.SecurityRuleSet);
}
[Fact]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, "SecurityRuleSet is ignored in .NET Core")]
public void Test_SecurityRuleSet_Netfx()
{
Assert.Equal(SecurityRuleSet.Level2, typeof(AssemblyTests).Assembly.SecurityRuleSet);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Assembly.LoadFile() not supported on UapAot")]
public void Test_LoadFile()
{
Assembly currentAssembly = typeof(AssemblyTests).Assembly;
const string RuntimeTestsDll = "System.Runtime.Tests.dll";
string fullRuntimeTestsPath = Path.GetFullPath(RuntimeTestsDll);
var loadedAssembly1 = Assembly.LoadFile(fullRuntimeTestsPath);
if (PlatformDetection.IsFullFramework)
{
Assert.Equal(currentAssembly, loadedAssembly1);
}
else
{
Assert.NotEqual(currentAssembly, loadedAssembly1);
}
string dir = Path.GetDirectoryName(fullRuntimeTestsPath);
fullRuntimeTestsPath = Path.Combine(dir, ".", RuntimeTestsDll);
Assembly loadedAssembly2 = Assembly.LoadFile(fullRuntimeTestsPath);
if (PlatformDetection.IsFullFramework)
{
Assert.NotEqual(loadedAssembly1, loadedAssembly2);
}
else
{
Assert.Equal(loadedAssembly1, loadedAssembly2);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.Uap, "The full .NET Framework has a bug and throws a NullReferenceException")]
public void LoadFile_NullPath_Netcore_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("path", () => Assembly.LoadFile(null));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Assembly.LoadFile() not supported on UapAot")]
public void LoadFile_NoSuchPath_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentException>("path", null, () => Assembly.LoadFile("System.Runtime.Tests.dll"));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.UapAot, "The full .NET Framework supports Assembly.LoadFrom")]
public void Test_LoadFromUsingHashValue_Netcore()
{
Assert.Throws<NotSupportedException>(() => Assembly.LoadFrom("abc", null, System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA1));
}
[Fact]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, "The implementation of Assembly.LoadFrom is stubbed out in .NET Core")]
public void Test_LoadFromUsingHashValue_Netfx()
{
Assert.Throws<FileNotFoundException>(() => Assembly.LoadFrom("abc", null, System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA1));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.UapAot, "The full .NET Framework supports more than one module per assembly")]
public void Test_LoadModule_Netcore()
{
Assembly assembly = typeof(AssemblyTests).Assembly;
Assert.Throws<NotImplementedException>(() => assembly.LoadModule("abc", null));
Assert.Throws<NotImplementedException>(() => assembly.LoadModule("abc", null, null));
}
[Fact]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, "The coreclr doesn't support more than one module per assembly")]
public void Test_LoadModule_Netfx()
{
Assembly assembly = typeof(AssemblyTests).Assembly;
AssertExtensions.Throws<ArgumentNullException>(null, () => assembly.LoadModule("abc", null));
AssertExtensions.Throws<ArgumentNullException>(null, () => assembly.LoadModule("abc", null, null));
}
#pragma warning disable 618
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.LoadFromWithPartialName() not supported on UapAot")]
public void Test_LoadWithPartialName()
{
string simplename = typeof(AssemblyTests).Assembly.GetName().Name;
var assem = Assembly.LoadWithPartialName(simplename);
Assert.Equal(typeof(AssemblyTests).Assembly, assem);
}
#pragma warning restore 618
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.LoadFrom() not supported on UapAot")]
public void LoadFrom_SamePath_ReturnsEqualAssemblies()
{
Assembly assembly1 = Assembly.LoadFrom(DestTestAssemblyPath);
Assembly assembly2 = Assembly.LoadFrom(DestTestAssemblyPath);
Assert.Equal(assembly1, assembly2);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.LoadFrom() not supported on UapAot")]
public void LoadFrom_SameIdentityAsAssemblyWithDifferentPath_ReturnsEqualAssemblies()
{
Assembly assembly1 = Assembly.LoadFrom(typeof(AssemblyTests).Assembly.Location);
Assert.Equal(assembly1, typeof(AssemblyTests).Assembly);
Assembly assembly2 = Assembly.LoadFrom(LoadFromTestPath);
if (PlatformDetection.IsFullFramework)
{
Assert.NotEqual(assembly1, assembly2);
}
else
{
Assert.Equal(assembly1, assembly2);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.LoadFrom() not supported on UapAot")]
public void LoadFrom_NullAssemblyFile_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("assemblyFile", () => Assembly.LoadFrom(null));
AssertExtensions.Throws<ArgumentNullException>("assemblyFile", () => Assembly.UnsafeLoadFrom(null));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.LoadFrom() not supported on UapAot")]
public void LoadFrom_EmptyAssemblyFile_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentException>("path", null, (() => Assembly.LoadFrom("")));
AssertExtensions.Throws<ArgumentException>("path", null, (() => Assembly.UnsafeLoadFrom("")));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.LoadFrom() not supported on UapAot")]
public void LoadFrom_NoSuchFile_ThrowsFileNotFoundException()
{
Assert.Throws<FileNotFoundException>(() => Assembly.LoadFrom("NoSuchPath"));
Assert.Throws<FileNotFoundException>(() => Assembly.UnsafeLoadFrom("NoSuchPath"));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.UnsafeLoadFrom() not supported on UapAot")]
public void UnsafeLoadFrom_SamePath_ReturnsEqualAssemblies()
{
Assembly assembly1 = Assembly.UnsafeLoadFrom(DestTestAssemblyPath);
Assembly assembly2 = Assembly.UnsafeLoadFrom(DestTestAssemblyPath);
Assert.Equal(assembly1, assembly2);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.UapAot, "The implementation of LoadFrom(string, byte[], AssemblyHashAlgorithm is not supported in .NET Core.")]
public void LoadFrom_WithHashValue_NetCoreCore_ThrowsNotSupportedException()
{
Assert.Throws<NotSupportedException>(() => Assembly.LoadFrom(DestTestAssemblyPath, new byte[0], Configuration.Assemblies.AssemblyHashAlgorithm.None));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.GetFile() not supported on UapAot")]
public void GetFile()
{
Assert.Throws<ArgumentNullException>(() => typeof(AssemblyTests).Assembly.GetFile(null));
AssertExtensions.Throws<ArgumentException>(null, () => typeof(AssemblyTests).Assembly.GetFile(""));
Assert.Null(typeof(AssemblyTests).Assembly.GetFile("NonExistentfile.dll"));
Assert.NotNull(typeof(AssemblyTests).Assembly.GetFile("System.Runtime.Tests.dll"));
Assert.Equal(typeof(AssemblyTests).Assembly.GetFile("System.Runtime.Tests.dll").Name, typeof(AssemblyTests).Assembly.Location);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.GetFiles() not supported on UapAot")]
public void GetFiles()
{
Assert.NotNull(typeof(AssemblyTests).Assembly.GetFiles());
Assert.Equal(typeof(AssemblyTests).Assembly.GetFiles().Length, 1);
Assert.Equal(typeof(AssemblyTests).Assembly.GetFiles()[0].Name, typeof(AssemblyTests).Assembly.Location);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.CodeBase not supported on UapAot")]
public void Load_AssemblyNameWithCodeBase()
{
AssemblyName an = typeof(AssemblyTests).Assembly.GetName();
Assert.NotNull(an.CodeBase);
Assembly a = Assembly.Load(an);
Assert.Equal(a, typeof(AssemblyTests).Assembly);
}
// Helpers
private static Assembly GetGetCallingAssembly()
{
return Assembly.GetCallingAssembly();
}
private static Assembly LoadSystemCollectionsAssembly()
{
// Force System.collections to be linked statically
List<int> li = new List<int>();
li.Add(1);
return Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName));
}
private static Assembly LoadSystemReflectionAssembly()
{
// Force System.Reflection to be linked statically
return Assembly.Load(new AssemblyName(typeof(AssemblyName).GetTypeInfo().Assembly.FullName));
}
public class AssemblyPublicClass
{
public class PublicNestedClass { }
}
private static class AssemblyPrivateClass { }
public class AssemblyClassWithPrivateCtor
{
private AssemblyClassWithPrivateCtor() { }
}
}
public class AssemblyCustomAttributeTest
{
[Fact]
public void Test_Int32AttrSimple()
{
bool result = false;
Type attrType = typeof(System.Reflection.CustomAttributesTests.Data.Int32Attr);
string attrstr = "[System.Reflection.CustomAttributesTests.Data.Int32Attr((Int32)77, name = \"Int32AttrSimple\")]";
result = VerifyCustomAttribute(attrType, attrstr);
Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType));
}
[Fact]
public void Test_Int64Attr()
{
bool result = false;
Type attrType = typeof(System.Reflection.CustomAttributesTests.Data.Int64Attr);
string attrstr = "[System.Reflection.CustomAttributesTests.Data.Int64Attr((Int64)77, name = \"Int64AttrSimple\")]";
result = VerifyCustomAttribute(attrType, attrstr);
Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType));
}
[Fact]
public void Test_StringAttr()
{
bool result = false;
Type attrType = typeof(System.Reflection.CustomAttributesTests.Data.StringAttr);
string attrstr = "[System.Reflection.CustomAttributesTests.Data.StringAttr(\"hello\", name = \"StringAttrSimple\")]";
result = VerifyCustomAttribute(attrType, attrstr);
Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType));
}
[Fact]
public void Test_EnumAttr()
{
bool result = false;
Type attrType = typeof(System.Reflection.CustomAttributesTests.Data.EnumAttr);
string attrstr = "[System.Reflection.CustomAttributesTests.Data.EnumAttr((System.Reflection.CustomAttributesTests.Data.MyColorEnum)1, name = \"EnumAttrSimple\")]";
result = VerifyCustomAttribute(attrType, attrstr);
Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType));
}
[Fact]
public void Test_TypeAttr()
{
bool result = false;
Type attrType = typeof(System.Reflection.CustomAttributesTests.Data.TypeAttr);
string attrstr = "[System.Reflection.CustomAttributesTests.Data.TypeAttr(typeof(System.Object), name = \"TypeAttrSimple\")]";
result = VerifyCustomAttribute(attrType, attrstr);
Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType));
}
[Fact]
public void Test_CompilationRelaxationsAttr()
{
bool result = false;
Type attrType = typeof(System.Runtime.CompilerServices.CompilationRelaxationsAttribute);
string attrstr = "[System.Runtime.CompilerServices.CompilationRelaxationsAttribute((Int32)8)]";
result = VerifyCustomAttribute(attrType, attrstr);
Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType));
}
[Fact]
public void Test_AssemblyIdentityAttr()
{
bool result = false;
Type attrType = typeof(System.Reflection.AssemblyTitleAttribute);
string attrstr = "[System.Reflection.AssemblyTitleAttribute(\"System.Reflection.Tests\")]";
result = VerifyCustomAttribute(attrType, attrstr);
Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType));
}
[Fact]
public void Test_AssemblyDescriptionAttribute()
{
bool result = false;
Type attrType = typeof(System.Reflection.AssemblyDescriptionAttribute);
string attrstr = "[System.Reflection.AssemblyDescriptionAttribute(\"System.Reflection.Tests\")]";
result = VerifyCustomAttribute(attrType, attrstr);
Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType));
}
[Fact]
public void Test_AssemblyCompanyAttribute()
{
bool result = false;
Type attrType = typeof(System.Reflection.AssemblyCompanyAttribute);
string attrstr = "[System.Reflection.AssemblyCompanyAttribute(\"Microsoft Corporation\")]";
result = VerifyCustomAttribute(attrType, attrstr);
Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType));
}
[Fact]
public void Test_CLSCompliantAttribute()
{
bool result = false;
Type attrType = typeof(System.CLSCompliantAttribute);
string attrstr = "[System.CLSCompliantAttribute((Boolean)True)]";
result = VerifyCustomAttribute(attrType, attrstr);
Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType));
}
[Fact]
public void Test_DebuggableAttribute()
{
bool result = false;
Type attrType = typeof(System.Diagnostics.DebuggableAttribute);
string attrstr = "[System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute+DebuggingModes)263)]";
result = VerifyCustomAttribute(attrType, attrstr);
Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType));
}
[Fact]
public void Test_SimpleAttribute()
{
bool result = false;
Type attrType = typeof(System.Reflection.CustomAttributesTests.Data.Attr);
string attrstr = "[System.Reflection.CustomAttributesTests.Data.Attr((Int32)77, name = \"AttrSimple\")]";
result = VerifyCustomAttribute(attrType, attrstr);
Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType));
}
private bool VerifyCustomAttribute(Type type, String attributeStr)
{
Assembly asm = typeof(AssemblyCustomAttributeTest).Assembly;
foreach (CustomAttributeData cad in asm.GetCustomAttributesData())
{
if (cad.AttributeType.Equals(type))
{
return true;
}
}
return false;
}
}
public class AssemblyTests_GetTYpe
{
[Fact]
public void AssemblyGetTypeNoQualifierAllowed()
{
Assembly a = typeof(G<int>).Assembly;
string s = typeof(G<int>).AssemblyQualifiedName;
AssertExtensions.Throws<ArgumentException>(null, () => a.GetType(s, throwOnError: true, ignoreCase: false));
}
[Fact]
public void AssemblyGetTypeDoesntSearchMscorlib()
{
Assembly a = typeof(AssemblyTests_GetTYpe).Assembly;
Assert.Throws<TypeLoadException>(() => a.GetType("System.Object", throwOnError: true, ignoreCase: false));
Assert.Throws<TypeLoadException>(() => a.GetType("G`1[[System.Object]]", throwOnError: true, ignoreCase: false));
}
[Fact]
public void AssemblyGetTypeDefaultsToItself()
{
Assembly a = typeof(AssemblyTests_GetTYpe).Assembly;
Type t = a.GetType("G`1[[G`1[[System.Int32, mscorlib]]]]", throwOnError: true, ignoreCase: false);
Assert.Equal(typeof(G<G<int>>), t);
}
}
}
internal class G<T> { }
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Weborb.Types;
using Weborb.Util.Logging;
namespace Weborb.Reader
{
public class NumberObject : IAdaptingType
{
//private static Type stringType = typeof( string );
//private static Type stringBuilderType = typeof( StringBuilder );
private object data;
public NumberObject( double data )
{
this.data = data;
}
public NumberObject( byte data )
{
this.data = data;
}
#region IAdaptingType Members
public Type getDefaultType()
{
if( this.data is Byte )
return typeof( Byte );
Double data = (Double) this.data;
if( Math.Round( data ) == data )
{
if( data >= Int32.MinValue && data <= Int32.MaxValue )
return typeof( Int32 );
else if( data >= Int64.MinValue && data <= Int64.MaxValue )
return typeof( Int64 );
}
return typeof( Double );
}
public virtual object defaultAdapt()
{
if( this.data is Byte )
return this.data;
Double data = (Double) this.data;
if( Double.IsNaN( data ) )
{
if( Log.isLogging( LoggingConstants.DEBUG ) )
Log.log( LoggingConstants.DEBUG, "Value is NaN, returning -1" );
return -1;
}
try
{
if( Math.Round( data ) == data )
return Convert.ToInt32( data );
else
return Convert.ToDouble( data );
}
catch( Exception )
{
if( Log.isLogging( LoggingConstants.EXCEPTION ) )
Log.log( LoggingConstants.EXCEPTION, "unable to convert data to Int32, attempting Int64. Data is " + data );
if( Math.Round( data ) == data )
return Convert.ToInt64( data );
else
return Convert.ToDouble( data );
}
}
public object adapt( Type type )
{
Double data = Convert.ToDouble( this.data );
object checkedValue = data;
if( Double.IsNaN( data ) )
checkedValue = null;
if( type.Equals( typeof( IAdaptingType ) ) )
return this;
else if( type.Equals( typeof( Byte ) ) )
return Convert.ToByte( checkedValue );
else if( type.Equals( typeof( Byte? ) ) )
return checkedValue == null ? null : (object) Convert.ToByte( data );
else if( type.Equals( typeof( SByte ) ) )
return Convert.ToSByte( checkedValue );
else if( type.Equals( typeof( SByte? ) ) )
return checkedValue == null ? null : (object) Convert.ToSByte( data );
else if( type.Equals( typeof( Char ) ) )
return Convert.ToChar( checkedValue );
else if( type.Equals( typeof( Char? ) ) )
return checkedValue == null ? null : (object) Convert.ToChar( data );
else if( type.Equals( typeof( Int16 ) ) )
return Convert.ToInt16( checkedValue );
else if( type.Equals( typeof( Int16? ) ) )
return checkedValue == null ? null : (object) Convert.ToInt16( data );
else if( type.Equals( typeof( Int32 ) ) )
return Convert.ToInt32( checkedValue );
else if( type.Equals( typeof( Int32? ) ) )
return checkedValue == null ? null : (object) Convert.ToInt32( data );
else if( type.Equals( typeof( Int64 ) ) )
return Convert.ToInt64( checkedValue );
else if( type.Equals( typeof( Int64? ) ) )
return checkedValue == null ? null : (object) Convert.ToInt64( data );
else if( type.Equals( typeof( UInt16 ) ) )
return Convert.ToUInt16( checkedValue );
else if( type.Equals( typeof( UInt16? ) ) )
return checkedValue == null ? null : (object) Convert.ToUInt16( data );
else if( type.Equals( typeof( UInt32 ) ) )
return Convert.ToUInt32( checkedValue );
else if( type.Equals( typeof( UInt32? ) ) )
return checkedValue == null ? null : (object) Convert.ToUInt32( data );
else if( type.Equals( typeof( UInt64 ) ) )
return Convert.ToUInt64( checkedValue );
else if( type.Equals( typeof( UInt64? ) ) )
return checkedValue == null ? null : (object) Convert.ToUInt64( data );
else if( type.Equals( typeof( Decimal ) ) )
return Convert.ToDecimal( checkedValue );
else if( type.Equals( typeof( Decimal? ) ) )
return checkedValue == null ? null : (object) Convert.ToDecimal( data );
else if( type.Equals( typeof( Single ) ) )
return Convert.ToSingle( checkedValue );
else if( type.Equals( typeof( Single? ) ) )
return checkedValue == null ? null : (object) Convert.ToSingle( data );
else if( type.Equals( typeof( Double ) ) )
return data;
else if( type.Equals( typeof( Double? ) ) )
return checkedValue == null ? null : (object) data;
else if( typeof( string ).IsAssignableFrom( type ) )
{
if( checkedValue == null )
return null;
if( data - Convert.ToInt32( data ) == 0.0d )
return Convert.ToInt32( data ).ToString();
else
return data.ToString();
}
else if( typeof( StringBuilder ).IsAssignableFrom( type ) )
return checkedValue == null ? new StringBuilder() : new StringBuilder( data.ToString() );
else if( type.Equals( typeof( Boolean ) ) )
return Convert.ToBoolean( checkedValue );
else if( type.Equals( typeof( DateTime ) ) )
{
long ticks = (new DateTime( 1970, 1, 1 )).Ticks;
// Intervals that have elapsed since 12:00:00 midnight, January 1, 0001
return new DateTime( Convert.ToInt64( checkedValue ) * 10000 + ticks ); //There are 10,000 ticks in a millisecond
}
else if( type.Equals( typeof( Boolean? ) ) )
return checkedValue == null ? null : (object) Convert.ToBoolean( data );
else if( type.BaseType == typeof( Enum ) )
{
Type enumUnderlyingType = Enum.GetUnderlyingType( type );
object adaptedNumber = adapt( enumUnderlyingType );
string enumItemName = Enum.GetName( type, adaptedNumber );
return type.GetField( enumItemName ).GetValue( null );
}
else if( type.Equals( typeof( TimeSpan ) ) )
return TimeSpan.FromMilliseconds( checkedValue == null ? 0 : data );
return data;
}
public bool canAdaptTo( Type formalArg )
{
return typeof( Byte ).IsAssignableFrom( formalArg ) ||
typeof( Int16 ).IsAssignableFrom( formalArg ) ||
typeof( Int32 ).IsAssignableFrom( formalArg ) ||
typeof( Int64 ).IsAssignableFrom( formalArg ) ||
typeof( UInt16 ).IsAssignableFrom( formalArg ) ||
typeof( UInt32 ).IsAssignableFrom( formalArg ) ||
typeof( UInt64 ).IsAssignableFrom( formalArg ) ||
typeof( Single ).IsAssignableFrom( formalArg ) ||
typeof( Double ).IsAssignableFrom( formalArg ) ||
typeof( string ).IsAssignableFrom( formalArg ) ||
typeof( Boolean ).IsAssignableFrom( formalArg ) ||
typeof( DateTime ).IsAssignableFrom( formalArg ) ||
typeof( Decimal ).IsAssignableFrom( formalArg ) ||
typeof( TimeSpan ).IsAssignableFrom( formalArg ) ||
typeof( StringBuilder ).IsAssignableFrom( formalArg ) ||
formalArg.IsGenericType && formalArg.GetGenericTypeDefinition().Equals( typeof( Nullable<> ) ) ||
typeof( IAdaptingType ).IsAssignableFrom( formalArg );
}
#endregion
public override string ToString()
{
return "Number type. Value - " + data;
}
public override bool Equals( object _obj )
{
NumberObject obj = _obj as NumberObject;
if( obj == null )
return false;
return obj.data.Equals( data );
}
public bool Equals( object _obj, Dictionary<DictionaryEntry, bool> visitedPairs )
{
return Equals( _obj );
}
public override int GetHashCode()
{
return data.GetHashCode();
}
}
}
| |
// 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;
namespace System.IO
{
/// <summary>
/// Provides a string parser that may be used instead of String.Split
/// to avoid unnecessary string and array allocations.
/// </summary>
internal struct StringParser
{
/// <summary>The string being parsed.</summary>
private readonly string _buffer;
/// <summary>The separator character used to separate subcomponents of the larger string.</summary>
private readonly char _separator;
/// <summary>true if empty subcomponents should be skipped; false to treat them as valid entries.</summary>
private readonly bool _skipEmpty;
/// <summary>The starting index from which to parse the current entry.</summary>
private int _startIndex;
/// <summary>The ending index that represents the next index after the last character that's part of the current entry.</summary>
private int _endIndex;
/// <summary>Initialize the StringParser.</summary>
/// <param name="buffer">The string to parse.</param>
/// <param name="separator">The separator character used to separate subcomponents of <paramref name="buffer"/>.</param>
/// <param name="skipEmpty">true if empty subcomponents should be skipped; false to treat them as valid entries. Defaults to false.</param>
public StringParser(string buffer, char separator, bool skipEmpty = false)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
_buffer = buffer;
_separator = separator;
_skipEmpty = skipEmpty;
_startIndex = -1;
_endIndex = -1;
}
/// <summary>Moves to the next component of the string.</summary>
/// <returns>true if there is a next component to be parsed; otherwise, false.</returns>
public bool MoveNext()
{
if (_buffer == null)
{
throw new InvalidOperationException();
}
while (true)
{
if (_endIndex >= _buffer.Length)
{
_startIndex = _endIndex;
return false;
}
int nextSeparator = _buffer.IndexOf(_separator, _endIndex + 1);
_startIndex = _endIndex + 1;
_endIndex = nextSeparator >= 0 ? nextSeparator : _buffer.Length;
if (!_skipEmpty || _endIndex >= _startIndex + 1)
{
return true;
}
}
}
/// <summary>
/// Moves to the next component of the string. If there isn't one, it throws an exception.
/// </summary>
public void MoveNextOrFail()
{
if (!MoveNext())
{
ThrowForInvalidData();
}
}
/// <summary>
/// Moves to the next component of the string and returns it as a string.
/// </summary>
/// <returns></returns>
public string MoveAndExtractNext()
{
MoveNextOrFail();
return _buffer.Substring(_startIndex, _endIndex - _startIndex);
}
/// <summary>
/// Moves to the next component of the string, which must be enclosed in the only set of top-level parentheses
/// in the string. The extracted value will be everything between (not including) those parentheses.
/// </summary>
/// <returns></returns>
public string MoveAndExtractNextInOuterParens()
{
// Move to the next position
MoveNextOrFail();
// After doing so, we should be sitting at a the opening paren.
if (_buffer[_startIndex] != '(')
{
ThrowForInvalidData();
}
// Since we only allow for one top-level set of parentheses, find the last
// parenthesis in the string; it's paired with the opening one we just found.
int lastParen = _buffer.LastIndexOf(')');
if (lastParen == -1 || lastParen < _startIndex)
{
ThrowForInvalidData();
}
// Extract the contents of the parens, then move our ending position to be after the paren
string result = _buffer.Substring(_startIndex + 1, lastParen - _startIndex - 1);
_endIndex = lastParen + 1;
return result;
}
/// <summary>
/// Gets the current subcomponent of the string as a string.
/// </summary>
public string ExtractCurrent()
{
if (_buffer == null || _startIndex == -1)
{
throw new InvalidOperationException();
}
return _buffer.Substring(_startIndex, _endIndex - _startIndex);
}
/// <summary>Moves to the next component and parses it as an Int32.</summary>
public unsafe int ParseNextInt32()
{
MoveNextOrFail();
bool negative = false;
int result = 0;
fixed (char* bufferPtr = _buffer)
{
char* p = bufferPtr + _startIndex;
char* end = bufferPtr + _endIndex;
if (p == end)
{
ThrowForInvalidData();
}
if (*p == '-')
{
negative = true;
p++;
if (p == end)
{
ThrowForInvalidData();
}
}
while (p != end)
{
int d = *p - '0';
if (d < 0 || d > 9)
{
ThrowForInvalidData();
}
result = negative ? checked((result * 10) - d) : checked((result * 10) + d);
p++;
}
}
Debug.Assert(result == int.Parse(ExtractCurrent()), "Expected manually parsed result to match Parse result");
return result;
}
/// <summary>Moves to the next component and parses it as an Int64.</summary>
public unsafe long ParseNextInt64()
{
MoveNextOrFail();
bool negative = false;
long result = 0;
fixed (char* bufferPtr = _buffer)
{
char* p = bufferPtr + _startIndex;
char* end = bufferPtr + _endIndex;
if (p == end)
{
ThrowForInvalidData();
}
if (*p == '-')
{
negative = true;
p++;
if (p == end)
{
ThrowForInvalidData();
}
}
while (p != end)
{
int d = *p - '0';
if (d < 0 || d > 9)
{
ThrowForInvalidData();
}
result = negative ? checked((result * 10) - d) : checked((result * 10) + d);
p++;
}
}
Debug.Assert(result == long.Parse(ExtractCurrent()), "Expected manually parsed result to match Parse result");
return result;
}
/// <summary>Moves to the next component and parses it as a UInt32.</summary>
public unsafe uint ParseNextUInt32()
{
MoveNextOrFail();
if (_startIndex == _endIndex)
{
ThrowForInvalidData();
}
uint result = 0;
fixed (char* bufferPtr = _buffer)
{
char* p = bufferPtr + _startIndex;
char* end = bufferPtr + _endIndex;
while (p != end)
{
int d = *p - '0';
if (d < 0 || d > 9)
{
ThrowForInvalidData();
}
result = (uint)checked((result * 10) + d);
p++;
}
}
Debug.Assert(result == uint.Parse(ExtractCurrent()), "Expected manually parsed result to match Parse result");
return result;
}
/// <summary>Moves to the next component and parses it as a UInt64.</summary>
public unsafe ulong ParseNextUInt64()
{
MoveNextOrFail();
ulong result = 0;
fixed (char* bufferPtr = _buffer)
{
char* p = bufferPtr + _startIndex;
char* end = bufferPtr + _endIndex;
while (p != end)
{
int d = *p - '0';
if (d < 0 || d > 9)
{
ThrowForInvalidData();
}
result = checked((result * 10ul) + (ulong)d);
p++;
}
}
Debug.Assert(result == ulong.Parse(ExtractCurrent()), "Expected manually parsed result to match Parse result");
return result;
}
/// <summary>Moves to the next component and parses it as a Char.</summary>
public char ParseNextChar()
{
MoveNextOrFail();
if (_endIndex - _startIndex != 1)
{
ThrowForInvalidData();
}
char result = _buffer[_startIndex];
Debug.Assert(result == char.Parse(ExtractCurrent()), "Expected manually parsed result to match Parse result");
return result;
}
internal delegate T ParseRawFunc<T>(string buffer, ref int startIndex, ref int endIndex);
/// <summary>
/// Moves to the next component and hands the raw buffer and indexing data to a selector function
/// that can validate and return the appropriate data from the component.
/// </summary>
internal T ParseRaw<T>(ParseRawFunc<T> selector)
{
MoveNextOrFail();
return selector(_buffer, ref _startIndex, ref _endIndex);
}
/// <summary>
/// Gets the current subcomponent and all remaining components of the string as a string.
/// </summary>
public string ExtractCurrentToEnd()
{
if (_buffer == null || _startIndex == -1)
{
throw new InvalidOperationException();
}
return _buffer.Substring(_startIndex);
}
/// <summary>Throws unconditionally for invalid data.</summary>
private static void ThrowForInvalidData()
{
throw new InvalidDataException();
}
}
}
| |
using Orleans.Runtime.Configuration;
using Orleans.Runtime.ConsistentRing;
using Orleans.Runtime.Scheduler;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Orleans.Runtime.ReminderService
{
internal class LocalReminderService : SystemTarget, IReminderService, IRingRangeListener
{
private enum ReminderServiceStatus
{
Booting = 0,
Started,
Stopped,
}
private const int InitialReadRetryCountBeforeFastFailForUpdates = 2;
private static readonly TimeSpan InitialReadMaxWaitTimeForUpdates = TimeSpan.FromSeconds(20);
private static readonly TimeSpan InitialReadRetryPeriod = TimeSpan.FromSeconds(30);
private readonly Dictionary<ReminderIdentity, LocalReminderData> localReminders;
private readonly IConsistentRingProvider ring;
private readonly IReminderTable reminderTable;
private readonly OrleansTaskScheduler scheduler;
private ReminderServiceStatus status;
private IRingRange myRange;
private long localTableSequence;
private int rangeSerialNumber;
private GrainTimer listRefresher; // timer that refreshes our list of reminders to reflect global reminder table
private readonly TaskCompletionSource<bool> startedTask;
private readonly CancellationTokenSource stoppedCancellationTokenSource;
private uint initialReadCallCount = 0;
private readonly AverageTimeSpanStatistic tardinessStat;
private readonly CounterStatistic ticksDeliveredStat;
private readonly TraceLogger logger;
private readonly GlobalConfiguration config;
private readonly TimeSpan initTimeout;
internal LocalReminderService(
SiloAddress addr,
GrainId id,
IConsistentRingProvider ring,
OrleansTaskScheduler localScheduler,
IReminderTable reminderTable,
GlobalConfiguration config,
TimeSpan initTimeout)
: base(id, addr)
{
logger = TraceLogger.GetLogger("ReminderService", TraceLogger.LoggerType.Runtime);
localReminders = new Dictionary<ReminderIdentity, LocalReminderData>();
this.ring = ring;
scheduler = localScheduler;
this.reminderTable = reminderTable;
this.config = config;
this.initTimeout = initTimeout;
status = ReminderServiceStatus.Booting;
myRange = null;
localTableSequence = 0;
rangeSerialNumber = 0;
tardinessStat = AverageTimeSpanStatistic.FindOrCreate(StatisticNames.REMINDERS_AVERAGE_TARDINESS_SECONDS);
IntValueStatistic.FindOrCreate(StatisticNames.REMINDERS_NUMBER_ACTIVE_REMINDERS, () => localReminders.Count);
ticksDeliveredStat = CounterStatistic.FindOrCreate(StatisticNames.REMINDERS_COUNTERS_TICKS_DELIVERED);
startedTask = new TaskCompletionSource<bool>();
stoppedCancellationTokenSource = new CancellationTokenSource();
}
#region Public methods
/// <summary>
/// Attempt to retrieve reminders, that are my responsibility, from the global reminder table when starting this silo (reminder service instance)
/// </summary>
/// <returns></returns>
public async Task Start()
{
myRange = ring.GetMyRange();
logger.Info(ErrorCode.RS_ServiceStarting, "Starting reminder system target on: {0} x{1,8:X8}, with range {2}", Silo, Silo.GetConsistentHashCode(), myRange);
// confirm that it can access the underlying store, as after this the ReminderService will load in the background, without the opportunity to prevent the Silo from starting
await reminderTable.Init(config,logger).WithTimeout(initTimeout);
StartInBackground().Ignore();
}
public Task Stop()
{
stoppedCancellationTokenSource.Cancel();
logger.Info(ErrorCode.RS_ServiceStopping, "Stopping reminder system target");
status = ReminderServiceStatus.Stopped;
ring.UnSubscribeFromRangeChangeEvents(this);
if (listRefresher != null)
{
listRefresher.Dispose();
listRefresher = null;
}
foreach (LocalReminderData r in localReminders.Values)
r.StopReminder(logger);
// for a graceful shutdown, also handover reminder responsibilities to new owner, and update the ReminderTable
// currently, this is taken care of by periodically reading the reminder table
return TaskDone.Done;
}
public async Task<IGrainReminder> RegisterOrUpdateReminder(GrainReference grainRef, string reminderName, TimeSpan dueTime, TimeSpan period)
{
var entry = new ReminderEntry
{
GrainRef = grainRef,
ReminderName = reminderName,
StartAt = DateTime.UtcNow.Add(dueTime),
Period = period,
};
if(logger.IsVerbose) logger.Verbose(ErrorCode.RS_RegisterOrUpdate, "RegisterOrUpdateReminder: {0}", entry.ToString());
await DoResponsibilitySanityCheck(grainRef, "RegisterReminder");
var newEtag = await reminderTable.UpsertRow(entry);
if (newEtag != null)
{
if (logger.IsVerbose) logger.Verbose("Registered reminder {0} in table, assigned localSequence {1}", entry, localTableSequence);
entry.ETag = newEtag;
StartAndAddTimer(entry);
if (logger.IsVerbose3) PrintReminders();
return new ReminderData(grainRef, reminderName, newEtag) as IGrainReminder;
}
var msg = string.Format("Could not register reminder {0} to reminder table due to a race. Please try again later.", entry);
logger.Error(ErrorCode.RS_Register_TableError, msg);
throw new ReminderException(msg);
}
/// <summary>
/// Stop the reminder locally, and remove it from the external storage system
/// </summary>
/// <param name="reminder"></param>
/// <returns></returns>
public async Task UnregisterReminder(IGrainReminder reminder)
{
var remData = (ReminderData)reminder;
if(logger.IsVerbose) logger.Verbose(ErrorCode.RS_Unregister, "UnregisterReminder: {0}, LocalTableSequence: {1}", remData, localTableSequence);
GrainReference grainRef = remData.GrainRef;
string reminderName = remData.ReminderName;
string eTag = remData.ETag;
await DoResponsibilitySanityCheck(grainRef, "RemoveReminder");
// it may happen that we dont have this reminder locally ... even then, we attempt to remove the reminder from the reminder
// table ... the periodic mechanism will stop this reminder at any silo's LocalReminderService that might have this reminder locally
// remove from persistent/memory store
var success = await reminderTable.RemoveRow(grainRef, reminderName, eTag);
if (success)
{
bool removed = TryStopPreviousTimer(grainRef, reminderName);
if (removed)
{
if(logger.IsVerbose) logger.Verbose(ErrorCode.RS_Stop, "Stopped reminder {0}", reminder);
if (logger.IsVerbose3) PrintReminders(string.Format("After removing {0}.", reminder));
}
else
{
// no-op
if(logger.IsVerbose) logger.Verbose(ErrorCode.RS_RemoveFromTable, "Removed reminder from table which I didn't have locally: {0}.", reminder);
}
}
else
{
var msg = string.Format("Could not unregister reminder {0} from the reminder table, due to tag mismatch. You can retry.", reminder);
logger.Error(ErrorCode.RS_Unregister_TableError, msg);
throw new ReminderException(msg);
}
}
public async Task<IGrainReminder> GetReminder(GrainReference grainRef, string reminderName)
{
if(logger.IsVerbose) logger.Verbose(ErrorCode.RS_GetReminder,"GetReminder: GrainReference={0} ReminderName={1}", grainRef.ToDetailedString(), reminderName);
var entry = await reminderTable.ReadRow(grainRef, reminderName);
return entry == null ? null : entry.ToIGrainReminder();
}
public async Task<List<IGrainReminder>> GetReminders(GrainReference grainRef)
{
if (logger.IsVerbose) logger.Verbose(ErrorCode.RS_GetReminders, "GetReminders: GrainReference={0}", grainRef.ToDetailedString());
var tableData = await reminderTable.ReadRows(grainRef);
return tableData.Reminders.Select(entry => entry.ToIGrainReminder()).ToList();
}
#endregion
/// <summary>
/// Attempt to retrieve reminders from the global reminder table
/// </summary>
private async Task ReadAndUpdateReminders()
{
if (stoppedCancellationTokenSource.IsCancellationRequested) return;
RemoveOutOfRangeReminders();
// try to retrieve reminders from all my subranges
var rangeSerialNumberCopy = rangeSerialNumber;
if (logger.IsVerbose2) logger.Verbose2($"My range= {myRange}, RangeSerialNumber {rangeSerialNumber}. Local reminders count {localReminders.Count}");
var acks = new List<Task>();
foreach (SingleRange range in RangeFactory.GetSubRanges(myRange))
{
acks.Add(ReadTableAndStartTimers(range, rangeSerialNumberCopy));
}
await Task.WhenAll(acks);
if (logger.IsVerbose3) PrintReminders();
}
private void RemoveOutOfRangeReminders()
{
var remindersOutOfRange = localReminders.Where(r => !myRange.InRange(r.Key.GrainRef)).Select(r => r.Value).ToArray();
foreach (var reminder in remindersOutOfRange)
{
if (logger.IsVerbose2)
logger.Verbose2("Not in my range anymore, so removing. {0}", reminder);
// remove locally
reminder.StopReminder(logger);
localReminders.Remove(reminder.Identity);
}
if (logger.IsInfo && remindersOutOfRange.Length > 0) logger.Info($"Removed {remindersOutOfRange.Length} local reminders that are now out of my range.");
}
#region Change in membership, e.g., failure of predecessor
/// <summary>
/// Actions to take when the range of this silo changes on the ring due to a failure or a join
/// </summary>
/// <param name="old">my previous responsibility range</param>
/// <param name="now">my new/current responsibility range</param>
/// <param name="increased">True: my responsibility increased, false otherwise</param>
public void RangeChangeNotification(IRingRange old, IRingRange now, bool increased)
{
// run on my own turn & context
scheduler.QueueTask(() => OnRangeChange(old, now, increased), this.SchedulingContext).Ignore();
}
private async Task OnRangeChange(IRingRange oldRange, IRingRange newRange, bool increased)
{
logger.Info(ErrorCode.RS_RangeChanged, "My range changed from {0} to {1} increased = {2}", oldRange, newRange, increased);
myRange = newRange;
rangeSerialNumber++;
if (status == ReminderServiceStatus.Started)
await ReadAndUpdateReminders();
else
if (logger.IsVerbose) logger.Verbose("Ignoring range change until ReminderService is Started -- Current status = {0}", status);
}
#endregion
#region Internal implementation methods
private async Task StartInBackground()
{
await DoInitialReadAndUpdateReminders();
if (status == ReminderServiceStatus.Booting)
{
var random = new SafeRandom();
listRefresher = GrainTimer.FromTaskCallback(
_ => DoInitialReadAndUpdateReminders(),
null,
random.NextTimeSpan(InitialReadRetryPeriod),
InitialReadRetryPeriod,
name: "ReminderService.ReminderListInitialRead");
listRefresher.Start();
}
}
private void PromoteToStarted()
{
if (stoppedCancellationTokenSource.IsCancellationRequested) return;
logger.Info(ErrorCode.RS_ServiceStarted, "Reminder system target started OK on: {0} x{1,8:X8}, with range {2}", this.Silo, this.Silo.GetConsistentHashCode(), this.myRange);
status = ReminderServiceStatus.Started;
startedTask.TrySetResult(true);
var random = new SafeRandom();
var dueTime = random.NextTimeSpan(Constants.RefreshReminderList);
if (listRefresher != null) listRefresher.Dispose();
listRefresher = GrainTimer.FromTaskCallback(
_ => ReadAndUpdateReminders(),
null,
dueTime,
Constants.RefreshReminderList,
name: "ReminderService.ReminderListRefresher");
listRefresher.Start();
ring.SubscribeToRangeChangeEvents(this);
}
private async Task DoInitialReadAndUpdateReminders()
{
try
{
if (stoppedCancellationTokenSource.IsCancellationRequested) return;
initialReadCallCount++;
await this.ReadAndUpdateReminders();
PromoteToStarted();
}
catch (Exception ex)
{
if (stoppedCancellationTokenSource.IsCancellationRequested) return;
if (initialReadCallCount <= InitialReadRetryCountBeforeFastFailForUpdates)
{
logger.Warn(
ErrorCode.RS_ServiceInitialLoadFailing,
string.Format("ReminderService failed initial load of reminders and will retry. Attempt #{0}", this.initialReadCallCount),
ex);
}
else
{
const string baseErrorMsg = "ReminderService failed initial load of reminders and cannot guarantee that the service will be eventually start without manual intervention or restarting the silo.";
var logErrorMessage = string.Format(baseErrorMsg + " Attempt #{0}", this.initialReadCallCount);
logger.Error(ErrorCode.RS_ServiceInitialLoadFailed, logErrorMessage, ex);
startedTask.TrySetException(new OrleansException(baseErrorMsg, ex));
}
}
}
private async Task ReadTableAndStartTimers(IRingRange range, int rangeSerialNumberCopy)
{
if (logger.IsVerbose) logger.Verbose("Reading rows from {0}", range.ToString());
localTableSequence++;
long cachedSequence = localTableSequence;
try
{
var srange = (SingleRange)range;
ReminderTableData table = await reminderTable.ReadRows(srange.Begin, srange.End); // get all reminders, even the ones we already have
if (rangeSerialNumberCopy < rangeSerialNumber)
{
if (logger.IsVerbose) logger.Verbose($"My range changed while reading from the table, ignoring the results. Another read has been started. RangeSerialNumber {rangeSerialNumber}, RangeSerialNumberCopy {rangeSerialNumberCopy}.");
return;
}
if (stoppedCancellationTokenSource.IsCancellationRequested) return;
// if null is a valid value, it means that there's nothing to do.
if (null == table && reminderTable is MockReminderTable) return;
var remindersNotInTable = localReminders.Where(r => range.InRange(r.Key.GrainRef)).ToDictionary(r => r.Key, r => r.Value); // shallow copy
if (logger.IsVerbose) logger.Verbose("For range {0}, I read in {1} reminders from table. LocalTableSequence {2}, CachedSequence {3}", range.ToString(), table.Reminders.Count, localTableSequence, cachedSequence);
foreach (ReminderEntry entry in table.Reminders)
{
var key = new ReminderIdentity(entry.GrainRef, entry.ReminderName);
LocalReminderData localRem;
if (localReminders.TryGetValue(key, out localRem))
{
if (cachedSequence > localRem.LocalSequenceNumber) // info read from table is same or newer than local info
{
if (localRem.Timer != null) // if ticking
{
if (logger.IsVerbose2) logger.Verbose2("In table, In local, Old, & Ticking {0}", localRem);
// it might happen that our local reminder is different than the one in the table, i.e., eTag is different
// if so, stop the local timer for the old reminder, and start again with new info
if (!localRem.ETag.Equals(entry.ETag))
// this reminder needs a restart
{
if (logger.IsVerbose2) logger.Verbose2("{0} Needs a restart", localRem);
localRem.StopReminder(logger);
localReminders.Remove(localRem.Identity);
StartAndAddTimer(entry);
}
}
else // if not ticking
{
// no-op
if (logger.IsVerbose2) logger.Verbose2("In table, In local, Old, & Not Ticking {0}", localRem);
}
}
else // cachedSequence < localRem.LocalSequenceNumber ... // info read from table is older than local info
{
if (localRem.Timer != null) // if ticking
{
// no-op
if (logger.IsVerbose2) logger.Verbose2("In table, In local, Newer, & Ticking {0}", localRem);
}
else // if not ticking
{
// no-op
if (logger.IsVerbose2) logger.Verbose2("In table, In local, Newer, & Not Ticking {0}", localRem);
}
}
}
else // exists in table, but not locally
{
if (logger.IsVerbose2) logger.Verbose2("In table, Not in local, {0}", entry);
// create and start the reminder
StartAndAddTimer(entry);
}
// keep a track of extra reminders ... this 'reminder' is useful, so remove it from extra list
remindersNotInTable.Remove(key);
} // foreach reminder read from table
int remindersCountBeforeRemove = localReminders.Count;
// foreach reminder that is not in global table, but exists locally
foreach (var reminder in remindersNotInTable.Values)
{
if (cachedSequence < reminder.LocalSequenceNumber)
{
// no-op
if (logger.IsVerbose2) logger.Verbose2("Not in table, In local, Newer, {0}", reminder);
}
else // cachedSequence > reminder.LocalSequenceNumber
{
if (logger.IsVerbose2) logger.Verbose2("Not in table, In local, Old, so removing. {0}", reminder);
// remove locally
reminder.StopReminder(logger);
localReminders.Remove(reminder.Identity);
}
}
if (logger.IsVerbose) logger.Verbose($"Removed {localReminders.Count - remindersCountBeforeRemove} reminders from local table");
}
catch (Exception exc)
{
logger.Error(ErrorCode.RS_FailedToReadTableAndStartTimer, "Failed to read rows from table.", exc);
throw;
}
}
private void StartAndAddTimer(ReminderEntry entry)
{
// it might happen that we already have a local reminder with a different eTag
// if so, stop the local timer for the old reminder, and start again with new info
// Note: it can happen here that we restart a reminder that has the same eTag as what we just registered ... its a rare case, and restarting it doesn't hurt, so we don't check for it
var key = new ReminderIdentity(entry.GrainRef, entry.ReminderName);
LocalReminderData prevReminder;
if (localReminders.TryGetValue(key, out prevReminder)) // if found locally
{
if (logger.IsVerbose) logger.Verbose(ErrorCode.RS_LocalStop, "Localy stopping reminder {0} as it is different than newly registered reminder {1}", prevReminder, entry);
prevReminder.StopReminder(logger);
localReminders.Remove(prevReminder.Identity);
}
var newReminder = new LocalReminderData(entry);
localTableSequence++;
newReminder.LocalSequenceNumber = localTableSequence;
localReminders.Add(newReminder.Identity, newReminder);
newReminder.StartTimer(AsyncTimerCallback, logger);
if (logger.IsVerbose) logger.Verbose(ErrorCode.RS_Started, "Started reminder {0}.", entry.ToString());
}
// stop without removing it. will remove later.
private bool TryStopPreviousTimer(GrainReference grainRef, string reminderName)
{
// we stop the locally running timer for this reminder
var key = new ReminderIdentity(grainRef, reminderName);
LocalReminderData localRem;
if (!localReminders.TryGetValue(key, out localRem)) return false;
// if we have it locally
localTableSequence++; // move to next sequence
localRem.LocalSequenceNumber = localTableSequence;
localRem.StopReminder(logger);
return true;
}
#endregion
/// <summary>
/// Local timer expired ... notify it as a 'tick' to the grain who registered this reminder
/// </summary>
/// <param name="rem">Reminder that this timeout represents</param>
private async Task AsyncTimerCallback(object rem)
{
var reminder = (LocalReminderData)rem;
if (!localReminders.ContainsKey(reminder.Identity) // we have already stopped this timer
|| reminder.Timer == null) // this timer was unregistered, and is waiting to be gc-ied
return;
ticksDeliveredStat.Increment();
await reminder.OnTimerTick(tardinessStat, logger);
}
#region Utility (less useful) methods
private async Task DoResponsibilitySanityCheck(GrainReference grainRef, string debugInfo)
{
switch (status)
{
case ReminderServiceStatus.Booting:
// if service didn't finish the initial load, it could still be loading normally or it might have already
// failed a few attempts and callers should not be hold waiting for it to complete
var task = this.startedTask.Task;
if (task.IsCompleted)
{
// task at this point is already Faulted
await task;
}
else
{
try
{
// wait for the initial load task to complete (with a timeout)
await task.WithTimeout(InitialReadMaxWaitTimeForUpdates);
}
catch (TimeoutException ex)
{
throw new OrleansException("Reminder Service is still initializing and it is taking a long time. Please retry again later.", ex);
}
}
break;
case ReminderServiceStatus.Started:
break;
case ReminderServiceStatus.Stopped:
throw new OperationCanceledException("ReminderService has been stopped.");
default:
throw new InvalidOperationException("status");
}
if (!myRange.InRange(grainRef))
{
logger.Warn(ErrorCode.RS_NotResponsible, "I shouldn't have received request '{0}' for {1}. It is not in my responsibility range: {2}",
debugInfo, grainRef.ToDetailedString(), myRange);
// For now, we still let the caller proceed without throwing an exception... the periodical mechanism will take care of reminders being registered at the wrong silo
// otherwise, we can either reject the request, or re-route the request
}
}
// Note: The list of reminders can be huge in production!
private void PrintReminders(string msg = null)
{
if (!logger.IsVerbose3) return;
var str = String.Format("{0}{1}{2}", (msg ?? "Current list of reminders:"), Environment.NewLine,
Utils.EnumerableToString(localReminders, null, Environment.NewLine));
logger.Verbose3(str);
}
#endregion
private class LocalReminderData
{
private readonly IRemindable remindable;
private Stopwatch stopwatch;
private readonly DateTime firstTickTime; // time for the first tick of this reminder
private readonly TimeSpan period;
private GrainReference GrainRef { get { return Identity.GrainRef; } }
private string ReminderName { get { return Identity.ReminderName; } }
internal ReminderIdentity Identity { get; private set; }
internal string ETag;
internal GrainTimer Timer;
internal long LocalSequenceNumber; // locally, we use this for resolving races between the periodic table reader, and any concurrent local register/unregister requests
internal LocalReminderData(ReminderEntry entry)
{
Identity = new ReminderIdentity(entry.GrainRef, entry.ReminderName);
firstTickTime = entry.StartAt;
period = entry.Period;
remindable = entry.GrainRef.Cast<IRemindable>();
ETag = entry.ETag;
LocalSequenceNumber = -1;
}
public void StartTimer(Func<object, Task> asyncCallback, TraceLogger logger)
{
StopReminder(logger); // just to make sure.
var dueTimeSpan = CalculateDueTime();
Timer = GrainTimer.FromTaskCallback(asyncCallback, this, dueTimeSpan, period, name: ReminderName);
if (logger.IsVerbose) logger.Verbose("Reminder {0}, Due time{1}", this, dueTimeSpan);
Timer.Start();
}
public void StopReminder(TraceLogger logger)
{
if (Timer != null)
Timer.Dispose();
Timer = null;
}
private TimeSpan CalculateDueTime()
{
TimeSpan dueTimeSpan;
var now = DateTime.UtcNow;
if (now < firstTickTime) // if the time for first tick hasn't passed yet
{
dueTimeSpan = firstTickTime.Subtract(now); // then duetime is duration between now and the first tick time
}
else // the first tick happened in the past ... compute duetime based on the first tick time, and period
{
// formula used:
// due = period - 'time passed since last tick (==sinceLast)'
// due = period - ((Now - FirstTickTime) % period)
// explanation of formula:
// (Now - FirstTickTime) => gives amount of time since first tick happened
// (Now - FirstTickTime) % period => gives amount of time passed since the last tick should have triggered
var sinceFirstTick = now.Subtract(firstTickTime);
var sinceLastTick = TimeSpan.FromTicks(sinceFirstTick.Ticks % period.Ticks);
dueTimeSpan = period.Subtract(sinceLastTick);
// in corner cases, dueTime can be equal to period ... so, take another mod
dueTimeSpan = TimeSpan.FromTicks(dueTimeSpan.Ticks % period.Ticks);
}
return dueTimeSpan;
}
public async Task OnTimerTick(AverageTimeSpanStatistic tardinessStat, TraceLogger logger)
{
var before = DateTime.UtcNow;
var status = TickStatus.NewStruct(firstTickTime, period, before);
if (logger.IsVerbose2) logger.Verbose2("Triggering tick for {0}, status {1}, now {2}", this.ToString(), status, before);
try
{
if (null != stopwatch)
{
stopwatch.Stop();
var tardiness = stopwatch.Elapsed - period;
tardinessStat.AddSample(Math.Max(0, tardiness.Ticks));
}
await remindable.ReceiveReminder(ReminderName, status);
if (null == stopwatch)
stopwatch = new Stopwatch();
stopwatch.Restart();
var after = DateTime.UtcNow;
if (logger.IsVerbose2)
logger.Verbose2("Tick triggered for {0}, dt {1} sec, next@~ {2}", this.ToString(), (after - before).TotalSeconds,
// the next tick isn't actually scheduled until we return control to
// AsyncSafeTimer but we can approximate it by adding the period of the reminder
// to the after time.
after + period);
}
catch (Exception exc)
{
var after = DateTime.UtcNow;
logger.Error(
ErrorCode.RS_Tick_Delivery_Error,
String.Format("Could not deliver reminder tick for {0}, next {1}.", this.ToString(), after + period),
exc);
// What to do with repeated failures to deliver a reminder's ticks?
}
}
public override string ToString()
{
return string.Format("[{0}, {1}, {2}, {3}, {4}, {5}, {6}]",
ReminderName,
GrainRef.ToDetailedString(),
period,
TraceLogger.PrintDate(firstTickTime),
ETag,
LocalSequenceNumber,
Timer == null ? "Not_ticking" : "Ticking");
}
}
private struct ReminderIdentity : IEquatable<ReminderIdentity>
{
private readonly GrainReference grainRef;
private readonly string reminderName;
public GrainReference GrainRef { get { return grainRef; } }
public string ReminderName { get { return reminderName; } }
public ReminderIdentity(GrainReference grainRef, string reminderName)
{
if (grainRef == null)
throw new ArgumentNullException("grainRef");
if (string.IsNullOrWhiteSpace(reminderName))
throw new ArgumentException("The reminder name is either null or whitespace.", "reminderName");
this.grainRef = grainRef;
this.reminderName = reminderName;
}
public bool Equals(ReminderIdentity other)
{
return grainRef.Equals(other.grainRef) && reminderName.Equals(other.reminderName);
}
public override bool Equals(object other)
{
return (other is ReminderIdentity) && Equals((ReminderIdentity)other);
}
public override int GetHashCode()
{
return unchecked((int)((uint)grainRef.GetHashCode() + (uint)reminderName.GetHashCode()));
}
}
}
}
| |
// Copyright (c) 2012, Event Store LLP
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// Neither the name of the Event Store LLP nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
using System.Linq;
using System.Threading;
using EventStore.Core.Index;
using EventStore.Core.Tests.Fakes;
using EventStore.Core.TransactionLog;
using NUnit.Framework;
namespace EventStore.Core.Tests.Index
{
[TestFixture]
public class table_index_with_two_ptables_and_memtable_on_range_query : SpecificationWithDirectoryPerTestFixture
{
private TableIndex _tableIndex;
private string _indexDir;
[TestFixtureSetUp]
public override void TestFixtureSetUp()
{
base.TestFixtureSetUp();
_indexDir = PathName;
var fakeReader = new TFReaderLease(new FakeTfReader());
_tableIndex = new TableIndex(_indexDir,
() => new HashListMemTable(maxSize: 10),
() => fakeReader,
maxSizeForMemory: 2,
maxTablesPerLevel: 2);
_tableIndex.Initialize(long.MaxValue);
// ptable level 2
_tableIndex.Add(0, 0xDEAD, 0, 0xFF00);
_tableIndex.Add(0, 0xDEAD, 1, 0xFF01);
_tableIndex.Add(0, 0xBEEF, 0, 0xFF00);
_tableIndex.Add(0, 0xBEEF, 1, 0xFF01);
_tableIndex.Add(0, 0xABBA, 0, 0xFF00);
_tableIndex.Add(0, 0xABBA, 1, 0xFF01);
_tableIndex.Add(0, 0xABBA, 0, 0xFF02);
_tableIndex.Add(0, 0xABBA, 1, 0xFF03);
// ptable level 1
_tableIndex.Add(0, 0xADA, 0, 0xFF00);
_tableIndex.Add(0, 0xCEED, 10, 0xFFF1);
_tableIndex.Add(0, 0xBABA, 0, 0xFF00);
_tableIndex.Add(0, 0xDEAD, 0, 0xFF10);
// ptable level 0
_tableIndex.Add(0, 0xBABA, 1, 0xFF01);
_tableIndex.Add(0, 0xDEAD, 1, 0xFF11);
// memtable
_tableIndex.Add(0, 0xADA, 0, 0xFF01);
Thread.Sleep(500);
}
[TestFixtureTearDown]
public override void TestFixtureTearDown()
{
_tableIndex.Close();
base.TestFixtureTearDown();
}
[Test]
public void should_not_return_latest_entry_for_nonexisting_stream()
{
IndexEntry entry;
Assert.IsFalse(_tableIndex.TryGetLatestEntry(0xFEED, out entry));
}
[Test]
public void should_not_return_oldest_entry_for_nonexisting_stream()
{
IndexEntry entry;
Assert.IsFalse(_tableIndex.TryGetLatestEntry(0xFEED, out entry));
}
[Test]
public void should_return_correct_latest_entry_for_stream_with_latest_entry_in_memtable()
{
IndexEntry entry;
Assert.IsTrue(_tableIndex.TryGetLatestEntry(0xADA, out entry));
Assert.AreEqual(0xADA, entry.Stream);
Assert.AreEqual(0, entry.Version);
Assert.AreEqual(0xFF01, entry.Position);
}
[Test]
public void should_return_correct_latest_entry_for_stream_with_latest_entry_in_ptable_0()
{
IndexEntry entry;
Assert.IsTrue(_tableIndex.TryGetLatestEntry(0xDEAD, out entry));
Assert.AreEqual(0xDEAD, entry.Stream);
Assert.AreEqual(1, entry.Version);
Assert.AreEqual(0xFF11, entry.Position);
}
[Test]
public void should_return_correct_latest_entry_for_another_stream_with_latest_entry_in_ptable_0()
{
IndexEntry entry;
Assert.IsTrue(_tableIndex.TryGetLatestEntry(0xBABA, out entry));
Assert.AreEqual(0xBABA, entry.Stream);
Assert.AreEqual(1, entry.Version);
Assert.AreEqual(0xFF01, entry.Position);
}
[Test]
public void should_return_correct_latest_entry_for_stream_with_latest_entry_in_ptable_1()
{
IndexEntry entry;
Assert.IsTrue(_tableIndex.TryGetLatestEntry(0xCEED, out entry));
Assert.AreEqual(0xCEED, entry.Stream);
Assert.AreEqual(10, entry.Version);
Assert.AreEqual(0xFFF1, entry.Position);
}
[Test]
public void should_return_correct_latest_entry_for_stream_with_latest_entry_in_ptable_2()
{
IndexEntry entry;
Assert.IsTrue(_tableIndex.TryGetLatestEntry(0xBEEF, out entry));
Assert.AreEqual(0xBEEF, entry.Stream);
Assert.AreEqual(1, entry.Version);
Assert.AreEqual(0xFF01, entry.Position);
}
[Test]
public void should_return_correct_latest_entry_for_another_stream_with_latest_entry_in_ptable_2()
{
IndexEntry entry;
Assert.IsTrue(_tableIndex.TryGetLatestEntry(0xABBA, out entry));
Assert.AreEqual(0xABBA, entry.Stream);
Assert.AreEqual(1, entry.Version);
Assert.AreEqual(0xFF03, entry.Position);
}
[Test]
public void should_return_correct_oldest_entries_for_each_stream()
{
IndexEntry entry;
Assert.IsTrue(_tableIndex.TryGetOldestEntry(0xDEAD, out entry));
Assert.AreEqual(0xDEAD, entry.Stream);
Assert.AreEqual(0, entry.Version);
Assert.AreEqual(0xFF00, entry.Position);
Assert.IsTrue(_tableIndex.TryGetOldestEntry(0xBEEF, out entry));
Assert.AreEqual(0xBEEF, entry.Stream);
Assert.AreEqual(0, entry.Version);
Assert.AreEqual(0xFF00, entry.Position);
Assert.IsTrue(_tableIndex.TryGetOldestEntry(0xABBA, out entry));
Assert.AreEqual(0xABBA, entry.Stream);
Assert.AreEqual(0, entry.Version);
Assert.AreEqual(0xFF00, entry.Position);
Assert.IsTrue(_tableIndex.TryGetOldestEntry(0xADA, out entry));
Assert.AreEqual(0xADA, entry.Stream);
Assert.AreEqual(0, entry.Version);
Assert.AreEqual(0xFF00, entry.Position);
Assert.IsTrue(_tableIndex.TryGetOldestEntry(0xCEED, out entry));
Assert.AreEqual(0xCEED, entry.Stream);
Assert.AreEqual(10, entry.Version);
Assert.AreEqual(0xFFF1, entry.Position);
Assert.IsTrue(_tableIndex.TryGetOldestEntry(0xBABA, out entry));
Assert.AreEqual(0xBABA, entry.Stream);
Assert.AreEqual(0, entry.Version);
Assert.AreEqual(0xFF00, entry.Position);
}
[Test]
public void should_return_empty_range_for_nonexisting_stream()
{
var range = _tableIndex.GetRange(0xFEED, 0, int.MaxValue).ToArray();
Assert.AreEqual(0, range.Length);
}
[Test]
public void should_return_correct_full_range_with_descending_order_for_0xDEAD()
{
var range = _tableIndex.GetRange(0xDEAD, 0, int.MaxValue).ToArray();
Assert.AreEqual(4, range.Length);
Assert.AreEqual(new IndexEntry(0xDEAD, 1, 0xFF11), range[0]);
Assert.AreEqual(new IndexEntry(0xDEAD, 1, 0xFF01), range[1]);
Assert.AreEqual(new IndexEntry(0xDEAD, 0, 0xFF10), range[2]);
Assert.AreEqual(new IndexEntry(0xDEAD, 0, 0xFF00), range[3]);
}
[Test]
public void should_return_correct_full_range_with_descending_order_for_0xBEEF()
{
var range = _tableIndex.GetRange(0xBEEF, 0, int.MaxValue).ToArray();
Assert.AreEqual(2, range.Length);
Assert.AreEqual(new IndexEntry(0xBEEF, 1, 0xFF01), range[0]);
Assert.AreEqual(new IndexEntry(0xBEEF, 0, 0xFF00), range[1]);
}
[Test]
public void should_return_correct_full_range_with_descending_order_for_0xABBA()
{
var range = _tableIndex.GetRange(0xABBA, 0, int.MaxValue).ToArray();
Assert.AreEqual(4, range.Length);
Assert.AreEqual(new IndexEntry(0xABBA, 1, 0xFF03), range[0]);
Assert.AreEqual(new IndexEntry(0xABBA, 1, 0xFF01), range[1]);
Assert.AreEqual(new IndexEntry(0xABBA, 0, 0xFF02), range[2]);
Assert.AreEqual(new IndexEntry(0xABBA, 0, 0xFF00), range[3]);
}
[Test]
public void should_return_correct_full_range_with_descending_order_for_0xADA()
{
var range = _tableIndex.GetRange(0xADA, 0, int.MaxValue).ToArray();
Assert.AreEqual(2, range.Length);
Assert.AreEqual(new IndexEntry(0xADA, 0, 0xFF01), range[0]);
Assert.AreEqual(new IndexEntry(0xADA, 0, 0xFF00), range[1]);
}
[Test]
public void should_return_correct_full_range_with_descending_order_for_0xCEED()
{
var range = _tableIndex.GetRange(0xCEED, 0, int.MaxValue).ToArray();
Assert.AreEqual(1, range.Length);
Assert.AreEqual(new IndexEntry(0xCEED, 10, 0xFFF1), range[0]);
}
[Test]
public void should_return_correct_full_range_with_descending_order_for_0xBABA()
{
var range = _tableIndex.GetRange(0xBABA, 0, int.MaxValue).ToArray();
Assert.AreEqual(2, range.Length);
Assert.AreEqual(new IndexEntry(0xBABA, 1, 0xFF01), range[0]);
Assert.AreEqual(new IndexEntry(0xBABA, 0, 0xFF00), range[1]);
}
[Test]
public void should_not_return_one_value_for_nonexistent_stream()
{
long pos;
Assert.IsFalse(_tableIndex.TryGetOneValue(0xFEED, 0, out pos));
}
[Test]
public void should_return_one_value_for_existing_streams_for_existing_version()
{
long pos;
Assert.IsTrue(_tableIndex.TryGetOneValue(0xDEAD, 1, out pos));
Assert.AreEqual(0xFF11, pos);
Assert.IsTrue(_tableIndex.TryGetOneValue(0xBEEF, 0, out pos));
Assert.AreEqual(0xFF00, pos);
Assert.IsTrue(_tableIndex.TryGetOneValue(0xABBA, 0, out pos));
Assert.AreEqual(0xFF02, pos);
Assert.IsTrue(_tableIndex.TryGetOneValue(0xADA, 0, out pos));
Assert.AreEqual(0xFF01, pos);
Assert.IsTrue(_tableIndex.TryGetOneValue(0xCEED, 10, out pos));
Assert.AreEqual(0xFFF1, pos);
Assert.IsTrue(_tableIndex.TryGetOneValue(0xBABA, 1, out pos));
Assert.AreEqual(0xFF01, pos);
}
[Test]
public void should_not_return_one_value_for_existing_streams_for_nonexistent_version()
{
long pos;
Assert.IsFalse(_tableIndex.TryGetOneValue(0xDEAD, 2, out pos));
Assert.IsFalse(_tableIndex.TryGetOneValue(0xBEEF, 2, out pos));
Assert.IsFalse(_tableIndex.TryGetOneValue(0xABBA, 2, out pos));
Assert.IsFalse(_tableIndex.TryGetOneValue(0xADA, 1, out pos));
Assert.IsFalse(_tableIndex.TryGetOneValue(0xCEED, 0, out pos));
Assert.IsFalse(_tableIndex.TryGetOneValue(0xBABA, 2, out pos));
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsHttp
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// HttpRetry operations.
/// </summary>
public partial class HttpRetry : IServiceOperations<AutoRestHttpInfrastructureTestService>, IHttpRetry
{
/// <summary>
/// Initializes a new instance of the HttpRetry class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
public HttpRetry(AutoRestHttpInfrastructureTestService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestHttpInfrastructureTestService
/// </summary>
public AutoRestHttpInfrastructureTestService Client { get; private set; }
/// <summary>
/// Return 408 status code, then 200 after retry
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Head408WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Head408", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/retry/408").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("HEAD");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Return 500 status code, then 200 after retry
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Put500WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Put500", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/retry/500").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
_requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Return 500 status code, then 200 after retry
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Patch500WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Patch500", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/retry/500").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
_requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Return 502 status code, then 200 after retry
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Get502WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get502", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/retry/502").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Return 503 status code, then 200 after retry
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Post503WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Post503", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/retry/503").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
_requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Return 503 status code, then 200 after retry
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Delete503WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete503", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/retry/503").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
_requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Return 504 status code, then 200 after retry
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Put504WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Put504", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/retry/504").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
_requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Return 504 status code, then 200 after retry
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Patch504WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Patch504", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/retry/504").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
_requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
if($GameCanvas == OculusCanvas)
$GameCanvas = Canvas;
// Cleanup Dialog created by 'core'
if( isObject( MessagePopupDlg ) )
MessagePopupDlg.delete();
if( isObject( MessageBoxYesNoDlg ) )
MessageBoxYesNoDlg.delete();
if( isObject( MessageBoxYesNoCancelDlg ) )
MessageBoxYesNoCancelDlg.delete();
if( isObject( MessageBoxOKCancelDetailsDlg ) )
MessageBoxOKCancelDetailsDlg.delete();
if( isObject( MessageBoxOKCancelDlg ) )
MessageBoxOKCancelDlg.delete();
if( isObject( MessageBoxOKDlg ) )
MessageBoxOKDlg.delete();
if( isObject( IODropdownDlg ) )
IODropdownDlg.delete();
// Load Editor Dialogs
exec("./messageBoxOk.ed.gui");
exec("./messageBoxYesNo.ed.gui");
exec("./messageBoxYesNoCancel.ed.gui");
exec("./messageBoxOkCancel.ed.gui");
exec("./MessageBoxOKCancelDetailsDlg.ed.gui");
exec("./messagePopup.ed.gui");
exec("./IODropdownDlg.ed.gui");
// --------------------------------------------------------------------
// Message Sound
// --------------------------------------------------------------------
/*new SFXDescription(MessageBoxAudioDescription)
{
volume = 1.0;
isLooping = false;
is3D = false;
channel = $GuiAudioType;
};
new SFXProfile(messageBoxBeep)
{
filename = "./messageBoxSound";
description = MessageBoxAudioDescription;
preload = true;
};*/
//---------------------------------------------------------------------------------------------
// messageCallback
// Calls a callback passed to a message box.
//---------------------------------------------------------------------------------------------
function messageCallback(%dlg, %callback)
{
$GameCanvas.popDialog(%dlg);
eval(%callback);
}
//The # in the function passed replaced with the output
//of the preset menu.
function IOCallback(%dlg, %callback)
{
%id = IODropdownMenu.getSelected();
%text = IODropdownMenu.getTextById(%id);
%callback = strreplace(%callback, "#", %text);
eval(%callback);
$GameCanvas.popDialog(%dlg);
}
//---------------------------------------------------------------------------------------------
// MBSetText
// Sets the text of a message box and resizes it to accomodate the new string.
//---------------------------------------------------------------------------------------------
function MBSetText(%text, %frame, %msg)
{
// Get the extent of the text box.
%ext = %text.getExtent();
// Set the text in the center of the text box.
%text.setText("<just:center>" @ %msg);
// Force the textbox to resize itself vertically.
%text.forceReflow();
// Grab the new extent of the text box.
%newExtent = %text.getExtent();
// Get the vertical change in extent.
%deltaY = getWord(%newExtent, 1) - getWord(%ext, 1);
// Resize the window housing the text box.
%windowPos = %frame.getPosition();
%windowExt = %frame.getExtent();
%frame.resize(getWord(%windowPos, 0), getWord(%windowPos, 1) - (%deltaY / 2),
getWord(%windowExt, 0), getWord(%windowExt, 1) + %deltaY);
%frame.canMove = "0";
//%frame.canClose = "0";
%frame.resizeWidth = "0";
%frame.resizeHeight = "0";
%frame.canMinimize = "0";
%frame.canMaximize = "0";
//sfxPlayOnce( messageBoxBeep );
}
//---------------------------------------------------------------------------------------------
// Various message box display functions. Each one takes a window title, a message, and a
// callback for each button.
//---------------------------------------------------------------------------------------------
function MessageBoxOK(%title, %message, %callback)
{
MBOKFrame.text = %title;
$GameCanvas.pushDialog(MessageBoxOKDlg);
MBSetText(MBOKText, MBOKFrame, %message);
MessageBoxOKDlg.callback = %callback;
}
function MessageBoxOKDlg::onSleep( %this )
{
%this.callback = "";
}
function MessageBoxOKCancel(%title, %message, %callback, %cancelCallback)
{
MBOKCancelFrame.text = %title;
$GameCanvas.pushDialog(MessageBoxOKCancelDlg);
MBSetText(MBOKCancelText, MBOKCancelFrame, %message);
MessageBoxOKCancelDlg.callback = %callback;
MessageBoxOKCancelDlg.cancelCallback = %cancelCallback;
}
function MessageBoxOKCancelDlg::onSleep( %this )
{
%this.callback = "";
}
function MessageBoxOKCancelDetails(%title, %message, %details, %callback, %cancelCallback)
{
if(%details $= "")
{
MBOKCancelDetailsButton.setVisible(false);
}
MBOKCancelDetailsScroll.setVisible(false);
MBOKCancelDetailsFrame.setText( %title );
$GameCanvas.pushDialog(MessageBoxOKCancelDetailsDlg);
MBSetText(MBOKCancelDetailsText, MBOKCancelDetailsFrame, %message);
MBOKCancelDetailsInfoText.setText(%details);
%textExtent = MBOKCancelDetailsText.getExtent();
%textExtentY = getWord(%textExtent, 1);
%textPos = MBOKCancelDetailsText.getPosition();
%textPosY = getWord(%textPos, 1);
%extentY = %textPosY + %textExtentY + 65;
MBOKCancelDetailsInfoText.setExtent(285, 128);
MBOKCancelDetailsFrame.setExtent(300, %extentY);
MessageBoxOKCancelDetailsDlg.callback = %callback;
MessageBoxOKCancelDetailsDlg.cancelCallback = %cancelCallback;
MBOKCancelDetailsFrame.defaultExtent = MBOKCancelDetailsFrame.getExtent();
}
function MBOKCancelDetailsToggleInfoFrame()
{
if(!MBOKCancelDetailsScroll.isVisible())
{
MBOKCancelDetailsScroll.setVisible(true);
MBOKCancelDetailsText.forceReflow();
%textExtent = MBOKCancelDetailsText.getExtent();
%textExtentY = getWord(%textExtent, 1);
%textPos = MBOKCancelDetailsText.getPosition();
%textPosY = getWord(%textPos, 1);
%verticalStretch = %textExtentY;
if((%verticalStretch > 260) || (%verticalStretch < 0))
%verticalStretch = 260;
%extent = MBOKCancelDetailsFrame.defaultExtent;
%height = getWord(%extent, 1);
%posY = %textPosY + %textExtentY + 10;
%posX = getWord(MBOKCancelDetailsScroll.getPosition(), 0);
MBOKCancelDetailsScroll.setPosition(%posX, %posY);
MBOKCancelDetailsScroll.setExtent(getWord(MBOKCancelDetailsScroll.getExtent(), 0), %verticalStretch);
MBOKCancelDetailsFrame.setExtent(300, %height + %verticalStretch + 10);
} else
{
%extent = MBOKCancelDetailsFrame.defaultExtent;
%width = getWord(%extent, 0);
%height = getWord(%extent, 1);
MBOKCancelDetailsFrame.setExtent(%width, %height);
MBOKCancelDetailsScroll.setVisible(false);
}
}
function MessageBoxOKCancelDetailsDlg::onSleep( %this )
{
%this.callback = "";
}
function MessageBoxYesNo(%title, %message, %yesCallback, %noCallback)
{
MBYesNoFrame.text = %title;
MessageBoxYesNoDlg.profile = "GuiOverlayProfile";
$GameCanvas.pushDialog(MessageBoxYesNoDlg);
MBSetText(MBYesNoText, MBYesNoFrame, %message);
MessageBoxYesNoDlg.yesCallBack = %yesCallback;
MessageBoxYesNoDlg.noCallback = %noCallBack;
}
function MessageBoxYesNoCancel(%title, %message, %yesCallback, %noCallback, %cancelCallback)
{
MBYesNoCancelFrame.text = %title;
MessageBoxYesNoDlg.profile = "GuiOverlayProfile";
$GameCanvas.pushDialog(MessageBoxYesNoCancelDlg);
MBSetText(MBYesNoCancelText, MBYesNoCancelFrame, %message);
MessageBoxYesNoCancelDlg.yesCallBack = %yesCallback;
MessageBoxYesNoCancelDlg.noCallback = %noCallBack;
MessageBoxYesNoCancelDlg.cancelCallback = %cancelCallback;
}
function MessageBoxYesNoDlg::onSleep( %this )
{
%this.yesCallback = "";
%this.noCallback = "";
}
//---------------------------------------------------------------------------------------------
// MessagePopup
// Displays a message box with no buttons. Disappears after %delay milliseconds.
//---------------------------------------------------------------------------------------------
function MessagePopup(%title, %message, %delay)
{
// Currently two lines max.
MessagePopFrame.setText(%title);
$GameCanvas.pushDialog(MessagePopupDlg);
MBSetText(MessagePopText, MessagePopFrame, %message);
if (%delay !$= "")
schedule(%delay, 0, CloseMessagePopup);
}
//---------------------------------------------------------------------------------------------
// IODropdown
// By passing in a simgroup or simset, the user will be able to choose a child of that group
// through a guiPopupMenuCtrl
//---------------------------------------------------------------------------------------------
function IODropdown(%title, %message, %simgroup, %callback, %cancelCallback)
{
IODropdownFrame.text = %title;
$GameCanvas.pushDialog(IODropdownDlg);
MBSetText(IODropdownText, IODropdownFrame, %message);
if(isObject(%simgroup))
{
for(%i = 0; %i < %simgroup.getCount(); %i++)
IODropdownMenu.add(%simgroup.getObject(%i).getName());
}
IODropdownMenu.sort();
IODropdownMenu.setFirstSelected(0);
IODropdownDlg.callback = %callback;
IODropdownDlg.cancelCallback = %cancelCallback;
}
function IODropdownDlg::onSleep( %this )
{
%this.callback = "";
%this.cancelCallback = "";
IODropdownMenu.clear();
}
function CloseMessagePopup()
{
$GameCanvas.popDialog(MessagePopupDlg);
}
//---------------------------------------------------------------------------------------------
// "Old" message box function aliases for backwards-compatibility.
//---------------------------------------------------------------------------------------------
function MessageBoxOKOld( %title, %message, %callback )
{
MessageBoxOK( %title, %message, %callback );
}
function MessageBoxOKCancelOld( %title, %message, %callback, %cancelCallback )
{
MessageBoxOKCancel( %title, %message, %callback, %cancelCallback );
}
function MessageBoxYesNoOld( %title, %message, %yesCallback, %noCallback )
{
MessageBoxYesNo( %title, %message, %yesCallback, %noCallback );
}
| |
//
// Copyright (C) Microsoft. All rights reserved.
//
using Microsoft.PowerShell.Activities;
using System.Management.Automation;
using System.Activities;
using System.Collections.Generic;
using System.ComponentModel;
namespace Microsoft.WSMan.Management.Activities
{
/// <summary>
/// Activity to invoke the Microsoft.WSMan.Management\Invoke-WSManAction command in a Workflow.
/// </summary>
[System.CodeDom.Compiler.GeneratedCode("Microsoft.PowerShell.Activities.ActivityGenerator.GenerateFromName", "3.0")]
public sealed class InvokeWSManAction : PSRemotingActivity
{
/// <summary>
/// Gets the display name of the command invoked by this activity.
/// </summary>
public InvokeWSManAction()
{
this.DisplayName = "Invoke-WSManAction";
}
/// <summary>
/// Gets the fully qualified name of the command invoked by this activity.
/// </summary>
public override string PSCommandName { get { return "Microsoft.WSMan.Management\\Invoke-WSManAction"; } }
// Arguments
/// <summary>
/// Provides access to the Action parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> Action { get; set; }
/// <summary>
/// Provides access to the ApplicationName parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> ApplicationName { get; set; }
/// <summary>
/// Provides access to the ComputerName parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> ComputerName { get; set; }
/// <summary>
/// Provides access to the ConnectionURI parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Uri> ConnectionURI { get; set; }
/// <summary>
/// Provides access to the FilePath parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> FilePath { get; set; }
/// <summary>
/// Provides access to the OptionSet parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Collections.Hashtable> OptionSet { get; set; }
/// <summary>
/// Provides access to the Port parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Int32> Port { get; set; }
/// <summary>
/// Provides access to the SelectorSet parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Collections.Hashtable> SelectorSet { get; set; }
/// <summary>
/// Provides access to the SessionOption parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<Microsoft.WSMan.Management.SessionOption> SessionOption { get; set; }
/// <summary>
/// Provides access to the UseSSL parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> UseSSL { get; set; }
/// <summary>
/// Provides access to the ValueSet parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Collections.Hashtable> ValueSet { get; set; }
/// <summary>
/// Provides access to the ResourceURI parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Uri> ResourceURI { get; set; }
/// <summary>
/// Provides access to the Credential parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.PSCredential> Credential { get; set; }
/// <summary>
/// Provides access to the Authentication parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<Microsoft.WSMan.Management.AuthenticationMechanism> Authentication { get; set; }
/// <summary>
/// Provides access to the CertificateThumbprint parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> CertificateThumbprint { get; set; }
/// <summary>
/// Declares that this activity supports its own remoting.
/// </summary>
protected override bool SupportsCustomRemoting { get { return true; } }
// Module defining this command
// Optional custom code for this activity
/// <summary>
/// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
/// </summary>
/// <param name="context">The NativeActivityContext for the currently running activity.</param>
/// <returns>A populated instance of System.Management.Automation.PowerShell</returns>
/// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
{
System.Management.Automation.PowerShell invoker = global::System.Management.Automation.PowerShell.Create();
System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);
// Initialize the arguments
if(Action.Expression != null)
{
targetCommand.AddParameter("Action", Action.Get(context));
}
if(ApplicationName.Expression != null)
{
targetCommand.AddParameter("ApplicationName", ApplicationName.Get(context));
}
if((ComputerName.Expression != null) && (PSRemotingBehavior.Get(context) != RemotingBehavior.Custom))
{
targetCommand.AddParameter("ComputerName", ComputerName.Get(context));
}
if(ConnectionURI.Expression != null)
{
targetCommand.AddParameter("ConnectionURI", ConnectionURI.Get(context));
}
if(FilePath.Expression != null)
{
targetCommand.AddParameter("FilePath", FilePath.Get(context));
}
if(OptionSet.Expression != null)
{
targetCommand.AddParameter("OptionSet", OptionSet.Get(context));
}
if(Port.Expression != null)
{
targetCommand.AddParameter("Port", Port.Get(context));
}
if(SelectorSet.Expression != null)
{
targetCommand.AddParameter("SelectorSet", SelectorSet.Get(context));
}
if(SessionOption.Expression != null)
{
targetCommand.AddParameter("SessionOption", SessionOption.Get(context));
}
if(UseSSL.Expression != null)
{
targetCommand.AddParameter("UseSSL", UseSSL.Get(context));
}
if(ValueSet.Expression != null)
{
targetCommand.AddParameter("ValueSet", ValueSet.Get(context));
}
if(ResourceURI.Expression != null)
{
targetCommand.AddParameter("ResourceURI", ResourceURI.Get(context));
}
if(Credential.Expression != null)
{
targetCommand.AddParameter("Credential", Credential.Get(context));
}
if(Authentication.Expression != null)
{
targetCommand.AddParameter("Authentication", Authentication.Get(context));
}
if(CertificateThumbprint.Expression != null)
{
targetCommand.AddParameter("CertificateThumbprint", CertificateThumbprint.Get(context));
}
if(GetIsComputerNameSpecified(context) && (PSRemotingBehavior.Get(context) == RemotingBehavior.Custom))
{
targetCommand.AddParameter("ComputerName", PSComputerName.Get(context));
}
return new ActivityImplementationContext() { PowerShellInstance = invoker };
}
}
}
| |
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information.
using Microsoft.VisualStudio.Shell.Interop;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security;
using System.Windows;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Collections;
using System.Text;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
using IServiceProvider = System.IServiceProvider;
using ShellConstants = Microsoft.VisualStudio.Shell.Interop.Constants;
using OleConstants = Microsoft.VisualStudio.OLE.Interop.Constants;
namespace Microsoft.VisualStudio.FSharp.ProjectSystem
{
/// <summary>
/// This abstract class handles opening, saving of items in the hierarchy.
/// </summary>
internal abstract class DocumentManager
{
private HierarchyNode node = null;
public HierarchyNode Node
{
get
{
return this.node;
}
}
public DocumentManager(HierarchyNode node)
{
this.node = node;
}
/// <summary>
/// Open a document using the standard editor. This method has no implementation since a document is abstract in this context
/// </summary>
/// <param name="logicalView">In MultiView case determines view to be activated by IVsMultiViewDocumentView. For a list of logical view GUIDS, see constants starting with LOGVIEWID_ defined in NativeMethods class</param>
/// <param name="docDataExisting">IntPtr to the IUnknown interface of the existing document data object</param>
/// <param name="windowFrame">A reference to the window frame that is mapped to the document</param>
/// <param name="windowFrameAction">Determine the UI action on the document window</param>
/// <returns>NotImplementedException</returns>
/// <remarks>See FileDocumentManager class for an implementation of this method</remarks>
public virtual int Open(ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame windowFrame, WindowFrameShowAction windowFrameAction)
{
throw new NotImplementedException();
}
/// <summary>
/// Open a document using a specific editor. This method has no implementation.
/// </summary>
/// <param name="editorFlags">Specifies actions to take when opening a specific editor. Possible editor flags are defined in the enumeration Microsoft.VisualStudio.Shell.Interop.__VSOSPEFLAGS</param>
/// <param name="editorType">Unique identifier of the editor type</param>
/// <param name="physicalView">Name of the physical view. If null, the environment calls MapLogicalView on the editor factory to determine the physical view that corresponds to the logical view. In this case, null does not specify the primary view, but rather indicates that you do not know which view corresponds to the logical view</param>
/// <param name="logicalView">In MultiView case determines view to be activated by IVsMultiViewDocumentView. For a list of logical view GUIDS, see constants starting with LOGVIEWID_ defined in NativeMethods class</param>
/// <param name="docDataExisting">IntPtr to the IUnknown interface of the existing document data object</param>
/// <param name="frame">A reference to the window frame that is mapped to the document</param>
/// <param name="windowFrameAction">Determine the UI action on the document window</param>
/// <returns>NotImplementedException</returns>
/// <remarks>See FileDocumentManager for an implementation of this method</remarks>
public virtual int OpenWithSpecific(uint editorFlags, ref Guid editorType, string physicalView, ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame frame, WindowFrameShowAction windowFrameAction)
{
throw new NotImplementedException();
}
/// <summary>
/// Close an open document window
/// </summary>
/// <param name="closeFlag">Decides how to close the document</param>
/// <returns>S_OK if successful, otherwise an error is returned</returns>
public virtual int Close(__FRAMECLOSE closeFlag)
{
if (this.node == null || this.node.ProjectMgr == null || this.node.ProjectMgr.IsClosed)
{
return VSConstants.E_FAIL;
}
// Get info about the document
bool isDirty, isOpen, isOpenedByUs;
uint docCookie;
IVsPersistDocData ppIVsPersistDocData;
this.GetDocInfo(out isOpen, out isDirty, out isOpenedByUs, out docCookie, out ppIVsPersistDocData);
if (isOpenedByUs)
{
IVsUIShellOpenDocument shell = this.Node.ProjectMgr.Site.GetService(typeof(IVsUIShellOpenDocument)) as IVsUIShellOpenDocument;
Guid logicalView = Guid.Empty;
uint grfIDO = 0;
IVsUIHierarchy pHierOpen;
uint[] itemIdOpen = new uint[1];
IVsWindowFrame windowFrame;
int fOpen;
ErrorHandler.ThrowOnFailure(shell.IsDocumentOpen(this.Node.ProjectMgr.InteropSafeIVsUIHierarchy, this.Node.ID, this.Node.Url, ref logicalView, grfIDO, out pHierOpen, itemIdOpen, out windowFrame, out fOpen));
if (windowFrame != null)
{
docCookie = 0;
return windowFrame.CloseFrame((uint)closeFlag);
}
}
return VSConstants.S_OK;
}
/// <summary>
/// Silently saves an open document
/// </summary>
/// <param name="saveIfDirty">Save the open document only if it is dirty</param>
/// <remarks>The call to SaveDocData may return Microsoft.VisualStudio.Shell.Interop.PFF_RESULTS.STG_S_DATALOSS to indicate some characters could not be represented in the current codepage</remarks>
public virtual void Save(bool saveIfDirty)
{
bool isDirty, isOpen, isOpenedByUs;
uint docCookie;
IVsPersistDocData persistDocData;
this.GetDocInfo(out isOpen, out isDirty, out isOpenedByUs, out docCookie, out persistDocData);
if (isDirty && saveIfDirty && persistDocData != null)
{
string name;
int cancelled;
ErrorHandler.ThrowOnFailure(persistDocData.SaveDocData(VSSAVEFLAGS.VSSAVE_SilentSave, out name, out cancelled));
}
}
/// <summary>
/// Get document properties from RDT
/// </summary>
public void GetDocInfo(
out bool isOpen, // true if the doc is opened
out bool isDirty, // true if the doc is dirty
out bool isOpenedByUs, // true if opened by our project
out uint docCookie, // VSDOCCOOKIE if open
out IVsPersistDocData persistDocData)
{
isOpen = isDirty = isOpenedByUs = false;
docCookie = (uint)ShellConstants.VSDOCCOOKIE_NIL;
persistDocData = null;
if (this.node == null || this.node.ProjectMgr == null || this.node.ProjectMgr.IsClosed)
{
return;
}
IVsHierarchy hierarchy;
uint vsitemid = VSConstants.VSITEMID_NIL;
VsShellUtilities.GetRDTDocumentInfo(this.node.ProjectMgr.Site, this.node.Url, out hierarchy, out vsitemid, out persistDocData, out docCookie);
if (hierarchy == null || docCookie == (uint)ShellConstants.VSDOCCOOKIE_NIL)
{
return;
}
isOpen = true;
// check if the doc is opened by another project
if (Utilities.IsSameComObject(this.node.ProjectMgr, hierarchy))
{
isOpenedByUs = true;
}
if (persistDocData != null)
{
int isDocDataDirty;
ErrorHandler.ThrowOnFailure(persistDocData.IsDocDataDirty(out isDocDataDirty));
isDirty = (isDocDataDirty != 0);
}
}
public string GetOwnerCaption()
{
Debug.Assert(this.node != null, "No node has been initialized for the document manager");
object pvar;
ErrorHandler.ThrowOnFailure(this.node.GetProperty(this.node.ID, (int)__VSHPROPID.VSHPROPID_Caption, out pvar));
return (pvar as string);
}
public void CloseWindowFrame(ref IVsWindowFrame windowFrame)
{
if (windowFrame != null)
{
try
{
ErrorHandler.ThrowOnFailure(windowFrame.CloseFrame(0));
}
finally
{
windowFrame = null;
}
}
}
public string GetFullPathForDocument()
{
string fullPath = String.Empty;
Debug.Assert(this.node != null, "No node has been initialized for the document manager");
// Get the URL representing the item
fullPath = this.node.GetMkDocument();
Debug.Assert(!String.IsNullOrEmpty(fullPath), "Could not retrive the fullpath for the node" + this.Node.ID.ToString(CultureInfo.CurrentCulture));
return fullPath;
}
/// <summary>
/// Updates the caption for all windows associated to the document.
/// </summary>
/// <param name="site">The service provider.</param>
/// <param name="caption">The new caption.</param>
/// <param name="docData">The IUnknown interface to a document data object associated with a registered document.</param>
public static void UpdateCaption(IServiceProvider site, string caption, IntPtr docData)
{
if (site == null)
{
throw new ArgumentNullException("site");
}
if (String.IsNullOrEmpty(caption))
{
throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty, CultureInfo.CurrentUICulture), "caption");
}
IVsUIShell uiShell = site.GetService(typeof(SVsUIShell)) as IVsUIShell;
// We need to tell the windows to update their captions.
IEnumWindowFrames windowFramesEnum;
ErrorHandler.ThrowOnFailure(uiShell.GetDocumentWindowEnum(out windowFramesEnum));
IVsWindowFrame[] windowFrames = new IVsWindowFrame[1];
uint fetched;
while (windowFramesEnum.Next(1, windowFrames, out fetched) == VSConstants.S_OK && fetched == 1)
{
IVsWindowFrame windowFrame = windowFrames[0];
object data;
ErrorHandler.ThrowOnFailure(windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out data));
IntPtr ptr = Marshal.GetIUnknownForObject(data);
try
{
if (ptr == docData)
{
ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID.VSFPROPID_OwnerCaption, caption));
}
}
finally
{
if (ptr != IntPtr.Zero)
{
Marshal.Release(ptr);
}
}
}
}
/// <summary>
/// Rename document in the running document table from oldName to newName.
/// </summary>
/// <param name="site">The service provider.</param>
/// <param name="oldName">Full path to the old name of the document.</param>
/// <param name="newName">Full path to the new name of the document.</param>
/// <param name="newItemId">The new item id of the document</param>
public static void RenameDocument(IServiceProvider site, string oldName, string newName, uint newItemId)
{
if (site == null)
{
throw new ArgumentNullException("site");
}
if (String.IsNullOrEmpty(oldName))
{
throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty, CultureInfo.CurrentUICulture), "oldName");
}
if (String.IsNullOrEmpty(newName))
{
throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty, CultureInfo.CurrentUICulture), "newName");
}
if (newItemId == VSConstants.VSITEMID_NIL)
{
throw new ArgumentNullException("newItemId");
}
IVsRunningDocumentTable pRDT = site.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
if (pRDT == null) return;
IVsHierarchy pIVsHierarchy;
uint itemId;
IntPtr docData = IntPtr.Zero;
uint uiVsDocCookie;
try
{
int hr = pRDT.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, oldName, out pIVsHierarchy, out itemId, out docData, out uiVsDocCookie);
ErrorHandler.ThrowOnFailure(hr);
if (pIVsHierarchy == null)
{
// the doc is not in the RDT yet, e.g. user never opened this doc.
// nothing to do then.
}
else
{
IntPtr pUnk = Marshal.GetIUnknownForObject(pIVsHierarchy);
Guid iid = typeof(IVsHierarchy).GUID;
IntPtr pHier;
Marshal.QueryInterface(pUnk, ref iid, out pHier);
try
{
ErrorHandler.ThrowOnFailure(pRDT.RenameDocument(oldName, newName, pHier, newItemId));
}
finally
{
if (pHier != IntPtr.Zero)
Marshal.Release(pHier);
if (pUnk != IntPtr.Zero)
Marshal.Release(pUnk);
}
}
}
finally
{
if (docData != IntPtr.Zero)
{
Marshal.Release(docData);
}
}
}
}
}
| |
//
// 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.Linq;
using System.Text;
using NetworkCommsDotNet;
using NetworkCommsDotNet.DPSBase;
using System.Net;
using NetworkCommsDotNet.Connections;
using NetworkCommsDotNet.Tools;
using NetworkCommsDotNet.Connections.TCP;
using NetworkCommsDotNet.Connections.UDP;
namespace Examples.ExamplesChat.WP8
{
/// <summary>
/// In an attempt to keep things as clear as possible all shared implementation across chat examples
/// has been provided in this base class.
/// </summary>
public abstract class ChatAppBase
{
#region Private Fields
/// <summary>
/// A boolean used to track the very first initialisation
/// </summary>
protected bool FirstInitialisation { get; set; }
/// <summary>
/// Dictionary to keep track of which peer messages have already been written to the chat window
/// </summary>
protected Dictionary<ShortGuid, ChatMessage> lastPeerMessageDict = new Dictionary<ShortGuid, ChatMessage>();
/// <summary>
/// The maximum number of times a chat message will be relayed
/// </summary>
int relayMaximum = 3;
/// <summary>
/// A local counter used to track the number of messages sent from
/// this instance.
/// </summary>
long messageSendIndex = 0;
/// <summary>
/// An optional encryption key to use should one be required.
/// This can be changed freely but must obviously be the same
/// for both sender and receiver.
/// </summary>
string _encryptionKey = "ljlhjf8uyfln23490jf;m21-=scm20--iflmk;";
#endregion
#region Public Fields
/// <summary>
/// The type of connection currently used to send and receive messages. Default is TCP.
/// </summary>
public ConnectionType ConnectionType { get; set; }
/// <summary>
/// The serializer to use when sending messages
/// </summary>
public DataSerializer Serializer { get; set; }
/// <summary>
/// The IP address of the server
/// </summary>
public string ServerIPAddress { get; set; }
/// <summary>
/// The port of the server
/// </summary>
public int ServerPort { get; set; }
/// <summary>
/// The local name used when sending messages
/// </summary>
public string LocalName { get; set; }
/// <summary>
/// A boolean used to track if the local device is acting as a server
/// </summary>
public bool LocalServerEnabled { get; set; }
/// <summary>
/// A boolean used to track if encryption is currently being used
/// </summary>
public bool EncryptionEnabled { get; set; }
#endregion
/// <summary>
/// Constructor for ChatAppBase
/// </summary>
public ChatAppBase(string name, ConnectionType connectionType)
{
LocalName = name;
ConnectionType = connectionType;
//Initialise the default values
ServerIPAddress = "";
ServerPort = 10000;
LocalServerEnabled = false;
EncryptionEnabled = false;
FirstInitialisation = true;
}
#region NetworkComms.Net Methods
/// <summary>
/// Updates the configuration of this instance depending on set fields
/// </summary>
public void RefreshNetworkCommsConfiguration()
{
#region First Initialisation
//On first initialisation we need to configure NetworkComms.Net to handle our incoming packet types
//We only need to add the packet handlers once. If we call NetworkComms.Shutdown() at some future point these are not removed.
if (FirstInitialisation)
{
FirstInitialisation = false;
//Configure NetworkComms.Net to handle any incoming packet of type 'ChatMessage'
//e.g. If we receive a packet of type 'ChatMessage' execute the method 'HandleIncomingChatMessage'
NetworkComms.AppendGlobalIncomingPacketHandler<ChatMessage>("ChatMessage", HandleIncomingChatMessage);
//Configure NetworkComms.Net to perform some action when a connection is closed
//e.g. When a connection is closed execute the method 'HandleConnectionClosed'
NetworkComms.AppendGlobalConnectionCloseHandler(HandleConnectionClosed);
}
#endregion
#region Set serializer
//Set the default send recieve options to use the specified serializer. Keep the DataProcessors and Options from the previous defaults
NetworkComms.DefaultSendReceiveOptions = new SendReceiveOptions(Serializer, NetworkComms.DefaultSendReceiveOptions.DataProcessors, NetworkComms.DefaultSendReceiveOptions.Options);
#endregion
#region Optional Encryption
//Configure encryption if requested
if (EncryptionEnabled && !NetworkComms.DefaultSendReceiveOptions.DataProcessors.Contains(DPSManager.GetDataProcessor<RijndaelPSKEncrypter>()))
{
//Encryption is currently implemented using a pre-shared key (PSK) system
//NetworkComms.Net supports multiple data processors which can be used with any level of granularity
//To enable encryption globally (i.e. for all connections) we first add the encryption password as an option
RijndaelPSKEncrypter.AddPasswordToOptions(NetworkComms.DefaultSendReceiveOptions.Options, _encryptionKey);
//Finally we add the RijndaelPSKEncrypter data processor to the sendReceiveOptions
NetworkComms.DefaultSendReceiveOptions.DataProcessors.Add(DPSManager.GetDataProcessor<RijndaelPSKEncrypter>());
}
else if (!EncryptionEnabled && NetworkComms.DefaultSendReceiveOptions.DataProcessors.Contains(DPSManager.GetDataProcessor<RijndaelPSKEncrypter>()))
{
//If encryption has been disabled but is currently enabled
//To disable encryption we just remove the RijndaelPSKEncrypter data processor from the sendReceiveOptions
NetworkComms.DefaultSendReceiveOptions.DataProcessors.Remove(DPSManager.GetDataProcessor<RijndaelPSKEncrypter>());
}
#endregion
#region Local Server Mode and Connection Type Changes
if (LocalServerEnabled && ConnectionType == ConnectionType.TCP && !Connection.Listening(ConnectionType.TCP))
{
//If we were previously listening for UDP we first shutdown NetworkComms.Net.
if (Connection.Listening(ConnectionType.UDP))
{
AppendLineToChatHistory("Connection mode has been changed. Any existing connections will be closed.");
NetworkComms.Shutdown();
}
else
{
AppendLineToChatHistory("Enabling local server mode. Any existing connections will be closed.");
NetworkComms.Shutdown();
}
//Start listening for new incoming TCP connections
//We want to select a random port on all available adaptors so provide
//an IPEndPoint using IPAddress.Any and port 0.
Connection.StartListening(ConnectionType.TCP, new IPEndPoint(IPAddress.Any, 0));
//Write the IP addresses and ports that we are listening on to the chatBox
AppendLineToChatHistory("Listening for incoming TCP connections on:");
foreach (IPEndPoint listenEndPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.TCP))
AppendLineToChatHistory(listenEndPoint.Address + ":" + listenEndPoint.Port);
//Add a blank line after the initialisation output
AppendLineToChatHistory(System.Environment.NewLine);
}
else if (LocalServerEnabled && ConnectionType == ConnectionType.UDP && !Connection.Listening(ConnectionType.UDP))
{
//If we were previously listening for TCP we first shutdown NetworkComms.Net.
if (Connection.Listening(ConnectionType.TCP))
{
AppendLineToChatHistory("Connection mode has been changed. Any existing connections will be closed.");
NetworkComms.Shutdown();
}
else
{
AppendLineToChatHistory("Enabling local server mode. Any existing connections will be closed.");
NetworkComms.Shutdown();
}
//Start listening for new incoming UDP connections
//We want to select a random port on all available adaptors so provide
//an IPEndPoint using IPAddress.Any and port 0.
Connection.StartListening(ConnectionType.UDP, new IPEndPoint(IPAddress.Any, 0));
//Write the IP addresses and ports that we are listening on to the chatBox
AppendLineToChatHistory("Listening for incoming UDP connections on:");
foreach (IPEndPoint listenEndPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.UDP))
AppendLineToChatHistory(listenEndPoint.Address + ":" + listenEndPoint.Port);
//Add a blank line after the initialisation output
AppendLineToChatHistory(System.Environment.NewLine);
}
else if (!LocalServerEnabled && (Connection.Listening(ConnectionType.TCP) || Connection.Listening(ConnectionType.UDP)))
{
//If the local server mode has been disabled but we are still listening we need to stop accepting incoming connections
NetworkComms.Shutdown();
AppendLineToChatHistory("Local server mode disabled. Any existing connections will be closed.");
AppendLineToChatHistory(System.Environment.NewLine);
}
else if (!LocalServerEnabled &&
((ConnectionType == ConnectionType.UDP && NetworkComms.GetExistingConnection(ConnectionType.TCP).Count > 0) ||
(ConnectionType == ConnectionType.TCP && NetworkComms.GetExistingConnection(ConnectionType.UDP).Count > 0)))
{
//If we are not running a local server but have changed the connection type after creating connections we need to close
//existing connections.
NetworkComms.Shutdown();
AppendLineToChatHistory("Connection mode has been changed. Existing connections will be closed.");
AppendLineToChatHistory(System.Environment.NewLine);
}
#endregion
}
/// <summary>
/// Performs whatever functions we might so desire when we receive an incoming ChatMessage
/// </summary>
/// <param name="header">The PacketHeader corresponding with the received object</param>
/// <param name="connection">The Connection from which this object was received</param>
/// <param name="incomingMessage">The incoming ChatMessage we are after</param>
protected virtual void HandleIncomingChatMessage(PacketHeader header, Connection connection, ChatMessage incomingMessage)
{
//We only want to write a message once to the chat window
//Because we support relaying and may receive the same message twice from multiple sources
//we use our history and message indexes to ensure we have a new message
//We perform this action within a lock as HandleIncomingChatMessage could be called in parallel
lock (lastPeerMessageDict)
{
if (lastPeerMessageDict.ContainsKey(incomingMessage.SourceIdentifier))
{
if (lastPeerMessageDict[incomingMessage.SourceIdentifier].MessageIndex < incomingMessage.MessageIndex)
{
//If this message index is greater than the last seen from this source we can safely
//write the message to the ChatBox
AppendLineToChatHistory(incomingMessage.SourceName + " - " + incomingMessage.Message);
//We now replace the last received message with the current one
lastPeerMessageDict[incomingMessage.SourceIdentifier] = incomingMessage;
}
}
else
{
//If we have never had a message from this source before then it has to be new
//by definition
lastPeerMessageDict.Add(incomingMessage.SourceIdentifier, incomingMessage);
AppendLineToChatHistory(incomingMessage.SourceName + " - " + incomingMessage.Message);
}
}
//This last section of the method is the relay feature
//We start by checking to see if this message has already been relayed the maximum number of times
if (incomingMessage.RelayCount < relayMaximum)
{
//If we are going to relay this message we need an array of
//all known connections, excluding the current one
var allRelayConnections = (from current in NetworkComms.GetExistingConnection() where current != connection select current).ToArray();
//We increment the relay count before we send
incomingMessage.IncrementRelayCount();
//We now send the message to every other connection
foreach (var relayConnection in allRelayConnections)
{
//We ensure we perform the send within a try catch
//To ensure a single failed send will not prevent the
//relay to all working connections.
try { relayConnection.SendObject("ChatMessage", incomingMessage); }
catch (CommsException) { /* Catch the general comms exception, ignore and continue */ }
}
}
}
/// <summary>
/// Performs whatever functions we might so desire when an existing connection is closed.
/// </summary>
/// <param name="connection">The closed connection</param>
private void HandleConnectionClosed(Connection connection)
{
//We are going to write a message to the chat history when a connection disconnects
//We perform the following within a lock in case multiple connections disconnect simultaneously
lock (lastPeerMessageDict)
{
//Get the remoteIdentifier from the closed connection
//This a unique GUID which can be used to identify peers
ShortGuid remoteIdentifier = connection.ConnectionInfo.NetworkIdentifier;
//If at any point we received a message with a matching identifier we can
//include the peer name in the disconnection message.
if (lastPeerMessageDict.ContainsKey(remoteIdentifier))
AppendLineToChatHistory("Connection with '" + lastPeerMessageDict[remoteIdentifier].SourceName + "' has been closed.");
else
AppendLineToChatHistory("Connection with '" + connection.ToString() + "' has been closed.");
//Last thing is to remove this peer from our message history
lastPeerMessageDict.Remove(connection.ConnectionInfo.NetworkIdentifier);
}
}
/// <summary>
/// Send a message.
/// </summary>
public void SendMessage(string stringToSend)
{
//If we have tried to send a zero length string we just return
if (stringToSend.Trim() == "") return;
//We may or may not have entered some server connection information
ConnectionInfo serverConnectionInfo = null;
if (ServerIPAddress != "")
{
try { serverConnectionInfo = new ConnectionInfo(ServerIPAddress, ServerPort); }
catch (Exception)
{
ShowMessage("Failed to parse the server IP and port. Please ensure it is correct and try again");
return;
}
}
//We wrap everything we want to send in the ChatMessage class we created
ChatMessage chatMessage = new ChatMessage(NetworkComms.NetworkIdentifier, LocalName, stringToSend, messageSendIndex++);
//We add our own message to the message history in case it gets relayed back to us
lock (lastPeerMessageDict) lastPeerMessageDict[NetworkComms.NetworkIdentifier] = chatMessage;
//We write our own message to the chatBox
AppendLineToChatHistory(chatMessage.SourceName + " - " + chatMessage.Message);
//Clear the input box text
ClearInputLine();
//If we provided server information we send to the server first
if (serverConnectionInfo != null)
{
//We perform the send within a try catch to ensure the application continues to run if there is a problem.
try
{
if (ConnectionType == ConnectionType.TCP)
TCPConnection.GetConnection(serverConnectionInfo).SendObject("ChatMessage", chatMessage);
else if (ConnectionType == ConnectionType.UDP)
UDPConnection.GetConnection(serverConnectionInfo, UDPOptions.None).SendObject("ChatMessage", chatMessage);
else
throw new Exception("An invalid connectionType is set.");
}
catch (CommsException) { AppendLineToChatHistory("Error: A communication error occurred while trying to send message to " + serverConnectionInfo + ". Please check settings and try again."); }
catch (Exception) { AppendLineToChatHistory("Error: A general error occurred while trying to send message to " + serverConnectionInfo + ". Please check settings and try again."); }
}
//If we have any other connections we now send the message to those as well
//This ensures that if we are the server everyone who is connected to us gets our message
//We want a list of all established connections not including the server if set
List<ConnectionInfo> otherConnectionInfos;
if (serverConnectionInfo != null)
otherConnectionInfos = (from current in NetworkComms.AllConnectionInfo() where current.RemoteEndPoint != serverConnectionInfo.RemoteEndPoint select current).ToList();
else
otherConnectionInfos = NetworkComms.AllConnectionInfo();
foreach (ConnectionInfo info in otherConnectionInfos)
{
//We perform the send within a try catch to ensure the application continues to run if there is a problem.
try
{
if (ConnectionType == ConnectionType.TCP)
TCPConnection.GetConnection(info).SendObject("ChatMessage", chatMessage);
else if (ConnectionType == ConnectionType.UDP)
UDPConnection.GetConnection(info, UDPOptions.None).SendObject("ChatMessage", chatMessage);
else
throw new Exception("An invalid connectionType is set.");
}
catch (CommsException) { AppendLineToChatHistory("Error: A communication error occurred while trying to send message to " + info + ". Please check settings and try again."); }
catch (Exception) { AppendLineToChatHistory("Error: A general error occurred while trying to send message to " + info + ". Please check settings and try again."); }
}
return;
}
#endregion
#region GUI Interface Methods
/// <summary>
/// Outputs the usage instructions to the chat window
/// </summary>
public void PrintUsageInstructions()
{
AppendLineToChatHistory("");
AppendLineToChatHistory("Chat usage instructions:");
AppendLineToChatHistory("");
AppendLineToChatHistory("Step 1. Open at least two chat applications. You can choose from Android, Windows Phone, iOS or native Windows versions.");
AppendLineToChatHistory("Step 2. Enable local server mode in a single application, see settings.");
AppendLineToChatHistory("Step 3. Provide remote server IP and port information in settings on remaining application.");
AppendLineToChatHistory("Step 4. Start chatting.");
AppendLineToChatHistory("");
AppendLineToChatHistory("Note: Connections are established on the first message send.");
AppendLineToChatHistory("");
}
/// <summary>
/// Append the provided message to the chat history text box.
/// </summary>
/// <param name="message">Message to be appended</param>
public abstract void AppendLineToChatHistory(string message);
/// <summary>
/// Clears the chat history
/// </summary>
public abstract void ClearChatHistory();
/// <summary>
/// Clears the input text box
/// </summary>
public abstract void ClearInputLine();
/// <summary>
/// Show a message box as an alternative to writing to the chat history
/// </summary>
/// <param name="message">Message to be output</param>
public abstract void ShowMessage(string message);
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using pbd = global::Google.ProtocolBuffers.Descriptors;
using pb = global::Google.ProtocolBuffers;
namespace Sirikata.Protocol {
public class Header : PBJ.IMessage {
protected _PBJ_Internal.Header super;
public _PBJ_Internal.Header _PBJSuper{ get { return super;} }
public Header() {
super=new _PBJ_Internal.Header();
}
public Header(_PBJ_Internal.Header reference) {
super=reference;
}
public static Header defaultInstance= new Header (_PBJ_Internal.Header.DefaultInstance);
public static Header DefaultInstance{
get {return defaultInstance;}
}
public static pbd.MessageDescriptor Descriptor {
get { return _PBJ_Internal.Header.Descriptor; } }
public static class Types {
public enum ReturnStatus {
SUCCESS=_PBJ_Internal.Header.Types.ReturnStatus.SUCCESS,
NETWORK_FAILURE=_PBJ_Internal.Header.Types.ReturnStatus.NETWORK_FAILURE,
TIMEOUT_FAILURE=_PBJ_Internal.Header.Types.ReturnStatus.TIMEOUT_FAILURE,
PROTOCOL_ERROR=_PBJ_Internal.Header.Types.ReturnStatus.PROTOCOL_ERROR,
PORT_FAILURE=_PBJ_Internal.Header.Types.ReturnStatus.PORT_FAILURE,
UNKNOWN_OBJECT=_PBJ_Internal.Header.Types.ReturnStatus.UNKNOWN_OBJECT
};
}
public static bool WithinReservedFieldTagRange(int field_tag) {
return false||(field_tag>=1&&field_tag<=8)||(field_tag>=1536&&field_tag<=2560)||(field_tag>=229376&&field_tag<=294912);
}
public static bool WithinExtensionFieldTagRange(int field_tag) {
return false;
}
public const int SourceObjectFieldTag=1;
public bool HasSourceObject{ get {return super.HasSourceObject&&PBJ._PBJ.ValidateUuid(super.SourceObject);} }
public PBJ.UUID SourceObject{ get {
if (HasSourceObject) {
return PBJ._PBJ.CastUuid(super.SourceObject);
} else {
return PBJ._PBJ.CastUuid();
}
}
}
public const int SourcePortFieldTag=3;
public bool HasSourcePort{ get {return super.HasSourcePort&&PBJ._PBJ.ValidateUint32(super.SourcePort);} }
public uint SourcePort{ get {
if (HasSourcePort) {
return PBJ._PBJ.CastUint32(super.SourcePort);
} else {
return PBJ._PBJ.CastUint32();
}
}
}
public const int SourceSpaceFieldTag=1536;
public bool HasSourceSpace{ get {return super.HasSourceSpace&&PBJ._PBJ.ValidateUuid(super.SourceSpace);} }
public PBJ.UUID SourceSpace{ get {
if (HasSourceSpace) {
return PBJ._PBJ.CastUuid(super.SourceSpace);
} else {
return PBJ._PBJ.CastUuid();
}
}
}
public const int DestinationObjectFieldTag=2;
public bool HasDestinationObject{ get {return super.HasDestinationObject&&PBJ._PBJ.ValidateUuid(super.DestinationObject);} }
public PBJ.UUID DestinationObject{ get {
if (HasDestinationObject) {
return PBJ._PBJ.CastUuid(super.DestinationObject);
} else {
return PBJ._PBJ.CastUuid();
}
}
}
public const int DestinationPortFieldTag=4;
public bool HasDestinationPort{ get {return super.HasDestinationPort&&PBJ._PBJ.ValidateUint32(super.DestinationPort);} }
public uint DestinationPort{ get {
if (HasDestinationPort) {
return PBJ._PBJ.CastUint32(super.DestinationPort);
} else {
return PBJ._PBJ.CastUint32();
}
}
}
public const int DestinationSpaceFieldTag=1537;
public bool HasDestinationSpace{ get {return super.HasDestinationSpace&&PBJ._PBJ.ValidateUuid(super.DestinationSpace);} }
public PBJ.UUID DestinationSpace{ get {
if (HasDestinationSpace) {
return PBJ._PBJ.CastUuid(super.DestinationSpace);
} else {
return PBJ._PBJ.CastUuid();
}
}
}
public const int IdFieldTag=7;
public bool HasId{ get {return super.HasId&&PBJ._PBJ.ValidateInt64(super.Id);} }
public long Id{ get {
if (HasId) {
return PBJ._PBJ.CastInt64(super.Id);
} else {
return PBJ._PBJ.CastInt64();
}
}
}
public const int ReplyIdFieldTag=8;
public bool HasReplyId{ get {return super.HasReplyId&&PBJ._PBJ.ValidateInt64(super.ReplyId);} }
public long ReplyId{ get {
if (HasReplyId) {
return PBJ._PBJ.CastInt64(super.ReplyId);
} else {
return PBJ._PBJ.CastInt64();
}
}
}
public const int ReturnStatusFieldTag=1792;
public bool HasReturnStatus{ get {return super.HasReturnStatus;} }
public Types.ReturnStatus ReturnStatus{ get {
if (HasReturnStatus) {
return (Types.ReturnStatus)super.ReturnStatus;
} else {
return new Types.ReturnStatus();
}
}
}
public override Google.ProtocolBuffers.IMessage _PBJISuper { get { return super; } }
public override PBJ.IMessage.IBuilder WeakCreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder() { return new Builder(); }
public static Builder CreateBuilder(Header prototype) {
return (Builder)new Builder().MergeFrom(prototype);
}
public static Header ParseFrom(pb::ByteString data) {
return new Header(_PBJ_Internal.Header.ParseFrom(data));
}
public static Header ParseFrom(pb::ByteString data, pb::ExtensionRegistry er) {
return new Header(_PBJ_Internal.Header.ParseFrom(data,er));
}
public static Header ParseFrom(byte[] data) {
return new Header(_PBJ_Internal.Header.ParseFrom(data));
}
public static Header ParseFrom(byte[] data, pb::ExtensionRegistry er) {
return new Header(_PBJ_Internal.Header.ParseFrom(data,er));
}
public static Header ParseFrom(global::System.IO.Stream data) {
return new Header(_PBJ_Internal.Header.ParseFrom(data));
}
public static Header ParseFrom(global::System.IO.Stream data, pb::ExtensionRegistry er) {
return new Header(_PBJ_Internal.Header.ParseFrom(data,er));
}
public static Header ParseFrom(pb::CodedInputStream data) {
return new Header(_PBJ_Internal.Header.ParseFrom(data));
}
public static Header ParseFrom(pb::CodedInputStream data, pb::ExtensionRegistry er) {
return new Header(_PBJ_Internal.Header.ParseFrom(data,er));
}
protected override bool _HasAllPBJFields{ get {
return true
;
} }
public bool IsInitialized { get {
return super.IsInitialized&&_HasAllPBJFields;
} }
public class Builder : global::PBJ.IMessage.IBuilder{
protected override bool _HasAllPBJFields{ get {
return true
;
} }
public bool IsInitialized { get {
return super.IsInitialized&&_HasAllPBJFields;
} }
protected _PBJ_Internal.Header.Builder super;
public override Google.ProtocolBuffers.IBuilder _PBJISuper { get { return super; } }
public _PBJ_Internal.Header.Builder _PBJSuper{ get { return super;} }
public Builder() {super = new _PBJ_Internal.Header.Builder();}
public Builder(_PBJ_Internal.Header.Builder other) {
super=other;
}
public Builder Clone() {return new Builder(super.Clone());}
public Builder MergeFrom(Header prototype) { super.MergeFrom(prototype._PBJSuper);return this;}
public Builder Clear() {super.Clear();return this;}
public Header BuildPartial() {return new Header(super.BuildPartial());}
public Header Build() {if (_HasAllPBJFields) return new Header(super.Build());return null;}
public pbd::MessageDescriptor DescriptorForType {
get { return Header.Descriptor; } }
public Builder ClearSourceObject() { super.ClearSourceObject();return this;}
public const int SourceObjectFieldTag=1;
public bool HasSourceObject{ get {return super.HasSourceObject&&PBJ._PBJ.ValidateUuid(super.SourceObject);} }
public PBJ.UUID SourceObject{ get {
if (HasSourceObject) {
return PBJ._PBJ.CastUuid(super.SourceObject);
} else {
return PBJ._PBJ.CastUuid();
}
}
set {
super.SourceObject=(PBJ._PBJ.Construct(value));
}
}
public Builder ClearSourcePort() { super.ClearSourcePort();return this;}
public const int SourcePortFieldTag=3;
public bool HasSourcePort{ get {return super.HasSourcePort&&PBJ._PBJ.ValidateUint32(super.SourcePort);} }
public uint SourcePort{ get {
if (HasSourcePort) {
return PBJ._PBJ.CastUint32(super.SourcePort);
} else {
return PBJ._PBJ.CastUint32();
}
}
set {
super.SourcePort=(PBJ._PBJ.Construct(value));
}
}
public Builder ClearSourceSpace() { super.ClearSourceSpace();return this;}
public const int SourceSpaceFieldTag=1536;
public bool HasSourceSpace{ get {return super.HasSourceSpace&&PBJ._PBJ.ValidateUuid(super.SourceSpace);} }
public PBJ.UUID SourceSpace{ get {
if (HasSourceSpace) {
return PBJ._PBJ.CastUuid(super.SourceSpace);
} else {
return PBJ._PBJ.CastUuid();
}
}
set {
super.SourceSpace=(PBJ._PBJ.Construct(value));
}
}
public Builder ClearDestinationObject() { super.ClearDestinationObject();return this;}
public const int DestinationObjectFieldTag=2;
public bool HasDestinationObject{ get {return super.HasDestinationObject&&PBJ._PBJ.ValidateUuid(super.DestinationObject);} }
public PBJ.UUID DestinationObject{ get {
if (HasDestinationObject) {
return PBJ._PBJ.CastUuid(super.DestinationObject);
} else {
return PBJ._PBJ.CastUuid();
}
}
set {
super.DestinationObject=(PBJ._PBJ.Construct(value));
}
}
public Builder ClearDestinationPort() { super.ClearDestinationPort();return this;}
public const int DestinationPortFieldTag=4;
public bool HasDestinationPort{ get {return super.HasDestinationPort&&PBJ._PBJ.ValidateUint32(super.DestinationPort);} }
public uint DestinationPort{ get {
if (HasDestinationPort) {
return PBJ._PBJ.CastUint32(super.DestinationPort);
} else {
return PBJ._PBJ.CastUint32();
}
}
set {
super.DestinationPort=(PBJ._PBJ.Construct(value));
}
}
public Builder ClearDestinationSpace() { super.ClearDestinationSpace();return this;}
public const int DestinationSpaceFieldTag=1537;
public bool HasDestinationSpace{ get {return super.HasDestinationSpace&&PBJ._PBJ.ValidateUuid(super.DestinationSpace);} }
public PBJ.UUID DestinationSpace{ get {
if (HasDestinationSpace) {
return PBJ._PBJ.CastUuid(super.DestinationSpace);
} else {
return PBJ._PBJ.CastUuid();
}
}
set {
super.DestinationSpace=(PBJ._PBJ.Construct(value));
}
}
public Builder ClearId() { super.ClearId();return this;}
public const int IdFieldTag=7;
public bool HasId{ get {return super.HasId&&PBJ._PBJ.ValidateInt64(super.Id);} }
public long Id{ get {
if (HasId) {
return PBJ._PBJ.CastInt64(super.Id);
} else {
return PBJ._PBJ.CastInt64();
}
}
set {
super.Id=(PBJ._PBJ.Construct(value));
}
}
public Builder ClearReplyId() { super.ClearReplyId();return this;}
public const int ReplyIdFieldTag=8;
public bool HasReplyId{ get {return super.HasReplyId&&PBJ._PBJ.ValidateInt64(super.ReplyId);} }
public long ReplyId{ get {
if (HasReplyId) {
return PBJ._PBJ.CastInt64(super.ReplyId);
} else {
return PBJ._PBJ.CastInt64();
}
}
set {
super.ReplyId=(PBJ._PBJ.Construct(value));
}
}
public Builder ClearReturnStatus() { super.ClearReturnStatus();return this;}
public const int ReturnStatusFieldTag=1792;
public bool HasReturnStatus{ get {return super.HasReturnStatus;} }
public Types.ReturnStatus ReturnStatus{ get {
if (HasReturnStatus) {
return (Types.ReturnStatus)super.ReturnStatus;
} else {
return new Types.ReturnStatus();
}
}
set {
super.ReturnStatus=((_PBJ_Internal.Header.Types.ReturnStatus)value);
}
}
}
}
}
| |
using System;
using System.Linq;
using System.Net;
using System.Text;
using EventStore.Common.Log;
using EventStore.Common.Utils;
using EventStore.Core.Bus;
using EventStore.Core.Cluster;
using EventStore.Core.Data;
using EventStore.Core.Messages;
using EventStore.Core.Messaging;
using EventStore.Core.Services.TimerService;
namespace EventStore.Core.Services.Gossip
{
public abstract class GossipServiceBase : IHandle<SystemMessage.SystemInit>,
IHandle<GossipMessage.RetrieveGossipSeedSources>,
IHandle<GossipMessage.GotGossipSeedSources>,
IHandle<GossipMessage.Gossip>,
IHandle<GossipMessage.GossipReceived>,
IHandle<SystemMessage.StateChangeMessage>,
IHandle<GossipMessage.GossipSendFailed>,
IHandle<SystemMessage.VNodeConnectionLost>,
IHandle<SystemMessage.VNodeConnectionEstablished>
{
private static readonly TimeSpan DnsRetryTimeout = TimeSpan.FromMilliseconds(1000);
private static readonly TimeSpan GossipInterval = TimeSpan.FromMilliseconds(1000);
private static readonly TimeSpan GossipStartupInterval = TimeSpan.FromMilliseconds(100);
private static readonly TimeSpan DeadMemberRemovalTimeout = TimeSpan.FromMinutes(30);
private static readonly TimeSpan AllowedTimeDifference = TimeSpan.FromMinutes(30);
private static readonly ILogger Log = LogManager.GetLoggerFor<GossipServiceBase>();
protected readonly VNodeInfo NodeInfo;
protected VNodeState CurrentRole = VNodeState.Initializing;
protected VNodeInfo CurrentMaster;
private readonly IPublisher _bus;
private readonly IEnvelope _publishEnvelope;
private readonly IGossipSeedSource _gossipSeedSource;
private GossipState _state;
private ClusterInfo _cluster;
private readonly Random _rnd = new Random(Math.Abs(Environment.TickCount));
protected GossipServiceBase(IPublisher bus,
IGossipSeedSource gossipSeedSource,
VNodeInfo nodeInfo)
{
Ensure.NotNull(bus, "bus");
Ensure.NotNull(gossipSeedSource, "gossipSeedSource");
Ensure.NotNull(nodeInfo, "nodeInfo");
_bus = bus;
_publishEnvelope = new PublishEnvelope(bus);
_gossipSeedSource = gossipSeedSource;
NodeInfo = nodeInfo;
_state = GossipState.Startup;
}
protected abstract MemberInfo GetInitialMe();
protected abstract MemberInfo GetUpdatedMe(MemberInfo me);
public void Handle(SystemMessage.SystemInit message)
{
if (_state != GossipState.Startup)
return;
_cluster = new ClusterInfo(GetInitialMe());
Handle(new GossipMessage.RetrieveGossipSeedSources());
}
public void Handle(GossipMessage.RetrieveGossipSeedSources message)
{
_state = GossipState.RetrievingGossipSeeds;
try
{
_gossipSeedSource.BeginGetHostEndpoints(OnGotGossipSeedSources, null);
}
catch (Exception ex)
{
Log.ErrorException(ex, "Error while retrieving cluster members through DNS.");
_bus.Publish(TimerMessage.Schedule.Create(DnsRetryTimeout, _publishEnvelope, new GossipMessage.RetrieveGossipSeedSources()));
}
}
private void OnGotGossipSeedSources(IAsyncResult ar)
{
try
{
var entries = _gossipSeedSource.EndGetHostEndpoints(ar);
_bus.Publish(new GossipMessage.GotGossipSeedSources(entries));
}
catch (Exception ex)
{
Log.ErrorException(ex, "Error while retrieving cluster members through DNS.");
_bus.Publish(TimerMessage.Schedule.Create(DnsRetryTimeout, _publishEnvelope, new GossipMessage.RetrieveGossipSeedSources()));
}
}
public void Handle(GossipMessage.GotGossipSeedSources message)
{
var now = DateTime.UtcNow;
var dnsCluster = new ClusterInfo(
message.GossipSeeds.Select(x => MemberInfo.ForManager(Guid.Empty, now, true, x, x)).ToArray());
var oldCluster = _cluster;
_cluster = MergeClusters(_cluster, dnsCluster, null, x => x);
LogClusterChange(oldCluster, _cluster, null);
_state = GossipState.Working;
Handle(new GossipMessage.Gossip(0)); // start gossiping
}
public void Handle(GossipMessage.Gossip message)
{
if (_state != GossipState.Working)
return;
var node = GetNodeToGossipTo(_cluster.Members);
if (node != null)
{
_cluster = UpdateCluster(_cluster, x => x.InstanceId == NodeInfo.InstanceId ? GetUpdatedMe(x) : x);
_bus.Publish(new HttpMessage.SendOverHttp(node.InternalHttpEndPoint, new GossipMessage.SendGossip(_cluster, NodeInfo.InternalHttp)));
}
var interval = message.GossipRound < 20 ? GossipStartupInterval : GossipInterval;
var gossipRound = Math.Min(2000000000, node == null ? message.GossipRound : message.GossipRound + 1);
_bus.Publish(TimerMessage.Schedule.Create(interval, _publishEnvelope, new GossipMessage.Gossip(gossipRound)));
}
private MemberInfo GetNodeToGossipTo(MemberInfo[] members)
{
if (members.Length == 0)
return null;
for (int i = 0; i < 5; ++i)
{
var node = members[_rnd.Next(members.Length)];
if (node.InstanceId != NodeInfo.InstanceId)
return node;
}
return null;
}
public void Handle(GossipMessage.GossipReceived message)
{
if (_state != GossipState.Working)
return;
var oldCluster = _cluster;
_cluster = MergeClusters(_cluster,
message.ClusterInfo,
message.Server,
x => x.InstanceId == NodeInfo.InstanceId ? GetUpdatedMe(x) : x);
message.Envelope.ReplyWith(new GossipMessage.SendGossip(_cluster, NodeInfo.InternalHttp));
if (_cluster.HasChangedSince(oldCluster))
LogClusterChange(oldCluster, _cluster, string.Format("gossip received from [{0}]", message.Server));
_bus.Publish(new GossipMessage.GossipUpdated(_cluster));
}
public void Handle(SystemMessage.StateChangeMessage message)
{
CurrentRole = message.State;
var replicaState = message as SystemMessage.ReplicaStateMessage;
CurrentMaster = replicaState == null ? null : replicaState.Master;
_cluster = UpdateCluster(_cluster, x => x.InstanceId == NodeInfo.InstanceId ? GetUpdatedMe(x) : x);
//if (_cluster.HasChangedSince(oldCluster))
//LogClusterChange(oldCluster, _cluster, _nodeInfo.InternalHttp);
_bus.Publish(new GossipMessage.GossipUpdated(_cluster));
}
public void Handle(GossipMessage.GossipSendFailed message)
{
var node = _cluster.Members.FirstOrDefault(x => x.Is(message.Recipient));
if (node == null || !node.IsAlive)
return;
if (CurrentMaster != null && node.InstanceId == CurrentMaster.InstanceId)
{
Log.Trace("Looks like master [{0}, {1:B}] is DEAD (Gossip send failed), though we wait for TCP to decide.",
message.Recipient, node.InstanceId);
return;
}
Log.Trace("Looks like node [{0}] is DEAD (Gossip send failed).", message.Recipient);
var oldCluster = _cluster;
_cluster = UpdateCluster(_cluster, x => x.Is(message.Recipient) ? x.Updated(isAlive: false) : x);
if (_cluster.HasChangedSince(oldCluster))
LogClusterChange(oldCluster, _cluster, string.Format("gossip send failed to [{0}]", message.Recipient));
_bus.Publish(new GossipMessage.GossipUpdated(_cluster));
}
public void Handle(SystemMessage.VNodeConnectionLost message)
{
var node = _cluster.Members.FirstOrDefault(x => x.Is(message.VNodeEndPoint));
if (node == null || !node.IsAlive)
return;
Log.Trace("Looks like node [{0}] is DEAD (TCP connection lost).", message.VNodeEndPoint);
var oldCluster = _cluster;
_cluster = UpdateCluster(_cluster, x => x.Is(message.VNodeEndPoint) ? x.Updated(isAlive: false) : x);
if (_cluster.HasChangedSince(oldCluster))
LogClusterChange(oldCluster, _cluster, string.Format("TCP connection lost to [{0}]", message.VNodeEndPoint));
_bus.Publish(new GossipMessage.GossipUpdated(_cluster));
}
public void Handle(SystemMessage.VNodeConnectionEstablished message)
{
var oldCluster = _cluster;
_cluster = UpdateCluster(_cluster, x => x.Is(message.VNodeEndPoint) ? x.Updated(isAlive: true) : x);
if (_cluster.HasChangedSince(oldCluster))
LogClusterChange(oldCluster, _cluster, string.Format("TCP connection established to [{0}]", message.VNodeEndPoint));
_bus.Publish(new GossipMessage.GossipUpdated(_cluster));
}
private ClusterInfo MergeClusters(ClusterInfo myCluster, ClusterInfo othersCluster,
IPEndPoint peerEndPoint, Func<MemberInfo, MemberInfo> update)
{
var mems = myCluster.Members.ToDictionary(member => member.InternalHttpEndPoint);
foreach (var member in othersCluster.Members)
{
if (member.InstanceId == NodeInfo.InstanceId || member.Is(NodeInfo.InternalHttp)) // we know about ourselves better
continue;
if (peerEndPoint != null && member.Is(peerEndPoint)) // peer knows about itself better
{
if ((DateTime.UtcNow - member.TimeStamp).Duration() > AllowedTimeDifference)
{
Log.Error("Time difference between us and [{0}] is too great! "
+ "UTC now: {1:yyyy-MM-dd HH:mm:ss.fff}, peer's time stamp: {2:yyyy-MM-dd HH:mm:ss.fff}.",
peerEndPoint, DateTime.UtcNow, member.TimeStamp);
}
mems[member.InternalHttpEndPoint] = member;
}
else
{
MemberInfo existingMem;
// if there is no data about this member or data is stale -- update
if (!mems.TryGetValue(member.InternalHttpEndPoint, out existingMem) || IsMoreUpToDate(member, existingMem))
{
// we do not trust master's alive status and state to come from outside
if (CurrentMaster != null && existingMem != null && member.InstanceId == CurrentMaster.InstanceId)
mems[member.InternalHttpEndPoint] = member.Updated(isAlive: existingMem.IsAlive, state: existingMem.State);
else
mems[member.InternalHttpEndPoint] = member;
}
}
}
// update members and remove dead timed-out members, if there are any
var newMembers = mems.Values.Select(update)
.Where(x => x.IsAlive || DateTime.UtcNow - x.TimeStamp < DeadMemberRemovalTimeout);
return new ClusterInfo(newMembers);
}
private static bool IsMoreUpToDate(MemberInfo member, MemberInfo existingMem)
{
if (member.EpochNumber != existingMem.EpochNumber)
return member.EpochNumber > existingMem.EpochNumber;
if (member.WriterCheckpoint != existingMem.WriterCheckpoint)
return member.WriterCheckpoint > existingMem.WriterCheckpoint;
return member.TimeStamp > existingMem.TimeStamp;
}
private static ClusterInfo UpdateCluster(ClusterInfo cluster, Func<MemberInfo, MemberInfo> update)
{
// update members and remove dead timed-out members, if there are any
var newMembers = cluster.Members.Select(update)
.Where(x => x.IsAlive || DateTime.UtcNow - x.TimeStamp < DeadMemberRemovalTimeout);
return new ClusterInfo(newMembers);
}
private static void LogClusterChange(ClusterInfo oldCluster, ClusterInfo newCluster, string source)
{
var sb = new StringBuilder();
sb.AppendFormat("CLUSTER HAS CHANGED{0}\n", source.IsNotEmptyString() ? " (" + source + ")" : string.Empty);
sb.AppendLine("Old:");
var ipEndPointComparer = new IPEndPointComparer();
foreach (var oldMember in oldCluster.Members.OrderByDescending(x => x.InternalHttpEndPoint, ipEndPointComparer))
{
sb.AppendLine(oldMember.ToString());
}
sb.AppendLine("New:");
foreach (var newMember in newCluster.Members.OrderByDescending(x => x.InternalHttpEndPoint, ipEndPointComparer))
{
sb.AppendLine(newMember.ToString());
}
sb.Append(new string('-', 80));
Log.Trace(sb.ToString());
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using InTheHand.Net;
using System.Globalization;
using System.Reflection;
using System.Threading;
using System.Diagnostics;
namespace ConsoleMenuTesting
{
class ConsoleMenu : MenuSystem
{
protected volatile bool quitMenu;
TextReader m_rdr;
TextWriter m_wtr;
string m_subMenu;
bool m_backChosen;
//
const string promptArrow = ">";
readonly int sizeOfBaseMenus; // Quit, Back etc
public ConsoleMenu()
: this(Console.In, Console.Out)
{
}
public ConsoleMenu(TextReader rdr, TextWriter wtr)
{
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
Options.Add(new Option("Quit", null, new ThreadStart(Quit).Method, this));
Options.Add(new Option("<-Back", null, new ThreadStart(Back).Method, this));
sizeOfBaseMenus = Options.Count;
//
m_rdr = rdr;
m_wtr = wtr;
}
[Conditional("DEBUG")]
private void TestGetOriginalException()
{
Exception input, result;
//
Console.WriteLine("Test GetOriginalException 0");
input = null;
result = Option.GetOriginalException(input);
//
Console.WriteLine("Test GetOriginalException 1");
input = new RankException("Outer.");
result = Option.GetOriginalException(input);
//
Console.WriteLine("Test GetOriginalException 2");
input = new TargetInvocationException(null);
result = Option.GetOriginalException(input);
//
Console.WriteLine("Test GetOriginalException 3");
input = new TargetInvocationException("Outer", new RankException("Inner."));
result = Option.GetOriginalException(input);
//
Console.WriteLine("Test GetOriginalException 4");
input = new TargetInvocationException(new RankException("Inner."));
result = Option.GetOriginalException(input);
//
Console.WriteLine("Test GetOriginalException DONE");
}
private void AddSubMenuMenus()
{
int idx = sizeOfBaseMenus;
foreach (string curSubMenu in SubMenus) {
#if false // ADD_SUB_MENUS_AT_BOTTOM
Options.Add(new OptionSubMenu(curSubMenu, MenuSubMenu, this));
#else
Options.Insert(idx++, new OptionSubMenu(curSubMenu, MenuSubMenu, this));
#endif
}
}
//--------
public override void RunMenu()
{
AddSubMenuMenus();
//
TestGetOriginalException();
//
try {
m_backChosen = true; //reset for init
while (!quitMenu) {
if (m_backChosen) {
m_subMenu = "root";
}
m_backChosen = false;
//
IList<Option> shownOptions = DisplayMenu(Options);
int item = ReadInteger("option");
if (item < 1 || item > shownOptions.Count) {
WriteLine("Not a menu item number");
continue;
}
Option selected = shownOptions[item - 1];
try {
try {
selected.EventHandlerInvoke(null, null);
} catch (TargetInvocationException tiex) {
Console.WriteLine("Original exception :"
+ Environment.NewLine + tiex.InnerException);
throw tiex.InnerException;
}
} catch (EndOfStreamException) {
throw;
} catch (Exception ex) {
WriteLine("Exception: {0}", ex);
bool cont = ReadYesNo("Continue after that exception", true);
if (!cont) {
throw;
}
}
}//while
} catch (EndOfStreamException eosex) {
Thread.Sleep(2000);
if (quitMenu) {
Console.WriteLine("[suppressed: " + FirstLine(eosex) + "]");
} else {
throw;
}
}
}
private string FirstLine(Exception eosex)
{
string t = eosex.ToString();
using (TextReader rdr = new StringReader(t)) {
return rdr.ReadLine();
}
}
private IList<Option> DisplayMenu(IList<Option> options)
{
int menuNum = 0;
IList<Option> shown = new List<Option>();
for (int i = 0; i < options.Count; ++i) {
Option cur = options[i];
if (cur.SubMenu == null
|| cur.SubMenu == m_subMenu) {
WriteLine("{0,2} -- {1}", menuNum + 1, cur.name);
shown.Add(cur);
++menuNum;
} else {
//DEBUG
}
}//for
return shown;
}
void Quit()
{
bool yes = this.ReadYesNo("Quit", false);
if (!yes) return;
quitMenu = true;
}
void Back()
{
m_backChosen = true;
}
void MenuSubMenu(string curSubMenu)
{
m_subMenu = curSubMenu;
}
void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
// Does this allow finalizers to run?
quitMenu = true;
if (quit != null)
quit.Set();
MemoryBarrier();
Console.WriteLine("Letting Finalizers run...");
BluetoothTesting.RunFinalizersAfterGc_();
//
//// TODO Console.WriteLine("Nulling peer stream.");
//peer = null;
//Console.WriteLine("Letting Finalizers run...");
//BluetoothTesting.RunFinalizersAfterGc_();
if (e.SpecialKey != ConsoleSpecialKey.ControlBreak) // May not cancel it!
e.Cancel = true;
}
private static void MemoryBarrier()
{
Thread.MemoryBarrier();
}
//--------
bool _newlineBeforeNextOutput;
public override void WriteLine(string msg)
{
if (_newlineBeforeNextOutput) m_wtr.WriteLine();
_newlineBeforeNextOutput = false;
m_wtr.WriteLine(msg);
}
public override void Write(string msg)
{
if (_newlineBeforeNextOutput) m_wtr.WriteLine();
_newlineBeforeNextOutput = false;
m_wtr.Write(msg);
}
public override void WriteLine(object arg0)
{
if (_newlineBeforeNextOutput) m_wtr.WriteLine();
_newlineBeforeNextOutput = false;
m_wtr.WriteLine(arg0);
}
public override void WriteLine(string fmt, params object[] args)
{
if (_newlineBeforeNextOutput) m_wtr.WriteLine();
_newlineBeforeNextOutput = false;
m_wtr.WriteLine(fmt, args);
}
public override void Write(string fmt, params object[] args)
{
if (_newlineBeforeNextOutput) m_wtr.WriteLine();
_newlineBeforeNextOutput = false;
m_wtr.Write(fmt, args);
}
//--------
public override string ReadLine(string prompt)
{
Write(prompt + promptArrow);
string line = m_rdr.ReadLine();
if (line == null)
throw new EndOfStreamException();
return line;
}
public override int ReadInteger(string prompt)
{
Write(prompt);
while (true) {
Write(promptArrow);
string line = m_rdr.ReadLine();
if (line == null)
throw new EndOfStreamException();
int result;
if (int.TryParse(line, out result))
return result;
Write("Invalid number");
}
}
public override int? ReadOptionalInteger(string prompt)
{
Write(prompt);
Write(" (optional)");
while (true) {
Write(promptArrow);
string line = m_rdr.ReadLine();
if (line == null)
throw new EndOfStreamException();
int result;
if (int.TryParse(line, out result))
return result;
else
return null;
}
}
public override int? ReadOptionalIntegerHexadecimal(string prompt)
{
Write(prompt);
Write(" (optional)");
while (true) {
Write(promptArrow);
string line = m_rdr.ReadLine();
if (line == null)
throw new EndOfStreamException();
int result;
if (int.TryParse(line, NumberStyles.HexNumber, null, out result))
return result;
else
return null;
}
}
public override InTheHand.Net.BluetoothAddress ReadBluetoothAddress(string prompt)
{
return ReadBluetoothAddress(prompt, false);
}
public override InTheHand.Net.BluetoothAddress ReadOptionalBluetoothAddress(string prompt)
{
return ReadBluetoothAddress(prompt, true);
}
InTheHand.Net.BluetoothAddress ReadBluetoothAddress(string prompt, bool optional)
{
Write(prompt);
while (true) {
Write(promptArrow);
string line = m_rdr.ReadLine();
if (line == null)
throw new EndOfStreamException();
if (optional && line.Length == 0) {
return null;
}
BluetoothAddress result;
if (BluetoothAddress.TryParse(line, out result))
return result;
Write("Invalid address");
}
}
public override void Pause(string prompt)
{
Write(prompt);
Write(promptArrow);
_newlineBeforeNextOutput = true;
string line = m_rdr.ReadLine();
if (line == null)
throw new EndOfStreamException();
}
public override bool ReadYesNo(string prompt, bool defaultYes)
{
bool? result = ReadYesNoCancel_(false, prompt, defaultYes);
return result.Value;
}
public override bool? ReadYesNoCancel(string prompt, bool? defaultYes)
{
return ReadYesNoCancel_(false, prompt, defaultYes);
}
bool? ReadYesNoCancel_(bool includeCancel, string prompt, bool? defaultYes)
{
Write(prompt);
if (!includeCancel) {
if (defaultYes.Value)
Write(" [Y/n]");
else
Write(" [y/N]");
} else {
switch (defaultYes) {
case true:
Write(" [Y/n/c]");
break;
case false:
Write(" [y/N/c]");
break;
case null:
Write(" [y/n/C]");
break;
}
}
while (true) {
Write(promptArrow);
string line = m_rdr.ReadLine();
if (line == null)
throw new EndOfStreamException();
if (line.Length == 0)
return defaultYes;
char val = line.Trim().ToUpper()[0];
if (val == 'Y')
return true;
else if (val == 'N')
return false;
else if (val == 'C')
return null;
Write("Need Y or N");
if (includeCancel)
Write(" or C");
}
}
public override Guid? ReadOptionalBluetoothUuid(string prompt, Guid? promptDefault)
{
Write(prompt + " Int32 or GUID");
Write(" (optional)");
if (promptDefault != null) {
Write(" (default: " + promptDefault.ToString() + ")");
}
while (true) {
Write(promptArrow);
string line = m_rdr.ReadLine();
if (line == null)
throw new EndOfStreamException();
if (line.Length == 0)
return null;
Guid result;
if (BluetoothService_TryParseIncludingShortForm(line, out result))
return result;
Write("Invalid UUID, re-enter");
}
}
public override string GetFilename()
{
return GetFilenameWinForms(this);
}
public override void UiInvoke(EventHandler dlgt)
{
dlgt(null, EventArgs.Empty);
}
public override bool? InvokeRequired { get { return null; } }
public override object InvokeeControl { get { return null; } }
}
}
| |
#region Copyright (c) all rights reserved.
// <copyright file="CsvDataReaderFacts.cs">
// THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND,
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// </copyright>
#endregion
namespace Ditto.DataLoad.Tests
{
using System;
using System.Data;
using System.IO;
using Xunit;
using Csv = CsvHelper.Configuration;
/// <summary>
/// CsvDataReader Facts.
/// </summary>
public sealed class CsvDataReaderFacts : IDisposable
{
/// <summary>
/// Simple CSV test data.
/// </summary>
private const string SimpleCsv =
@"stringval,intval,dateval,boolval,byteval,charval,decimalval,doubleval,floatval,guidval,
""wibb,le"",2,2015-01-31,true,1,x,-10.4321,1.456E5,-4E2,""{11A59F73-6905-4299-8E54-5E749B2ACD68}"",
,,,,,,,,,,
";
/// <summary>
/// The test target.
/// </summary>
private readonly IDataReader target;
/// <summary>
/// Initializes a new instance of the <see cref="CsvDataReaderFacts"/> class.
/// </summary>
public CsvDataReaderFacts()
{
TextReader source = null;
try
{
source = new StringReader(SimpleCsv);
this.target = new CsvDataReader(source, "simple.csv", new Csv.Configuration());
source = null;
}
finally
{
if (source != null)
{
source.Dispose();
}
}
}
/// <summary>
/// Should throw when null source passed to constructor.
/// </summary>
[Fact]
public static void ShouldThrowWhenNullSourcePassedToConstructor()
{
Assert.Throws<ArgumentNullException>(() => new CsvDataReader(null, "not checked", new Csv.Configuration()));
}
/// <summary>
/// Should throw when null filename passed to constructor.
/// </summary>
[Fact]
public static void ShouldThrowWhenNullFileNamePassedToConstructor()
{
TextReader source = null;
try
{
source = new StringReader(SimpleCsv);
Assert.Throws<ArgumentNullException>(() => new CsvDataReader(source, null, new Csv.Configuration()));
source = null;
}
finally
{
if (source != null)
{
source.Dispose();
}
}
}
/// <summary>
/// Determines whether this instance [can read correct number of rows].
/// </summary>
[Fact]
public void CanReadCorrectNumberOfRows()
{
int rows = 0;
while (this.target.Read())
{
rows++;
}
Assert.Equal(2, rows);
}
/// <summary>
/// Should be closed once all rows read.
/// </summary>
[Fact]
public void ShouldBeClosedOnceAllRowsRead()
{
while (this.target.Read())
{
}
Assert.True(this.target.IsClosed);
}
/// <summary>
/// The field count should be correct.
/// </summary>
[Fact]
public void FieldCountIsCorrect()
{
Assert.Equal(14, this.target.FieldCount);
}
/// <summary>
/// Should return the correct field values.
/// </summary>
[Fact]
public void ShouldReturnTheCorrectFieldValues()
{
this.target.Read();
Assert.Equal(1, this.target.GetInt32(0));
Assert.Equal(1, this.target.GetValue(0));
Assert.Equal("simple.csv", this.target.GetString(1));
Assert.Equal("wibb,le", this.target.GetString(3));
Assert.Equal(2, this.target.GetInt16(4));
Assert.Equal(2, this.target.GetInt32(4));
Assert.Equal(2, this.target.GetInt64(4));
Assert.Equal(new DateTime(2015, 1, 31), this.target.GetDateTime(5));
Assert.Equal(new DateTime(1601, 1, 1), this.target.GetDateTime(2));
Assert.True(this.target.GetBoolean(6));
Assert.Equal(1, this.target.GetByte(7));
Assert.Equal('x', this.target.GetChar(8));
Assert.Equal(-10.4321M, this.target.GetDecimal(9));
Assert.Equal(1.456E5, this.target.GetDouble(10));
Assert.Equal(-4E2, this.target.GetFloat(11));
Assert.Equal(new Guid("{11A59F73-6905-4299-8E54-5E749B2ACD68}"), this.target.GetGuid(12));
}
/// <summary>
/// Should read null field and return is database null.
/// </summary>
[Fact]
public void ShouldReadNullFieldAndReturnIsDBNull()
{
this.target.Read();
this.target.Read();
Assert.True(this.target.IsDBNull(3));
}
/// <summary>
/// Should return correct column ordinals.
/// </summary>
[Fact]
public void ShouldReturnCorrectColumnOrdinals()
{
Assert.Equal(0, this.target.GetOrdinal("_LineNumber"));
Assert.Equal(3, this.target.GetOrdinal("stringval"));
Assert.Equal(-1, this.target.GetOrdinal("thiscolumndoesntexist"));
}
/// <summary>
/// GetColumnOrdinal() should throw when passed null.
/// </summary>
[Fact]
public void GetColumnOrdinalShouldThrowWhenPassedNull()
{
Assert.Throws<ArgumentNullException>(() => this.target.GetOrdinal(null));
}
/// <summary>
/// Should return correct column names.
/// </summary>
[Fact]
public void ShouldReturnCorrectColumnNames()
{
Assert.Equal("_SourceFile", this.target.GetName(1));
Assert.Equal("intval", this.target.GetName(4));
}
/// <summary>
/// Name indexer should return same as get value.
/// </summary>
[Fact]
public void NameIndexerShouldReturnSameAsGetValue()
{
var column = "dateval";
Assert.Equal(this.target.GetValue(this.target.GetOrdinal(column)), this.target[column]);
}
/// <summary>
/// Ordinal indexer should return same as get value.
/// </summary>
[Fact]
public void OrdinalIndexerShouldReturnSameAsGetValue()
{
var index = 4;
Assert.Equal(this.target.GetValue(index), this.target[index]);
}
/// <summary>
/// Hard coded values should be correct.
/// </summary>
[Fact]
public void HardcodedValuesShouldBeCorrect()
{
Assert.Equal(0, this.target.Depth);
Assert.Equal(-1, this.target.RecordsAffected);
Assert.False(this.target.NextResult());
}
/// <summary>
/// Should throw when fixed field index is passed.
/// </summary>
[Fact]
public void ShouldThrowWhenFixedFieldIndexIsPassed()
{
Assert.Throws<InvalidOperationException>(() => this.target.GetDecimal(0));
Assert.Throws<InvalidOperationException>(() => this.target.GetBoolean(0));
Assert.Throws<InvalidOperationException>(() => this.target.GetByte(0));
Assert.Throws<InvalidOperationException>(() => this.target.GetChar(0));
Assert.Throws<InvalidOperationException>(() => this.target.GetDouble(0));
Assert.Throws<InvalidOperationException>(() => this.target.GetFloat(0));
Assert.Throws<InvalidOperationException>(() => this.target.GetGuid(0));
Assert.Throws<InvalidOperationException>(() => this.target.GetInt16(0));
Assert.Throws<InvalidOperationException>(() => this.target.GetInt64(0));
}
/// <summary>
/// Should not be implemented.
/// </summary>
[Fact]
public void ShouldNotBeImplemented()
{
char[] charBuffer = null;
Assert.Throws<NotImplementedException>(() => this.target.GetChars(0, 0, charBuffer, 0, 0));
byte[] byteBuffer = null;
Assert.Throws<NotImplementedException>(() => this.target.GetBytes(0, 0, byteBuffer, 0, 0));
Assert.Throws<NotImplementedException>(() => this.target.GetSchemaTable());
Assert.Throws<NotImplementedException>(() => this.target.GetDataTypeName(0));
Assert.Throws<NotImplementedException>(() => this.target.GetFieldType(0));
object[] valueBuffer = null;
Assert.Throws<NotImplementedException>(() => this.target.GetValues(valueBuffer));
Assert.Throws<NotImplementedException>(() => this.target.GetData(0));
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
this.target.Close();
}
}
}
| |
/*
* Copyright (c) 2015, InWorldz Halcyon Developers
* 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 halcyon nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using OpenMetaverse.Interfaces;
using System.Threading;
using log4net;
using System.Reflection;
#pragma warning disable 420
namespace OpenSim.Framework
{
/// <summary>
/// Creates a collection of byte buffers that can be leased for use on long running
/// operations to prevent unnecessary allocations and gc thrashing as well as preventing
/// too much gen0 memory from being pinned in the case of network operations
/// </summary>
public class ByteBufferPool : IByteBufferPool
{
private static readonly ILog s_Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Maximum memory to allocate in all pools in bytes
/// </summary>
private readonly int _maxAllocatedBytes;
/// <summary>
/// The number of bytes currently allocated to all pools
/// </summary>
private volatile int _currAllocatedBytes;
/// <summary>
/// The max age in ms for an idle byte buffer before it is culled
/// </summary>
private ulong _idleBufferMaxAge;
/// <summary>
/// Stores byte arrays of varying sizes
/// </summary>
private List<KeyValuePair<int, LocklessQueue<ImmutableTimestampedItem<byte[]>>>> _storage
= new List<KeyValuePair<int, LocklessQueue<ImmutableTimestampedItem<byte[]>>>>();
public int AllocatedBytes
{
get
{
return _currAllocatedBytes;
}
}
/// <summary>
/// Creates a new buffer pool with the given levels
/// </summary>
/// <param name="maxAllocatedBytes">Maximum bytes to allow to be allocated total for all pools</param>
/// <param name="bufferSizes">List of buffer sizes in bytes to split the pool by</param>
public ByteBufferPool(int maxAllocatedBytes, int[] bufferSizes) : this(maxAllocatedBytes, bufferSizes, 0)
{
}
/// <summary>
/// Creates a new buffer pool with the given levels
/// </summary>
/// <param name="maxAllocatedBytes">Maximum bytes to allow to be allocated total for all pools</param>
/// <param name="bufferSizes">List of buffer sizes in bytes to split the pool by</param>
/// <param name="idleBufferMaxAge">The maximum age a buffer (in ms) can sit idle before it will be purged</param>
public ByteBufferPool(int maxAllocatedBytes, int[] bufferSizes, ulong idleBufferMaxAge)
{
_maxAllocatedBytes = maxAllocatedBytes;
_idleBufferMaxAge = idleBufferMaxAge;
foreach (int bufferSz in bufferSizes)
{
_storage.Add(
new KeyValuePair<int, LocklessQueue<ImmutableTimestampedItem<byte[]>>>(
bufferSz, new LocklessQueue<ImmutableTimestampedItem<byte[]>>()));
}
}
private LocklessQueue<ImmutableTimestampedItem<byte[]>> FindContainer(int minSize)
{
foreach (var kvp in _storage)
{
if (kvp.Key >= minSize)
{
return kvp.Value;
}
}
return null;
}
private LocklessQueue<ImmutableTimestampedItem<byte[]>> FindExactContainer(int size)
{
foreach (var kvp in _storage)
{
if (kvp.Key == size)
{
return kvp.Value;
}
}
return null;
}
private int FindContainerSize(int minSize)
{
foreach (var kvp in _storage)
{
if (kvp.Key >= minSize)
{
return kvp.Key;
}
}
return 0;
}
#region IByteBufferPool Members
public byte[] LeaseBytes(int minSize)
{
LocklessQueue<ImmutableTimestampedItem<byte[]>> container = this.FindContainer(minSize);
if (container == null)
{
s_Log.WarnFormat("[ByteBufferPool] Not servicing request for {0} bytes", minSize);
//we cant service a request for this size
return new byte[minSize];
}
ImmutableTimestampedItem<byte[]> buffer;
if (container.Dequeue(out buffer))
{
Interlocked.Add(ref _currAllocatedBytes, -buffer.Item.Length);
return buffer.Item;
}
else
{
int closestContainerSize = this.FindContainerSize(minSize);
return new byte[closestContainerSize];
}
}
public void ReturnBytes(byte[] bytes)
{
LocklessQueue<ImmutableTimestampedItem<byte[]>> container = this.FindExactContainer(bytes.Length);
if (container != null)
{
if (_currAllocatedBytes < _maxAllocatedBytes)
{
Interlocked.Add(ref _currAllocatedBytes, bytes.Length);
container.Enqueue(new ImmutableTimestampedItem<byte[]>(bytes));
}
}
}
#endregion
/// <summary>
/// Removes any buffer that has been idle for more than the max age
/// specified during construction
/// </summary>
public void Maintain()
{
if (_idleBufferMaxAge == 0) return;
foreach (var kvp in _storage)
{
var queue = kvp.Value;
HashSet<byte[]> knownBuffers = new HashSet<byte[]>();
//dequeue and requeue until we get false back (no items)
//or we hit an item we've already seen
//it would be nice if we could just rely on the implicit queue
//FIFO ordering to allow us to stop early, but the way this loop
//works with enqueue/dequeue, it actually breaks the time sorted
//ordering so we can't just rely on it to break out of the loop early
ImmutableTimestampedItem<byte[]> item;
while (queue.Dequeue(out item))
{
//have we seen this item before?
if (knownBuffers.Contains(item.Item))
{
//yes, we're done
break;
}
if (item.ElapsedMilliseconds < _idleBufferMaxAge)
{
//track that we've seen the item
knownBuffers.Add(item.Item);
//put the item back
queue.Enqueue(item);
}
else
{
// this buffer is too old. mark it as deallocated
Interlocked.Add(ref _currAllocatedBytes, -item.Item.Length);
}
}
}
}
}
}
#pragma warning restore 420
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using CookComputing.XmlRpc;
namespace XenAPI
{
/// <summary>
/// A physical GPU (pGPU)
/// First published in XenServer 6.0.
/// </summary>
public partial class PGPU : XenObject<PGPU>
{
public PGPU()
{
}
public PGPU(string uuid,
XenRef<PCI> PCI,
XenRef<GPU_group> GPU_group,
XenRef<Host> host,
Dictionary<string, string> other_config,
List<XenRef<VGPU_type>> supported_VGPU_types,
List<XenRef<VGPU_type>> enabled_VGPU_types,
List<XenRef<VGPU>> resident_VGPUs,
Dictionary<XenRef<VGPU_type>, long> supported_VGPU_max_capacities)
{
this.uuid = uuid;
this.PCI = PCI;
this.GPU_group = GPU_group;
this.host = host;
this.other_config = other_config;
this.supported_VGPU_types = supported_VGPU_types;
this.enabled_VGPU_types = enabled_VGPU_types;
this.resident_VGPUs = resident_VGPUs;
this.supported_VGPU_max_capacities = supported_VGPU_max_capacities;
}
/// <summary>
/// Creates a new PGPU from a Proxy_PGPU.
/// </summary>
/// <param name="proxy"></param>
public PGPU(Proxy_PGPU proxy)
{
this.UpdateFromProxy(proxy);
}
public override void UpdateFrom(PGPU update)
{
uuid = update.uuid;
PCI = update.PCI;
GPU_group = update.GPU_group;
host = update.host;
other_config = update.other_config;
supported_VGPU_types = update.supported_VGPU_types;
enabled_VGPU_types = update.enabled_VGPU_types;
resident_VGPUs = update.resident_VGPUs;
supported_VGPU_max_capacities = update.supported_VGPU_max_capacities;
}
internal void UpdateFromProxy(Proxy_PGPU proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
PCI = proxy.PCI == null ? null : XenRef<PCI>.Create(proxy.PCI);
GPU_group = proxy.GPU_group == null ? null : XenRef<GPU_group>.Create(proxy.GPU_group);
host = proxy.host == null ? null : XenRef<Host>.Create(proxy.host);
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
supported_VGPU_types = proxy.supported_VGPU_types == null ? null : XenRef<VGPU_type>.Create(proxy.supported_VGPU_types);
enabled_VGPU_types = proxy.enabled_VGPU_types == null ? null : XenRef<VGPU_type>.Create(proxy.enabled_VGPU_types);
resident_VGPUs = proxy.resident_VGPUs == null ? null : XenRef<VGPU>.Create(proxy.resident_VGPUs);
supported_VGPU_max_capacities = proxy.supported_VGPU_max_capacities == null ? null : Maps.convert_from_proxy_XenRefVGPU_type_long(proxy.supported_VGPU_max_capacities);
}
public Proxy_PGPU ToProxy()
{
Proxy_PGPU result_ = new Proxy_PGPU();
result_.uuid = (uuid != null) ? uuid : "";
result_.PCI = (PCI != null) ? PCI : "";
result_.GPU_group = (GPU_group != null) ? GPU_group : "";
result_.host = (host != null) ? host : "";
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
result_.supported_VGPU_types = (supported_VGPU_types != null) ? Helper.RefListToStringArray(supported_VGPU_types) : new string[] {};
result_.enabled_VGPU_types = (enabled_VGPU_types != null) ? Helper.RefListToStringArray(enabled_VGPU_types) : new string[] {};
result_.resident_VGPUs = (resident_VGPUs != null) ? Helper.RefListToStringArray(resident_VGPUs) : new string[] {};
result_.supported_VGPU_max_capacities = Maps.convert_to_proxy_XenRefVGPU_type_long(supported_VGPU_max_capacities);
return result_;
}
/// <summary>
/// Creates a new PGPU from a Hashtable.
/// </summary>
/// <param name="table"></param>
public PGPU(Hashtable table)
{
uuid = Marshalling.ParseString(table, "uuid");
PCI = Marshalling.ParseRef<PCI>(table, "PCI");
GPU_group = Marshalling.ParseRef<GPU_group>(table, "GPU_group");
host = Marshalling.ParseRef<Host>(table, "host");
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
supported_VGPU_types = Marshalling.ParseSetRef<VGPU_type>(table, "supported_VGPU_types");
enabled_VGPU_types = Marshalling.ParseSetRef<VGPU_type>(table, "enabled_VGPU_types");
resident_VGPUs = Marshalling.ParseSetRef<VGPU>(table, "resident_VGPUs");
supported_VGPU_max_capacities = Maps.convert_from_proxy_XenRefVGPU_type_long(Marshalling.ParseHashTable(table, "supported_VGPU_max_capacities"));
}
public bool DeepEquals(PGPU other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._PCI, other._PCI) &&
Helper.AreEqual2(this._GPU_group, other._GPU_group) &&
Helper.AreEqual2(this._host, other._host) &&
Helper.AreEqual2(this._other_config, other._other_config) &&
Helper.AreEqual2(this._supported_VGPU_types, other._supported_VGPU_types) &&
Helper.AreEqual2(this._enabled_VGPU_types, other._enabled_VGPU_types) &&
Helper.AreEqual2(this._resident_VGPUs, other._resident_VGPUs) &&
Helper.AreEqual2(this._supported_VGPU_max_capacities, other._supported_VGPU_max_capacities);
}
public override string SaveChanges(Session session, string opaqueRef, PGPU server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_other_config, server._other_config))
{
PGPU.set_other_config(session, opaqueRef, _other_config);
}
if (!Helper.AreEqual2(_GPU_group, server._GPU_group))
{
PGPU.set_GPU_group(session, opaqueRef, _GPU_group);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given PGPU.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pgpu">The opaque_ref of the given pgpu</param>
public static PGPU get_record(Session session, string _pgpu)
{
return new PGPU((Proxy_PGPU)session.proxy.pgpu_get_record(session.uuid, (_pgpu != null) ? _pgpu : "").parse());
}
/// <summary>
/// Get a reference to the PGPU instance with the specified UUID.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<PGPU> get_by_uuid(Session session, string _uuid)
{
return XenRef<PGPU>.Create(session.proxy.pgpu_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse());
}
/// <summary>
/// Get the uuid field of the given PGPU.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pgpu">The opaque_ref of the given pgpu</param>
public static string get_uuid(Session session, string _pgpu)
{
return (string)session.proxy.pgpu_get_uuid(session.uuid, (_pgpu != null) ? _pgpu : "").parse();
}
/// <summary>
/// Get the PCI field of the given PGPU.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pgpu">The opaque_ref of the given pgpu</param>
public static XenRef<PCI> get_PCI(Session session, string _pgpu)
{
return XenRef<PCI>.Create(session.proxy.pgpu_get_pci(session.uuid, (_pgpu != null) ? _pgpu : "").parse());
}
/// <summary>
/// Get the GPU_group field of the given PGPU.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pgpu">The opaque_ref of the given pgpu</param>
public static XenRef<GPU_group> get_GPU_group(Session session, string _pgpu)
{
return XenRef<GPU_group>.Create(session.proxy.pgpu_get_gpu_group(session.uuid, (_pgpu != null) ? _pgpu : "").parse());
}
/// <summary>
/// Get the host field of the given PGPU.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pgpu">The opaque_ref of the given pgpu</param>
public static XenRef<Host> get_host(Session session, string _pgpu)
{
return XenRef<Host>.Create(session.proxy.pgpu_get_host(session.uuid, (_pgpu != null) ? _pgpu : "").parse());
}
/// <summary>
/// Get the other_config field of the given PGPU.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pgpu">The opaque_ref of the given pgpu</param>
public static Dictionary<string, string> get_other_config(Session session, string _pgpu)
{
return Maps.convert_from_proxy_string_string(session.proxy.pgpu_get_other_config(session.uuid, (_pgpu != null) ? _pgpu : "").parse());
}
/// <summary>
/// Get the supported_VGPU_types field of the given PGPU.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pgpu">The opaque_ref of the given pgpu</param>
public static List<XenRef<VGPU_type>> get_supported_VGPU_types(Session session, string _pgpu)
{
return XenRef<VGPU_type>.Create(session.proxy.pgpu_get_supported_vgpu_types(session.uuid, (_pgpu != null) ? _pgpu : "").parse());
}
/// <summary>
/// Get the enabled_VGPU_types field of the given PGPU.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pgpu">The opaque_ref of the given pgpu</param>
public static List<XenRef<VGPU_type>> get_enabled_VGPU_types(Session session, string _pgpu)
{
return XenRef<VGPU_type>.Create(session.proxy.pgpu_get_enabled_vgpu_types(session.uuid, (_pgpu != null) ? _pgpu : "").parse());
}
/// <summary>
/// Get the resident_VGPUs field of the given PGPU.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pgpu">The opaque_ref of the given pgpu</param>
public static List<XenRef<VGPU>> get_resident_VGPUs(Session session, string _pgpu)
{
return XenRef<VGPU>.Create(session.proxy.pgpu_get_resident_vgpus(session.uuid, (_pgpu != null) ? _pgpu : "").parse());
}
/// <summary>
/// Get the supported_VGPU_max_capacities field of the given PGPU.
/// First published in XenServer 6.2 SP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pgpu">The opaque_ref of the given pgpu</param>
public static Dictionary<XenRef<VGPU_type>, long> get_supported_VGPU_max_capacities(Session session, string _pgpu)
{
return Maps.convert_from_proxy_XenRefVGPU_type_long(session.proxy.pgpu_get_supported_vgpu_max_capacities(session.uuid, (_pgpu != null) ? _pgpu : "").parse());
}
/// <summary>
/// Set the other_config field of the given PGPU.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pgpu">The opaque_ref of the given pgpu</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _pgpu, Dictionary<string, string> _other_config)
{
session.proxy.pgpu_set_other_config(session.uuid, (_pgpu != null) ? _pgpu : "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given PGPU.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pgpu">The opaque_ref of the given pgpu</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _pgpu, string _key, string _value)
{
session.proxy.pgpu_add_to_other_config(session.uuid, (_pgpu != null) ? _pgpu : "", (_key != null) ? _key : "", (_value != null) ? _value : "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given PGPU. If the key is not in that Map, then do nothing.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pgpu">The opaque_ref of the given pgpu</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _pgpu, string _key)
{
session.proxy.pgpu_remove_from_other_config(session.uuid, (_pgpu != null) ? _pgpu : "", (_key != null) ? _key : "").parse();
}
/// <summary>
///
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pgpu">The opaque_ref of the given pgpu</param>
/// <param name="_value">The VGPU type to enable</param>
public static void add_enabled_VGPU_types(Session session, string _pgpu, string _value)
{
session.proxy.pgpu_add_enabled_vgpu_types(session.uuid, (_pgpu != null) ? _pgpu : "", (_value != null) ? _value : "").parse();
}
/// <summary>
///
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pgpu">The opaque_ref of the given pgpu</param>
/// <param name="_value">The VGPU type to enable</param>
public static XenRef<Task> async_add_enabled_VGPU_types(Session session, string _pgpu, string _value)
{
return XenRef<Task>.Create(session.proxy.async_pgpu_add_enabled_vgpu_types(session.uuid, (_pgpu != null) ? _pgpu : "", (_value != null) ? _value : "").parse());
}
/// <summary>
///
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pgpu">The opaque_ref of the given pgpu</param>
/// <param name="_value">The VGPU type to disable</param>
public static void remove_enabled_VGPU_types(Session session, string _pgpu, string _value)
{
session.proxy.pgpu_remove_enabled_vgpu_types(session.uuid, (_pgpu != null) ? _pgpu : "", (_value != null) ? _value : "").parse();
}
/// <summary>
///
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pgpu">The opaque_ref of the given pgpu</param>
/// <param name="_value">The VGPU type to disable</param>
public static XenRef<Task> async_remove_enabled_VGPU_types(Session session, string _pgpu, string _value)
{
return XenRef<Task>.Create(session.proxy.async_pgpu_remove_enabled_vgpu_types(session.uuid, (_pgpu != null) ? _pgpu : "", (_value != null) ? _value : "").parse());
}
/// <summary>
///
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pgpu">The opaque_ref of the given pgpu</param>
/// <param name="_value">The VGPU types to enable</param>
public static void set_enabled_VGPU_types(Session session, string _pgpu, List<XenRef<VGPU_type>> _value)
{
session.proxy.pgpu_set_enabled_vgpu_types(session.uuid, (_pgpu != null) ? _pgpu : "", (_value != null) ? Helper.RefListToStringArray(_value) : new string[] {}).parse();
}
/// <summary>
///
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pgpu">The opaque_ref of the given pgpu</param>
/// <param name="_value">The VGPU types to enable</param>
public static XenRef<Task> async_set_enabled_VGPU_types(Session session, string _pgpu, List<XenRef<VGPU_type>> _value)
{
return XenRef<Task>.Create(session.proxy.async_pgpu_set_enabled_vgpu_types(session.uuid, (_pgpu != null) ? _pgpu : "", (_value != null) ? Helper.RefListToStringArray(_value) : new string[] {}).parse());
}
/// <summary>
///
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pgpu">The opaque_ref of the given pgpu</param>
/// <param name="_value">The group to which the PGPU will be moved</param>
public static void set_GPU_group(Session session, string _pgpu, string _value)
{
session.proxy.pgpu_set_gpu_group(session.uuid, (_pgpu != null) ? _pgpu : "", (_value != null) ? _value : "").parse();
}
/// <summary>
///
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pgpu">The opaque_ref of the given pgpu</param>
/// <param name="_value">The group to which the PGPU will be moved</param>
public static XenRef<Task> async_set_GPU_group(Session session, string _pgpu, string _value)
{
return XenRef<Task>.Create(session.proxy.async_pgpu_set_gpu_group(session.uuid, (_pgpu != null) ? _pgpu : "", (_value != null) ? _value : "").parse());
}
/// <summary>
///
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pgpu">The opaque_ref of the given pgpu</param>
/// <param name="_vgpu_type">The VGPU type for which we want to find the number of VGPUs which can still be started on this PGPU</param>
public static long get_remaining_capacity(Session session, string _pgpu, string _vgpu_type)
{
return long.Parse((string)session.proxy.pgpu_get_remaining_capacity(session.uuid, (_pgpu != null) ? _pgpu : "", (_vgpu_type != null) ? _vgpu_type : "").parse());
}
/// <summary>
///
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pgpu">The opaque_ref of the given pgpu</param>
/// <param name="_vgpu_type">The VGPU type for which we want to find the number of VGPUs which can still be started on this PGPU</param>
public static XenRef<Task> async_get_remaining_capacity(Session session, string _pgpu, string _vgpu_type)
{
return XenRef<Task>.Create(session.proxy.async_pgpu_get_remaining_capacity(session.uuid, (_pgpu != null) ? _pgpu : "", (_vgpu_type != null) ? _vgpu_type : "").parse());
}
/// <summary>
/// Return a list of all the PGPUs known to the system.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<PGPU>> get_all(Session session)
{
return XenRef<PGPU>.Create(session.proxy.pgpu_get_all(session.uuid).parse());
}
/// <summary>
/// Get all the PGPU Records at once, in a single XML RPC call
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<PGPU>, PGPU> get_all_records(Session session)
{
return XenRef<PGPU>.Create<Proxy_PGPU>(session.proxy.pgpu_get_all_records(session.uuid).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid;
/// <summary>
/// Link to underlying PCI device
/// </summary>
public virtual XenRef<PCI> PCI
{
get { return _PCI; }
set
{
if (!Helper.AreEqual(value, _PCI))
{
_PCI = value;
Changed = true;
NotifyPropertyChanged("PCI");
}
}
}
private XenRef<PCI> _PCI;
/// <summary>
/// GPU group the pGPU is contained in
/// </summary>
public virtual XenRef<GPU_group> GPU_group
{
get { return _GPU_group; }
set
{
if (!Helper.AreEqual(value, _GPU_group))
{
_GPU_group = value;
Changed = true;
NotifyPropertyChanged("GPU_group");
}
}
}
private XenRef<GPU_group> _GPU_group;
/// <summary>
/// Host that own the GPU
/// </summary>
public virtual XenRef<Host> host
{
get { return _host; }
set
{
if (!Helper.AreEqual(value, _host))
{
_host = value;
Changed = true;
NotifyPropertyChanged("host");
}
}
}
private XenRef<Host> _host;
/// <summary>
/// Additional configuration
/// </summary>
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config;
/// <summary>
/// List of VGPU types supported by the underlying hardware
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
public virtual List<XenRef<VGPU_type>> supported_VGPU_types
{
get { return _supported_VGPU_types; }
set
{
if (!Helper.AreEqual(value, _supported_VGPU_types))
{
_supported_VGPU_types = value;
Changed = true;
NotifyPropertyChanged("supported_VGPU_types");
}
}
}
private List<XenRef<VGPU_type>> _supported_VGPU_types;
/// <summary>
/// List of VGPU types which have been enabled for this PGPU
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
public virtual List<XenRef<VGPU_type>> enabled_VGPU_types
{
get { return _enabled_VGPU_types; }
set
{
if (!Helper.AreEqual(value, _enabled_VGPU_types))
{
_enabled_VGPU_types = value;
Changed = true;
NotifyPropertyChanged("enabled_VGPU_types");
}
}
}
private List<XenRef<VGPU_type>> _enabled_VGPU_types;
/// <summary>
/// List of VGPUs running on this PGPU
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
public virtual List<XenRef<VGPU>> resident_VGPUs
{
get { return _resident_VGPUs; }
set
{
if (!Helper.AreEqual(value, _resident_VGPUs))
{
_resident_VGPUs = value;
Changed = true;
NotifyPropertyChanged("resident_VGPUs");
}
}
}
private List<XenRef<VGPU>> _resident_VGPUs;
/// <summary>
/// A map relating each VGPU type supported on this GPU to the maximum number of VGPUs of that type which can run simultaneously on this GPU
/// First published in XenServer 6.2 SP1.
/// </summary>
public virtual Dictionary<XenRef<VGPU_type>, long> supported_VGPU_max_capacities
{
get { return _supported_VGPU_max_capacities; }
set
{
if (!Helper.AreEqual(value, _supported_VGPU_max_capacities))
{
_supported_VGPU_max_capacities = value;
Changed = true;
NotifyPropertyChanged("supported_VGPU_max_capacities");
}
}
}
private Dictionary<XenRef<VGPU_type>, long> _supported_VGPU_max_capacities;
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
namespace System.Reflection.Emit
{
using System.Text;
using System;
using System.Diagnostics.Contracts;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Permissions;
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_SignatureHelper))]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class SignatureHelper : _SignatureHelper
{
#region Consts Fields
private const int NO_SIZE_IN_SIG = -1;
#endregion
#region Static Members
[System.Security.SecuritySafeCritical] // auto-generated
public static SignatureHelper GetMethodSigHelper(Module mod, Type returnType, Type[] parameterTypes)
{
return GetMethodSigHelper(mod, CallingConventions.Standard, returnType, null, null, parameterTypes, null, null);
}
[System.Security.SecurityCritical] // auto-generated
internal static SignatureHelper GetMethodSigHelper(Module mod, CallingConventions callingConvention, Type returnType, int cGenericParam)
{
return GetMethodSigHelper(mod, callingConvention, cGenericParam, returnType, null, null, null, null, null);
}
[System.Security.SecuritySafeCritical] // auto-generated
public static SignatureHelper GetMethodSigHelper(Module mod, CallingConventions callingConvention, Type returnType)
{
return GetMethodSigHelper(mod, callingConvention, returnType, null, null, null, null, null);
}
internal static SignatureHelper GetMethodSpecSigHelper(Module scope, Type[] inst)
{
SignatureHelper sigHelp = new SignatureHelper(scope, MdSigCallingConvention.GenericInst);
sigHelp.AddData(inst.Length);
foreach(Type t in inst)
sigHelp.AddArgument(t);
return sigHelp;
}
[System.Security.SecurityCritical] // auto-generated
internal static SignatureHelper GetMethodSigHelper(
Module scope, CallingConventions callingConvention,
Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
{
return GetMethodSigHelper(scope, callingConvention, 0, returnType, requiredReturnTypeCustomModifiers,
optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
}
[System.Security.SecurityCritical] // auto-generated
internal static SignatureHelper GetMethodSigHelper(
Module scope, CallingConventions callingConvention, int cGenericParam,
Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
{
SignatureHelper sigHelp;
MdSigCallingConvention intCall;
if (returnType == null)
{
returnType = typeof(void);
}
intCall = MdSigCallingConvention.Default;
if ((callingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs)
intCall = MdSigCallingConvention.Vararg;
if (cGenericParam > 0)
{
intCall |= MdSigCallingConvention.Generic;
}
if ((callingConvention & CallingConventions.HasThis) == CallingConventions.HasThis)
intCall |= MdSigCallingConvention.HasThis;
sigHelp = new SignatureHelper(scope, intCall, cGenericParam, returnType,
requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers);
sigHelp.AddArguments(parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
return sigHelp;
}
[System.Security.SecuritySafeCritical] // auto-generated
public static SignatureHelper GetMethodSigHelper(Module mod, CallingConvention unmanagedCallConv, Type returnType)
{
SignatureHelper sigHelp;
MdSigCallingConvention intCall;
if (returnType == null)
returnType = typeof(void);
if (unmanagedCallConv == CallingConvention.Cdecl)
{
intCall = MdSigCallingConvention.C;
}
else if (unmanagedCallConv == CallingConvention.StdCall || unmanagedCallConv == CallingConvention.Winapi)
{
intCall = MdSigCallingConvention.StdCall;
}
else if (unmanagedCallConv == CallingConvention.ThisCall)
{
intCall = MdSigCallingConvention.ThisCall;
}
else if (unmanagedCallConv == CallingConvention.FastCall)
{
intCall = MdSigCallingConvention.FastCall;
}
else
{
throw new ArgumentException(Environment.GetResourceString("Argument_UnknownUnmanagedCallConv"), "unmanagedCallConv");
}
sigHelp = new SignatureHelper(mod, intCall, returnType, null, null);
return sigHelp;
}
public static SignatureHelper GetLocalVarSigHelper()
{
return GetLocalVarSigHelper(null);
}
public static SignatureHelper GetMethodSigHelper(CallingConventions callingConvention, Type returnType)
{
return GetMethodSigHelper(null, callingConvention, returnType);
}
public static SignatureHelper GetMethodSigHelper(CallingConvention unmanagedCallingConvention, Type returnType)
{
return GetMethodSigHelper(null, unmanagedCallingConvention, returnType);
}
public static SignatureHelper GetLocalVarSigHelper(Module mod)
{
return new SignatureHelper(mod, MdSigCallingConvention.LocalSig);
}
public static SignatureHelper GetFieldSigHelper(Module mod)
{
return new SignatureHelper(mod, MdSigCallingConvention.Field);
}
public static SignatureHelper GetPropertySigHelper(Module mod, Type returnType, Type[] parameterTypes)
{
return GetPropertySigHelper(mod, returnType, null, null, parameterTypes, null, null);
}
public static SignatureHelper GetPropertySigHelper(Module mod,
Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
{
return GetPropertySigHelper(mod, (CallingConventions)0, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers,
parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
}
[System.Security.SecuritySafeCritical] // auto-generated
public static SignatureHelper GetPropertySigHelper(Module mod, CallingConventions callingConvention,
Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
{
SignatureHelper sigHelp;
if (returnType == null)
{
returnType = typeof(void);
}
MdSigCallingConvention intCall = MdSigCallingConvention.Property;
if ((callingConvention & CallingConventions.HasThis) == CallingConventions.HasThis)
intCall |= MdSigCallingConvention.HasThis;
sigHelp = new SignatureHelper(mod, intCall,
returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers);
sigHelp.AddArguments(parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
return sigHelp;
}
[System.Security.SecurityCritical] // auto-generated
internal static SignatureHelper GetTypeSigToken(Module mod, Type type)
{
if (mod == null)
throw new ArgumentNullException("module");
if (type == null)
throw new ArgumentNullException("type");
return new SignatureHelper(mod, type);
}
#endregion
#region Private Data Members
private byte[] m_signature;
private int m_currSig; // index into m_signature buffer for next available byte
private int m_sizeLoc; // index into m_signature buffer to put m_argCount (will be NO_SIZE_IN_SIG if no arg count is needed)
private ModuleBuilder m_module;
private bool m_sigDone;
private int m_argCount; // tracking number of arguments in the signature
#endregion
#region Constructor
private SignatureHelper(Module mod, MdSigCallingConvention callingConvention)
{
// Use this constructor to instantiate a local var sig or Field where return type is not applied.
Init(mod, callingConvention);
}
[System.Security.SecurityCritical] // auto-generated
private SignatureHelper(Module mod, MdSigCallingConvention callingConvention, int cGenericParameters,
Type returnType, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers)
{
// Use this constructor to instantiate a any signatures that will require a return type.
Init(mod, callingConvention, cGenericParameters);
if (callingConvention == MdSigCallingConvention.Field)
throw new ArgumentException(Environment.GetResourceString("Argument_BadFieldSig"));
AddOneArgTypeHelper(returnType, requiredCustomModifiers, optionalCustomModifiers);
}
[System.Security.SecurityCritical] // auto-generated
private SignatureHelper(Module mod, MdSigCallingConvention callingConvention,
Type returnType, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers)
: this(mod, callingConvention, 0, returnType, requiredCustomModifiers, optionalCustomModifiers)
{
}
[System.Security.SecurityCritical] // auto-generated
private SignatureHelper(Module mod, Type type)
{
Init(mod);
AddOneArgTypeHelper(type);
}
private void Init(Module mod)
{
m_signature = new byte[32];
m_currSig = 0;
m_module = mod as ModuleBuilder;
m_argCount = 0;
m_sigDone = false;
m_sizeLoc = NO_SIZE_IN_SIG;
if (m_module == null && mod != null)
throw new ArgumentException(Environment.GetResourceString("NotSupported_MustBeModuleBuilder"));
}
private void Init(Module mod, MdSigCallingConvention callingConvention)
{
Init(mod, callingConvention, 0);
}
private void Init(Module mod, MdSigCallingConvention callingConvention, int cGenericParam)
{
Init(mod);
AddData((byte)callingConvention);
if (callingConvention == MdSigCallingConvention.Field ||
callingConvention == MdSigCallingConvention.GenericInst)
{
m_sizeLoc = NO_SIZE_IN_SIG;
}
else
{
if (cGenericParam > 0)
AddData(cGenericParam);
m_sizeLoc = m_currSig++;
}
}
#endregion
#region Private Members
[System.Security.SecurityCritical] // auto-generated
private void AddOneArgTypeHelper(Type argument, bool pinned)
{
if (pinned)
AddElementType(CorElementType.Pinned);
AddOneArgTypeHelper(argument);
}
[System.Security.SecurityCritical] // auto-generated
private void AddOneArgTypeHelper(Type clsArgument, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers)
{
// This function will not increase the argument count. It only fills in bytes
// in the signature based on clsArgument. This helper is called for return type.
Contract.Requires(clsArgument != null);
Contract.Requires((optionalCustomModifiers == null && requiredCustomModifiers == null) || !clsArgument.ContainsGenericParameters);
if (optionalCustomModifiers != null)
{
for (int i = 0; i < optionalCustomModifiers.Length; i++)
{
Type t = optionalCustomModifiers[i];
if (t == null)
throw new ArgumentNullException("optionalCustomModifiers");
if (t.HasElementType)
throw new ArgumentException(Environment.GetResourceString("Argument_ArraysInvalid"), "optionalCustomModifiers");
if (t.ContainsGenericParameters)
throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), "optionalCustomModifiers");
AddElementType(CorElementType.CModOpt);
int token = m_module.GetTypeToken(t).Token;
Contract.Assert(!MetadataToken.IsNullToken(token));
AddToken(token);
}
}
if (requiredCustomModifiers != null)
{
for (int i = 0; i < requiredCustomModifiers.Length; i++)
{
Type t = requiredCustomModifiers[i];
if (t == null)
throw new ArgumentNullException("requiredCustomModifiers");
if (t.HasElementType)
throw new ArgumentException(Environment.GetResourceString("Argument_ArraysInvalid"), "requiredCustomModifiers");
if (t.ContainsGenericParameters)
throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), "requiredCustomModifiers");
AddElementType(CorElementType.CModReqd);
int token = m_module.GetTypeToken(t).Token;
Contract.Assert(!MetadataToken.IsNullToken(token));
AddToken(token);
}
}
AddOneArgTypeHelper(clsArgument);
}
[System.Security.SecurityCritical] // auto-generated
private void AddOneArgTypeHelper(Type clsArgument) { AddOneArgTypeHelperWorker(clsArgument, false); }
[System.Security.SecurityCritical] // auto-generated
private void AddOneArgTypeHelperWorker(Type clsArgument, bool lastWasGenericInst)
{
if (clsArgument.IsGenericParameter)
{
if (clsArgument.DeclaringMethod != null)
AddElementType(CorElementType.MVar);
else
AddElementType(CorElementType.Var);
AddData(clsArgument.GenericParameterPosition);
}
else if (clsArgument.IsGenericType && (!clsArgument.IsGenericTypeDefinition || !lastWasGenericInst))
{
AddElementType(CorElementType.GenericInst);
AddOneArgTypeHelperWorker(clsArgument.GetGenericTypeDefinition(), true);
Type[] args = clsArgument.GetGenericArguments();
AddData(args.Length);
foreach (Type t in args)
AddOneArgTypeHelper(t);
}
else if (clsArgument is TypeBuilder)
{
TypeBuilder clsBuilder = (TypeBuilder)clsArgument;
TypeToken tkType;
if (clsBuilder.Module.Equals(m_module))
{
tkType = clsBuilder.TypeToken;
}
else
{
tkType = m_module.GetTypeToken(clsArgument);
}
if (clsArgument.IsValueType)
{
InternalAddTypeToken(tkType, CorElementType.ValueType);
}
else
{
InternalAddTypeToken(tkType, CorElementType.Class);
}
}
else if (clsArgument is EnumBuilder)
{
TypeBuilder clsBuilder = ((EnumBuilder)clsArgument).m_typeBuilder;
TypeToken tkType;
if (clsBuilder.Module.Equals(m_module))
{
tkType = clsBuilder.TypeToken;
}
else
{
tkType = m_module.GetTypeToken(clsArgument);
}
if (clsArgument.IsValueType)
{
InternalAddTypeToken(tkType, CorElementType.ValueType);
}
else
{
InternalAddTypeToken(tkType, CorElementType.Class);
}
}
else if (clsArgument.IsByRef)
{
AddElementType(CorElementType.ByRef);
clsArgument = clsArgument.GetElementType();
AddOneArgTypeHelper(clsArgument);
}
else if (clsArgument.IsPointer)
{
AddElementType(CorElementType.Ptr);
AddOneArgTypeHelper(clsArgument.GetElementType());
}
else if (clsArgument.IsArray)
{
if (clsArgument.IsSzArray)
{
AddElementType(CorElementType.SzArray);
AddOneArgTypeHelper(clsArgument.GetElementType());
}
else
{
AddElementType(CorElementType.Array);
AddOneArgTypeHelper(clsArgument.GetElementType());
// put the rank information
int rank = clsArgument.GetArrayRank();
AddData(rank); // rank
AddData(0); // upper bounds
AddData(rank); // lower bound
for (int i = 0; i < rank; i++)
AddData(0);
}
}
else
{
CorElementType type = CorElementType.Max;
if (clsArgument is RuntimeType)
{
type = RuntimeTypeHandle.GetCorElementType((RuntimeType)clsArgument);
//GetCorElementType returns CorElementType.Class for both object and string
if (type == CorElementType.Class)
{
if (clsArgument == typeof(object))
type = CorElementType.Object;
else if (clsArgument == typeof(string))
type = CorElementType.String;
}
}
if (IsSimpleType(type))
{
AddElementType(type);
}
else if (m_module == null)
{
InternalAddRuntimeType(clsArgument);
}
else if (clsArgument.IsValueType)
{
InternalAddTypeToken(m_module.GetTypeToken(clsArgument), CorElementType.ValueType);
}
else
{
InternalAddTypeToken(m_module.GetTypeToken(clsArgument), CorElementType.Class);
}
}
}
private void AddData(int data)
{
// A managed representation of CorSigCompressData;
if (m_currSig + 4 > m_signature.Length)
{
m_signature = ExpandArray(m_signature);
}
if (data <= 0x7F)
{
m_signature[m_currSig++] = (byte)(data & 0xFF);
}
else if (data <= 0x3FFF)
{
m_signature[m_currSig++] = (byte)((data >>8) | 0x80);
m_signature[m_currSig++] = (byte)(data & 0xFF);
}
else if (data <= 0x1FFFFFFF)
{
m_signature[m_currSig++] = (byte)((data >>24) | 0xC0);
m_signature[m_currSig++] = (byte)((data >>16) & 0xFF);
m_signature[m_currSig++] = (byte)((data >>8) & 0xFF);
m_signature[m_currSig++] = (byte)((data) & 0xFF);
}
else
{
throw new ArgumentException(Environment.GetResourceString("Argument_LargeInteger"));
}
}
private void AddData(uint data)
{
if (m_currSig + 4 > m_signature.Length)
{
m_signature = ExpandArray(m_signature);
}
m_signature[m_currSig++] = (byte)((data) & 0xFF);
m_signature[m_currSig++] = (byte)((data>>8) & 0xFF);
m_signature[m_currSig++] = (byte)((data>>16) & 0xFF);
m_signature[m_currSig++] = (byte)((data>>24) & 0xFF);
}
private void AddData(ulong data)
{
if (m_currSig + 8 > m_signature.Length)
{
m_signature = ExpandArray(m_signature);
}
m_signature[m_currSig++] = (byte)((data) & 0xFF);
m_signature[m_currSig++] = (byte)((data>>8) & 0xFF);
m_signature[m_currSig++] = (byte)((data>>16) & 0xFF);
m_signature[m_currSig++] = (byte)((data>>24) & 0xFF);
m_signature[m_currSig++] = (byte)((data>>32) & 0xFF);
m_signature[m_currSig++] = (byte)((data>>40) & 0xFF);
m_signature[m_currSig++] = (byte)((data>>48) & 0xFF);
m_signature[m_currSig++] = (byte)((data>>56) & 0xFF);
}
private void AddElementType(CorElementType cvt)
{
// Adds an element to the signature. A managed represenation of CorSigCompressElement
if (m_currSig + 1 > m_signature.Length)
m_signature = ExpandArray(m_signature);
m_signature[m_currSig++] = (byte)cvt;
}
private void AddToken(int token)
{
// A managed represenation of CompressToken
// Pulls the token appart to get a rid, adds some appropriate bits
// to the token and then adds this to the signature.
int rid = (token & 0x00FFFFFF); //This is RidFromToken;
MetadataTokenType type = (MetadataTokenType)(token & unchecked((int)0xFF000000)); //This is TypeFromToken;
if (rid > 0x3FFFFFF)
{
// token is too big to be compressed
throw new ArgumentException(Environment.GetResourceString("Argument_LargeInteger"));
}
rid = (rid << 2);
// TypeDef is encoded with low bits 00
// TypeRef is encoded with low bits 01
// TypeSpec is encoded with low bits 10
if (type == MetadataTokenType.TypeRef)
{
//if type is mdtTypeRef
rid|=0x1;
}
else if (type == MetadataTokenType.TypeSpec)
{
//if type is mdtTypeSpec
rid|=0x2;
}
AddData(rid);
}
private void InternalAddTypeToken(TypeToken clsToken, CorElementType CorType)
{
// Add a type token into signature. CorType will be either CorElementType.Class or CorElementType.ValueType
AddElementType(CorType);
AddToken(clsToken.Token);
}
[System.Security.SecurityCritical] // auto-generated
private unsafe void InternalAddRuntimeType(Type type)
{
// Add a runtime type into the signature.
AddElementType(CorElementType.Internal);
IntPtr handle = type.GetTypeHandleInternal().Value;
// Internal types must have their pointer written into the signature directly (we don't
// want to convert to little-endian format on big-endian machines because the value is
// going to be extracted and used directly as a pointer (and only within this process)).
if (m_currSig + sizeof(void*) > m_signature.Length)
m_signature = ExpandArray(m_signature);
byte *phandle = (byte*)&handle;
for (int i = 0; i < sizeof(void*); i++)
m_signature[m_currSig++] = phandle[i];
}
private byte[] ExpandArray(byte[] inArray)
{
// Expand the signature buffer size
return ExpandArray(inArray, inArray.Length * 2);
}
private byte[] ExpandArray(byte[] inArray, int requiredLength)
{
// Expand the signature buffer size
if (requiredLength < inArray.Length)
requiredLength = inArray.Length*2;
byte[] outArray = new byte[requiredLength];
Array.Copy(inArray, outArray, inArray.Length);
return outArray;
}
private void IncrementArgCounts()
{
if (m_sizeLoc == NO_SIZE_IN_SIG)
{
//We don't have a size if this is a field.
return;
}
m_argCount++;
}
private void SetNumberOfSignatureElements(bool forceCopy)
{
// For most signatures, this will set the number of elements in a byte which we have reserved for it.
// However, if we have a field signature, we don't set the length and return.
// If we have a signature with more than 128 arguments, we can't just set the number of elements,
// we actually have to allocate more space (e.g. shift everything in the array one or more spaces to the
// right. We do this by making a copy of the array and leaving the correct number of blanks. This new
// array is now set to be m_signature and we use the AddData method to set the number of elements properly.
// The forceCopy argument can be used to force SetNumberOfSignatureElements to make a copy of
// the array. This is useful for GetSignature which promises to trim the array to be the correct size anyway.
byte[] temp;
int newSigSize;
int currSigHolder = m_currSig;
if (m_sizeLoc == NO_SIZE_IN_SIG)
return;
//If we have fewer than 128 arguments and we haven't been told to copy the
//array, we can just set the appropriate bit and return.
if (m_argCount < 0x80 && !forceCopy)
{
m_signature[m_sizeLoc] = (byte)m_argCount;
return;
}
//We need to have more bytes for the size. Figure out how many bytes here.
//Since we need to copy anyway, we're just going to take the cost of doing a
//new allocation.
if (m_argCount < 0x80)
{
newSigSize = 1;
}
else if (m_argCount < 0x4000)
{
newSigSize = 2;
}
else
{
newSigSize = 4;
}
//Allocate the new array.
temp = new byte[m_currSig + newSigSize - 1];
//Copy the calling convention. The calling convention is always just one byte
//so we just copy that byte. Then copy the rest of the array, shifting everything
//to make room for the new number of elements.
temp[0] = m_signature[0];
Array.Copy(m_signature, m_sizeLoc + 1, temp, m_sizeLoc + newSigSize, currSigHolder - (m_sizeLoc + 1));
m_signature = temp;
//Use the AddData method to add the number of elements appropriately compressed.
m_currSig = m_sizeLoc;
AddData(m_argCount);
m_currSig = currSigHolder + (newSigSize - 1);
}
#endregion
#region Internal Members
internal int ArgumentCount
{
get
{
return m_argCount;
}
}
internal static bool IsSimpleType(CorElementType type)
{
if (type <= CorElementType.String)
return true;
if (type == CorElementType.TypedByRef || type == CorElementType.I || type == CorElementType.U || type == CorElementType.Object)
return true;
return false;
}
internal byte[] InternalGetSignature(out int length)
{
// An internal method to return the signature. Does not trim the
// array, but passes out the length of the array in an out parameter.
// This is the actual array -- not a copy -- so the callee must agree
// to not copy it.
//
// param length : an out param indicating the length of the array.
// return : A reference to the internal ubyte array.
if (!m_sigDone)
{
m_sigDone = true;
// If we have more than 128 variables, we can't just set the length, we need
// to compress it. Unfortunately, this means that we need to copy the entire
// array. Bummer, eh?
SetNumberOfSignatureElements(false);
}
length = m_currSig;
return m_signature;
}
internal byte[] InternalGetSignatureArray()
{
int argCount = m_argCount;
int currSigLength = m_currSig;
int newSigSize = currSigLength;
//Allocate the new array.
if (argCount < 0x7F)
newSigSize += 1;
else if (argCount < 0x3FFF)
newSigSize += 2;
else
newSigSize += 4;
byte[] temp = new byte[newSigSize];
// copy the sig
int sigCopyIndex = 0;
// calling convention
temp[sigCopyIndex++] = m_signature[0];
// arg size
if (argCount <= 0x7F)
temp[sigCopyIndex++] = (byte)(argCount & 0xFF);
else if (argCount <= 0x3FFF)
{
temp[sigCopyIndex++] = (byte)((argCount >>8) | 0x80);
temp[sigCopyIndex++] = (byte)(argCount & 0xFF);
}
else if (argCount <= 0x1FFFFFFF)
{
temp[sigCopyIndex++] = (byte)((argCount >>24) | 0xC0);
temp[sigCopyIndex++] = (byte)((argCount >>16) & 0xFF);
temp[sigCopyIndex++] = (byte)((argCount >>8) & 0xFF);
temp[sigCopyIndex++] = (byte)((argCount) & 0xFF);
}
else
throw new ArgumentException(Environment.GetResourceString("Argument_LargeInteger"));
// copy the sig part of the sig
Array.Copy(m_signature, 2, temp, sigCopyIndex, currSigLength - 2);
// mark the end of sig
temp[newSigSize - 1] = (byte)CorElementType.End;
return temp;
}
#endregion
#region Public Methods
public void AddArgument(Type clsArgument)
{
AddArgument(clsArgument, null, null);
}
[System.Security.SecuritySafeCritical] // auto-generated
public void AddArgument(Type argument, bool pinned)
{
if (argument == null)
throw new ArgumentNullException("argument");
IncrementArgCounts();
AddOneArgTypeHelper(argument, pinned);
}
public void AddArguments(Type[] arguments, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers)
{
if (requiredCustomModifiers != null && (arguments == null || requiredCustomModifiers.Length != arguments.Length))
throw new ArgumentException(Environment.GetResourceString("Argument_MismatchedArrays", "requiredCustomModifiers", "arguments"));
if (optionalCustomModifiers != null && (arguments == null || optionalCustomModifiers.Length != arguments.Length))
throw new ArgumentException(Environment.GetResourceString("Argument_MismatchedArrays", "optionalCustomModifiers", "arguments"));
if (arguments != null)
{
for (int i =0; i < arguments.Length; i++)
{
AddArgument(arguments[i],
requiredCustomModifiers == null ? null : requiredCustomModifiers[i],
optionalCustomModifiers == null ? null : optionalCustomModifiers[i]);
}
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public void AddArgument(Type argument, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers)
{
if (m_sigDone)
throw new ArgumentException(Environment.GetResourceString("Argument_SigIsFinalized"));
if (argument == null)
throw new ArgumentNullException("argument");
IncrementArgCounts();
// Add an argument to the signature. Takes a Type and determines whether it
// is one of the primitive types of which we have special knowledge or a more
// general class. In the former case, we only add the appropriate short cut encoding,
// otherwise we will calculate proper description for the type.
AddOneArgTypeHelper(argument, requiredCustomModifiers, optionalCustomModifiers);
}
public void AddSentinel()
{
AddElementType(CorElementType.Sentinel);
}
public override bool Equals(Object obj)
{
if (!(obj is SignatureHelper))
{
return false;
}
SignatureHelper temp = (SignatureHelper)obj;
if ( !temp.m_module.Equals(m_module) || temp.m_currSig!=m_currSig || temp.m_sizeLoc!=m_sizeLoc || temp.m_sigDone !=m_sigDone )
{
return false;
}
for (int i=0; i<m_currSig; i++)
{
if (m_signature[i]!=temp.m_signature[i])
return false;
}
return true;
}
public override int GetHashCode()
{
// Start the hash code with the hash code of the module and the values of the member variables.
int HashCode = m_module.GetHashCode() + m_currSig + m_sizeLoc;
// Add one if the sig is done.
if (m_sigDone)
HashCode += 1;
// Then add the hash code of all the arguments.
for (int i=0; i < m_currSig; i++)
HashCode += m_signature[i].GetHashCode();
return HashCode;
}
public byte[] GetSignature()
{
return GetSignature(false);
}
internal byte[] GetSignature(bool appendEndOfSig)
{
// Chops the internal signature to the appropriate length. Adds the
// end token to the signature and marks the signature as finished so that
// no further tokens can be added. Return the full signature in a trimmed array.
if (!m_sigDone)
{
if (appendEndOfSig)
AddElementType(CorElementType.End);
SetNumberOfSignatureElements(true);
m_sigDone = true;
}
// This case will only happen if the user got the signature through
// InternalGetSignature first and then called GetSignature.
if (m_signature.Length > m_currSig)
{
byte[] temp = new byte[m_currSig];
Array.Copy(m_signature, temp, m_currSig);
m_signature = temp;
}
return m_signature;
}
public override String ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("Length: " + m_currSig + Environment.NewLine);
if (m_sizeLoc != -1)
{
sb.Append("Arguments: " + m_signature[m_sizeLoc] + Environment.NewLine);
}
else
{
sb.Append("Field Signature" + Environment.NewLine);
}
sb.Append("Signature: " + Environment.NewLine);
for (int i=0; i<=m_currSig; i++)
{
sb.Append(m_signature[i] + " ");
}
sb.Append(Environment.NewLine);
return sb.ToString();
}
#endregion
#if !FEATURE_CORECLR
void _SignatureHelper.GetTypeInfoCount(out uint pcTInfo)
{
throw new NotImplementedException();
}
void _SignatureHelper.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
{
throw new NotImplementedException();
}
void _SignatureHelper.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
{
throw new NotImplementedException();
}
void _SignatureHelper.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
{
throw new NotImplementedException();
}
#endif
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace ModestTree
{
public static class TypeExtensions
{
public static bool DerivesFrom<T>(this Type a)
{
return DerivesFrom(a, typeof(T));
}
// This seems easier to think about than IsAssignableFrom
public static bool DerivesFrom(this Type a, Type b)
{
return b != a && b.IsAssignableFrom(a);
}
public static bool DerivesFromOrEqual<T>(this Type a)
{
return DerivesFromOrEqual(a, typeof(T));
}
public static bool DerivesFromOrEqual(this Type a, Type b)
{
return b == a || b.IsAssignableFrom(a);
}
public static object GetDefaultValue(this Type type)
{
if (type.IsValueType)
{
return Activator.CreateInstance(type);
}
return null;
}
// Returns name without generic arguments
public static string GetSimpleName(this Type type)
{
var name = type.Name;
var quoteIndex = name.IndexOf("`");
if (quoteIndex == -1)
{
return name;
}
// Remove the backtick
return name.Substring(0, quoteIndex);
}
public static IEnumerable<Type> GetParentTypes(this Type type)
{
if (type == null || type.BaseType == null || type == typeof(object) || type.BaseType == typeof(object))
{
yield break;
}
yield return type.BaseType;
foreach (var ancestor in type.BaseType.GetParentTypes())
{
yield return ancestor;
}
}
public static string NameWithParents(this Type type)
{
var typeList = type.GetParentTypes().Prepend(type).Select(x => x.Name()).ToArray();
return string.Join(":", typeList);
}
public static bool IsClosedGenericType(this Type type)
{
return type.IsGenericType && type != type.GetGenericTypeDefinition();
}
public static bool IsOpenGenericType(this Type type)
{
return type.IsGenericType && type == type.GetGenericTypeDefinition();
}
// This is the same as the standard GetFields except it also supports getting the private
// fields in base classes
public static IEnumerable<FieldInfo> GetAllFields(this Type type, BindingFlags flags)
{
if ((int)(flags & BindingFlags.DeclaredOnly) != 0)
{
// Can use normal method in this case
foreach (var fieldInfo in type.GetFields(flags))
{
yield return fieldInfo;
}
}
else
{
// Add DeclaredOnly because we will get the base classes below
foreach (var fieldInfo in type.GetFields(flags | BindingFlags.DeclaredOnly))
{
yield return fieldInfo;
}
if (type.BaseType != null && type.BaseType != typeof(object))
{
foreach (var fieldInfo in type.BaseType.GetAllFields(flags))
{
yield return fieldInfo;
}
}
}
}
// This is the same as the standard GetProperties except it also supports getting the private
// members in base classes
public static IEnumerable<PropertyInfo> GetAllProperties(this Type type, BindingFlags flags)
{
if ((int)(flags & BindingFlags.DeclaredOnly) != 0)
{
// Can use normal method in this case
foreach (var propertyInfo in type.GetProperties(flags))
{
yield return propertyInfo;
}
}
else
{
// Add DeclaredOnly because we will get the base classes below
foreach (var propertyInfo in type.GetProperties(flags | BindingFlags.DeclaredOnly))
{
yield return propertyInfo;
}
if (type.BaseType != null && type.BaseType != typeof(object))
{
foreach (var propertyInfo in type.BaseType.GetAllProperties(flags))
{
yield return propertyInfo;
}
}
}
}
// This is the same as the standard GetMethods except it also supports getting the private
// members in base classes
public static IEnumerable<MethodInfo> GetAllMethods(this Type type, BindingFlags flags)
{
if ((int)(flags & BindingFlags.DeclaredOnly) != 0)
{
// Can use normal method in this case
foreach (var methodInfo in type.GetMethods(flags))
{
yield return methodInfo;
}
}
else
{
// Add DeclaredOnly because we will get the base classes below
foreach (var methodInfo in type.GetMethods(flags | BindingFlags.DeclaredOnly))
{
yield return methodInfo;
}
if (type.BaseType != null && type.BaseType != typeof(object))
{
foreach (var methodInfo in type.BaseType.GetAllMethods(flags))
{
yield return methodInfo;
}
}
}
}
public static string Name(this Type type)
{
if (type.IsArray)
{
return string.Format("{0}[]", type.GetElementType().Name());
}
if (type.ContainsGenericParameters || type.IsGenericType)
{
if (type.BaseType == typeof(Nullable<>) || (type.BaseType == typeof(ValueType) && type.UnderlyingSystemType.Name.StartsWith("Nullable")))
{
return GetCSharpTypeName(type.GetGenericArguments().Single().Name) + "?";
}
int index = type.Name.IndexOf("`");
string genericTypeName = index > 0 ? type.Name.Substring(0, index) : type.Name;
string genericArgs = string.Join(",", type.GetGenericArguments().Select(t => t.Name()).ToArray());
return genericArgs.Length == 0 ? genericTypeName : genericTypeName + "<" + genericArgs + ">";
}
// If a nested class, include the parent classes as well
return (type.DeclaringType == null ? "" : type.DeclaringType.Name() + ".") + GetCSharpTypeName(type.Name);
}
static string GetCSharpTypeName(string typeName)
{
switch (typeName)
{
case "String":
case "Object":
case "Void":
case "Byte":
case "Double":
case "Decimal":
return typeName.ToLower();
case "Int16":
return "short";
case "Int32":
return "int";
case "Int64":
return "long";
case "Single":
return "float";
case "Boolean":
return "bool";
default:
return typeName;
}
}
public static bool HasAttribute(
this ICustomAttributeProvider provider, params Type[] attributeTypes)
{
return provider.AllAttributes(attributeTypes).Any();
}
public static bool HasAttribute<T>(this ICustomAttributeProvider provider)
where T : Attribute
{
return provider.AllAttributes(typeof(T)).Any();
}
public static IEnumerable<T> AllAttributes<T>(
this ICustomAttributeProvider provider)
where T : Attribute
{
return provider.AllAttributes(typeof(T)).Cast<T>();
}
public static IEnumerable<Attribute> AllAttributes(
this ICustomAttributeProvider provider, params Type[] attributeTypes)
{
var allAttributes = provider.GetCustomAttributes(true).Cast<Attribute>();
if (attributeTypes.Length == 0)
{
return allAttributes;
}
return allAttributes.Where(a => attributeTypes.Any(x => a.GetType().DerivesFromOrEqual(x)));
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the opsworks-2013-02-18.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.OpsWorks.Model
{
/// <summary>
/// Describes an instance's Amazon EBS volume.
/// </summary>
public partial class Volume
{
private string _availabilityZone;
private string _device;
private string _ec2VolumeId;
private string _instanceId;
private int? _iops;
private string _mountPoint;
private string _name;
private string _raidArrayId;
private string _region;
private int? _size;
private string _status;
private string _volumeId;
private string _volumeType;
/// <summary>
/// Gets and sets the property AvailabilityZone.
/// <para>
/// The volume Availability Zone. For more information, see <a href="http://docs.aws.amazon.com/general/latest/gr/rande.html">Regions
/// and Endpoints</a>.
/// </para>
/// </summary>
public string AvailabilityZone
{
get { return this._availabilityZone; }
set { this._availabilityZone = value; }
}
// Check to see if AvailabilityZone property is set
internal bool IsSetAvailabilityZone()
{
return this._availabilityZone != null;
}
/// <summary>
/// Gets and sets the property Device.
/// <para>
/// The device name.
/// </para>
/// </summary>
public string Device
{
get { return this._device; }
set { this._device = value; }
}
// Check to see if Device property is set
internal bool IsSetDevice()
{
return this._device != null;
}
/// <summary>
/// Gets and sets the property Ec2VolumeId.
/// <para>
/// The Amazon EC2 volume ID.
/// </para>
/// </summary>
public string Ec2VolumeId
{
get { return this._ec2VolumeId; }
set { this._ec2VolumeId = value; }
}
// Check to see if Ec2VolumeId property is set
internal bool IsSetEc2VolumeId()
{
return this._ec2VolumeId != null;
}
/// <summary>
/// Gets and sets the property InstanceId.
/// <para>
/// The instance ID.
/// </para>
/// </summary>
public string InstanceId
{
get { return this._instanceId; }
set { this._instanceId = value; }
}
// Check to see if InstanceId property is set
internal bool IsSetInstanceId()
{
return this._instanceId != null;
}
/// <summary>
/// Gets and sets the property Iops.
/// <para>
/// For PIOPS volumes, the IOPS per disk.
/// </para>
/// </summary>
public int Iops
{
get { return this._iops.GetValueOrDefault(); }
set { this._iops = value; }
}
// Check to see if Iops property is set
internal bool IsSetIops()
{
return this._iops.HasValue;
}
/// <summary>
/// Gets and sets the property MountPoint.
/// <para>
/// The volume mount point. For example "/dev/sdh".
/// </para>
/// </summary>
public string MountPoint
{
get { return this._mountPoint; }
set { this._mountPoint = value; }
}
// Check to see if MountPoint property is set
internal bool IsSetMountPoint()
{
return this._mountPoint != null;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// The volume name.
/// </para>
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
/// <summary>
/// Gets and sets the property RaidArrayId.
/// <para>
/// The RAID array ID.
/// </para>
/// </summary>
public string RaidArrayId
{
get { return this._raidArrayId; }
set { this._raidArrayId = value; }
}
// Check to see if RaidArrayId property is set
internal bool IsSetRaidArrayId()
{
return this._raidArrayId != null;
}
/// <summary>
/// Gets and sets the property Region.
/// <para>
/// The AWS region. For more information about AWS regions, see <a href="http://docs.aws.amazon.com/general/latest/gr/rande.html">Regions
/// and Endpoints</a>.
/// </para>
/// </summary>
public string Region
{
get { return this._region; }
set { this._region = value; }
}
// Check to see if Region property is set
internal bool IsSetRegion()
{
return this._region != null;
}
/// <summary>
/// Gets and sets the property Size.
/// <para>
/// The volume size.
/// </para>
/// </summary>
public int Size
{
get { return this._size.GetValueOrDefault(); }
set { this._size = value; }
}
// Check to see if Size property is set
internal bool IsSetSize()
{
return this._size.HasValue;
}
/// <summary>
/// Gets and sets the property Status.
/// <para>
/// The value returned by <a href="http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeVolumes.html">DescribeVolumes</a>.
/// </para>
/// </summary>
public string Status
{
get { return this._status; }
set { this._status = value; }
}
// Check to see if Status property is set
internal bool IsSetStatus()
{
return this._status != null;
}
/// <summary>
/// Gets and sets the property VolumeId.
/// <para>
/// The volume ID.
/// </para>
/// </summary>
public string VolumeId
{
get { return this._volumeId; }
set { this._volumeId = value; }
}
// Check to see if VolumeId property is set
internal bool IsSetVolumeId()
{
return this._volumeId != null;
}
/// <summary>
/// Gets and sets the property VolumeType.
/// <para>
/// The volume type, standard or PIOPS.
/// </para>
/// </summary>
public string VolumeType
{
get { return this._volumeType; }
set { this._volumeType = value; }
}
// Check to see if VolumeType property is set
internal bool IsSetVolumeType()
{
return this._volumeType != null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class LambdaAddNullableTests
{
#region Test methods
[Fact]
public static void LambdaAddNullableDecimalTest()
{
decimal?[] values = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyAddNullableDecimal(values[i], values[j]);
}
}
}
[Fact]
public static void LambdaAddNullableDoubleTest()
{
double?[] values = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyAddNullableDouble(values[i], values[j]);
}
}
}
[Fact]
public static void LambdaAddNullableFloatTest()
{
float?[] values = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyAddNullableFloat(values[i], values[j]);
}
}
}
[Fact]
public static void LambdaAddNullableIntTest()
{
int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyAddNullableInt(values[i], values[j]);
}
}
}
[Fact]
public static void LambdaAddNullableLongTest()
{
long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyAddNullableLong(values[i], values[j]);
}
}
}
[Fact]
public static void LambdaAddNullableShortTest()
{
short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyAddNullableShort(values[i], values[j]);
}
}
}
[Fact]
public static void LambdaAddNullableUIntTest()
{
uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyAddNullableUInt(values[i], values[j]);
}
}
}
[Fact]
public static void LambdaAddNullableULongTest()
{
ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyAddNullableULong(values[i], values[j]);
}
}
}
[Fact]
public static void LambdaAddNullableUShortTest()
{
ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyAddNullableUShort(values[i], values[j]);
}
}
}
#endregion
#region Test verifiers
#region Verify decimal?
private static void VerifyAddNullableDecimal(decimal? a, decimal? b)
{
ParameterExpression p0 = Expression.Parameter(typeof(decimal?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(decimal?), "p1");
// verify with parameters supplied
Expression<Func<decimal?>> e1 =
Expression.Lambda<Func<decimal?>>(
Expression.Invoke(
Expression.Lambda<Func<decimal?, decimal?, decimal?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(decimal?)),
Expression.Constant(b, typeof(decimal?))
}),
Enumerable.Empty<ParameterExpression>());
Func<decimal?> f1 = e1.Compile();
decimal? f1Result = default(decimal?);
Exception f1Ex = null;
try
{
f1Result = f1();
}
catch (Exception ex)
{
f1Ex = ex;
}
// verify with values passed to make parameters
Expression<Func<decimal?, decimal?, Func<decimal?>>> e2 =
Expression.Lambda<Func<decimal?, decimal?, Func<decimal?>>>(
Expression.Lambda<Func<decimal?>>(
Expression.Add(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<decimal?, decimal?, Func<decimal?>> f2 = e2.Compile();
decimal? f2Result = default(decimal?);
Exception f2Ex = null;
try
{
f2Result = f2(a, b)();
}
catch (Exception ex)
{
f2Ex = ex;
}
// verify with values directly passed
Expression<Func<Func<decimal?, decimal?, decimal?>>> e3 =
Expression.Lambda<Func<Func<decimal?, decimal?, decimal?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<decimal?, decimal?, decimal?>>>(
Expression.Lambda<Func<decimal?, decimal?, decimal?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<decimal?, decimal?, decimal?> f3 = e3.Compile()();
decimal? f3Result = default(decimal?);
Exception f3Ex = null;
try
{
f3Result = f3(a, b);
}
catch (Exception ex)
{
f3Ex = ex;
}
// verify as a function generator
Expression<Func<Func<decimal?, decimal?, decimal?>>> e4 =
Expression.Lambda<Func<Func<decimal?, decimal?, decimal?>>>(
Expression.Lambda<Func<decimal?, decimal?, decimal?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<decimal?, decimal?, decimal?>> f4 = e4.Compile();
decimal? f4Result = default(decimal?);
Exception f4Ex = null;
try
{
f4Result = f4()(a, b);
}
catch (Exception ex)
{
f4Ex = ex;
}
// verify with currying
Expression<Func<decimal?, Func<decimal?, decimal?>>> e5 =
Expression.Lambda<Func<decimal?, Func<decimal?, decimal?>>>(
Expression.Lambda<Func<decimal?, decimal?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<decimal?, Func<decimal?, decimal?>> f5 = e5.Compile();
decimal? f5Result = default(decimal?);
Exception f5Ex = null;
try
{
f5Result = f5(a)(b);
}
catch (Exception ex)
{
f5Ex = ex;
}
// verify with one parameter
Expression<Func<Func<decimal?, decimal?>>> e6 =
Expression.Lambda<Func<Func<decimal?, decimal?>>>(
Expression.Invoke(
Expression.Lambda<Func<decimal?, Func<decimal?, decimal?>>>(
Expression.Lambda<Func<decimal?, decimal?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(decimal?)) }),
Enumerable.Empty<ParameterExpression>());
Func<decimal?, decimal?> f6 = e6.Compile()();
decimal? f6Result = default(decimal?);
Exception f6Ex = null;
try
{
f6Result = f6(b);
}
catch (Exception ex)
{
f6Ex = ex;
}
// verify with regular IL
decimal? csResult = default(decimal?);
Exception csEx = null;
try
{
csResult = (decimal?)(a + b);
}
catch (Exception ex)
{
csEx = ex;
}
// either all should have failed the same way or they should all produce the same result
if (f1Ex != null || f2Ex != null || f3Ex != null || f4Ex != null || f5Ex != null || f6Ex != null || csEx != null)
{
Assert.NotNull(f1Ex);
Assert.NotNull(f2Ex);
Assert.NotNull(f3Ex);
Assert.NotNull(f4Ex);
Assert.NotNull(f5Ex);
Assert.NotNull(f6Ex);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), f1Ex.GetType());
Assert.Equal(csEx.GetType(), f2Ex.GetType());
Assert.Equal(csEx.GetType(), f3Ex.GetType());
Assert.Equal(csEx.GetType(), f4Ex.GetType());
Assert.Equal(csEx.GetType(), f5Ex.GetType());
Assert.Equal(csEx.GetType(), f6Ex.GetType());
}
else
{
Assert.Equal(csResult, f1Result);
Assert.Equal(csResult, f2Result);
Assert.Equal(csResult, f3Result);
Assert.Equal(csResult, f4Result);
Assert.Equal(csResult, f5Result);
Assert.Equal(csResult, f6Result);
}
}
#endregion
#region Verify double?
private static void VerifyAddNullableDouble(double? a, double? b)
{
ParameterExpression p0 = Expression.Parameter(typeof(double?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(double?), "p1");
// verify with parameters supplied
Expression<Func<double?>> e1 =
Expression.Lambda<Func<double?>>(
Expression.Invoke(
Expression.Lambda<Func<double?, double?, double?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(double?)),
Expression.Constant(b, typeof(double?))
}),
Enumerable.Empty<ParameterExpression>());
Func<double?> f1 = e1.Compile();
double? f1Result = default(double?);
Exception f1Ex = null;
try
{
f1Result = f1();
}
catch (Exception ex)
{
f1Ex = ex;
}
// verify with values passed to make parameters
Expression<Func<double?, double?, Func<double?>>> e2 =
Expression.Lambda<Func<double?, double?, Func<double?>>>(
Expression.Lambda<Func<double?>>(
Expression.Add(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<double?, double?, Func<double?>> f2 = e2.Compile();
double? f2Result = default(double?);
Exception f2Ex = null;
try
{
f2Result = f2(a, b)();
}
catch (Exception ex)
{
f2Ex = ex;
}
// verify with values directly passed
Expression<Func<Func<double?, double?, double?>>> e3 =
Expression.Lambda<Func<Func<double?, double?, double?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<double?, double?, double?>>>(
Expression.Lambda<Func<double?, double?, double?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<double?, double?, double?> f3 = e3.Compile()();
double? f3Result = default(double?);
Exception f3Ex = null;
try
{
f3Result = f3(a, b);
}
catch (Exception ex)
{
f3Ex = ex;
}
// verify as a function generator
Expression<Func<Func<double?, double?, double?>>> e4 =
Expression.Lambda<Func<Func<double?, double?, double?>>>(
Expression.Lambda<Func<double?, double?, double?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<double?, double?, double?>> f4 = e4.Compile();
double? f4Result = default(double?);
Exception f4Ex = null;
try
{
f4Result = f4()(a, b);
}
catch (Exception ex)
{
f4Ex = ex;
}
// verify with currying
Expression<Func<double?, Func<double?, double?>>> e5 =
Expression.Lambda<Func<double?, Func<double?, double?>>>(
Expression.Lambda<Func<double?, double?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<double?, Func<double?, double?>> f5 = e5.Compile();
double? f5Result = default(double?);
Exception f5Ex = null;
try
{
f5Result = f5(a)(b);
}
catch (Exception ex)
{
f5Ex = ex;
}
// verify with one parameter
Expression<Func<Func<double?, double?>>> e6 =
Expression.Lambda<Func<Func<double?, double?>>>(
Expression.Invoke(
Expression.Lambda<Func<double?, Func<double?, double?>>>(
Expression.Lambda<Func<double?, double?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(double?)) }),
Enumerable.Empty<ParameterExpression>());
Func<double?, double?> f6 = e6.Compile()();
double? f6Result = default(double?);
Exception f6Ex = null;
try
{
f6Result = f6(b);
}
catch (Exception ex)
{
f6Ex = ex;
}
// verify with regular IL
double? csResult = default(double?);
Exception csEx = null;
try
{
csResult = (double?)(a + b);
}
catch (Exception ex)
{
csEx = ex;
}
// either all should have failed the same way or they should all produce the same result
if (f1Ex != null || f2Ex != null || f3Ex != null || f4Ex != null || f5Ex != null || f6Ex != null || csEx != null)
{
Assert.NotNull(f1Ex);
Assert.NotNull(f2Ex);
Assert.NotNull(f3Ex);
Assert.NotNull(f4Ex);
Assert.NotNull(f5Ex);
Assert.NotNull(f6Ex);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), f1Ex.GetType());
Assert.Equal(csEx.GetType(), f2Ex.GetType());
Assert.Equal(csEx.GetType(), f3Ex.GetType());
Assert.Equal(csEx.GetType(), f4Ex.GetType());
Assert.Equal(csEx.GetType(), f5Ex.GetType());
Assert.Equal(csEx.GetType(), f6Ex.GetType());
}
else
{
Assert.Equal(csResult, f1Result);
Assert.Equal(csResult, f2Result);
Assert.Equal(csResult, f3Result);
Assert.Equal(csResult, f4Result);
Assert.Equal(csResult, f5Result);
Assert.Equal(csResult, f6Result);
}
}
#endregion
#region Verify float?
private static void VerifyAddNullableFloat(float? a, float? b)
{
ParameterExpression p0 = Expression.Parameter(typeof(float?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(float?), "p1");
// verify with parameters supplied
Expression<Func<float?>> e1 =
Expression.Lambda<Func<float?>>(
Expression.Invoke(
Expression.Lambda<Func<float?, float?, float?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(float?)),
Expression.Constant(b, typeof(float?))
}),
Enumerable.Empty<ParameterExpression>());
Func<float?> f1 = e1.Compile();
float? f1Result = default(float?);
Exception f1Ex = null;
try
{
f1Result = f1();
}
catch (Exception ex)
{
f1Ex = ex;
}
// verify with values passed to make parameters
Expression<Func<float?, float?, Func<float?>>> e2 =
Expression.Lambda<Func<float?, float?, Func<float?>>>(
Expression.Lambda<Func<float?>>(
Expression.Add(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<float?, float?, Func<float?>> f2 = e2.Compile();
float? f2Result = default(float?);
Exception f2Ex = null;
try
{
f2Result = f2(a, b)();
}
catch (Exception ex)
{
f2Ex = ex;
}
// verify with values directly passed
Expression<Func<Func<float?, float?, float?>>> e3 =
Expression.Lambda<Func<Func<float?, float?, float?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<float?, float?, float?>>>(
Expression.Lambda<Func<float?, float?, float?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<float?, float?, float?> f3 = e3.Compile()();
float? f3Result = default(float?);
Exception f3Ex = null;
try
{
f3Result = f3(a, b);
}
catch (Exception ex)
{
f3Ex = ex;
}
// verify as a function generator
Expression<Func<Func<float?, float?, float?>>> e4 =
Expression.Lambda<Func<Func<float?, float?, float?>>>(
Expression.Lambda<Func<float?, float?, float?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<float?, float?, float?>> f4 = e4.Compile();
float? f4Result = default(float?);
Exception f4Ex = null;
try
{
f4Result = f4()(a, b);
}
catch (Exception ex)
{
f4Ex = ex;
}
// verify with currying
Expression<Func<float?, Func<float?, float?>>> e5 =
Expression.Lambda<Func<float?, Func<float?, float?>>>(
Expression.Lambda<Func<float?, float?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<float?, Func<float?, float?>> f5 = e5.Compile();
float? f5Result = default(float?);
Exception f5Ex = null;
try
{
f5Result = f5(a)(b);
}
catch (Exception ex)
{
f5Ex = ex;
}
// verify with one parameter
Expression<Func<Func<float?, float?>>> e6 =
Expression.Lambda<Func<Func<float?, float?>>>(
Expression.Invoke(
Expression.Lambda<Func<float?, Func<float?, float?>>>(
Expression.Lambda<Func<float?, float?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(float?)) }),
Enumerable.Empty<ParameterExpression>());
Func<float?, float?> f6 = e6.Compile()();
float? f6Result = default(float?);
Exception f6Ex = null;
try
{
f6Result = f6(b);
}
catch (Exception ex)
{
f6Ex = ex;
}
// verify with regular IL
float? csResult = default(float?);
Exception csEx = null;
try
{
csResult = (float?)(a + b);
}
catch (Exception ex)
{
csEx = ex;
}
// either all should have failed the same way or they should all produce the same result
if (f1Ex != null || f2Ex != null || f3Ex != null || f4Ex != null || f5Ex != null || f6Ex != null || csEx != null)
{
Assert.NotNull(f1Ex);
Assert.NotNull(f2Ex);
Assert.NotNull(f3Ex);
Assert.NotNull(f4Ex);
Assert.NotNull(f5Ex);
Assert.NotNull(f6Ex);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), f1Ex.GetType());
Assert.Equal(csEx.GetType(), f2Ex.GetType());
Assert.Equal(csEx.GetType(), f3Ex.GetType());
Assert.Equal(csEx.GetType(), f4Ex.GetType());
Assert.Equal(csEx.GetType(), f5Ex.GetType());
Assert.Equal(csEx.GetType(), f6Ex.GetType());
}
else
{
Assert.Equal(csResult, f1Result);
Assert.Equal(csResult, f2Result);
Assert.Equal(csResult, f3Result);
Assert.Equal(csResult, f4Result);
Assert.Equal(csResult, f5Result);
Assert.Equal(csResult, f6Result);
}
}
#endregion
#region Verify int?
private static void VerifyAddNullableInt(int? a, int? b)
{
ParameterExpression p0 = Expression.Parameter(typeof(int?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(int?), "p1");
// verify with parameters supplied
Expression<Func<int?>> e1 =
Expression.Lambda<Func<int?>>(
Expression.Invoke(
Expression.Lambda<Func<int?, int?, int?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int?))
}),
Enumerable.Empty<ParameterExpression>());
Func<int?> f1 = e1.Compile();
int? f1Result = default(int?);
Exception f1Ex = null;
try
{
f1Result = f1();
}
catch (Exception ex)
{
f1Ex = ex;
}
// verify with values passed to make parameters
Expression<Func<int?, int?, Func<int?>>> e2 =
Expression.Lambda<Func<int?, int?, Func<int?>>>(
Expression.Lambda<Func<int?>>(
Expression.Add(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<int?, int?, Func<int?>> f2 = e2.Compile();
int? f2Result = default(int?);
Exception f2Ex = null;
try
{
f2Result = f2(a, b)();
}
catch (Exception ex)
{
f2Ex = ex;
}
// verify with values directly passed
Expression<Func<Func<int?, int?, int?>>> e3 =
Expression.Lambda<Func<Func<int?, int?, int?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<int?, int?, int?>>>(
Expression.Lambda<Func<int?, int?, int?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<int?, int?, int?> f3 = e3.Compile()();
int? f3Result = default(int?);
Exception f3Ex = null;
try
{
f3Result = f3(a, b);
}
catch (Exception ex)
{
f3Ex = ex;
}
// verify as a function generator
Expression<Func<Func<int?, int?, int?>>> e4 =
Expression.Lambda<Func<Func<int?, int?, int?>>>(
Expression.Lambda<Func<int?, int?, int?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<int?, int?, int?>> f4 = e4.Compile();
int? f4Result = default(int?);
Exception f4Ex = null;
try
{
f4Result = f4()(a, b);
}
catch (Exception ex)
{
f4Ex = ex;
}
// verify with currying
Expression<Func<int?, Func<int?, int?>>> e5 =
Expression.Lambda<Func<int?, Func<int?, int?>>>(
Expression.Lambda<Func<int?, int?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<int?, Func<int?, int?>> f5 = e5.Compile();
int? f5Result = default(int?);
Exception f5Ex = null;
try
{
f5Result = f5(a)(b);
}
catch (Exception ex)
{
f5Ex = ex;
}
// verify with one parameter
Expression<Func<Func<int?, int?>>> e6 =
Expression.Lambda<Func<Func<int?, int?>>>(
Expression.Invoke(
Expression.Lambda<Func<int?, Func<int?, int?>>>(
Expression.Lambda<Func<int?, int?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(int?)) }),
Enumerable.Empty<ParameterExpression>());
Func<int?, int?> f6 = e6.Compile()();
int? f6Result = default(int?);
Exception f6Ex = null;
try
{
f6Result = f6(b);
}
catch (Exception ex)
{
f6Ex = ex;
}
// verify with regular IL
int? csResult = default(int?);
Exception csEx = null;
try
{
csResult = (int?)(a + b);
}
catch (Exception ex)
{
csEx = ex;
}
// either all should have failed the same way or they should all produce the same result
if (f1Ex != null || f2Ex != null || f3Ex != null || f4Ex != null || f5Ex != null || f6Ex != null || csEx != null)
{
Assert.NotNull(f1Ex);
Assert.NotNull(f2Ex);
Assert.NotNull(f3Ex);
Assert.NotNull(f4Ex);
Assert.NotNull(f5Ex);
Assert.NotNull(f6Ex);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), f1Ex.GetType());
Assert.Equal(csEx.GetType(), f2Ex.GetType());
Assert.Equal(csEx.GetType(), f3Ex.GetType());
Assert.Equal(csEx.GetType(), f4Ex.GetType());
Assert.Equal(csEx.GetType(), f5Ex.GetType());
Assert.Equal(csEx.GetType(), f6Ex.GetType());
}
else
{
Assert.Equal(csResult, f1Result);
Assert.Equal(csResult, f2Result);
Assert.Equal(csResult, f3Result);
Assert.Equal(csResult, f4Result);
Assert.Equal(csResult, f5Result);
Assert.Equal(csResult, f6Result);
}
}
#endregion
#region Verify long?
private static void VerifyAddNullableLong(long? a, long? b)
{
ParameterExpression p0 = Expression.Parameter(typeof(long?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(long?), "p1");
// verify with parameters supplied
Expression<Func<long?>> e1 =
Expression.Lambda<Func<long?>>(
Expression.Invoke(
Expression.Lambda<Func<long?, long?, long?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(long?))
}),
Enumerable.Empty<ParameterExpression>());
Func<long?> f1 = e1.Compile();
long? f1Result = default(long?);
Exception f1Ex = null;
try
{
f1Result = f1();
}
catch (Exception ex)
{
f1Ex = ex;
}
// verify with values passed to make parameters
Expression<Func<long?, long?, Func<long?>>> e2 =
Expression.Lambda<Func<long?, long?, Func<long?>>>(
Expression.Lambda<Func<long?>>(
Expression.Add(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<long?, long?, Func<long?>> f2 = e2.Compile();
long? f2Result = default(long?);
Exception f2Ex = null;
try
{
f2Result = f2(a, b)();
}
catch (Exception ex)
{
f2Ex = ex;
}
// verify with values directly passed
Expression<Func<Func<long?, long?, long?>>> e3 =
Expression.Lambda<Func<Func<long?, long?, long?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<long?, long?, long?>>>(
Expression.Lambda<Func<long?, long?, long?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<long?, long?, long?> f3 = e3.Compile()();
long? f3Result = default(long?);
Exception f3Ex = null;
try
{
f3Result = f3(a, b);
}
catch (Exception ex)
{
f3Ex = ex;
}
// verify as a function generator
Expression<Func<Func<long?, long?, long?>>> e4 =
Expression.Lambda<Func<Func<long?, long?, long?>>>(
Expression.Lambda<Func<long?, long?, long?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<long?, long?, long?>> f4 = e4.Compile();
long? f4Result = default(long?);
Exception f4Ex = null;
try
{
f4Result = f4()(a, b);
}
catch (Exception ex)
{
f4Ex = ex;
}
// verify with currying
Expression<Func<long?, Func<long?, long?>>> e5 =
Expression.Lambda<Func<long?, Func<long?, long?>>>(
Expression.Lambda<Func<long?, long?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<long?, Func<long?, long?>> f5 = e5.Compile();
long? f5Result = default(long?);
Exception f5Ex = null;
try
{
f5Result = f5(a)(b);
}
catch (Exception ex)
{
f5Ex = ex;
}
// verify with one parameter
Expression<Func<Func<long?, long?>>> e6 =
Expression.Lambda<Func<Func<long?, long?>>>(
Expression.Invoke(
Expression.Lambda<Func<long?, Func<long?, long?>>>(
Expression.Lambda<Func<long?, long?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(long?)) }),
Enumerable.Empty<ParameterExpression>());
Func<long?, long?> f6 = e6.Compile()();
long? f6Result = default(long?);
Exception f6Ex = null;
try
{
f6Result = f6(b);
}
catch (Exception ex)
{
f6Ex = ex;
}
// verify with regular IL
long? csResult = default(long?);
Exception csEx = null;
try
{
csResult = (long?)(a + b);
}
catch (Exception ex)
{
csEx = ex;
}
// either all should have failed the same way or they should all produce the same result
if (f1Ex != null || f2Ex != null || f3Ex != null || f4Ex != null || f5Ex != null || f6Ex != null || csEx != null)
{
Assert.NotNull(f1Ex);
Assert.NotNull(f2Ex);
Assert.NotNull(f3Ex);
Assert.NotNull(f4Ex);
Assert.NotNull(f5Ex);
Assert.NotNull(f6Ex);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), f1Ex.GetType());
Assert.Equal(csEx.GetType(), f2Ex.GetType());
Assert.Equal(csEx.GetType(), f3Ex.GetType());
Assert.Equal(csEx.GetType(), f4Ex.GetType());
Assert.Equal(csEx.GetType(), f5Ex.GetType());
Assert.Equal(csEx.GetType(), f6Ex.GetType());
}
else
{
Assert.Equal(csResult, f1Result);
Assert.Equal(csResult, f2Result);
Assert.Equal(csResult, f3Result);
Assert.Equal(csResult, f4Result);
Assert.Equal(csResult, f5Result);
Assert.Equal(csResult, f6Result);
}
}
#endregion
#region Verify short?
private static void VerifyAddNullableShort(short? a, short? b)
{
ParameterExpression p0 = Expression.Parameter(typeof(short?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(short?), "p1");
// verify with parameters supplied
Expression<Func<short?>> e1 =
Expression.Lambda<Func<short?>>(
Expression.Invoke(
Expression.Lambda<Func<short?, short?, short?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(short?))
}),
Enumerable.Empty<ParameterExpression>());
Func<short?> f1 = e1.Compile();
short? f1Result = default(short?);
Exception f1Ex = null;
try
{
f1Result = f1();
}
catch (Exception ex)
{
f1Ex = ex;
}
// verify with values passed to make parameters
Expression<Func<short?, short?, Func<short?>>> e2 =
Expression.Lambda<Func<short?, short?, Func<short?>>>(
Expression.Lambda<Func<short?>>(
Expression.Add(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<short?, short?, Func<short?>> f2 = e2.Compile();
short? f2Result = default(short?);
Exception f2Ex = null;
try
{
f2Result = f2(a, b)();
}
catch (Exception ex)
{
f2Ex = ex;
}
// verify with values directly passed
Expression<Func<Func<short?, short?, short?>>> e3 =
Expression.Lambda<Func<Func<short?, short?, short?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<short?, short?, short?>>>(
Expression.Lambda<Func<short?, short?, short?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<short?, short?, short?> f3 = e3.Compile()();
short? f3Result = default(short?);
Exception f3Ex = null;
try
{
f3Result = f3(a, b);
}
catch (Exception ex)
{
f3Ex = ex;
}
// verify as a function generator
Expression<Func<Func<short?, short?, short?>>> e4 =
Expression.Lambda<Func<Func<short?, short?, short?>>>(
Expression.Lambda<Func<short?, short?, short?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<short?, short?, short?>> f4 = e4.Compile();
short? f4Result = default(short?);
Exception f4Ex = null;
try
{
f4Result = f4()(a, b);
}
catch (Exception ex)
{
f4Ex = ex;
}
// verify with currying
Expression<Func<short?, Func<short?, short?>>> e5 =
Expression.Lambda<Func<short?, Func<short?, short?>>>(
Expression.Lambda<Func<short?, short?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<short?, Func<short?, short?>> f5 = e5.Compile();
short? f5Result = default(short?);
Exception f5Ex = null;
try
{
f5Result = f5(a)(b);
}
catch (Exception ex)
{
f5Ex = ex;
}
// verify with one parameter
Expression<Func<Func<short?, short?>>> e6 =
Expression.Lambda<Func<Func<short?, short?>>>(
Expression.Invoke(
Expression.Lambda<Func<short?, Func<short?, short?>>>(
Expression.Lambda<Func<short?, short?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(short?)) }),
Enumerable.Empty<ParameterExpression>());
Func<short?, short?> f6 = e6.Compile()();
short? f6Result = default(short?);
Exception f6Ex = null;
try
{
f6Result = f6(b);
}
catch (Exception ex)
{
f6Ex = ex;
}
// verify with regular IL
short? csResult = default(short?);
Exception csEx = null;
try
{
csResult = (short?)(a + b);
}
catch (Exception ex)
{
csEx = ex;
}
// either all should have failed the same way or they should all produce the same result
if (f1Ex != null || f2Ex != null || f3Ex != null || f4Ex != null || f5Ex != null || f6Ex != null || csEx != null)
{
Assert.NotNull(f1Ex);
Assert.NotNull(f2Ex);
Assert.NotNull(f3Ex);
Assert.NotNull(f4Ex);
Assert.NotNull(f5Ex);
Assert.NotNull(f6Ex);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), f1Ex.GetType());
Assert.Equal(csEx.GetType(), f2Ex.GetType());
Assert.Equal(csEx.GetType(), f3Ex.GetType());
Assert.Equal(csEx.GetType(), f4Ex.GetType());
Assert.Equal(csEx.GetType(), f5Ex.GetType());
Assert.Equal(csEx.GetType(), f6Ex.GetType());
}
else
{
Assert.Equal(csResult, f1Result);
Assert.Equal(csResult, f2Result);
Assert.Equal(csResult, f3Result);
Assert.Equal(csResult, f4Result);
Assert.Equal(csResult, f5Result);
Assert.Equal(csResult, f6Result);
}
}
#endregion
#region Verify uint?
private static void VerifyAddNullableUInt(uint? a, uint? b)
{
ParameterExpression p0 = Expression.Parameter(typeof(uint?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(uint?), "p1");
// verify with parameters supplied
Expression<Func<uint?>> e1 =
Expression.Lambda<Func<uint?>>(
Expression.Invoke(
Expression.Lambda<Func<uint?, uint?, uint?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(uint?))
}),
Enumerable.Empty<ParameterExpression>());
Func<uint?> f1 = e1.Compile();
uint? f1Result = default(uint?);
Exception f1Ex = null;
try
{
f1Result = f1();
}
catch (Exception ex)
{
f1Ex = ex;
}
// verify with values passed to make parameters
Expression<Func<uint?, uint?, Func<uint?>>> e2 =
Expression.Lambda<Func<uint?, uint?, Func<uint?>>>(
Expression.Lambda<Func<uint?>>(
Expression.Add(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<uint?, uint?, Func<uint?>> f2 = e2.Compile();
uint? f2Result = default(uint?);
Exception f2Ex = null;
try
{
f2Result = f2(a, b)();
}
catch (Exception ex)
{
f2Ex = ex;
}
// verify with values directly passed
Expression<Func<Func<uint?, uint?, uint?>>> e3 =
Expression.Lambda<Func<Func<uint?, uint?, uint?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<uint?, uint?, uint?>>>(
Expression.Lambda<Func<uint?, uint?, uint?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<uint?, uint?, uint?> f3 = e3.Compile()();
uint? f3Result = default(uint?);
Exception f3Ex = null;
try
{
f3Result = f3(a, b);
}
catch (Exception ex)
{
f3Ex = ex;
}
// verify as a function generator
Expression<Func<Func<uint?, uint?, uint?>>> e4 =
Expression.Lambda<Func<Func<uint?, uint?, uint?>>>(
Expression.Lambda<Func<uint?, uint?, uint?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<uint?, uint?, uint?>> f4 = e4.Compile();
uint? f4Result = default(uint?);
Exception f4Ex = null;
try
{
f4Result = f4()(a, b);
}
catch (Exception ex)
{
f4Ex = ex;
}
// verify with currying
Expression<Func<uint?, Func<uint?, uint?>>> e5 =
Expression.Lambda<Func<uint?, Func<uint?, uint?>>>(
Expression.Lambda<Func<uint?, uint?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<uint?, Func<uint?, uint?>> f5 = e5.Compile();
uint? f5Result = default(uint?);
Exception f5Ex = null;
try
{
f5Result = f5(a)(b);
}
catch (Exception ex)
{
f5Ex = ex;
}
// verify with one parameter
Expression<Func<Func<uint?, uint?>>> e6 =
Expression.Lambda<Func<Func<uint?, uint?>>>(
Expression.Invoke(
Expression.Lambda<Func<uint?, Func<uint?, uint?>>>(
Expression.Lambda<Func<uint?, uint?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(uint?)) }),
Enumerable.Empty<ParameterExpression>());
Func<uint?, uint?> f6 = e6.Compile()();
uint? f6Result = default(uint?);
Exception f6Ex = null;
try
{
f6Result = f6(b);
}
catch (Exception ex)
{
f6Ex = ex;
}
// verify with regular IL
uint? csResult = default(uint?);
Exception csEx = null;
try
{
csResult = (uint?)(a + b);
}
catch (Exception ex)
{
csEx = ex;
}
// either all should have failed the same way or they should all produce the same result
if (f1Ex != null || f2Ex != null || f3Ex != null || f4Ex != null || f5Ex != null || f6Ex != null || csEx != null)
{
Assert.NotNull(f1Ex);
Assert.NotNull(f2Ex);
Assert.NotNull(f3Ex);
Assert.NotNull(f4Ex);
Assert.NotNull(f5Ex);
Assert.NotNull(f6Ex);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), f1Ex.GetType());
Assert.Equal(csEx.GetType(), f2Ex.GetType());
Assert.Equal(csEx.GetType(), f3Ex.GetType());
Assert.Equal(csEx.GetType(), f4Ex.GetType());
Assert.Equal(csEx.GetType(), f5Ex.GetType());
Assert.Equal(csEx.GetType(), f6Ex.GetType());
}
else
{
Assert.Equal(csResult, f1Result);
Assert.Equal(csResult, f2Result);
Assert.Equal(csResult, f3Result);
Assert.Equal(csResult, f4Result);
Assert.Equal(csResult, f5Result);
Assert.Equal(csResult, f6Result);
}
}
#endregion
#region Verify ulong?
private static void VerifyAddNullableULong(ulong? a, ulong? b)
{
ParameterExpression p0 = Expression.Parameter(typeof(ulong?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(ulong?), "p1");
// verify with parameters supplied
Expression<Func<ulong?>> e1 =
Expression.Lambda<Func<ulong?>>(
Expression.Invoke(
Expression.Lambda<Func<ulong?, ulong?, ulong?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(ulong?))
}),
Enumerable.Empty<ParameterExpression>());
Func<ulong?> f1 = e1.Compile();
ulong? f1Result = default(ulong?);
Exception f1Ex = null;
try
{
f1Result = f1();
}
catch (Exception ex)
{
f1Ex = ex;
}
// verify with values passed to make parameters
Expression<Func<ulong?, ulong?, Func<ulong?>>> e2 =
Expression.Lambda<Func<ulong?, ulong?, Func<ulong?>>>(
Expression.Lambda<Func<ulong?>>(
Expression.Add(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<ulong?, ulong?, Func<ulong?>> f2 = e2.Compile();
ulong? f2Result = default(ulong?);
Exception f2Ex = null;
try
{
f2Result = f2(a, b)();
}
catch (Exception ex)
{
f2Ex = ex;
}
// verify with values directly passed
Expression<Func<Func<ulong?, ulong?, ulong?>>> e3 =
Expression.Lambda<Func<Func<ulong?, ulong?, ulong?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<ulong?, ulong?, ulong?>>>(
Expression.Lambda<Func<ulong?, ulong?, ulong?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<ulong?, ulong?, ulong?> f3 = e3.Compile()();
ulong? f3Result = default(ulong?);
Exception f3Ex = null;
try
{
f3Result = f3(a, b);
}
catch (Exception ex)
{
f3Ex = ex;
}
// verify as a function generator
Expression<Func<Func<ulong?, ulong?, ulong?>>> e4 =
Expression.Lambda<Func<Func<ulong?, ulong?, ulong?>>>(
Expression.Lambda<Func<ulong?, ulong?, ulong?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<ulong?, ulong?, ulong?>> f4 = e4.Compile();
ulong? f4Result = default(ulong?);
Exception f4Ex = null;
try
{
f4Result = f4()(a, b);
}
catch (Exception ex)
{
f4Ex = ex;
}
// verify with currying
Expression<Func<ulong?, Func<ulong?, ulong?>>> e5 =
Expression.Lambda<Func<ulong?, Func<ulong?, ulong?>>>(
Expression.Lambda<Func<ulong?, ulong?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<ulong?, Func<ulong?, ulong?>> f5 = e5.Compile();
ulong? f5Result = default(ulong?);
Exception f5Ex = null;
try
{
f5Result = f5(a)(b);
}
catch (Exception ex)
{
f5Ex = ex;
}
// verify with one parameter
Expression<Func<Func<ulong?, ulong?>>> e6 =
Expression.Lambda<Func<Func<ulong?, ulong?>>>(
Expression.Invoke(
Expression.Lambda<Func<ulong?, Func<ulong?, ulong?>>>(
Expression.Lambda<Func<ulong?, ulong?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(ulong?)) }),
Enumerable.Empty<ParameterExpression>());
Func<ulong?, ulong?> f6 = e6.Compile()();
ulong? f6Result = default(ulong?);
Exception f6Ex = null;
try
{
f6Result = f6(b);
}
catch (Exception ex)
{
f6Ex = ex;
}
// verify with regular IL
ulong? csResult = default(ulong?);
Exception csEx = null;
try
{
csResult = (ulong?)(a + b);
}
catch (Exception ex)
{
csEx = ex;
}
// either all should have failed the same way or they should all produce the same result
if (f1Ex != null || f2Ex != null || f3Ex != null || f4Ex != null || f5Ex != null || f6Ex != null || csEx != null)
{
Assert.NotNull(f1Ex);
Assert.NotNull(f2Ex);
Assert.NotNull(f3Ex);
Assert.NotNull(f4Ex);
Assert.NotNull(f5Ex);
Assert.NotNull(f6Ex);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), f1Ex.GetType());
Assert.Equal(csEx.GetType(), f2Ex.GetType());
Assert.Equal(csEx.GetType(), f3Ex.GetType());
Assert.Equal(csEx.GetType(), f4Ex.GetType());
Assert.Equal(csEx.GetType(), f5Ex.GetType());
Assert.Equal(csEx.GetType(), f6Ex.GetType());
}
else
{
Assert.Equal(csResult, f1Result);
Assert.Equal(csResult, f2Result);
Assert.Equal(csResult, f3Result);
Assert.Equal(csResult, f4Result);
Assert.Equal(csResult, f5Result);
Assert.Equal(csResult, f6Result);
}
}
#endregion
#region Verify ushort?
private static void VerifyAddNullableUShort(ushort? a, ushort? b)
{
ParameterExpression p0 = Expression.Parameter(typeof(ushort?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(ushort?), "p1");
// verify with parameters supplied
Expression<Func<ushort?>> e1 =
Expression.Lambda<Func<ushort?>>(
Expression.Invoke(
Expression.Lambda<Func<ushort?, ushort?, ushort?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(ushort?))
}),
Enumerable.Empty<ParameterExpression>());
Func<ushort?> f1 = e1.Compile();
ushort? f1Result = default(ushort?);
Exception f1Ex = null;
try
{
f1Result = f1();
}
catch (Exception ex)
{
f1Ex = ex;
}
// verify with values passed to make parameters
Expression<Func<ushort?, ushort?, Func<ushort?>>> e2 =
Expression.Lambda<Func<ushort?, ushort?, Func<ushort?>>>(
Expression.Lambda<Func<ushort?>>(
Expression.Add(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<ushort?, ushort?, Func<ushort?>> f2 = e2.Compile();
ushort? f2Result = default(ushort?);
Exception f2Ex = null;
try
{
f2Result = f2(a, b)();
}
catch (Exception ex)
{
f2Ex = ex;
}
// verify with values directly passed
Expression<Func<Func<ushort?, ushort?, ushort?>>> e3 =
Expression.Lambda<Func<Func<ushort?, ushort?, ushort?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<ushort?, ushort?, ushort?>>>(
Expression.Lambda<Func<ushort?, ushort?, ushort?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<ushort?, ushort?, ushort?> f3 = e3.Compile()();
ushort? f3Result = default(ushort?);
Exception f3Ex = null;
try
{
f3Result = f3(a, b);
}
catch (Exception ex)
{
f3Ex = ex;
}
// verify as a function generator
Expression<Func<Func<ushort?, ushort?, ushort?>>> e4 =
Expression.Lambda<Func<Func<ushort?, ushort?, ushort?>>>(
Expression.Lambda<Func<ushort?, ushort?, ushort?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<ushort?, ushort?, ushort?>> f4 = e4.Compile();
ushort? f4Result = default(ushort?);
Exception f4Ex = null;
try
{
f4Result = f4()(a, b);
}
catch (Exception ex)
{
f4Ex = ex;
}
// verify with currying
Expression<Func<ushort?, Func<ushort?, ushort?>>> e5 =
Expression.Lambda<Func<ushort?, Func<ushort?, ushort?>>>(
Expression.Lambda<Func<ushort?, ushort?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<ushort?, Func<ushort?, ushort?>> f5 = e5.Compile();
ushort? f5Result = default(ushort?);
Exception f5Ex = null;
try
{
f5Result = f5(a)(b);
}
catch (Exception ex)
{
f5Ex = ex;
}
// verify with one parameter
Expression<Func<Func<ushort?, ushort?>>> e6 =
Expression.Lambda<Func<Func<ushort?, ushort?>>>(
Expression.Invoke(
Expression.Lambda<Func<ushort?, Func<ushort?, ushort?>>>(
Expression.Lambda<Func<ushort?, ushort?>>(
Expression.Add(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(ushort?)) }),
Enumerable.Empty<ParameterExpression>());
Func<ushort?, ushort?> f6 = e6.Compile()();
ushort? f6Result = default(ushort?);
Exception f6Ex = null;
try
{
f6Result = f6(b);
}
catch (Exception ex)
{
f6Ex = ex;
}
// verify with regular IL
ushort? csResult = default(ushort?);
Exception csEx = null;
try
{
csResult = (ushort?)(a + b);
}
catch (Exception ex)
{
csEx = ex;
}
// either all should have failed the same way or they should all produce the same result
if (f1Ex != null || f2Ex != null || f3Ex != null || f4Ex != null || f5Ex != null || f6Ex != null || csEx != null)
{
Assert.NotNull(f1Ex);
Assert.NotNull(f2Ex);
Assert.NotNull(f3Ex);
Assert.NotNull(f4Ex);
Assert.NotNull(f5Ex);
Assert.NotNull(f6Ex);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), f1Ex.GetType());
Assert.Equal(csEx.GetType(), f2Ex.GetType());
Assert.Equal(csEx.GetType(), f3Ex.GetType());
Assert.Equal(csEx.GetType(), f4Ex.GetType());
Assert.Equal(csEx.GetType(), f5Ex.GetType());
Assert.Equal(csEx.GetType(), f6Ex.GetType());
}
else
{
Assert.Equal(csResult, f1Result);
Assert.Equal(csResult, f2Result);
Assert.Equal(csResult, f3Result);
Assert.Equal(csResult, f4Result);
Assert.Equal(csResult, f5Result);
Assert.Equal(csResult, f6Result);
}
}
#endregion
#endregion
}
}
| |
#region license
// Copyright (c) 2003, 2004, 2005 Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * 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 Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using Boo.Lang.Compiler.TypeSystem.Core;
using Boo.Lang.Compiler.TypeSystem.Internal;
using Boo.Lang.Compiler.TypeSystem.Services;
using Boo.Lang.Compiler.Util;
using Boo.Lang.Environments;
namespace Boo.Lang.Compiler.TypeSystem.Generics
{
/// <summary>
/// A type constructed by supplying type parameters to a generic type, involving internal types.
/// </summary>
/// <remarks>
/// Constructed types constructed from an external generic type with external type arguments
/// are themselves external, and are represented as ExternalType instances. All other cases
/// are represented by this type.
/// </remarks>
public class GenericConstructedType : IType, IConstructedTypeInfo
{
protected readonly IType _definition;
IType[] _arguments;
GenericMapping _genericMapping;
bool _fullyConstructed;
string _fullName = null;
public GenericConstructedType(IType definition, IType[] arguments)
{
_definition = definition;
_arguments = arguments;
_genericMapping = new InternalGenericMapping(this, arguments);
_fullyConstructed = IsFullyConstructed();
}
protected bool IsFullyConstructed()
{
return GenericsServices.GetTypeGenerity(this) == 0;
}
protected string BuildFullName()
{
return _definition.FullName;
}
protected GenericMapping GenericMapping
{
get { return _genericMapping; }
}
public IEntity DeclaringEntity
{
get { return _definition.DeclaringEntity; }
}
public bool IsClass
{
get { return _definition.IsClass; }
}
public bool IsAbstract
{
get { return _definition.IsAbstract; }
}
public bool IsInterface
{
get { return _definition.IsInterface; }
}
public bool IsEnum
{
get { return _definition.IsEnum; }
}
public bool IsByRef
{
get { return _definition.IsByRef; }
}
public bool IsValueType
{
get { return _definition.IsValueType; }
}
public bool IsFinal
{
get { return _definition.IsFinal; }
}
public bool IsArray
{
get { return _definition.IsArray; }
}
public bool IsPointer
{
get { return _definition.IsPointer; }
}
public int GetTypeDepth()
{
return _definition.GetTypeDepth();
}
public IType ElementType
{
get { return GenericMapping.MapType(_definition.ElementType); }
}
public IType BaseType
{
get { return GenericMapping.MapType(_definition.BaseType); }
}
public IEntity GetDefaultMember()
{
IEntity definitionDefaultMember = _definition.GetDefaultMember();
if (definitionDefaultMember != null) return GenericMapping.Map(definitionDefaultMember);
return null;
}
public IType[] GetInterfaces()
{
return Array.ConvertAll<IType, IType>(
_definition.GetInterfaces(),
GenericMapping.MapType);
}
public bool IsSubclassOf(IType other)
{
if (null == other)
return false;
if (BaseType != null && (BaseType == other || BaseType.IsSubclassOf(other)))
{
return true;
}
if (other.IsInterface && Array.Exists(
GetInterfaces(),
i => TypeCompatibilityRules.IsAssignableFrom(other, i)))
{
return true;
}
if (null != other.ConstructedInfo
&& ConstructedInfo.GenericDefinition == other.ConstructedInfo.GenericDefinition)
{
for (int i = 0; i < ConstructedInfo.GenericArguments.Length; ++i)
{
if (!ConstructedInfo.GenericArguments[i].IsSubclassOf(other.ConstructedInfo.GenericArguments[i]))
return false;
}
return true;
}
return false;
}
public virtual bool IsAssignableFrom(IType other)
{
if (other == null)
return false;
if (other == this || other.IsSubclassOf(this) || (other.IsNull() && !IsValueType))
return true;
return false;
}
public IGenericTypeInfo GenericInfo
{
get { return _definition.GenericInfo; }
}
public IConstructedTypeInfo ConstructedInfo
{
get { return this; }
}
public IType Type
{
get { return this; }
}
public INamespace ParentNamespace
{
get
{
return GenericMapping.Map(_definition.ParentNamespace as IEntity) as INamespace;
}
}
public bool Resolve(ICollection<IEntity> resultingSet, string name, EntityType typesToConsider)
{
Set<IEntity> definitionMatches = new Set<IEntity>();
if (!_definition.Resolve(definitionMatches, name, typesToConsider))
return false;
foreach (IEntity match in definitionMatches)
resultingSet.Add(GenericMapping.Map(match));
return true;
}
public IEnumerable<IEntity> GetMembers()
{
return _definition.GetMembers().Select<IEntity, IEntity>(GenericMapping.Map);
}
public string Name
{
get { return _definition.Name; }
}
public string FullName
{
get { return _fullName ?? (_fullName = BuildFullName()); }
}
public EntityType EntityType
{
get { return EntityType.Type; }
}
IType[] IGenericArgumentsProvider.GenericArguments
{
get { return _arguments; }
}
IType IConstructedTypeInfo.GenericDefinition
{
get { return _definition; }
}
bool IConstructedTypeInfo.FullyConstructed
{
get { return _fullyConstructed; }
}
IType IConstructedTypeInfo.Map(IType type)
{
return GenericMapping.MapType(type);
}
IMember IConstructedTypeInfo.Map(IMember member)
{
return (IMember)GenericMapping.Map(member);
}
IMember IConstructedTypeInfo.UnMap(IMember mapped)
{
return GenericMapping.UnMap(mapped);
}
public bool IsDefined(IType attributeType)
{
return _definition.IsDefined(GenericMapping.MapType(attributeType));
}
public override string ToString()
{
return FullName;
}
private ArrayTypeCache _arrayTypes;
public IArrayType MakeArrayType(int rank)
{
if (null == _arrayTypes)
_arrayTypes = new ArrayTypeCache(this);
return _arrayTypes.MakeArrayType(rank);
}
public IType MakePointerType()
{
return null;
}
}
public class GenericConstructedCallableType : GenericConstructedType, ICallableType
{
CallableSignature _signature;
public GenericConstructedCallableType(ICallableType definition, IType[] arguments)
: base(definition, arguments)
{
}
public CallableSignature GetSignature()
{
if (_signature == null)
{
CallableSignature definitionSignature = ((ICallableType)_definition).GetSignature();
IParameter[] parameters = GenericMapping.MapParameters(definitionSignature.Parameters);
IType returnType = GenericMapping.MapType(definitionSignature.ReturnType);
_signature = new CallableSignature(parameters, returnType);
}
return _signature;
}
public bool IsAnonymous
{
get { return false; }
}
override public bool IsAssignableFrom(IType other)
{
return My<TypeSystemServices>.Instance.IsCallableTypeAssignableFrom(this, other);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Umbraco.Cms.Core.Hosting;
using Umbraco.Extensions;
namespace Umbraco.Cms.Core.Runtime
{
/// <summary>
/// Provides the full implementation of <see cref="IMainDom"/>.
/// </summary>
/// <remarks>
/// <para>When an AppDomain starts, it tries to acquire the main domain status.</para>
/// <para>When an AppDomain stops (eg the application is restarting) it should release the main domain status.</para>
/// </remarks>
public class MainDom : IMainDom, IRegisteredObject, IDisposable
{
#region Vars
private readonly ILogger<MainDom> _logger;
private IApplicationShutdownRegistry _hostingEnvironment;
private readonly IMainDomLock _mainDomLock;
// our own lock for local consistency
private object _locko = new object();
private bool _isInitialized;
// indicates whether...
private bool? _isMainDom; // we are the main domain
private volatile bool _signaled; // we have been signaled
// actions to run before releasing the main domain
private readonly List<KeyValuePair<int, Action>> _callbacks = new List<KeyValuePair<int, Action>>();
private const int LockTimeoutMilliseconds = 40000; // 40 seconds
private Task _listenTask;
private Task _listenCompleteTask;
#endregion
#region Ctor
// initializes a new instance of MainDom
public MainDom(ILogger<MainDom> logger, IMainDomLock systemLock)
{
_logger = logger;
_mainDomLock = systemLock;
}
#endregion
/// <inheritdoc/>
public bool Acquire(IApplicationShutdownRegistry hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment ?? throw new ArgumentNullException(nameof(hostingEnvironment));
return LazyInitializer.EnsureInitialized(ref _isMainDom, ref _isInitialized, ref _locko, () =>
{
hostingEnvironment.RegisterObject(this);
return Acquire();
}).Value;
}
/// <summary>
/// Registers a resource that requires the current AppDomain to be the main domain to function.
/// </summary>
/// <param name="install">An action to execute when registering.</param>
/// <param name="release">An action to execute before the AppDomain releases the main domain status.</param>
/// <param name="weight">An optional weight (lower goes first).</param>
/// <returns>A value indicating whether it was possible to register.</returns>
/// <remarks>If registering is successful, then the <paramref name="install"/> action
/// is guaranteed to execute before the AppDomain releases the main domain status.</remarks>
public bool Register(Action install = null, Action release = null, int weight = 100)
{
lock (_locko)
{
if (_signaled)
{
return false;
}
if (_isMainDom.HasValue == false)
{
throw new InvalidOperationException("Register called when MainDom has not been acquired");
}
else if (_isMainDom == false)
{
_logger.LogWarning("Register called when MainDom has not been acquired");
return false;
}
install?.Invoke();
if (release != null)
{
_callbacks.Add(new KeyValuePair<int, Action>(weight, release));
}
return true;
}
}
// handles the signal requesting that the main domain is released
private void OnSignal(string source)
{
// once signaled, we stop waiting, but then there is the hosting environment
// so we have to make sure that we only enter that method once
lock (_locko)
{
_logger.LogDebug("Signaled ({Signaled}) ({SignalSource})", _signaled ? "again" : "first", source);
if (_signaled) return;
if (_isMainDom == false) return; // probably not needed
_signaled = true;
try
{
_logger.LogInformation("Stopping ({SignalSource})", source);
foreach (var callback in _callbacks.OrderBy(x => x.Key).Select(x => x.Value))
{
try
{
callback(); // no timeout on callbacks
}
catch (Exception e)
{
_logger.LogError(e, "Error while running callback");
continue;
}
}
_logger.LogDebug("Stopped ({SignalSource})", source);
}
finally
{
// in any case...
_isMainDom = false;
_mainDomLock.Dispose();
_logger.LogInformation("Released ({SignalSource})", source);
}
}
}
// acquires the main domain
private bool Acquire()
{
// if signaled, too late to acquire, give up
// the handler is not installed so that would be the hosting environment
if (_signaled)
{
_logger.LogInformation("Cannot acquire (signaled).");
return false;
}
_logger.LogInformation("Acquiring.");
// Get the lock
var acquired = false;
try
{
acquired = _mainDomLock.AcquireLockAsync(LockTimeoutMilliseconds).GetAwaiter().GetResult();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error while acquiring");
}
if (!acquired)
{
_logger.LogInformation("Cannot acquire (timeout).");
// In previous versions we'd let a TimeoutException be thrown
// and the appdomain would not start. We have the opportunity to allow it to
// start without having MainDom? This would mean that it couldn't write
// to nucache/examine and would only be ok if this was a super short lived appdomain.
// maybe safer to just keep throwing in this case.
throw new TimeoutException("Cannot acquire MainDom");
// return false;
}
try
{
// Listen for the signal from another AppDomain coming online to release the lock
_listenTask = _mainDomLock.ListenAsync();
_listenCompleteTask = _listenTask.ContinueWith(t =>
{
if (_listenTask.Exception != null)
{
_logger.LogWarning("Listening task completed with {TaskStatus}, Exception: {Exception}", _listenTask.Status, _listenTask.Exception);
}
else
{
_logger.LogDebug("Listening task completed with {TaskStatus}", _listenTask.Status);
}
OnSignal("signal");
}, TaskScheduler.Default); // Must explicitly specify this, see https://blog.stephencleary.com/2013/10/continuewith-is-dangerous-too.html
}
catch (OperationCanceledException ex)
{
// the waiting task could be canceled if this appdomain is naturally shutting down, we'll just swallow this exception
_logger.LogWarning(ex, ex.Message);
}
_logger.LogInformation("Acquired.");
return true;
}
/// <summary>
/// Gets a value indicating whether the current domain is the main domain.
/// </summary>
/// <remarks>
/// Acquire must be called first else this will always return false
/// </remarks>
public bool IsMainDom
{
get
{
if (!_isMainDom.HasValue)
{
throw new InvalidOperationException("MainDom has not been acquired yet");
}
return _isMainDom.Value;
}
}
// IRegisteredObject
void IRegisteredObject.Stop(bool immediate)
{
OnSignal("environment"); // will run once
// The web app is stopping, need to wind down
Dispose(true);
_hostingEnvironment?.UnregisterObject(this);
}
#region IDisposable Support
// This code added to correctly implement the disposable pattern.
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
_mainDomLock.Dispose();
}
disposedValue = true;
}
}
public void Dispose()
{
Dispose(true);
}
#endregion
public static string GetMainDomId(IHostingEnvironment hostingEnvironment)
{
// HostingEnvironment.ApplicationID is null in unit tests, making ReplaceNonAlphanumericChars fail
var appId = hostingEnvironment.ApplicationId?.ReplaceNonAlphanumericChars(string.Empty) ?? string.Empty;
// combining with the physical path because if running on eg IIS Express,
// two sites could have the same appId even though they are different.
//
// now what could still collide is... two sites, running in two different processes
// and having the same appId, and running on the same app physical path
//
// we *cannot* use the process ID here because when an AppPool restarts it is
// a new process for the same application path
var appPath = hostingEnvironment.ApplicationPhysicalPath?.ToLowerInvariant() ?? string.Empty;
var hash = (appId + ":::" + appPath).GenerateHash<SHA1>();
return hash;
}
}
}
| |
namespace ExpandingPages
{
partial class Form1
{
/// <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();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.newToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator = new System.Windows.Forms.ToolStripSeparator();
this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveAsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.printToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.printPreviewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.undoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.redoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.cutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pasteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.selectAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.customizeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.optionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.contentsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.indexToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.searchToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator();
this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStrip1 = new System.Windows.Forms.ToolStrip();
this.newToolStripButton = new System.Windows.Forms.ToolStripButton();
this.openToolStripButton = new System.Windows.Forms.ToolStripButton();
this.saveToolStripButton = new System.Windows.Forms.ToolStripButton();
this.printToolStripButton = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator();
this.cutToolStripButton = new System.Windows.Forms.ToolStripButton();
this.copyToolStripButton = new System.Windows.Forms.ToolStripButton();
this.pasteToolStripButton = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator();
this.helpToolStripButton = new System.Windows.Forms.ToolStripButton();
this.toolStripContainer1 = new System.Windows.Forms.ToolStripContainer();
this.kryptonPanel1 = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.pageButtons = new ComponentFactory.Krypton.Toolkit.KryptonGroup();
this.richTextBox2 = new ComponentFactory.Krypton.Toolkit.KryptonRichTextBox();
this.kryptonPanel3 = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.navigatorTop = new ComponentFactory.Krypton.Navigator.KryptonNavigator();
this.buttonTopArrow = new ComponentFactory.Krypton.Navigator.ButtonSpecNavigator();
this.pageEntryForm = new ComponentFactory.Krypton.Navigator.KryptonPage();
this.textBox3 = new ComponentFactory.Krypton.Toolkit.KryptonTextBox();
this.textBox4 = new ComponentFactory.Krypton.Toolkit.KryptonTextBox();
this.kryptonLabel3 = new ComponentFactory.Krypton.Toolkit.KryptonLabel();
this.kryptonLabel4 = new ComponentFactory.Krypton.Toolkit.KryptonLabel();
this.textBox2 = new ComponentFactory.Krypton.Toolkit.KryptonTextBox();
this.textBox1 = new ComponentFactory.Krypton.Toolkit.KryptonTextBox();
this.kryptonLabel2 = new ComponentFactory.Krypton.Toolkit.KryptonLabel();
this.kryptonLabel1 = new ComponentFactory.Krypton.Toolkit.KryptonLabel();
this.kryptonPage4 = new ComponentFactory.Krypton.Navigator.KryptonPage();
this.button7 = new System.Windows.Forms.Button();
this.button8 = new System.Windows.Forms.Button();
this.button5 = new System.Windows.Forms.Button();
this.button6 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.button4 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button1 = new System.Windows.Forms.Button();
this.pageProgressBars = new ComponentFactory.Krypton.Navigator.KryptonPage();
this.progressBar5 = new System.Windows.Forms.ProgressBar();
this.progressBar6 = new System.Windows.Forms.ProgressBar();
this.progressBar3 = new System.Windows.Forms.ProgressBar();
this.progressBar4 = new System.Windows.Forms.ProgressBar();
this.progressBar2 = new System.Windows.Forms.ProgressBar();
this.progressBar1 = new System.Windows.Forms.ProgressBar();
this.pageColors = new ComponentFactory.Krypton.Navigator.KryptonPage();
this.panel5 = new System.Windows.Forms.Panel();
this.panel3 = new System.Windows.Forms.Panel();
this.panel6 = new System.Windows.Forms.Panel();
this.panel2 = new System.Windows.Forms.Panel();
this.panel4 = new System.Windows.Forms.Panel();
this.panel1 = new System.Windows.Forms.Panel();
this.kryptonPanel2 = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.navigatorLeft = new ComponentFactory.Krypton.Navigator.KryptonNavigator();
this.buttonLeft = new ComponentFactory.Krypton.Navigator.ButtonSpecNavigator();
this.pageRichTextBox = new ComponentFactory.Krypton.Navigator.KryptonPage();
this.richTextBox1 = new ComponentFactory.Krypton.Toolkit.KryptonRichTextBox();
this.pageListBox = new ComponentFactory.Krypton.Navigator.KryptonPage();
this.kryptonCheckButton6 = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton();
this.kryptonCheckButton5 = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton();
this.kryptonCheckButton4 = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton();
this.kryptonCheckButton3 = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton();
this.kryptonCheckButton2 = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton();
this.kryptonCheckButton1 = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton();
this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.kryptonManager1 = new ComponentFactory.Krypton.Toolkit.KryptonManager(this.components);
this.kryptonPalettes = new ComponentFactory.Krypton.Toolkit.KryptonCheckSet(this.components);
this.kryptonCheckButton7 = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton();
this.kryptonCheckButton8 = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton();
this.kryptonCheckButton9 = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton();
this.menuStrip1.SuspendLayout();
this.toolStrip1.SuspendLayout();
this.toolStripContainer1.ContentPanel.SuspendLayout();
this.toolStripContainer1.TopToolStripPanel.SuspendLayout();
this.toolStripContainer1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonPanel1)).BeginInit();
this.kryptonPanel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pageButtons)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pageButtons.Panel)).BeginInit();
this.pageButtons.Panel.SuspendLayout();
this.pageButtons.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonPanel3)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.navigatorTop)).BeginInit();
this.navigatorTop.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pageEntryForm)).BeginInit();
this.pageEntryForm.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonPage4)).BeginInit();
this.kryptonPage4.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pageProgressBars)).BeginInit();
this.pageProgressBars.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pageColors)).BeginInit();
this.pageColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonPanel2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.navigatorLeft)).BeginInit();
this.navigatorLeft.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pageRichTextBox)).BeginInit();
this.pageRichTextBox.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pageListBox)).BeginInit();
this.pageListBox.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonPalettes)).BeginInit();
this.SuspendLayout();
//
// menuStrip1
//
this.menuStrip1.Dock = System.Windows.Forms.DockStyle.None;
this.menuStrip1.Font = new System.Drawing.Font("Segoe UI", 9F);
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.editToolStripMenuItem,
this.toolsToolStripMenuItem,
this.helpToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(606, 24);
this.menuStrip1.TabIndex = 0;
this.menuStrip1.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.newToolStripMenuItem,
this.openToolStripMenuItem,
this.toolStripSeparator,
this.saveToolStripMenuItem,
this.saveAsToolStripMenuItem,
this.toolStripSeparator1,
this.printToolStripMenuItem,
this.printPreviewToolStripMenuItem,
this.toolStripSeparator2,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
this.fileToolStripMenuItem.Text = "&File";
//
// newToolStripMenuItem
//
this.newToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("newToolStripMenuItem.Image")));
this.newToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.newToolStripMenuItem.Name = "newToolStripMenuItem";
this.newToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N)));
this.newToolStripMenuItem.Size = new System.Drawing.Size(146, 22);
this.newToolStripMenuItem.Text = "&New";
//
// openToolStripMenuItem
//
this.openToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("openToolStripMenuItem.Image")));
this.openToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.openToolStripMenuItem.Name = "openToolStripMenuItem";
this.openToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O)));
this.openToolStripMenuItem.Size = new System.Drawing.Size(146, 22);
this.openToolStripMenuItem.Text = "&Open";
//
// toolStripSeparator
//
this.toolStripSeparator.Name = "toolStripSeparator";
this.toolStripSeparator.Size = new System.Drawing.Size(143, 6);
//
// saveToolStripMenuItem
//
this.saveToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("saveToolStripMenuItem.Image")));
this.saveToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.saveToolStripMenuItem.Name = "saveToolStripMenuItem";
this.saveToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S)));
this.saveToolStripMenuItem.Size = new System.Drawing.Size(146, 22);
this.saveToolStripMenuItem.Text = "&Save";
//
// saveAsToolStripMenuItem
//
this.saveAsToolStripMenuItem.Name = "saveAsToolStripMenuItem";
this.saveAsToolStripMenuItem.Size = new System.Drawing.Size(146, 22);
this.saveAsToolStripMenuItem.Text = "Save &As";
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(143, 6);
//
// printToolStripMenuItem
//
this.printToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("printToolStripMenuItem.Image")));
this.printToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.printToolStripMenuItem.Name = "printToolStripMenuItem";
this.printToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.P)));
this.printToolStripMenuItem.Size = new System.Drawing.Size(146, 22);
this.printToolStripMenuItem.Text = "&Print";
//
// printPreviewToolStripMenuItem
//
this.printPreviewToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("printPreviewToolStripMenuItem.Image")));
this.printPreviewToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.printPreviewToolStripMenuItem.Name = "printPreviewToolStripMenuItem";
this.printPreviewToolStripMenuItem.Size = new System.Drawing.Size(146, 22);
this.printPreviewToolStripMenuItem.Text = "Print Pre&view";
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size(143, 6);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(146, 22);
this.exitToolStripMenuItem.Text = "E&xit";
//
// editToolStripMenuItem
//
this.editToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.undoToolStripMenuItem,
this.redoToolStripMenuItem,
this.toolStripSeparator3,
this.cutToolStripMenuItem,
this.copyToolStripMenuItem,
this.pasteToolStripMenuItem,
this.toolStripSeparator4,
this.selectAllToolStripMenuItem});
this.editToolStripMenuItem.Name = "editToolStripMenuItem";
this.editToolStripMenuItem.Size = new System.Drawing.Size(39, 20);
this.editToolStripMenuItem.Text = "&Edit";
//
// undoToolStripMenuItem
//
this.undoToolStripMenuItem.Name = "undoToolStripMenuItem";
this.undoToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Z)));
this.undoToolStripMenuItem.Size = new System.Drawing.Size(144, 22);
this.undoToolStripMenuItem.Text = "&Undo";
//
// redoToolStripMenuItem
//
this.redoToolStripMenuItem.Name = "redoToolStripMenuItem";
this.redoToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Y)));
this.redoToolStripMenuItem.Size = new System.Drawing.Size(144, 22);
this.redoToolStripMenuItem.Text = "&Redo";
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
this.toolStripSeparator3.Size = new System.Drawing.Size(141, 6);
//
// cutToolStripMenuItem
//
this.cutToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("cutToolStripMenuItem.Image")));
this.cutToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.cutToolStripMenuItem.Name = "cutToolStripMenuItem";
this.cutToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.X)));
this.cutToolStripMenuItem.Size = new System.Drawing.Size(144, 22);
this.cutToolStripMenuItem.Text = "Cu&t";
//
// copyToolStripMenuItem
//
this.copyToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("copyToolStripMenuItem.Image")));
this.copyToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.copyToolStripMenuItem.Name = "copyToolStripMenuItem";
this.copyToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.C)));
this.copyToolStripMenuItem.Size = new System.Drawing.Size(144, 22);
this.copyToolStripMenuItem.Text = "&Copy";
//
// pasteToolStripMenuItem
//
this.pasteToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("pasteToolStripMenuItem.Image")));
this.pasteToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.pasteToolStripMenuItem.Name = "pasteToolStripMenuItem";
this.pasteToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.V)));
this.pasteToolStripMenuItem.Size = new System.Drawing.Size(144, 22);
this.pasteToolStripMenuItem.Text = "&Paste";
//
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
this.toolStripSeparator4.Size = new System.Drawing.Size(141, 6);
//
// selectAllToolStripMenuItem
//
this.selectAllToolStripMenuItem.Name = "selectAllToolStripMenuItem";
this.selectAllToolStripMenuItem.Size = new System.Drawing.Size(144, 22);
this.selectAllToolStripMenuItem.Text = "Select &All";
//
// toolsToolStripMenuItem
//
this.toolsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.customizeToolStripMenuItem,
this.optionsToolStripMenuItem});
this.toolsToolStripMenuItem.Name = "toolsToolStripMenuItem";
this.toolsToolStripMenuItem.Size = new System.Drawing.Size(48, 20);
this.toolsToolStripMenuItem.Text = "&Tools";
//
// customizeToolStripMenuItem
//
this.customizeToolStripMenuItem.Name = "customizeToolStripMenuItem";
this.customizeToolStripMenuItem.Size = new System.Drawing.Size(130, 22);
this.customizeToolStripMenuItem.Text = "&Customize";
//
// optionsToolStripMenuItem
//
this.optionsToolStripMenuItem.Name = "optionsToolStripMenuItem";
this.optionsToolStripMenuItem.Size = new System.Drawing.Size(130, 22);
this.optionsToolStripMenuItem.Text = "&Options";
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.contentsToolStripMenuItem,
this.indexToolStripMenuItem,
this.searchToolStripMenuItem,
this.toolStripSeparator5,
this.aboutToolStripMenuItem});
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
this.helpToolStripMenuItem.Size = new System.Drawing.Size(44, 20);
this.helpToolStripMenuItem.Text = "&Help";
//
// contentsToolStripMenuItem
//
this.contentsToolStripMenuItem.Name = "contentsToolStripMenuItem";
this.contentsToolStripMenuItem.Size = new System.Drawing.Size(122, 22);
this.contentsToolStripMenuItem.Text = "&Contents";
//
// indexToolStripMenuItem
//
this.indexToolStripMenuItem.Name = "indexToolStripMenuItem";
this.indexToolStripMenuItem.Size = new System.Drawing.Size(122, 22);
this.indexToolStripMenuItem.Text = "&Index";
//
// searchToolStripMenuItem
//
this.searchToolStripMenuItem.Name = "searchToolStripMenuItem";
this.searchToolStripMenuItem.Size = new System.Drawing.Size(122, 22);
this.searchToolStripMenuItem.Text = "&Search";
//
// toolStripSeparator5
//
this.toolStripSeparator5.Name = "toolStripSeparator5";
this.toolStripSeparator5.Size = new System.Drawing.Size(119, 6);
//
// aboutToolStripMenuItem
//
this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
this.aboutToolStripMenuItem.Size = new System.Drawing.Size(122, 22);
this.aboutToolStripMenuItem.Text = "&About...";
//
// toolStrip1
//
this.toolStrip1.Dock = System.Windows.Forms.DockStyle.None;
this.toolStrip1.Font = new System.Drawing.Font("Segoe UI", 9F);
this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.newToolStripButton,
this.openToolStripButton,
this.saveToolStripButton,
this.printToolStripButton,
this.toolStripSeparator6,
this.cutToolStripButton,
this.copyToolStripButton,
this.pasteToolStripButton,
this.toolStripSeparator7,
this.helpToolStripButton});
this.toolStrip1.Location = new System.Drawing.Point(3, 24);
this.toolStrip1.Name = "toolStrip1";
this.toolStrip1.Size = new System.Drawing.Size(208, 25);
this.toolStrip1.TabIndex = 1;
this.toolStrip1.Text = "toolStrip1";
//
// newToolStripButton
//
this.newToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.newToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("newToolStripButton.Image")));
this.newToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.newToolStripButton.Name = "newToolStripButton";
this.newToolStripButton.Size = new System.Drawing.Size(23, 22);
this.newToolStripButton.Text = "&New";
//
// openToolStripButton
//
this.openToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.openToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("openToolStripButton.Image")));
this.openToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.openToolStripButton.Name = "openToolStripButton";
this.openToolStripButton.Size = new System.Drawing.Size(23, 22);
this.openToolStripButton.Text = "&Open";
//
// saveToolStripButton
//
this.saveToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.saveToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("saveToolStripButton.Image")));
this.saveToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.saveToolStripButton.Name = "saveToolStripButton";
this.saveToolStripButton.Size = new System.Drawing.Size(23, 22);
this.saveToolStripButton.Text = "&Save";
//
// printToolStripButton
//
this.printToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.printToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("printToolStripButton.Image")));
this.printToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.printToolStripButton.Name = "printToolStripButton";
this.printToolStripButton.Size = new System.Drawing.Size(23, 22);
this.printToolStripButton.Text = "&Print";
//
// toolStripSeparator6
//
this.toolStripSeparator6.Name = "toolStripSeparator6";
this.toolStripSeparator6.Size = new System.Drawing.Size(6, 25);
//
// cutToolStripButton
//
this.cutToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.cutToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("cutToolStripButton.Image")));
this.cutToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.cutToolStripButton.Name = "cutToolStripButton";
this.cutToolStripButton.Size = new System.Drawing.Size(23, 22);
this.cutToolStripButton.Text = "C&ut";
//
// copyToolStripButton
//
this.copyToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.copyToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("copyToolStripButton.Image")));
this.copyToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.copyToolStripButton.Name = "copyToolStripButton";
this.copyToolStripButton.Size = new System.Drawing.Size(23, 22);
this.copyToolStripButton.Text = "&Copy";
//
// pasteToolStripButton
//
this.pasteToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.pasteToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("pasteToolStripButton.Image")));
this.pasteToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.pasteToolStripButton.Name = "pasteToolStripButton";
this.pasteToolStripButton.Size = new System.Drawing.Size(23, 22);
this.pasteToolStripButton.Text = "&Paste";
//
// toolStripSeparator7
//
this.toolStripSeparator7.Name = "toolStripSeparator7";
this.toolStripSeparator7.Size = new System.Drawing.Size(6, 25);
//
// helpToolStripButton
//
this.helpToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.helpToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("helpToolStripButton.Image")));
this.helpToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.helpToolStripButton.Name = "helpToolStripButton";
this.helpToolStripButton.Size = new System.Drawing.Size(23, 22);
this.helpToolStripButton.Text = "He&lp";
//
// toolStripContainer1
//
//
// toolStripContainer1.ContentPanel
//
this.toolStripContainer1.ContentPanel.Controls.Add(this.kryptonPanel1);
this.toolStripContainer1.ContentPanel.Size = new System.Drawing.Size(606, 403);
this.toolStripContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.toolStripContainer1.Location = new System.Drawing.Point(0, 0);
this.toolStripContainer1.Name = "toolStripContainer1";
this.toolStripContainer1.Size = new System.Drawing.Size(606, 452);
this.toolStripContainer1.TabIndex = 2;
this.toolStripContainer1.Text = "toolStripContainer1";
//
// toolStripContainer1.TopToolStripPanel
//
this.toolStripContainer1.TopToolStripPanel.Controls.Add(this.menuStrip1);
this.toolStripContainer1.TopToolStripPanel.Controls.Add(this.toolStrip1);
//
// kryptonPanel1
//
this.kryptonPanel1.Controls.Add(this.pageButtons);
this.kryptonPanel1.Controls.Add(this.kryptonPanel3);
this.kryptonPanel1.Controls.Add(this.navigatorTop);
this.kryptonPanel1.Controls.Add(this.kryptonPanel2);
this.kryptonPanel1.Controls.Add(this.navigatorLeft);
this.kryptonPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryptonPanel1.Location = new System.Drawing.Point(0, 0);
this.kryptonPanel1.Name = "kryptonPanel1";
this.kryptonPanel1.Padding = new System.Windows.Forms.Padding(5);
this.kryptonPanel1.Size = new System.Drawing.Size(606, 403);
this.kryptonPanel1.TabIndex = 0;
//
// pageButtons
//
this.pageButtons.Dock = System.Windows.Forms.DockStyle.Fill;
this.pageButtons.Location = new System.Drawing.Point(173, 128);
this.pageButtons.Name = "pageButtons";
//
// pageButtons.Panel
//
this.pageButtons.Panel.Controls.Add(this.richTextBox2);
this.pageButtons.Panel.Padding = new System.Windows.Forms.Padding(5);
this.pageButtons.Size = new System.Drawing.Size(428, 270);
this.pageButtons.TabIndex = 4;
//
// richTextBox2
//
this.richTextBox2.AutoSize = true;
this.richTextBox2.Dock = System.Windows.Forms.DockStyle.Fill;
this.richTextBox2.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.richTextBox2.Location = new System.Drawing.Point(5, 5);
this.richTextBox2.Name = "richTextBox2";
this.richTextBox2.Size = new System.Drawing.Size(416, 258);
this.richTextBox2.StateCommon.Border.Draw = ComponentFactory.Krypton.Toolkit.InheritBool.False;
this.richTextBox2.StateCommon.Border.DrawBorders = ((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders)((((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Top | ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Bottom)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Left)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Right)));
this.richTextBox2.TabIndex = 0;
this.richTextBox2.Text = resources.GetString("richTextBox2.Text");
//
// kryptonPanel3
//
this.kryptonPanel3.Dock = System.Windows.Forms.DockStyle.Top;
this.kryptonPanel3.Location = new System.Drawing.Point(173, 123);
this.kryptonPanel3.Name = "kryptonPanel3";
this.kryptonPanel3.Size = new System.Drawing.Size(428, 5);
this.kryptonPanel3.TabIndex = 3;
//
// navigatorTop
//
this.navigatorTop.AutoSize = true;
this.navigatorTop.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.navigatorTop.Button.ButtonDisplayLogic = ComponentFactory.Krypton.Navigator.ButtonDisplayLogic.None;
this.navigatorTop.Button.ButtonSpecs.AddRange(new ComponentFactory.Krypton.Navigator.ButtonSpecNavigator[] {
this.buttonTopArrow});
this.navigatorTop.Button.CloseButtonDisplay = ComponentFactory.Krypton.Navigator.ButtonDisplay.Hide;
this.navigatorTop.Dock = System.Windows.Forms.DockStyle.Top;
this.navigatorTop.Location = new System.Drawing.Point(173, 5);
this.navigatorTop.Name = "navigatorTop";
this.navigatorTop.NavigatorMode = ComponentFactory.Krypton.Navigator.NavigatorMode.HeaderBarCheckButtonGroup;
this.navigatorTop.Pages.AddRange(new ComponentFactory.Krypton.Navigator.KryptonPage[] {
this.pageEntryForm,
this.kryptonPage4,
this.pageProgressBars,
this.pageColors});
this.navigatorTop.PopupPages.AllowPopupPages = ComponentFactory.Krypton.Navigator.PopupPageAllow.OnlyCompatibleModes;
this.navigatorTop.PopupPages.Element = ComponentFactory.Krypton.Navigator.PopupPageElement.Navigator;
this.navigatorTop.PopupPages.Position = ComponentFactory.Krypton.Navigator.PopupPagePosition.BelowMatch;
this.navigatorTop.SelectedIndex = 0;
this.navigatorTop.Size = new System.Drawing.Size(428, 118);
this.navigatorTop.TabIndex = 2;
this.navigatorTop.Text = "kryptonNavigator2";
//
// buttonTopArrow
//
this.buttonTopArrow.Type = ComponentFactory.Krypton.Toolkit.PaletteButtonSpecStyle.ArrowUp;
this.buttonTopArrow.TypeRestricted = ComponentFactory.Krypton.Navigator.PaletteNavButtonSpecStyle.ArrowUp;
this.buttonTopArrow.UniqueName = "E1E00112A6104D0EE1E00112A6104D0E";
this.buttonTopArrow.Click += new System.EventHandler(this.buttonTopArrow_Click);
//
// pageEntryForm
//
this.pageEntryForm.AutoHiddenSlideSize = new System.Drawing.Size(200, 200);
this.pageEntryForm.Controls.Add(this.textBox3);
this.pageEntryForm.Controls.Add(this.textBox4);
this.pageEntryForm.Controls.Add(this.kryptonLabel3);
this.pageEntryForm.Controls.Add(this.kryptonLabel4);
this.pageEntryForm.Controls.Add(this.textBox2);
this.pageEntryForm.Controls.Add(this.textBox1);
this.pageEntryForm.Controls.Add(this.kryptonLabel2);
this.pageEntryForm.Controls.Add(this.kryptonLabel1);
this.pageEntryForm.Flags = 65534;
this.pageEntryForm.LastVisibleSet = true;
this.pageEntryForm.MinimumSize = new System.Drawing.Size(50, 85);
this.pageEntryForm.Name = "pageEntryForm";
this.pageEntryForm.Padding = new System.Windows.Forms.Padding(15);
this.pageEntryForm.Size = new System.Drawing.Size(426, 86);
this.pageEntryForm.Text = "Entry Form";
this.pageEntryForm.ToolTipTitle = "Page ToolTip";
this.pageEntryForm.UniqueName = "7F2D1092960E4B537F2D1092960E4B53";
//
// textBox3
//
this.textBox3.Location = new System.Drawing.Point(217, 39);
this.textBox3.Name = "textBox3";
this.textBox3.Size = new System.Drawing.Size(100, 20);
this.textBox3.TabIndex = 7;
this.textBox3.Text = "Dead";
//
// textBox4
//
this.textBox4.Location = new System.Drawing.Point(217, 15);
this.textBox4.Name = "textBox4";
this.textBox4.Size = new System.Drawing.Size(100, 20);
this.textBox4.TabIndex = 6;
this.textBox4.Text = "Prime Minister";
//
// kryptonLabel3
//
this.kryptonLabel3.Location = new System.Drawing.Point(170, 40);
this.kryptonLabel3.Name = "kryptonLabel3";
this.kryptonLabel3.Size = new System.Drawing.Size(42, 19);
this.kryptonLabel3.TabIndex = 5;
this.kryptonLabel3.Values.Text = "Status";
//
// kryptonLabel4
//
this.kryptonLabel4.Location = new System.Drawing.Point(161, 15);
this.kryptonLabel4.Name = "kryptonLabel4";
this.kryptonLabel4.Size = new System.Drawing.Size(52, 19);
this.kryptonLabel4.TabIndex = 4;
this.kryptonLabel4.Values.Text = "Position";
//
// textBox2
//
this.textBox2.Location = new System.Drawing.Point(53, 39);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(100, 20);
this.textBox2.TabIndex = 3;
this.textBox2.Text = "Chruchill";
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(53, 15);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(100, 20);
this.textBox1.TabIndex = 2;
this.textBox1.Text = "Winston";
//
// kryptonLabel2
//
this.kryptonLabel2.Location = new System.Drawing.Point(18, 40);
this.kryptonLabel2.Name = "kryptonLabel2";
this.kryptonLabel2.Size = new System.Drawing.Size(31, 19);
this.kryptonLabel2.TabIndex = 1;
this.kryptonLabel2.Values.Text = "Last";
//
// kryptonLabel1
//
this.kryptonLabel1.Location = new System.Drawing.Point(17, 15);
this.kryptonLabel1.Name = "kryptonLabel1";
this.kryptonLabel1.Size = new System.Drawing.Size(32, 19);
this.kryptonLabel1.TabIndex = 0;
this.kryptonLabel1.Values.Text = "First";
//
// kryptonPage4
//
this.kryptonPage4.AutoHiddenSlideSize = new System.Drawing.Size(200, 200);
this.kryptonPage4.Controls.Add(this.button7);
this.kryptonPage4.Controls.Add(this.button8);
this.kryptonPage4.Controls.Add(this.button5);
this.kryptonPage4.Controls.Add(this.button6);
this.kryptonPage4.Controls.Add(this.button3);
this.kryptonPage4.Controls.Add(this.button4);
this.kryptonPage4.Controls.Add(this.button2);
this.kryptonPage4.Controls.Add(this.button1);
this.kryptonPage4.Flags = 65534;
this.kryptonPage4.LastVisibleSet = true;
this.kryptonPage4.MinimumSize = new System.Drawing.Size(50, 85);
this.kryptonPage4.Name = "kryptonPage4";
this.kryptonPage4.Padding = new System.Windows.Forms.Padding(15);
this.kryptonPage4.Size = new System.Drawing.Size(364, 86);
this.kryptonPage4.Text = "Buttons";
this.kryptonPage4.ToolTipTitle = "Page ToolTip";
this.kryptonPage4.UniqueName = "DD2472F0D7BA4602DD2472F0D7BA4602";
//
// button7
//
this.button7.Location = new System.Drawing.Point(258, 43);
this.button7.Name = "button7";
this.button7.Size = new System.Drawing.Size(75, 23);
this.button7.TabIndex = 7;
this.button7.Text = "button7";
this.button7.UseVisualStyleBackColor = true;
//
// button8
//
this.button8.Location = new System.Drawing.Point(258, 15);
this.button8.Name = "button8";
this.button8.Size = new System.Drawing.Size(75, 23);
this.button8.TabIndex = 6;
this.button8.Text = "button8";
this.button8.UseVisualStyleBackColor = true;
//
// button5
//
this.button5.Location = new System.Drawing.Point(177, 43);
this.button5.Name = "button5";
this.button5.Size = new System.Drawing.Size(75, 23);
this.button5.TabIndex = 5;
this.button5.Text = "button5";
this.button5.UseVisualStyleBackColor = true;
//
// button6
//
this.button6.Location = new System.Drawing.Point(177, 15);
this.button6.Name = "button6";
this.button6.Size = new System.Drawing.Size(75, 23);
this.button6.TabIndex = 4;
this.button6.Text = "button6";
this.button6.UseVisualStyleBackColor = true;
//
// button3
//
this.button3.Location = new System.Drawing.Point(96, 43);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(75, 23);
this.button3.TabIndex = 3;
this.button3.Text = "button3";
this.button3.UseVisualStyleBackColor = true;
//
// button4
//
this.button4.Location = new System.Drawing.Point(96, 15);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(75, 23);
this.button4.TabIndex = 2;
this.button4.Text = "button4";
this.button4.UseVisualStyleBackColor = true;
//
// button2
//
this.button2.Location = new System.Drawing.Point(15, 43);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(75, 23);
this.button2.TabIndex = 1;
this.button2.Text = "button2";
this.button2.UseVisualStyleBackColor = true;
//
// button1
//
this.button1.Location = new System.Drawing.Point(15, 15);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
//
// pageProgressBars
//
this.pageProgressBars.AutoHiddenSlideSize = new System.Drawing.Size(200, 200);
this.pageProgressBars.Controls.Add(this.progressBar5);
this.pageProgressBars.Controls.Add(this.progressBar6);
this.pageProgressBars.Controls.Add(this.progressBar3);
this.pageProgressBars.Controls.Add(this.progressBar4);
this.pageProgressBars.Controls.Add(this.progressBar2);
this.pageProgressBars.Controls.Add(this.progressBar1);
this.pageProgressBars.Flags = 65534;
this.pageProgressBars.LastVisibleSet = true;
this.pageProgressBars.MinimumSize = new System.Drawing.Size(50, 85);
this.pageProgressBars.Name = "pageProgressBars";
this.pageProgressBars.Padding = new System.Windows.Forms.Padding(15);
this.pageProgressBars.Size = new System.Drawing.Size(364, 86);
this.pageProgressBars.Text = "Progress Bars";
this.pageProgressBars.ToolTipTitle = "Page ToolTip";
this.pageProgressBars.UniqueName = "74F866C9CBEC40D974F866C9CBEC40D9";
//
// progressBar5
//
this.progressBar5.Location = new System.Drawing.Point(227, 43);
this.progressBar5.Name = "progressBar5";
this.progressBar5.Size = new System.Drawing.Size(100, 23);
this.progressBar5.TabIndex = 5;
this.progressBar5.Value = 10;
//
// progressBar6
//
this.progressBar6.Location = new System.Drawing.Point(227, 15);
this.progressBar6.Name = "progressBar6";
this.progressBar6.Size = new System.Drawing.Size(100, 23);
this.progressBar6.TabIndex = 4;
this.progressBar6.Value = 60;
//
// progressBar3
//
this.progressBar3.Location = new System.Drawing.Point(121, 43);
this.progressBar3.Name = "progressBar3";
this.progressBar3.Size = new System.Drawing.Size(100, 23);
this.progressBar3.TabIndex = 3;
this.progressBar3.Value = 30;
//
// progressBar4
//
this.progressBar4.Location = new System.Drawing.Point(121, 15);
this.progressBar4.Name = "progressBar4";
this.progressBar4.Size = new System.Drawing.Size(100, 23);
this.progressBar4.TabIndex = 2;
this.progressBar4.Value = 90;
//
// progressBar2
//
this.progressBar2.Location = new System.Drawing.Point(15, 43);
this.progressBar2.Name = "progressBar2";
this.progressBar2.Size = new System.Drawing.Size(100, 23);
this.progressBar2.TabIndex = 1;
this.progressBar2.Value = 70;
//
// progressBar1
//
this.progressBar1.Location = new System.Drawing.Point(15, 15);
this.progressBar1.Name = "progressBar1";
this.progressBar1.Size = new System.Drawing.Size(100, 23);
this.progressBar1.TabIndex = 0;
this.progressBar1.Value = 20;
//
// pageColors
//
this.pageColors.AutoHiddenSlideSize = new System.Drawing.Size(200, 200);
this.pageColors.Controls.Add(this.panel5);
this.pageColors.Controls.Add(this.panel3);
this.pageColors.Controls.Add(this.panel6);
this.pageColors.Controls.Add(this.panel2);
this.pageColors.Controls.Add(this.panel4);
this.pageColors.Controls.Add(this.panel1);
this.pageColors.Flags = 65534;
this.pageColors.LastVisibleSet = true;
this.pageColors.MinimumSize = new System.Drawing.Size(50, 85);
this.pageColors.Name = "pageColors";
this.pageColors.Padding = new System.Windows.Forms.Padding(15);
this.pageColors.Size = new System.Drawing.Size(364, 86);
this.pageColors.Text = "Colors";
this.pageColors.ToolTipTitle = "Page ToolTip";
this.pageColors.UniqueName = "9A2BCC004A1B461D9A2BCC004A1B461D";
//
// panel5
//
this.panel5.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
this.panel5.Location = new System.Drawing.Point(227, 43);
this.panel5.Name = "panel5";
this.panel5.Size = new System.Drawing.Size(100, 22);
this.panel5.TabIndex = 3;
//
// panel3
//
this.panel3.BackColor = System.Drawing.Color.Blue;
this.panel3.Location = new System.Drawing.Point(121, 43);
this.panel3.Name = "panel3";
this.panel3.Size = new System.Drawing.Size(100, 22);
this.panel3.TabIndex = 3;
//
// panel6
//
this.panel6.BackColor = System.Drawing.Color.Fuchsia;
this.panel6.Location = new System.Drawing.Point(227, 15);
this.panel6.Name = "panel6";
this.panel6.Size = new System.Drawing.Size(100, 22);
this.panel6.TabIndex = 2;
//
// panel2
//
this.panel2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(192)))), ((int)(((byte)(0)))));
this.panel2.Location = new System.Drawing.Point(15, 43);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(100, 22);
this.panel2.TabIndex = 1;
//
// panel4
//
this.panel4.BackColor = System.Drawing.Color.Yellow;
this.panel4.Location = new System.Drawing.Point(121, 15);
this.panel4.Name = "panel4";
this.panel4.Size = new System.Drawing.Size(100, 22);
this.panel4.TabIndex = 2;
//
// panel1
//
this.panel1.BackColor = System.Drawing.Color.Red;
this.panel1.Location = new System.Drawing.Point(15, 15);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(100, 22);
this.panel1.TabIndex = 0;
//
// kryptonPanel2
//
this.kryptonPanel2.Dock = System.Windows.Forms.DockStyle.Left;
this.kryptonPanel2.Location = new System.Drawing.Point(168, 5);
this.kryptonPanel2.Name = "kryptonPanel2";
this.kryptonPanel2.Size = new System.Drawing.Size(5, 393);
this.kryptonPanel2.TabIndex = 1;
//
// navigatorLeft
//
this.navigatorLeft.AutoSize = true;
this.navigatorLeft.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.navigatorLeft.Button.ButtonDisplayLogic = ComponentFactory.Krypton.Navigator.ButtonDisplayLogic.None;
this.navigatorLeft.Button.ButtonSpecs.AddRange(new ComponentFactory.Krypton.Navigator.ButtonSpecNavigator[] {
this.buttonLeft});
this.navigatorLeft.Button.CloseButtonDisplay = ComponentFactory.Krypton.Navigator.ButtonDisplay.Hide;
this.navigatorLeft.Dock = System.Windows.Forms.DockStyle.Left;
this.navigatorLeft.Header.HeaderPositionBar = ComponentFactory.Krypton.Toolkit.VisualOrientation.Left;
this.navigatorLeft.Location = new System.Drawing.Point(5, 5);
this.navigatorLeft.Name = "navigatorLeft";
this.navigatorLeft.NavigatorMode = ComponentFactory.Krypton.Navigator.NavigatorMode.HeaderBarCheckButtonGroup;
this.navigatorLeft.Pages.AddRange(new ComponentFactory.Krypton.Navigator.KryptonPage[] {
this.pageRichTextBox,
this.pageListBox});
this.navigatorLeft.PopupPages.AllowPopupPages = ComponentFactory.Krypton.Navigator.PopupPageAllow.OnlyCompatibleModes;
this.navigatorLeft.PopupPages.Element = ComponentFactory.Krypton.Navigator.PopupPageElement.Navigator;
this.navigatorLeft.PopupPages.Position = ComponentFactory.Krypton.Navigator.PopupPagePosition.FarMatch;
this.navigatorLeft.SelectedIndex = 1;
this.navigatorLeft.Size = new System.Drawing.Size(163, 393);
this.navigatorLeft.TabIndex = 0;
this.navigatorLeft.Text = "kryptonNavigator1";
//
// buttonLeft
//
this.buttonLeft.Edge = ComponentFactory.Krypton.Toolkit.PaletteRelativeEdgeAlign.Near;
this.buttonLeft.Type = ComponentFactory.Krypton.Toolkit.PaletteButtonSpecStyle.ArrowLeft;
this.buttonLeft.TypeRestricted = ComponentFactory.Krypton.Navigator.PaletteNavButtonSpecStyle.ArrowLeft;
this.buttonLeft.UniqueName = "BF82C2ACF6354EAABF82C2ACF6354EAA";
this.buttonLeft.Click += new System.EventHandler(this.buttonLeft_Click);
//
// pageRichTextBox
//
this.pageRichTextBox.AutoHiddenSlideSize = new System.Drawing.Size(200, 200);
this.pageRichTextBox.Controls.Add(this.richTextBox1);
this.pageRichTextBox.Flags = 65534;
this.pageRichTextBox.LastVisibleSet = true;
this.pageRichTextBox.MinimumSize = new System.Drawing.Size(130, 50);
this.pageRichTextBox.Name = "pageRichTextBox";
this.pageRichTextBox.Padding = new System.Windows.Forms.Padding(5);
this.pageRichTextBox.Size = new System.Drawing.Size(131, 296);
this.pageRichTextBox.Text = "Notebook";
this.pageRichTextBox.ToolTipTitle = "Page ToolTip";
this.pageRichTextBox.UniqueName = "8C64EF9E7C89449E8C64EF9E7C89449E";
//
// richTextBox1
//
this.richTextBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.richTextBox1.Location = new System.Drawing.Point(5, 5);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.Size = new System.Drawing.Size(121, 286);
this.richTextBox1.StateCommon.Border.Draw = ComponentFactory.Krypton.Toolkit.InheritBool.False;
this.richTextBox1.StateCommon.Border.DrawBorders = ((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders)((((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Top | ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Bottom)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Left)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Right)));
this.richTextBox1.TabIndex = 0;
this.richTextBox1.Text = "Plenty of room here to enter some notes. Help yourself!";
//
// pageListBox
//
this.pageListBox.AutoHiddenSlideSize = new System.Drawing.Size(200, 200);
this.pageListBox.Controls.Add(this.kryptonCheckButton7);
this.pageListBox.Controls.Add(this.kryptonCheckButton8);
this.pageListBox.Controls.Add(this.kryptonCheckButton9);
this.pageListBox.Controls.Add(this.kryptonCheckButton6);
this.pageListBox.Controls.Add(this.kryptonCheckButton5);
this.pageListBox.Controls.Add(this.kryptonCheckButton4);
this.pageListBox.Controls.Add(this.kryptonCheckButton3);
this.pageListBox.Controls.Add(this.kryptonCheckButton2);
this.pageListBox.Controls.Add(this.kryptonCheckButton1);
this.pageListBox.Flags = 65534;
this.pageListBox.LastVisibleSet = true;
this.pageListBox.MinimumSize = new System.Drawing.Size(130, 50);
this.pageListBox.Name = "pageListBox";
this.pageListBox.Padding = new System.Windows.Forms.Padding(5);
this.pageListBox.Size = new System.Drawing.Size(131, 391);
this.pageListBox.Text = "Palettes";
this.pageListBox.ToolTipTitle = "Page ToolTip";
this.pageListBox.UniqueName = "DC2FDC906EBE4062DC2FDC906EBE4062";
//
// kryptonCheckButton6
//
this.kryptonCheckButton6.ButtonStyle = ComponentFactory.Krypton.Toolkit.ButtonStyle.Cluster;
this.kryptonCheckButton6.Location = new System.Drawing.Point(16, 243);
this.kryptonCheckButton6.Name = "kryptonCheckButton6";
this.kryptonCheckButton6.Size = new System.Drawing.Size(100, 25);
this.kryptonCheckButton6.TabIndex = 4;
this.kryptonCheckButton6.Values.Text = "Sparkle";
//
// kryptonCheckButton5
//
this.kryptonCheckButton5.ButtonStyle = ComponentFactory.Krypton.Toolkit.ButtonStyle.Cluster;
this.kryptonCheckButton5.Location = new System.Drawing.Point(16, 210);
this.kryptonCheckButton5.Name = "kryptonCheckButton5";
this.kryptonCheckButton5.Size = new System.Drawing.Size(100, 25);
this.kryptonCheckButton5.TabIndex = 3;
this.kryptonCheckButton5.Values.Text = "2003";
this.kryptonCheckButton5.Click += new System.EventHandler(this.kryptonPaletteButtons_Click);
//
// kryptonCheckButton4
//
this.kryptonCheckButton4.ButtonStyle = ComponentFactory.Krypton.Toolkit.ButtonStyle.Cluster;
this.kryptonCheckButton4.Location = new System.Drawing.Point(16, 276);
this.kryptonCheckButton4.Name = "kryptonCheckButton4";
this.kryptonCheckButton4.Size = new System.Drawing.Size(100, 25);
this.kryptonCheckButton4.TabIndex = 5;
this.kryptonCheckButton4.Values.Text = "System";
this.kryptonCheckButton4.Click += new System.EventHandler(this.kryptonPaletteButtons_Click);
//
// kryptonCheckButton3
//
this.kryptonCheckButton3.ButtonStyle = ComponentFactory.Krypton.Toolkit.ButtonStyle.Cluster;
this.kryptonCheckButton3.Location = new System.Drawing.Point(16, 177);
this.kryptonCheckButton3.Name = "kryptonCheckButton3";
this.kryptonCheckButton3.Size = new System.Drawing.Size(100, 25);
this.kryptonCheckButton3.TabIndex = 2;
this.kryptonCheckButton3.Values.Text = "2007 Black";
this.kryptonCheckButton3.Click += new System.EventHandler(this.kryptonPaletteButtons_Click);
//
// kryptonCheckButton2
//
this.kryptonCheckButton2.ButtonStyle = ComponentFactory.Krypton.Toolkit.ButtonStyle.Cluster;
this.kryptonCheckButton2.Location = new System.Drawing.Point(16, 144);
this.kryptonCheckButton2.Name = "kryptonCheckButton2";
this.kryptonCheckButton2.Size = new System.Drawing.Size(100, 25);
this.kryptonCheckButton2.TabIndex = 1;
this.kryptonCheckButton2.Values.Text = "2007 Silver";
this.kryptonCheckButton2.Click += new System.EventHandler(this.kryptonPaletteButtons_Click);
//
// kryptonCheckButton1
//
this.kryptonCheckButton1.ButtonStyle = ComponentFactory.Krypton.Toolkit.ButtonStyle.Cluster;
this.kryptonCheckButton1.Checked = true;
this.kryptonCheckButton1.Location = new System.Drawing.Point(16, 111);
this.kryptonCheckButton1.Name = "kryptonCheckButton1";
this.kryptonCheckButton1.Size = new System.Drawing.Size(100, 25);
this.kryptonCheckButton1.TabIndex = 0;
this.kryptonCheckButton1.Values.Text = "2007 Blue";
this.kryptonCheckButton1.Click += new System.EventHandler(this.kryptonPaletteButtons_Click);
//
// statusStrip1
//
this.statusStrip1.Font = new System.Drawing.Font("Segoe UI", 9F);
this.statusStrip1.Location = new System.Drawing.Point(0, 452);
this.statusStrip1.Name = "statusStrip1";
this.statusStrip1.RenderMode = System.Windows.Forms.ToolStripRenderMode.ManagerRenderMode;
this.statusStrip1.Size = new System.Drawing.Size(606, 22);
this.statusStrip1.TabIndex = 3;
this.statusStrip1.Text = "statusStrip1";
//
// kryptonPalettes
//
this.kryptonPalettes.CheckButtons.Add(this.kryptonCheckButton1);
this.kryptonPalettes.CheckButtons.Add(this.kryptonCheckButton2);
this.kryptonPalettes.CheckButtons.Add(this.kryptonCheckButton3);
this.kryptonPalettes.CheckButtons.Add(this.kryptonCheckButton4);
this.kryptonPalettes.CheckButtons.Add(this.kryptonCheckButton5);
this.kryptonPalettes.CheckButtons.Add(this.kryptonCheckButton6);
this.kryptonPalettes.CheckButtons.Add(this.kryptonCheckButton7);
this.kryptonPalettes.CheckButtons.Add(this.kryptonCheckButton8);
this.kryptonPalettes.CheckButtons.Add(this.kryptonCheckButton9);
this.kryptonPalettes.CheckedButton = this.kryptonCheckButton9;
this.kryptonPalettes.CheckedButtonChanged += new System.EventHandler(this.kryptonPalettes_CheckedButtonChanged);
//
// kryptonCheckButton7
//
this.kryptonCheckButton7.ButtonStyle = ComponentFactory.Krypton.Toolkit.ButtonStyle.Cluster;
this.kryptonCheckButton7.Location = new System.Drawing.Point(16, 78);
this.kryptonCheckButton7.Name = "kryptonCheckButton7";
this.kryptonCheckButton7.Size = new System.Drawing.Size(100, 25);
this.kryptonCheckButton7.TabIndex = 8;
this.kryptonCheckButton7.Values.Text = "2010 Black";
this.kryptonCheckButton7.Click += new System.EventHandler(this.kryptonPaletteButtons_Click);
//
// kryptonCheckButton8
//
this.kryptonCheckButton8.ButtonStyle = ComponentFactory.Krypton.Toolkit.ButtonStyle.Cluster;
this.kryptonCheckButton8.Location = new System.Drawing.Point(16, 45);
this.kryptonCheckButton8.Name = "kryptonCheckButton8";
this.kryptonCheckButton8.Size = new System.Drawing.Size(100, 25);
this.kryptonCheckButton8.TabIndex = 7;
this.kryptonCheckButton8.Values.Text = "2010 Silver";
this.kryptonCheckButton8.Click += new System.EventHandler(this.kryptonPaletteButtons_Click);
//
// kryptonCheckButton9
//
this.kryptonCheckButton9.ButtonStyle = ComponentFactory.Krypton.Toolkit.ButtonStyle.Cluster;
this.kryptonCheckButton9.Checked = true;
this.kryptonCheckButton9.Location = new System.Drawing.Point(16, 12);
this.kryptonCheckButton9.Name = "kryptonCheckButton9";
this.kryptonCheckButton9.Size = new System.Drawing.Size(100, 25);
this.kryptonCheckButton9.TabIndex = 6;
this.kryptonCheckButton9.Values.Text = "2010 Blue";
this.kryptonCheckButton9.Click += new System.EventHandler(this.kryptonPaletteButtons_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(606, 474);
this.Controls.Add(this.toolStripContainer1);
this.Controls.Add(this.statusStrip1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MainMenuStrip = this.menuStrip1;
this.MinimumSize = new System.Drawing.Size(541, 313);
this.Name = "Form1";
this.Text = "Expanding Pages";
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.toolStrip1.ResumeLayout(false);
this.toolStrip1.PerformLayout();
this.toolStripContainer1.ContentPanel.ResumeLayout(false);
this.toolStripContainer1.TopToolStripPanel.ResumeLayout(false);
this.toolStripContainer1.TopToolStripPanel.PerformLayout();
this.toolStripContainer1.ResumeLayout(false);
this.toolStripContainer1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonPanel1)).EndInit();
this.kryptonPanel1.ResumeLayout(false);
this.kryptonPanel1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pageButtons.Panel)).EndInit();
this.pageButtons.Panel.ResumeLayout(false);
this.pageButtons.Panel.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pageButtons)).EndInit();
this.pageButtons.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.kryptonPanel3)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.navigatorTop)).EndInit();
this.navigatorTop.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pageEntryForm)).EndInit();
this.pageEntryForm.ResumeLayout(false);
this.pageEntryForm.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonPage4)).EndInit();
this.kryptonPage4.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pageProgressBars)).EndInit();
this.pageProgressBars.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pageColors)).EndInit();
this.pageColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.kryptonPanel2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.navigatorLeft)).EndInit();
this.navigatorLeft.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pageRichTextBox)).EndInit();
this.pageRichTextBox.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pageListBox)).EndInit();
this.pageListBox.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.kryptonPalettes)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem newToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator;
private System.Windows.Forms.ToolStripMenuItem saveToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveAsToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripMenuItem printToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem printPreviewToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem editToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem undoToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem redoToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
private System.Windows.Forms.ToolStripMenuItem cutToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem pasteToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
private System.Windows.Forms.ToolStripMenuItem selectAllToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem toolsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem customizeToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem optionsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem contentsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem indexToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem searchToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator5;
private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem;
private System.Windows.Forms.ToolStrip toolStrip1;
private System.Windows.Forms.ToolStripButton newToolStripButton;
private System.Windows.Forms.ToolStripButton openToolStripButton;
private System.Windows.Forms.ToolStripButton saveToolStripButton;
private System.Windows.Forms.ToolStripButton printToolStripButton;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator6;
private System.Windows.Forms.ToolStripButton cutToolStripButton;
private System.Windows.Forms.ToolStripButton copyToolStripButton;
private System.Windows.Forms.ToolStripButton pasteToolStripButton;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator7;
private System.Windows.Forms.ToolStripButton helpToolStripButton;
private System.Windows.Forms.ToolStripContainer toolStripContainer1;
private ComponentFactory.Krypton.Toolkit.KryptonPanel kryptonPanel1;
private System.Windows.Forms.StatusStrip statusStrip1;
private ComponentFactory.Krypton.Navigator.KryptonNavigator navigatorLeft;
private ComponentFactory.Krypton.Navigator.KryptonPage pageRichTextBox;
private ComponentFactory.Krypton.Navigator.KryptonPage pageListBox;
private ComponentFactory.Krypton.Navigator.KryptonNavigator navigatorTop;
private ComponentFactory.Krypton.Navigator.ButtonSpecNavigator buttonTopArrow;
private ComponentFactory.Krypton.Navigator.KryptonPage pageEntryForm;
private ComponentFactory.Krypton.Navigator.KryptonPage kryptonPage4;
private ComponentFactory.Krypton.Toolkit.KryptonPanel kryptonPanel2;
private ComponentFactory.Krypton.Toolkit.KryptonGroup pageButtons;
private ComponentFactory.Krypton.Toolkit.KryptonPanel kryptonPanel3;
private ComponentFactory.Krypton.Navigator.ButtonSpecNavigator buttonLeft;
private ComponentFactory.Krypton.Navigator.KryptonPage pageProgressBars;
private ComponentFactory.Krypton.Navigator.KryptonPage pageColors;
private ComponentFactory.Krypton.Toolkit.KryptonManager kryptonManager1;
private System.Windows.Forms.Button button7;
private System.Windows.Forms.Button button8;
private System.Windows.Forms.Button button5;
private System.Windows.Forms.Button button6;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Button button4;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.ProgressBar progressBar5;
private System.Windows.Forms.ProgressBar progressBar6;
private System.Windows.Forms.ProgressBar progressBar3;
private System.Windows.Forms.ProgressBar progressBar4;
private System.Windows.Forms.ProgressBar progressBar2;
private System.Windows.Forms.ProgressBar progressBar1;
private System.Windows.Forms.Panel panel5;
private System.Windows.Forms.Panel panel3;
private System.Windows.Forms.Panel panel6;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.Panel panel4;
private System.Windows.Forms.Panel panel1;
private ComponentFactory.Krypton.Toolkit.KryptonTextBox textBox3;
private ComponentFactory.Krypton.Toolkit.KryptonTextBox textBox4;
private ComponentFactory.Krypton.Toolkit.KryptonLabel kryptonLabel3;
private ComponentFactory.Krypton.Toolkit.KryptonLabel kryptonLabel4;
private ComponentFactory.Krypton.Toolkit.KryptonTextBox textBox2;
private ComponentFactory.Krypton.Toolkit.KryptonTextBox textBox1;
private ComponentFactory.Krypton.Toolkit.KryptonLabel kryptonLabel2;
private ComponentFactory.Krypton.Toolkit.KryptonLabel kryptonLabel1;
private ComponentFactory.Krypton.Toolkit.KryptonRichTextBox richTextBox1;
private ComponentFactory.Krypton.Toolkit.KryptonCheckButton kryptonCheckButton5;
private ComponentFactory.Krypton.Toolkit.KryptonCheckButton kryptonCheckButton4;
private ComponentFactory.Krypton.Toolkit.KryptonCheckButton kryptonCheckButton3;
private ComponentFactory.Krypton.Toolkit.KryptonCheckButton kryptonCheckButton2;
private ComponentFactory.Krypton.Toolkit.KryptonCheckButton kryptonCheckButton1;
private ComponentFactory.Krypton.Toolkit.KryptonCheckSet kryptonPalettes;
private ComponentFactory.Krypton.Toolkit.KryptonRichTextBox richTextBox2;
private ComponentFactory.Krypton.Toolkit.KryptonCheckButton kryptonCheckButton6;
private ComponentFactory.Krypton.Toolkit.KryptonCheckButton kryptonCheckButton7;
private ComponentFactory.Krypton.Toolkit.KryptonCheckButton kryptonCheckButton8;
private ComponentFactory.Krypton.Toolkit.KryptonCheckButton kryptonCheckButton9;
}
}
| |
// 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.Immutable;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Shell.TableManager;
using Microsoft.VisualStudio.Text;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource
{
[Export(typeof(VisualStudioDiagnosticListTable))]
internal class VisualStudioDiagnosticListTable : VisualStudioBaseDiagnosticListTable
{
internal const string IdentifierString = nameof(VisualStudioDiagnosticListTable);
private readonly IErrorList _errorList;
private readonly LiveTableDataSource _liveTableSource;
private readonly BuildTableDataSource _buildTableSource;
[ImportingConstructor]
public VisualStudioDiagnosticListTable(
SVsServiceProvider serviceProvider,
VisualStudioWorkspace workspace,
IDiagnosticService diagnosticService,
ExternalErrorDiagnosticUpdateSource errorSource,
ITableManagerProvider provider) :
this(serviceProvider, (Workspace)workspace, diagnosticService, errorSource, provider)
{
ConnectWorkspaceEvents();
_errorList = serviceProvider.GetService(typeof(SVsErrorList)) as IErrorList;
if (_errorList == null)
{
AddInitialTableSource(workspace.CurrentSolution, _liveTableSource);
return;
}
_errorList.PropertyChanged += OnErrorListPropertyChanged;
AddInitialTableSource(workspace.CurrentSolution, GetCurrentDataSource());
}
private ITableDataSource GetCurrentDataSource()
{
if (_errorList == null)
{
return _liveTableSource;
}
return _errorList.AreOtherErrorSourceEntriesShown ? (ITableDataSource)_liveTableSource : _buildTableSource;
}
/// this is for test only
internal VisualStudioDiagnosticListTable(Workspace workspace, IDiagnosticService diagnosticService, ITableManagerProvider provider) :
this(null, workspace, diagnosticService, null, provider)
{
AddInitialTableSource(workspace.CurrentSolution, _liveTableSource);
}
private VisualStudioDiagnosticListTable(
SVsServiceProvider serviceProvider,
Workspace workspace,
IDiagnosticService diagnosticService,
ExternalErrorDiagnosticUpdateSource errorSource,
ITableManagerProvider provider) :
base(serviceProvider, workspace, diagnosticService, provider)
{
_liveTableSource = new LiveTableDataSource(serviceProvider, workspace, diagnosticService, IdentifierString);
_buildTableSource = new BuildTableDataSource(workspace, errorSource);
}
protected override void AddTableSourceIfNecessary(Solution solution)
{
if (solution.ProjectIds.Count == 0)
{
return;
}
RemoveTableSourcesIfNecessary();
AddTableSource(GetCurrentDataSource());
}
protected override void RemoveTableSourceIfNecessary(Solution solution)
{
if (solution.ProjectIds.Count > 0)
{
return;
}
RemoveTableSourcesIfNecessary();
}
private void RemoveTableSourcesIfNecessary()
{
RemoveTableSourceIfNecessary(_buildTableSource);
RemoveTableSourceIfNecessary(_liveTableSource);
}
private void RemoveTableSourceIfNecessary(ITableDataSource source)
{
if (!this.TableManager.Sources.Any(s => s == source))
{
return;
}
this.TableManager.RemoveSource(source);
}
protected override void ShutdownSource()
{
_liveTableSource.Shutdown();
_buildTableSource.Shutdown();
}
private void OnErrorListPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(IErrorList.AreOtherErrorSourceEntriesShown))
{
AddTableSourceIfNecessary(this.Workspace.CurrentSolution);
}
}
private class BuildTableDataSource : AbstractTableDataSource<DiagnosticData>
{
private readonly Workspace _workspace;
private readonly ExternalErrorDiagnosticUpdateSource _buildErrorSource;
public BuildTableDataSource(Workspace workspace, ExternalErrorDiagnosticUpdateSource errorSource)
{
_workspace = workspace;
_buildErrorSource = errorSource;
ConnectToBuildUpdateSource(errorSource);
}
private void ConnectToBuildUpdateSource(ExternalErrorDiagnosticUpdateSource errorSource)
{
if (errorSource == null)
{
return;
}
SetStableState(errorSource.IsInProgress);
errorSource.BuildStarted += OnBuildStarted;
}
private void OnBuildStarted(object sender, bool started)
{
SetStableState(started);
if (!started)
{
OnDataAddedOrChanged(this, _buildErrorSource.GetBuildErrors().Length);
}
}
private void SetStableState(bool started)
{
IsStable = !started;
ChangeStableState(IsStable);
}
public override string DisplayName => ServicesVSResources.BuildTableSourceName;
public override string SourceTypeIdentifier => StandardTableDataSources.ErrorTableDataSource;
public override string Identifier => IdentifierString;
protected void OnDataAddedOrChanged(object key, int itemCount)
{
// reuse factory. it is okay to re-use factory since we make sure we remove the factory before
// adding it back
bool newFactory = false;
ImmutableArray<SubscriptionWithoutLock> snapshot;
AbstractTableEntriesFactory<DiagnosticData> factory;
lock (Gate)
{
snapshot = Subscriptions;
if (!Map.TryGetValue(key, out factory))
{
factory = new TableEntriesFactory(this, _workspace);
Map.Add(key, factory);
newFactory = true;
}
}
factory.OnUpdated(itemCount);
for (var i = 0; i < snapshot.Length; i++)
{
snapshot[i].AddOrUpdate(factory, newFactory);
}
}
private class TableEntriesFactory : AbstractTableEntriesFactory<DiagnosticData>
{
private readonly BuildTableDataSource _source;
private readonly Workspace _workspace;
public TableEntriesFactory(BuildTableDataSource source, Workspace workspace) :
base(source)
{
_source = source;
_workspace = workspace;
}
protected override ImmutableArray<DiagnosticData> GetItems()
{
return _source._buildErrorSource.GetBuildErrors();
}
protected override ImmutableArray<ITrackingPoint> GetTrackingPoints(ImmutableArray<DiagnosticData> items)
{
return ImmutableArray<ITrackingPoint>.Empty;
}
protected override AbstractTableEntriesSnapshot<DiagnosticData> CreateSnapshot(
int version, ImmutableArray<DiagnosticData> items, ImmutableArray<ITrackingPoint> trackingPoints)
{
return new TableEntriesSnapshot(this, version, items);
}
private class TableEntriesSnapshot : AbstractTableEntriesSnapshot<DiagnosticData>
{
private readonly TableEntriesFactory _factory;
public TableEntriesSnapshot(
TableEntriesFactory factory, int version, ImmutableArray<DiagnosticData> items) :
base(version, Guid.Empty, items, ImmutableArray<ITrackingPoint>.Empty)
{
_factory = factory;
}
public override bool TryGetValue(int index, string columnName, out object content)
{
// REVIEW: this method is too-chatty to make async, but otherwise, how one can implement it async?
// also, what is cancellation mechanism?
var item = GetItem(index);
if (item == null)
{
content = null;
return false;
}
switch (columnName)
{
case StandardTableKeyNames.ErrorRank:
content = WellKnownDiagnosticTags.Build;
return true;
case StandardTableKeyNames.ErrorSeverity:
content = GetErrorCategory(item.Severity);
return true;
case StandardTableKeyNames.ErrorCode:
content = item.Id;
return true;
case StandardTableKeyNames.ErrorCodeToolTip:
content = GetHelpLinkToolTipText(item);
return content != null;
case StandardTableKeyNames.HelpLink:
content = GetHelpLink(item);
return content != null;
case StandardTableKeyNames.ErrorCategory:
content = item.Category;
return true;
case StandardTableKeyNames.ErrorSource:
content = ErrorSource.Build;
return true;
case StandardTableKeyNames.BuildTool:
content = PredefinedBuildTools.Build;
return true;
case StandardTableKeyNames.Text:
content = item.Message;
return true;
case StandardTableKeyNames.DocumentName:
content = GetFileName(item.OriginalFilePath, item.MappedFilePath);
return true;
case StandardTableKeyNames.Line:
content = item.MappedStartLine;
return true;
case StandardTableKeyNames.Column:
content = item.MappedStartColumn;
return true;
case StandardTableKeyNames.ProjectName:
content = GetProjectName(_factory._workspace, item.ProjectId);
return content != null;
case StandardTableKeyNames.ProjectGuid:
var guid = GetProjectGuid(_factory._workspace, item.ProjectId);
content = guid;
return guid != Guid.Empty;
default:
content = null;
return false;
}
}
public override bool TryNavigateTo(int index, bool previewTab)
{
var item = GetItem(index);
if (item == null)
{
return false;
}
// this item is not navigatable
if (item.DocumentId == null)
{
return false;
}
return TryNavigateTo(_factory._workspace, item.DocumentId, item.OriginalStartLine, item.OriginalStartColumn, previewTab);
}
protected override bool IsEquivalent(DiagnosticData item1, DiagnosticData item2)
{
// everything same except location
return item1.Id == item2.Id &&
item1.ProjectId == item2.ProjectId &&
item1.DocumentId == item2.DocumentId &&
item1.Category == item2.Category &&
item1.Severity == item2.Severity &&
item1.WarningLevel == item2.WarningLevel &&
item1.Message == item2.Message;
}
}
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="Trace.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
*/
#define TRACE
namespace System.Diagnostics {
using System;
using System.Collections;
using System.Security.Permissions;
using System.Threading;
/// <devdoc>
/// <para>Provides a set of properties and methods to trace the execution of your code.</para>
/// </devdoc>
public sealed class Trace {
private static volatile CorrelationManager correlationManager = null;
// not creatble...
//
private Trace() {
}
/// <devdoc>
/// <para>Gets the collection of listeners that is monitoring the trace output.</para>
/// </devdoc>
public static TraceListenerCollection Listeners {
[HostProtection(SharedState=true)]
get {
#if !DISABLE_CAS_USE
// Do a full damand
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
#endif
return TraceInternal.Listeners;
}
}
/// <devdoc>
/// <para>
/// Gets or sets whether <see cref='System.Diagnostics.Trace.Flush'/> should be called on the <see cref='System.Diagnostics.Trace.Listeners'/> after every write.
/// </para>
/// </devdoc>
public static bool AutoFlush {
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
get {
return TraceInternal.AutoFlush;
}
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
set {
TraceInternal.AutoFlush = value;
}
}
public static bool UseGlobalLock {
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
get {
return TraceInternal.UseGlobalLock;
}
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
set {
TraceInternal.UseGlobalLock = value;
}
}
public static CorrelationManager CorrelationManager {
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
get {
if (correlationManager == null)
correlationManager = new CorrelationManager();
return correlationManager;
}
}
/// <devdoc>
/// <para>Gets or sets the indent level.</para>
/// </devdoc>
public static int IndentLevel {
get { return TraceInternal.IndentLevel; }
set { TraceInternal.IndentLevel = value; }
}
/// <devdoc>
/// <para>
/// Gets or sets the number of spaces in an indent.
/// </para>
/// </devdoc>
public static int IndentSize {
get { return TraceInternal.IndentSize; }
set { TraceInternal.IndentSize = value; }
}
/// <devdoc>
/// <para>Clears the output buffer, and causes buffered data to
/// be written to the <see cref='System.Diagnostics.Trace.Listeners'/>.</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Flush() {
TraceInternal.Flush();
}
/// <devdoc>
/// <para>Clears the output buffer, and then closes the <see cref='System.Diagnostics.Trace.Listeners'/> so that they no
/// longer receive debugging output.</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Close() {
#if !DISABLE_CAS_USE
// Do a full damand
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
#endif
TraceInternal.Close();
}
/// <devdoc>
/// <para>Checks for a condition, and outputs the callstack if the
/// condition
/// is <see langword='false'/>.</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Assert(bool condition) {
TraceInternal.Assert(condition);
}
/// <devdoc>
/// <para>Checks for a condition, and displays a message if the condition is
/// <see langword='false'/>. </para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Assert(bool condition, string message) {
TraceInternal.Assert(condition, message);
}
/// <devdoc>
/// <para>Checks for a condition, and displays both messages if the condition
/// is <see langword='false'/>. </para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Assert(bool condition, string message, string detailMessage) {
TraceInternal.Assert(condition, message, detailMessage);
}
/// <devdoc>
/// <para>Emits or displays a message for an assertion that always fails.</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Fail(string message) {
TraceInternal.Fail(message);
}
/// <devdoc>
/// <para>Emits or displays both messages for an assertion that always fails.</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Fail(string message, string detailMessage) {
TraceInternal.Fail(message, detailMessage);
}
public static void Refresh() {
#if CONFIGURATION_DEP
DiagnosticsConfiguration.Refresh();
#endif
Switch.RefreshAll();
TraceSource.RefreshAll();
TraceInternal.Refresh();
}
[System.Diagnostics.Conditional("TRACE")]
public static void TraceInformation(string message) {
TraceInternal.TraceEvent(TraceEventType.Information, 0, message, null);
}
[System.Diagnostics.Conditional("TRACE")]
public static void TraceInformation(string format, params object[] args) {
TraceInternal.TraceEvent(TraceEventType.Information, 0, format, args);
}
[System.Diagnostics.Conditional("TRACE")]
public static void TraceWarning(string message) {
TraceInternal.TraceEvent(TraceEventType.Warning, 0, message, null);
}
[System.Diagnostics.Conditional("TRACE")]
public static void TraceWarning(string format, params object[] args) {
TraceInternal.TraceEvent(TraceEventType.Warning, 0, format, args);
}
[System.Diagnostics.Conditional("TRACE")]
public static void TraceError(string message) {
TraceInternal.TraceEvent(TraceEventType.Error, 0, message, null);
}
[System.Diagnostics.Conditional("TRACE")]
public static void TraceError(string format, params object[] args) {
TraceInternal.TraceEvent(TraceEventType.Error, 0, format, args);
}
/// <devdoc>
/// <para>Writes a message to the trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/>
/// collection.</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Write(string message) {
TraceInternal.Write(message);
}
/// <devdoc>
/// <para>Writes the name of the <paramref name="value "/>
/// parameter to the trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection.</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Write(object value) {
TraceInternal.Write(value);
}
/// <devdoc>
/// <para>Writes a category name and message to the trace listeners
/// in the <see cref='System.Diagnostics.Trace.Listeners'/> collection.</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Write(string message, string category) {
TraceInternal.Write(message, category);
}
/// <devdoc>
/// <para>Writes a category name and the name of the value parameter to the trace listeners
/// in the <see cref='System.Diagnostics.Trace.Listeners'/> collection.</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Write(object value, string category) {
TraceInternal.Write(value, category);
}
/// <devdoc>
/// <para>Writes a message followed by a line terminator to the
/// trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection.
/// The default line terminator is a carriage return followed by a line feed (\r\n).</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteLine(string message) {
TraceInternal.WriteLine(message);
}
/// <devdoc>
/// <para>Writes the name of the <paramref name="value "/> parameter followed by a line terminator to the trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection. The default line
/// terminator is a carriage return followed by a line feed (\r\n).</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteLine(object value) {
TraceInternal.WriteLine(value);
}
/// <devdoc>
/// <para>Writes a category name and message followed by a line terminator to the trace
/// listeners in the <see cref='System.Diagnostics.Trace.Listeners'/>
/// collection. The default line terminator is a carriage return followed by a line
/// feed (\r\n).</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteLine(string message, string category) {
TraceInternal.WriteLine(message, category);
}
/// <devdoc>
/// <para>Writes a <paramref name="category "/>name and the name of the <paramref name="value "/> parameter followed by a line
/// terminator to the trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection. The default line
/// terminator is a carriage return followed by a line feed (\r\n).</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteLine(object value, string category) {
TraceInternal.WriteLine(value, category);
}
/// <devdoc>
/// <para>Writes a message to the trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection
/// if a condition is <see langword='true'/>.</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteIf(bool condition, string message) {
TraceInternal.WriteIf(condition, message);
}
/// <devdoc>
/// <para>Writes the name of the <paramref name="value "/>
/// parameter to the trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection if a condition is
/// <see langword='true'/>. </para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteIf(bool condition, object value) {
TraceInternal.WriteIf(condition, value);
}
/// <devdoc>
/// <para>Writes a category name and message to the trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/>
/// collection if a condition is <see langword='true'/>. </para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteIf(bool condition, string message, string category) {
TraceInternal.WriteIf(condition, message, category);
}
/// <devdoc>
/// <para>Writes a category name and the name of the <paramref name="value"/> parameter to the trace
/// listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection
/// if a condition is <see langword='true'/>. </para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteIf(bool condition, object value, string category) {
TraceInternal.WriteIf(condition, value, category);
}
/// <devdoc>
/// <para>Writes a message followed by a line terminator to the trace listeners in the
/// <see cref='System.Diagnostics.Trace.Listeners'/> collection if a condition is
/// <see langword='true'/>. The default line terminator is a carriage return followed
/// by a line feed (\r\n).</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteLineIf(bool condition, string message) {
TraceInternal.WriteLineIf(condition, message);
}
/// <devdoc>
/// <para>Writes the name of the <paramref name="value"/> parameter followed by a line terminator to the
/// trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection
/// if a condition is
/// <see langword='true'/>. The default line
/// terminator is a carriage return followed by a line feed (\r\n).</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteLineIf(bool condition, object value) {
TraceInternal.WriteLineIf(condition, value);
}
/// <devdoc>
/// <para>Writes a category name and message followed by a line terminator to the trace
/// listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection if a condition is
/// <see langword='true'/>. The default line terminator is a carriage return followed by a line feed (\r\n).</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteLineIf(bool condition, string message, string category) {
TraceInternal.WriteLineIf(condition, message, category);
}
/// <devdoc>
/// <para>Writes a category name and the name of the <paramref name="value "/> parameter followed by a line
/// terminator to the trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection
/// if a <paramref name="condition"/> is <see langword='true'/>. The
/// default line terminator is a carriage return followed by a line feed (\r\n).</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteLineIf(bool condition, object value, string category) {
TraceInternal.WriteLineIf(condition, value, category);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Indent() {
TraceInternal.Indent();
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Unindent() {
TraceInternal.Unindent();
}
}
}
| |
#region License
/*
* WebSocketServer.cs
*
* A C# implementation of the WebSocket protocol server.
*
* The MIT License
*
* 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 Contributors
/*
* Contributors:
* - Juan Manuel Lallana <juan.manuel.lallana@gmail.com>
* - Jonas Hovgaard <j@jhovgaard.dk>
* - Liryna <liryna.stark@gmail.com>
* - Rohan Singh <rohan-singh@hotmail.com>
*/
#endregion
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.Text;
using System.Threading;
using WebSocketSharp.Net;
using WebSocketSharp.Net.WebSockets;
namespace WebSocketSharp.Server
{
/// <summary>
/// Provides a WebSocket protocol server.
/// </summary>
/// <remarks>
/// The WebSocketServer class can provide multiple WebSocket services.
/// </remarks>
public class WebSocketServer
{
#region Private Fields
private System.Net.IPAddress _address;
private AuthenticationSchemes _authSchemes;
private Func<IIdentity, NetworkCredential> _credFinder;
private bool _dnsStyle;
private string _hostname;
private TcpListener _listener;
private Logger _logger;
private int _port;
private string _realm;
private Thread _receiveThread;
private bool _reuseAddress;
private bool _secure;
private object _callerContext;
private WebSocketServiceManager _services;
private ServerSslConfiguration _sslConfig;
private volatile ServerState _state;
private object _sync;
#endregion
#region Public Constructors
/// <summary>
/// Initializes a new instance of the <see cref="WebSocketServer"/> class.
/// </summary>
/// <remarks>
/// An instance initialized by this constructor listens for the incoming connection requests on
/// port 80.
/// </remarks>
public WebSocketServer()
{
init(null, System.Net.IPAddress.Any, 80, false, null);
}
/// <summary>
/// Initializes a new instance of the <see cref="WebSocketServer"/> class with
/// the specified <paramref name="port"/>.
/// </summary>
/// <remarks>
/// <para>
/// An instance initialized by this constructor listens for the incoming connection requests
/// on <paramref name="port"/>.
/// </para>
/// <para>
/// If <paramref name="port"/> is 443, that instance provides a secure connection.
/// </para>
/// </remarks>
/// <param name="port">
/// An <see cref="int"/> that represents the port number on which to listen.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="port"/> isn't between 1 and 65535 inclusive.
/// </exception>
public WebSocketServer(int port)
: this(port, port == 443)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WebSocketServer"/> class with
/// the specified WebSocket URL.
/// </summary>
/// <remarks>
/// <para>
/// An instance initialized by this constructor listens for the incoming connection requests
/// on the host name and port in <paramref name="url"/>.
/// </para>
/// <para>
/// If <paramref name="url"/> doesn't include a port, either port 80 or 443 is used on
/// which to listen. It's determined by the scheme (ws or wss) in <paramref name="url"/>.
/// (Port 80 if the scheme is ws.)
/// </para>
/// </remarks>
/// <param name="url">
/// A <see cref="string"/> that represents the WebSocket URL of the server.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="url"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="url"/> is empty.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="url"/> is invalid.
/// </para>
/// </exception>
public WebSocketServer(string url, object context)
{
if (url == null)
throw new ArgumentNullException("url");
if (url.Length == 0)
throw new ArgumentException("An empty string.", "url");
Uri uri;
string msg;
if (!tryCreateUri(url, out uri, out msg))
throw new ArgumentException(msg, "url");
var host = uri.DnsSafeHost;
var addr = host.ToIPAddress();
if (!addr.IsLocal())
throw new ArgumentException("The host part isn't a local host name: " + url, "url");
init(host, addr, uri.Port, uri.Scheme == "wss", context);
}
/// <summary>
/// Initializes a new instance of the <see cref="WebSocketServer"/> class with
/// the specified <paramref name="port"/> and <paramref name="secure"/>.
/// </summary>
/// <remarks>
/// An instance initialized by this constructor listens for the incoming connection requests on
/// <paramref name="port"/>.
/// </remarks>
/// <param name="port">
/// An <see cref="int"/> that represents the port number on which to listen.
/// </param>
/// <param name="secure">
/// A <see cref="bool"/> that indicates providing a secure connection or not.
/// (<c>true</c> indicates providing a secure connection.)
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="port"/> isn't between 1 and 65535 inclusive.
/// </exception>
public WebSocketServer(int port, bool secure, object context = null)
{
if (!port.IsPortNumber())
throw new ArgumentOutOfRangeException(
"port", "Not between 1 and 65535 inclusive: " + port);
init(null, System.Net.IPAddress.Any, port, secure, context);
}
/// <summary>
/// Initializes a new instance of the <see cref="WebSocketServer"/> class with
/// the specified <paramref name="address"/> and <paramref name="port"/>.
/// </summary>
/// <remarks>
/// <para>
/// An instance initialized by this constructor listens for the incoming connection requests
/// on <paramref name="address"/> and <paramref name="port"/>.
/// </para>
/// <para>
/// If <paramref name="port"/> is 443, that instance provides a secure connection.
/// </para>
/// </remarks>
/// <param name="address">
/// A <see cref="System.Net.IPAddress"/> that represents the local IP address of the server.
/// </param>
/// <param name="port">
/// An <see cref="int"/> that represents the port number on which to listen.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="address"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="address"/> isn't a local IP address.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="port"/> isn't between 1 and 65535 inclusive.
/// </exception>
public WebSocketServer(System.Net.IPAddress address, int port, object context)
: this(address, port, port == 443, context)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WebSocketServer"/> class with
/// the specified <paramref name="address"/>, <paramref name="port"/>,
/// and <paramref name="secure"/>.
/// </summary>
/// <remarks>
/// An instance initialized by this constructor listens for the incoming connection requests on
/// <paramref name="address"/> and <paramref name="port"/>.
/// </remarks>
/// <param name="address">
/// A <see cref="System.Net.IPAddress"/> that represents the local IP address of the server.
/// </param>
/// <param name="port">
/// An <see cref="int"/> that represents the port number on which to listen.
/// </param>
/// <param name="secure">
/// A <see cref="bool"/> that indicates providing a secure connection or not.
/// (<c>true</c> indicates providing a secure connection.)
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="address"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="address"/> isn't a local IP address.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="port"/> isn't between 1 and 65535 inclusive.
/// </exception>
public WebSocketServer(System.Net.IPAddress address, int port, bool secure, object context)
{
if (address == null)
throw new ArgumentNullException("address");
if (!address.IsLocal())
throw new ArgumentException("Not a local IP address: " + address, "address");
if (!port.IsPortNumber())
throw new ArgumentOutOfRangeException(
"port", "Not between 1 and 65535 inclusive: " + port);
init(null, address, port, secure, context);
}
#endregion
#region Public Properties
/// <summary>
/// Gets the local IP address of the server.
/// </summary>
/// <value>
/// A <see cref="System.Net.IPAddress"/> that represents the local IP address of the server.
/// </value>
public System.Net.IPAddress Address
{
get
{
return _address;
}
}
/// <summary>
/// Gets or sets the scheme used to authenticate the clients.
/// </summary>
/// <value>
/// One of the <see cref="WebSocketSharp.Net.AuthenticationSchemes"/> enum values,
/// indicates the scheme used to authenticate the clients. The default value is
/// <see cref="WebSocketSharp.Net.AuthenticationSchemes.Anonymous"/>.
/// </value>
public AuthenticationSchemes AuthenticationSchemes
{
get
{
return _authSchemes;
}
set
{
var msg = _state.CheckIfAvailable(true, false, false);
if (msg != null)
{
_logger.Error(msg);
return;
}
_authSchemes = value;
}
}
/// <summary>
/// Gets a value indicating whether the server has started.
/// </summary>
/// <value>
/// <c>true</c> if the server has started; otherwise, <c>false</c>.
/// </value>
public bool IsListening
{
get
{
return _state == ServerState.Start;
}
}
/// <summary>
/// Gets a value indicating whether the server provides a secure connection.
/// </summary>
/// <value>
/// <c>true</c> if the server provides a secure connection; otherwise, <c>false</c>.
/// </value>
public bool IsSecure
{
get
{
return _secure;
}
}
/// <summary>
/// Gets or sets a value indicating whether the server cleans up
/// the inactive sessions periodically.
/// </summary>
/// <value>
/// <c>true</c> if the server cleans up the inactive sessions every 60 seconds;
/// otherwise, <c>false</c>. The default value is <c>true</c>.
/// </value>
public bool KeepClean
{
get
{
return _services.KeepClean;
}
set
{
var msg = _state.CheckIfAvailable(true, false, false);
if (msg != null)
{
_logger.Error(msg);
return;
}
_services.KeepClean = value;
}
}
/// <summary>
/// Gets the logging functions.
/// </summary>
/// <remarks>
/// The default logging level is <see cref="LogLevel.Error"/>. If you would like to change it,
/// you should set the <c>Log.Level</c> property to any of the <see cref="LogLevel"/> enum
/// values.
/// </remarks>
/// <value>
/// A <see cref="Logger"/> that provides the logging functions.
/// </value>
public Logger Log
{
get
{
return _logger;
}
}
/// <summary>
/// Gets the port on which to listen for incoming connection requests.
/// </summary>
/// <value>
/// An <see cref="int"/> that represents the port number on which to listen.
/// </value>
public int Port
{
get
{
return _port;
}
}
/// <summary>
/// Gets or sets the name of the realm associated with the server.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the name of the realm. The default value is
/// <c>"SECRET AREA"</c>.
/// </value>
public string Realm
{
get
{
return _realm ?? (_realm = "SECRET AREA");
}
set
{
var msg = _state.CheckIfAvailable(true, false, false);
if (msg != null)
{
_logger.Error(msg);
return;
}
_realm = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether the server is allowed to be bound to
/// an address that is already in use.
/// </summary>
/// <remarks>
/// If you would like to resolve to wait for socket in <c>TIME_WAIT</c> state,
/// you should set this property to <c>true</c>.
/// </remarks>
/// <value>
/// <c>true</c> if the server is allowed to be bound to an address that is already in use;
/// otherwise, <c>false</c>. The default value is <c>false</c>.
/// </value>
public bool ReuseAddress
{
get
{
return _reuseAddress;
}
set
{
var msg = _state.CheckIfAvailable(true, false, false);
if (msg != null)
{
_logger.Error(msg);
return;
}
_reuseAddress = value;
}
}
/// <summary>
/// Gets or sets the SSL configuration used to authenticate the server and
/// optionally the client for secure connection.
/// </summary>
/// <value>
/// A <see cref="ServerSslConfiguration"/> that represents the configuration used to
/// authenticate the server and optionally the client for secure connection.
/// </value>
public ServerSslConfiguration SslConfiguration
{
get
{
return _sslConfig ?? (_sslConfig = new ServerSslConfiguration(null));
}
set
{
var msg = _state.CheckIfAvailable(true, false, false);
if (msg != null)
{
_logger.Error(msg);
return;
}
_sslConfig = value;
}
}
/// <summary>
/// Gets or sets the delegate called to find the credentials for an identity used to
/// authenticate a client.
/// </summary>
/// <value>
/// A <c>Func<<see cref="IIdentity"/>, <see cref="NetworkCredential"/>></c> delegate that
/// references the method(s) used to find the credentials. The default value is a function that
/// only returns <see langword="null"/>.
/// </value>
public Func<IIdentity, NetworkCredential> UserCredentialsFinder
{
get
{
return _credFinder ?? (_credFinder = identity => null);
}
set
{
var msg = _state.CheckIfAvailable(true, false, false);
if (msg != null)
{
_logger.Error(msg);
return;
}
_credFinder = value;
}
}
/// <summary>
/// Gets or sets the wait time for the response to the WebSocket Ping or Close.
/// </summary>
/// <value>
/// A <see cref="TimeSpan"/> that represents the wait time. The default value is
/// the same as 1 second.
/// </value>
public TimeSpan WaitTime
{
get
{
return _services.WaitTime;
}
set
{
var msg = _state.CheckIfAvailable(true, false, false) ?? value.CheckIfValidWaitTime();
if (msg != null)
{
_logger.Error(msg);
return;
}
_services.WaitTime = value;
}
}
/// <summary>
/// Gets the access to the WebSocket services provided by the server.
/// </summary>
/// <value>
/// A <see cref="WebSocketServiceManager"/> that manages the WebSocket services.
/// </value>
public WebSocketServiceManager WebSocketServices
{
get
{
return _services;
}
}
#endregion
#region Private Methods
private void abort()
{
lock (_sync)
{
if (!IsListening)
return;
_state = ServerState.ShuttingDown;
}
_listener.Stop();
_services.Stop(new CloseEventArgs(CloseStatusCode.ServerError), true, false);
_state = ServerState.Stop;
}
private static bool authenticate(
TcpListenerWebSocketContext context,
AuthenticationSchemes scheme,
string realm,
Func<IIdentity, NetworkCredential> credentialsFinder)
{
var chal = scheme == AuthenticationSchemes.Basic
? AuthenticationChallenge.CreateBasicChallenge(realm).ToBasicString()
: scheme == AuthenticationSchemes.Digest
? AuthenticationChallenge.CreateDigestChallenge(realm).ToDigestString()
: null;
if (chal == null)
{
context.Close(HttpStatusCode.Forbidden);
return false;
}
var retry = -1;
Func<bool> auth = null;
auth = () =>
{
retry++;
if (retry > 99)
{
context.Close(HttpStatusCode.Forbidden);
return false;
}
var user = HttpUtility.CreateUser(
context.Headers["Authorization"], scheme, realm, context.HttpMethod, credentialsFinder);
if (user != null && user.Identity.IsAuthenticated)
{
context.SetUser(user);
return true;
}
context.SendAuthenticationChallenge(chal);
return auth();
};
return auth();
}
private string checkIfCertificateExists()
{
return _secure && (_sslConfig == null || _sslConfig.ServerCertificate == null)
? "The secure connection requires a server certificate."
: null;
}
private void init(string hostname, System.Net.IPAddress address, int port, bool secure, object context)
{
_hostname = hostname ?? address.ToString();
_address = address;
_port = port;
_secure = secure;
_callerContext = context;
_authSchemes = AuthenticationSchemes.Anonymous;
_dnsStyle = Uri.CheckHostName(hostname) == UriHostNameType.Dns;
_listener = new TcpListener(address, port);
_logger = new Logger();
_services = new WebSocketServiceManager(_logger);
_sync = new object();
}
private void processRequest(TcpListenerWebSocketContext context)
{
var uri = context.RequestUri;
if (uri == null || uri.Port != _port)
{
context.Close(HttpStatusCode.BadRequest);
return;
}
if (_dnsStyle)
{
var hostname = uri.DnsSafeHost;
if (Uri.CheckHostName(hostname) == UriHostNameType.Dns && hostname != _hostname)
{
context.Close(HttpStatusCode.NotFound);
return;
}
}
WebSocketServiceHost host;
if (!_services.InternalTryGetServiceHost(uri.AbsolutePath, out host))
{
context.Close(HttpStatusCode.NotImplemented);
return;
}
host.StartSession(context);
}
private void receiveRequest()
{
while (true)
{
try
{
var cl = _listener.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(
state =>
{
try
{
var ctx = cl.GetWebSocketContext(_callerContext, null, _secure, _sslConfig, _logger);
if (_authSchemes != AuthenticationSchemes.Anonymous &&
!authenticate(ctx, _authSchemes, Realm, UserCredentialsFinder))
return;
processRequest(ctx);
}
catch (Exception ex)
{
_logger.Fatal(ex.ToString());
cl.Close();
}
});
}
catch (SocketException ex)
{
_logger.Warn("Receiving has been stopped.\n reason: " + ex.Message);
break;
}
catch (Exception ex)
{
_logger.Fatal(ex.ToString());
break;
}
}
if (IsListening)
abort();
}
private void startReceiving()
{
if (_reuseAddress)
_listener.Server.SetSocketOption(
SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
_listener.Start();
_receiveThread = new Thread(new ThreadStart(receiveRequest));
_receiveThread.IsBackground = true;
_receiveThread.Start();
}
private void stopReceiving(int millisecondsTimeout)
{
_listener.Stop();
_receiveThread.Join(millisecondsTimeout);
}
private static bool tryCreateUri(string uriString, out Uri result, out string message)
{
if (!uriString.TryCreateWebSocketUri(out result, out message))
return false;
if (result.PathAndQuery != "/")
{
result = null;
message = "Includes the path or query component: " + uriString;
return false;
}
return true;
}
#endregion
#region Public Methods
/// <summary>
/// Adds a WebSocket service with the specified behavior, <paramref name="path"/>,
/// and <paramref name="initializer"/>.
/// </summary>
/// <remarks>
/// <para>
/// This method converts <paramref name="path"/> to URL-decoded string,
/// and removes <c>'/'</c> from tail end of <paramref name="path"/>.
/// </para>
/// <para>
/// <paramref name="initializer"/> returns an initialized specified typed
/// <see cref="WebSocketBehavior"/> instance.
/// </para>
/// </remarks>
/// <param name="path">
/// A <see cref="string"/> that represents the absolute path to the service to add.
/// </param>
/// <param name="initializer">
/// A <c>Func<T></c> delegate that references the method used to initialize
/// a new specified typed <see cref="WebSocketBehavior"/> instance (a new
/// <see cref="IWebSocketSession"/> instance).
/// </param>
/// <typeparam name="TBehavior">
/// The type of the behavior of the service to add. The TBehavior must inherit
/// the <see cref="WebSocketBehavior"/> class.
/// </typeparam>
public void AddWebSocketService<TBehavior>(string path, Func<TBehavior> initializer, object callerContext)
where TBehavior : WebSocketBehavior
{
var msg = path.CheckIfValidServicePath() ??
(initializer == null ? "'initializer' is null." : null);
if (msg != null)
{
_logger.Error(msg);
return;
}
_services.Add<TBehavior>(path, initializer, callerContext);
}
/// <summary>
/// Adds a WebSocket service with the specified behavior and <paramref name="path"/>.
/// </summary>
/// <remarks>
/// This method converts <paramref name="path"/> to URL-decoded string,
/// and removes <c>'/'</c> from tail end of <paramref name="path"/>.
/// </remarks>
/// <param name="path">
/// A <see cref="string"/> that represents the absolute path to the service to add.
/// </param>
/// <typeparam name="TBehaviorWithNew">
/// The type of the behavior of the service to add. The TBehaviorWithNew must inherit
/// the <see cref="WebSocketBehavior"/> class, and must have a public parameterless
/// constructor.
/// </typeparam>
public void AddWebSocketService<TBehaviorWithNew>(string path)
where TBehaviorWithNew : WebSocketBehavior, new()
{
AddWebSocketService<TBehaviorWithNew>(path, () => new TBehaviorWithNew(), _callerContext);
}
/// <summary>
/// Removes the WebSocket service with the specified <paramref name="path"/>.
/// </summary>
/// <remarks>
/// This method converts <paramref name="path"/> to URL-decoded string,
/// and removes <c>'/'</c> from tail end of <paramref name="path"/>.
/// </remarks>
/// <returns>
/// <c>true</c> if the service is successfully found and removed; otherwise, <c>false</c>.
/// </returns>
/// <param name="path">
/// A <see cref="string"/> that represents the absolute path to the service to find.
/// </param>
public bool RemoveWebSocketService(string path)
{
var msg = path.CheckIfValidServicePath();
if (msg != null)
{
_logger.Error(msg);
return false;
}
return _services.Remove(path);
}
/// <summary>
/// Starts receiving the WebSocket connection requests.
/// </summary>
public void Start()
{
lock (_sync)
{
var msg = _state.CheckIfAvailable(true, false, false) ?? checkIfCertificateExists();
if (msg != null)
{
_logger.Error(msg);
return;
}
_services.Start();
startReceiving();
_state = ServerState.Start;
}
}
/// <summary>
/// Stops receiving the WebSocket connection requests.
/// </summary>
public void Stop()
{
lock (_sync)
{
var msg = _state.CheckIfAvailable(false, true, false);
if (msg != null)
{
_logger.Error(msg);
return;
}
_state = ServerState.ShuttingDown;
}
stopReceiving(5000);
_services.Stop(new CloseEventArgs(), true, true);
_state = ServerState.Stop;
}
/// <summary>
/// Stops receiving the WebSocket connection requests with
/// the specified <see cref="ushort"/> and <see cref="string"/>.
/// </summary>
/// <param name="code">
/// A <see cref="ushort"/> that represents the status code indicating the reason for the stop.
/// </param>
/// <param name="reason">
/// A <see cref="string"/> that represents the reason for the stop.
/// </param>
public void Stop(ushort code, string reason)
{
lock (_sync)
{
var msg = _state.CheckIfAvailable(false, true, false) ??
WebSocket.CheckCloseParameters(code, reason, false);
if (msg != null)
{
_logger.Error(msg);
return;
}
_state = ServerState.ShuttingDown;
}
stopReceiving(5000);
if (code == (ushort)CloseStatusCode.NoStatus)
{
_services.Stop(new CloseEventArgs(), true, true);
}
else
{
var send = !code.IsReserved();
_services.Stop(new CloseEventArgs(code, reason), send, send);
}
_state = ServerState.Stop;
}
/// <summary>
/// Stops receiving the WebSocket connection requests with
/// the specified <see cref="CloseStatusCode"/> and <see cref="string"/>.
/// </summary>
/// <param name="code">
/// One of the <see cref="CloseStatusCode"/> enum values, represents the status code indicating
/// the reason for the stop.
/// </param>
/// <param name="reason">
/// A <see cref="string"/> that represents the reason for the stop.
/// </param>
public void Stop(CloseStatusCode code, string reason)
{
lock (_sync)
{
var msg = _state.CheckIfAvailable(false, true, false) ??
WebSocket.CheckCloseParameters(code, reason, false);
if (msg != null)
{
_logger.Error(msg);
return;
}
_state = ServerState.ShuttingDown;
}
stopReceiving(5000);
if (code == CloseStatusCode.NoStatus)
{
_services.Stop(new CloseEventArgs(), true, true);
}
else
{
var send = !code.IsReserved();
_services.Stop(new CloseEventArgs(code, reason), send, send);
}
_state = ServerState.Stop;
}
#endregion
}
}
| |
//
// Genres.cs: Provides convenience functions for converting between String
// genres and their respective audio and video indices as used by several
// formats.
//
// Author:
// Brian Nickel (brian.nickel@gmail.com)
//
// Original Source:
// id3v1genres.cpp from TagLib
//
// Copyright (C) 2005-2007 Brian Nickel
// Copyright (C) 2002 Scott Wheeler (Original Implementation)
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License version
// 2.1 as published by the Free Software Foundation.
//
// 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
//
using System.Collections;
using System;
namespace TagLib {
/// <summary>
/// This static class provides convenience functions for converting
/// between <see cref="string" /> genres and their respective audio
/// and video indices as used by several formats.
/// </summary>
public static class Genres
{
/// <summary>
/// Contains a list of ID3v1 audio generes.
/// </summary>
private static readonly string [] audio = {
"Blues",
"Classic Rock",
"Country",
"Dance",
"Disco",
"Funk",
"Grunge",
"Hip-Hop",
"Jazz",
"Metal",
"New Age",
"Oldies",
"Other",
"Pop",
"R&B",
"Rap",
"Reggae",
"Rock",
"Techno",
"Industrial",
"Alternative",
"Ska",
"Death Metal",
"Pranks",
"Soundtrack",
"Euro-Techno",
"Ambient",
"Trip-Hop",
"Vocal",
"Jazz+Funk",
"Fusion",
"Trance",
"Classical",
"Instrumental",
"Acid",
"House",
"Game",
"Sound Clip",
"Gospel",
"Noise",
"Alternative Rock",
"Bass",
"Soul",
"Punk",
"Space",
"Meditative",
"Instrumental Pop",
"Instrumental Rock",
"Ethnic",
"Gothic",
"Darkwave",
"Techno-Industrial",
"Electronic",
"Pop-Folk",
"Eurodance",
"Dream",
"Southern Rock",
"Comedy",
"Cult",
"Gangsta",
"Top 40",
"Christian Rap",
"Pop/Funk",
"Jungle",
"Native American",
"Cabaret",
"New Wave",
"Psychedelic",
"Rave",
"Showtunes",
"Trailer",
"Lo-Fi",
"Tribal",
"Acid Punk",
"Acid Jazz",
"Polka",
"Retro",
"Musical",
"Rock & Roll",
"Hard Rock",
"Folk",
"Folk/Rock",
"National Folk",
"Swing",
"Fusion",
"Bebob",
"Latin",
"Revival",
"Celtic",
"Bluegrass",
"Avantgarde",
"Gothic Rock",
"Progressive Rock",
"Psychedelic Rock",
"Symphonic Rock",
"Slow Rock",
"Big Band",
"Chorus",
"Easy Listening",
"Acoustic",
"Humour",
"Speech",
"Chanson",
"Opera",
"Chamber Music",
"Sonata",
"Symphony",
"Booty Bass",
"Primus",
"Porn Groove",
"Satire",
"Slow Jam",
"Club",
"Tango",
"Samba",
"Folklore",
"Ballad",
"Power Ballad",
"Rhythmic Soul",
"Freestyle",
"Duet",
"Punk Rock",
"Drum Solo",
"A Cappella",
"Euro-House",
"Dance Hall",
"Goa",
"Drum & Bass",
"Club-House",
"Hardcore",
"Terror",
"Indie",
"BritPop",
"Negerpunk",
"Polsk Punk",
"Beat",
"Christian Gangsta Rap",
"Heavy Metal",
"Black Metal",
"Crossover",
"Contemporary Christian",
"Christian Rock",
"Merengue",
"Salsa",
"Thrash Metal",
"Anime",
"Jpop",
"Synthpop"
};
/// <summary>
/// Contains a list of DivX audio generes.
/// </summary>
private static readonly string [] video = new string [] {
"Action",
"Action/Adventure",
"Adult",
"Adventure",
"Catastrophe",
"Child's",
"Claymation",
"Comedy",
"Concert",
"Documentary",
"Drama",
"Eastern",
"Entertaining",
"Erotic",
"Extremal Sport",
"Fantasy",
"Fashion",
"Historical",
"Horror",
"Horror/Mystic",
"Humor",
"Indian",
"Informercial",
"Melodrama",
"Military & War",
"Music Video",
"Musical",
"Mystery",
"Nature",
"Political Satire",
"Popular Science",
"Psychological Thriller",
"Religion",
"Science Fiction",
"Scifi Action",
"Slapstick",
"Splatter",
"Sports",
"Thriller",
"Western"
};
/// <summary>
/// Gets a list of standard audio generes.
/// </summary>
/// <value>
/// A <see cref="string[]" /> containing standard audio
/// genres.
/// </value>
/// <remarks>
/// The genres are stored in the same order and with the same
/// values as in the ID3v1 format.
/// </remarks>
public static string [] Audio {
get {return (string []) audio.Clone ();}
}
/// <summary>
/// Gets a list of standard video generes.
/// </summary>
/// <value>
/// A <see cref="string[]" /> containing standard video
/// genres.
/// </value>
/// <remarks>
/// The genres are stored in the same order and with the same
/// values as in the DivX format.
/// </remarks>
public static string [] Video {
get {return (string []) video.Clone ();}
}
/// <summary>
/// Gets the genre index for a specified audio genre.
/// </summary>
/// <param name="name">
/// A <see cref="string" /> object containing the name of the
/// genre to look up.
/// </param>
/// <returns>
/// A <see cref="byte" /> value containing the index of the
/// genre in the audio array or 255 if it could not be found.
/// </returns>
public static byte AudioToIndex (string name)
{
for (byte i = 0; i < audio.Length; i ++)
if (name == audio [i])
return i;
return 255;
}
/// <summary>
/// Gets the genre index for a specified video genre.
/// </summary>
/// <param name="name">
/// A <see cref="string" /> object containing the name of the
/// genre to look up.
/// </param>
/// <returns>
/// A <see cref="byte" /> value containing the index of the
/// genre in the video array or 255 if it could not be found.
/// </returns>
public static byte VideoToIndex (string name)
{
for (byte i = 0; i < video.Length; i ++)
if (name == video [i])
return i;
return 255;
}
/// <summary>
/// Gets the audio genre from its index in the array.
/// </summary>
/// <param name="index">
/// A <see cref="byte" /> value containing the index to
/// aquire the genre from.
/// </param>
/// <returns>
/// A <see cref="string" /> object containing the audio genre
/// found at the index, or <see langword="null" /> if it does
/// not exist.
/// </returns>
public static string IndexToAudio (byte index)
{
return (index < audio.Length) ? audio [index] : null;
}
/// <summary>
/// Gets the video genre from its index in the array.
/// </summary>
/// <param name="index">
/// A <see cref="byte" /> value containing the index to
/// aquire the genre from.
/// </param>
/// <returns>
/// A <see cref="string" /> object containing the video genre
/// found at the index, or <see langword="null" /> if it does
/// not exist.
/// </returns>
public static string IndexToVideo (byte index)
{
return (index < video.Length) ? video [index] : null;
}
/// <summary>
/// Gets the audio genre from its index in the array.
/// </summary>
/// <param name="text">
/// A <see cref="string" /> object, either in the format
/// <c>"(123)"</c> or <c>"123"</c>.
/// </param>
/// <returns>
/// A <see cref="string" /> object containing the audio genre
/// found at the index, or <see langword="null" /> if it does
/// not exist.
/// </returns>
public static string IndexToAudio (string text)
{
return IndexToAudio (StringToByte (text));
}
/// <summary>
/// Gets the video genre from its index in the array.
/// </summary>
/// <param name="text">
/// A <see cref="string" /> object, either in the format
/// <c>"(123)"</c> or <c>"123"</c>.
/// </param>
/// <returns>
/// A <see cref="string" /> object containing the video genre
/// found at the index, or <see langword="null" /> if it does
/// not exist.
/// </returns>
public static string IndexToVideo (string text)
{
return IndexToVideo (StringToByte (text));
}
/// <summary>
/// Converts a string, either in the format <c>"(123)"</c> or
/// <c>"123"</c> into a byte or equal numeric value.
/// </summary>
/// <param name="text">
/// A <see cref="string" /> object, either in the format
/// <c>"(123)"</c> or <c>"123"</c>, to be converted.
/// </param>
/// <returns>
/// A <see cref="byte" /> value containing the numeric value
/// of <paramref name="text" /> or 255 if no numeric value
/// could be extracted.
/// </returns>
private static byte StringToByte (string text)
{
byte value;
int last_pos;
if (text != null && text.Length > 2 && text [0] == '('
&& (last_pos = text.IndexOf (')')) != -1
&& byte.TryParse (text.Substring (1,
last_pos - 1), out value))
return value;
if (text != null && byte.TryParse (text, out value))
return value;
return 255;
}
}
}
| |
/*
* Copyright 2002-2015 Drew Noakes
*
* Modified by Yakov Danilov <yakodani@gmail.com> for Imazen LLC (Ported from Java to C#)
* 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.
*
* More information about this project is available at:
*
* https://drewnoakes.com/code/exif/
* https://github.com/drewnoakes/metadata-extractor
*/
using System.Collections.Generic;
using JetBrains.Annotations;
using Sharpen;
namespace Com.Drew.Metadata.Exif.Makernotes
{
/// <summary>Describes tags specific to Casio (type 2) cameras.</summary>
/// <remarks>
/// Describes tags specific to Casio (type 2) cameras.
/// A standard TIFF IFD directory but always uses Motorola (Big-Endian) Byte Alignment.
/// Makernote data begins after a 6-byte header: "QVC\x00\x00\x00"
/// </remarks>
/// <author>Drew Noakes https://drewnoakes.com</author>
public class CasioType2MakernoteDirectory : Com.Drew.Metadata.Directory
{
/// <summary>2 values - x,y dimensions in pixels.</summary>
public const int TagThumbnailDimensions = unchecked((int)(0x0002));
/// <summary>Size in bytes</summary>
public const int TagThumbnailSize = unchecked((int)(0x0003));
/// <summary>Offset of Preview Thumbnail</summary>
public const int TagThumbnailOffset = unchecked((int)(0x0004));
/// <summary>
/// 1 = Fine
/// 2 = Super Fine
/// </summary>
public const int TagQualityMode = unchecked((int)(0x0008));
/// <summary>
/// 0 = 640 x 480 pixels
/// 4 = 1600 x 1200 pixels
/// 5 = 2048 x 1536 pixels
/// 20 = 2288 x 1712 pixels
/// 21 = 2592 x 1944 pixels
/// 22 = 2304 x 1728 pixels
/// 36 = 3008 x 2008 pixels
/// </summary>
public const int TagImageSize = unchecked((int)(0x0009));
/// <summary>
/// 0 = Normal
/// 1 = Macro
/// </summary>
public const int TagFocusMode1 = unchecked((int)(0x000D));
/// <summary>
/// 3 = 50
/// 4 = 64
/// 6 = 100
/// 9 = 200
/// </summary>
public const int TagIsoSensitivity = unchecked((int)(0x0014));
/// <summary>
/// 0 = Auto
/// 1 = Daylight
/// 2 = Shade
/// 3 = Tungsten
/// 4 = Fluorescent
/// 5 = Manual
/// </summary>
public const int TagWhiteBalance1 = unchecked((int)(0x0019));
/// <summary>Units are tenths of a millimetre</summary>
public const int TagFocalLength = unchecked((int)(0x001D));
/// <summary>
/// 0 = -1
/// 1 = Normal
/// 2 = +1
/// </summary>
public const int TagSaturation = unchecked((int)(0x001F));
/// <summary>
/// 0 = -1
/// 1 = Normal
/// 2 = +1
/// </summary>
public const int TagContrast = unchecked((int)(0x0020));
/// <summary>
/// 0 = -1
/// 1 = Normal
/// 2 = +1
/// </summary>
public const int TagSharpness = unchecked((int)(0x0021));
/// <summary>See PIM specification here: http://www.ozhiker.com/electronics/pjmt/jpeg_info/pim.html</summary>
public const int TagPrintImageMatchingInfo = unchecked((int)(0x0E00));
/// <summary>Alternate thumbnail offset</summary>
public const int TagPreviewThumbnail = unchecked((int)(0x2000));
public const int TagWhiteBalanceBias = unchecked((int)(0x2011));
/// <summary>
/// 12 = Flash
/// 0 = Manual
/// 1 = Auto?
/// 4 = Flash?
/// </summary>
public const int TagWhiteBalance2 = unchecked((int)(0x2012));
/// <summary>Units are millimetres</summary>
public const int TagObjectDistance = unchecked((int)(0x2022));
/// <summary>0 = Off</summary>
public const int TagFlashDistance = unchecked((int)(0x2034));
/// <summary>2 = Normal Mode</summary>
public const int TagRecordMode = unchecked((int)(0x3000));
/// <summary>1 = Off?</summary>
public const int TagSelfTimer = unchecked((int)(0x3001));
/// <summary>3 = Fine</summary>
public const int TagQuality = unchecked((int)(0x3002));
/// <summary>
/// 1 = Fixation
/// 6 = Multi-Area Auto Focus
/// </summary>
public const int TagFocusMode2 = unchecked((int)(0x3003));
/// <summary>(string)</summary>
public const int TagTimeZone = unchecked((int)(0x3006));
public const int TagBestshotMode = unchecked((int)(0x3007));
/// <summary>
/// 0 = Off
/// 1 = On?
/// </summary>
public const int TagCcdIsoSensitivity = unchecked((int)(0x3014));
/// <summary>0 = Off</summary>
public const int TagColourMode = unchecked((int)(0x3015));
/// <summary>0 = Off</summary>
public const int TagEnhancement = unchecked((int)(0x3016));
/// <summary>0 = Off</summary>
public const int TagFilter = unchecked((int)(0x3017));
[NotNull]
protected internal static readonly Dictionary<int?, string> _tagNameMap = new Dictionary<int?, string>();
static CasioType2MakernoteDirectory()
{
// TODO add missing names
_tagNameMap.Put(TagThumbnailDimensions, "Thumbnail Dimensions");
_tagNameMap.Put(TagThumbnailSize, "Thumbnail Size");
_tagNameMap.Put(TagThumbnailOffset, "Thumbnail Offset");
_tagNameMap.Put(TagQualityMode, "Quality Mode");
_tagNameMap.Put(TagImageSize, "Image Size");
_tagNameMap.Put(TagFocusMode1, "Focus Mode");
_tagNameMap.Put(TagIsoSensitivity, "ISO Sensitivity");
_tagNameMap.Put(TagWhiteBalance1, "White Balance");
_tagNameMap.Put(TagFocalLength, "Focal Length");
_tagNameMap.Put(TagSaturation, "Saturation");
_tagNameMap.Put(TagContrast, "Contrast");
_tagNameMap.Put(TagSharpness, "Sharpness");
_tagNameMap.Put(TagPrintImageMatchingInfo, "Print Image Matching (PIM) Info");
_tagNameMap.Put(TagPreviewThumbnail, "Casio Preview Thumbnail");
_tagNameMap.Put(TagWhiteBalanceBias, "White Balance Bias");
_tagNameMap.Put(TagWhiteBalance2, "White Balance");
_tagNameMap.Put(TagObjectDistance, "Object Distance");
_tagNameMap.Put(TagFlashDistance, "Flash Distance");
_tagNameMap.Put(TagRecordMode, "Record Mode");
_tagNameMap.Put(TagSelfTimer, "Self Timer");
_tagNameMap.Put(TagQuality, "Quality");
_tagNameMap.Put(TagFocusMode2, "Focus Mode");
_tagNameMap.Put(TagTimeZone, "Time Zone");
_tagNameMap.Put(TagBestshotMode, "BestShot Mode");
_tagNameMap.Put(TagCcdIsoSensitivity, "CCD ISO Sensitivity");
_tagNameMap.Put(TagColourMode, "Colour Mode");
_tagNameMap.Put(TagEnhancement, "Enhancement");
_tagNameMap.Put(TagFilter, "Filter");
}
public CasioType2MakernoteDirectory()
{
this.SetDescriptor(new CasioType2MakernoteDescriptor(this));
}
[NotNull]
public override string GetName()
{
return "Casio Makernote";
}
[NotNull]
protected internal override Dictionary<int?, string> GetTagNameMap()
{
return _tagNameMap;
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// Books for Hire Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class BKHDataSet : EduHubDataSet<BKH>
{
/// <inheritdoc />
public override string Name { get { return "BKH"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal BKHDataSet(EduHubContext Context)
: base(Context)
{
Index_BKHKEY = new Lazy<Dictionary<string, BKH>>(() => this.ToDictionary(i => i.BKHKEY));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="BKH" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="BKH" /> fields for each CSV column header</returns>
internal override Action<BKH, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<BKH, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "BKHKEY":
mapper[i] = (e, v) => e.BKHKEY = v;
break;
case "TITLE":
mapper[i] = (e, v) => e.TITLE = v;
break;
case "EDITION":
mapper[i] = (e, v) => e.EDITION = v;
break;
case "AUTHOR":
mapper[i] = (e, v) => e.AUTHOR = v;
break;
case "PUBLISHER":
mapper[i] = (e, v) => e.PUBLISHER = v;
break;
case "PRICE":
mapper[i] = (e, v) => e.PRICE = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "ITEM_TYPE":
mapper[i] = (e, v) => e.ITEM_TYPE = v;
break;
case "NO_COPIES":
mapper[i] = (e, v) => e.NO_COPIES = v == null ? (short?)null : short.Parse(v);
break;
case "SEEDED_NUM":
mapper[i] = (e, v) => e.SEEDED_NUM = v == null ? (short?)null : short.Parse(v);
break;
case "AVAIL_COPIES":
mapper[i] = (e, v) => e.AVAIL_COPIES = v == null ? (short?)null : short.Parse(v);
break;
case "ISBN":
mapper[i] = (e, v) => e.ISBN = v;
break;
case "ANNOTATIONS":
mapper[i] = (e, v) => e.ANNOTATIONS = v;
break;
case "PURCHASE_DATE":
mapper[i] = (e, v) => e.PURCHASE_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "PURCHASE_PRICE":
mapper[i] = (e, v) => e.PURCHASE_PRICE = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "HIRE_FEE":
mapper[i] = (e, v) => e.HIRE_FEE = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "REMOVE":
mapper[i] = (e, v) => e.REMOVE = v;
break;
case "BOOK_MOVIE":
mapper[i] = (e, v) => e.BOOK_MOVIE = null; // eduHub is not encoding byte arrays
break;
case "BOOK_SOUND":
mapper[i] = (e, v) => e.BOOK_SOUND = null; // eduHub is not encoding byte arrays
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="BKH" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="BKH" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="BKH" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{BKH}"/> of entities</returns>
internal override IEnumerable<BKH> ApplyDeltaEntities(IEnumerable<BKH> Entities, List<BKH> DeltaEntities)
{
HashSet<string> Index_BKHKEY = new HashSet<string>(DeltaEntities.Select(i => i.BKHKEY));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.BKHKEY;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_BKHKEY.Remove(entity.BKHKEY);
if (entity.BKHKEY.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<Dictionary<string, BKH>> Index_BKHKEY;
#endregion
#region Index Methods
/// <summary>
/// Find BKH by BKHKEY field
/// </summary>
/// <param name="BKHKEY">BKHKEY value used to find BKH</param>
/// <returns>Related BKH entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public BKH FindByBKHKEY(string BKHKEY)
{
return Index_BKHKEY.Value[BKHKEY];
}
/// <summary>
/// Attempt to find BKH by BKHKEY field
/// </summary>
/// <param name="BKHKEY">BKHKEY value used to find BKH</param>
/// <param name="Value">Related BKH entity</param>
/// <returns>True if the related BKH entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByBKHKEY(string BKHKEY, out BKH Value)
{
return Index_BKHKEY.Value.TryGetValue(BKHKEY, out Value);
}
/// <summary>
/// Attempt to find BKH by BKHKEY field
/// </summary>
/// <param name="BKHKEY">BKHKEY value used to find BKH</param>
/// <returns>Related BKH entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public BKH TryFindByBKHKEY(string BKHKEY)
{
BKH value;
if (Index_BKHKEY.Value.TryGetValue(BKHKEY, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a BKH table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[BKH]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[BKH](
[BKHKEY] varchar(13) NOT NULL,
[TITLE] varchar(40) NULL,
[EDITION] varchar(20) NULL,
[AUTHOR] varchar(20) NULL,
[PUBLISHER] varchar(30) NULL,
[PRICE] money NULL,
[ITEM_TYPE] varchar(1) NULL,
[NO_COPIES] smallint NULL,
[SEEDED_NUM] smallint NULL,
[AVAIL_COPIES] smallint NULL,
[ISBN] varchar(13) NULL,
[ANNOTATIONS] varchar(MAX) NULL,
[PURCHASE_DATE] datetime NULL,
[PURCHASE_PRICE] money NULL,
[HIRE_FEE] money NULL,
[REMOVE] varchar(1) NULL,
[BOOK_MOVIE] varbinary(MAX) NULL,
[BOOK_SOUND] varbinary(MAX) NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [BKH_Index_BKHKEY] PRIMARY KEY CLUSTERED (
[BKHKEY] ASC
)
);
END");
}
/// <summary>
/// Returns null as <see cref="BKHDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns null as <see cref="BKHDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="BKH"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="BKH"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<BKH> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<string> Index_BKHKEY = new List<string>();
foreach (var entity in Entities)
{
Index_BKHKEY.Add(entity.BKHKEY);
}
builder.AppendLine("DELETE [dbo].[BKH] WHERE");
// Index_BKHKEY
builder.Append("[BKHKEY] IN (");
for (int index = 0; index < Index_BKHKEY.Count; index++)
{
if (index != 0)
builder.Append(", ");
// BKHKEY
var parameterBKHKEY = $"@p{parameterIndex++}";
builder.Append(parameterBKHKEY);
command.Parameters.Add(parameterBKHKEY, SqlDbType.VarChar, 13).Value = Index_BKHKEY[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the BKH data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the BKH data set</returns>
public override EduHubDataSetDataReader<BKH> GetDataSetDataReader()
{
return new BKHDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the BKH data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the BKH data set</returns>
public override EduHubDataSetDataReader<BKH> GetDataSetDataReader(List<BKH> Entities)
{
return new BKHDataReader(new EduHubDataSetLoadedReader<BKH>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class BKHDataReader : EduHubDataSetDataReader<BKH>
{
public BKHDataReader(IEduHubDataSetReader<BKH> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 21; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // BKHKEY
return Current.BKHKEY;
case 1: // TITLE
return Current.TITLE;
case 2: // EDITION
return Current.EDITION;
case 3: // AUTHOR
return Current.AUTHOR;
case 4: // PUBLISHER
return Current.PUBLISHER;
case 5: // PRICE
return Current.PRICE;
case 6: // ITEM_TYPE
return Current.ITEM_TYPE;
case 7: // NO_COPIES
return Current.NO_COPIES;
case 8: // SEEDED_NUM
return Current.SEEDED_NUM;
case 9: // AVAIL_COPIES
return Current.AVAIL_COPIES;
case 10: // ISBN
return Current.ISBN;
case 11: // ANNOTATIONS
return Current.ANNOTATIONS;
case 12: // PURCHASE_DATE
return Current.PURCHASE_DATE;
case 13: // PURCHASE_PRICE
return Current.PURCHASE_PRICE;
case 14: // HIRE_FEE
return Current.HIRE_FEE;
case 15: // REMOVE
return Current.REMOVE;
case 16: // BOOK_MOVIE
return Current.BOOK_MOVIE;
case 17: // BOOK_SOUND
return Current.BOOK_SOUND;
case 18: // LW_DATE
return Current.LW_DATE;
case 19: // LW_TIME
return Current.LW_TIME;
case 20: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 1: // TITLE
return Current.TITLE == null;
case 2: // EDITION
return Current.EDITION == null;
case 3: // AUTHOR
return Current.AUTHOR == null;
case 4: // PUBLISHER
return Current.PUBLISHER == null;
case 5: // PRICE
return Current.PRICE == null;
case 6: // ITEM_TYPE
return Current.ITEM_TYPE == null;
case 7: // NO_COPIES
return Current.NO_COPIES == null;
case 8: // SEEDED_NUM
return Current.SEEDED_NUM == null;
case 9: // AVAIL_COPIES
return Current.AVAIL_COPIES == null;
case 10: // ISBN
return Current.ISBN == null;
case 11: // ANNOTATIONS
return Current.ANNOTATIONS == null;
case 12: // PURCHASE_DATE
return Current.PURCHASE_DATE == null;
case 13: // PURCHASE_PRICE
return Current.PURCHASE_PRICE == null;
case 14: // HIRE_FEE
return Current.HIRE_FEE == null;
case 15: // REMOVE
return Current.REMOVE == null;
case 16: // BOOK_MOVIE
return Current.BOOK_MOVIE == null;
case 17: // BOOK_SOUND
return Current.BOOK_SOUND == null;
case 18: // LW_DATE
return Current.LW_DATE == null;
case 19: // LW_TIME
return Current.LW_TIME == null;
case 20: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // BKHKEY
return "BKHKEY";
case 1: // TITLE
return "TITLE";
case 2: // EDITION
return "EDITION";
case 3: // AUTHOR
return "AUTHOR";
case 4: // PUBLISHER
return "PUBLISHER";
case 5: // PRICE
return "PRICE";
case 6: // ITEM_TYPE
return "ITEM_TYPE";
case 7: // NO_COPIES
return "NO_COPIES";
case 8: // SEEDED_NUM
return "SEEDED_NUM";
case 9: // AVAIL_COPIES
return "AVAIL_COPIES";
case 10: // ISBN
return "ISBN";
case 11: // ANNOTATIONS
return "ANNOTATIONS";
case 12: // PURCHASE_DATE
return "PURCHASE_DATE";
case 13: // PURCHASE_PRICE
return "PURCHASE_PRICE";
case 14: // HIRE_FEE
return "HIRE_FEE";
case 15: // REMOVE
return "REMOVE";
case 16: // BOOK_MOVIE
return "BOOK_MOVIE";
case 17: // BOOK_SOUND
return "BOOK_SOUND";
case 18: // LW_DATE
return "LW_DATE";
case 19: // LW_TIME
return "LW_TIME";
case 20: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "BKHKEY":
return 0;
case "TITLE":
return 1;
case "EDITION":
return 2;
case "AUTHOR":
return 3;
case "PUBLISHER":
return 4;
case "PRICE":
return 5;
case "ITEM_TYPE":
return 6;
case "NO_COPIES":
return 7;
case "SEEDED_NUM":
return 8;
case "AVAIL_COPIES":
return 9;
case "ISBN":
return 10;
case "ANNOTATIONS":
return 11;
case "PURCHASE_DATE":
return 12;
case "PURCHASE_PRICE":
return 13;
case "HIRE_FEE":
return 14;
case "REMOVE":
return 15;
case "BOOK_MOVIE":
return 16;
case "BOOK_SOUND":
return 17;
case "LW_DATE":
return 18;
case "LW_TIME":
return 19;
case "LW_USER":
return 20;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Net.Http.Headers
{
// This type is used for headers supporting a list of values. It essentially just forwards calls to
// the actual header-store in HttpHeaders.
//
// This type can deal with a so called "special value": The RFC defines some headers which are collection of
// values, but the RFC only defines 1 value, e.g. Transfer-Encoding: chunked, Connection: close,
// Expect: 100-continue.
// We expose strongly typed properties for these special values: TransferEncodingChunked, ConnectionClose,
// ExpectContinue.
// So we have 2 properties for each of these headers ('Transfer-Encoding' => TransferEncoding,
// TransferEncodingChunked; 'Connection' => Connection, ConnectionClose; 'Expect' => Expect, ExpectContinue)
//
// The following solution was chosen:
// - Keep HttpHeaders clean: HttpHeaders is unaware of these "special values"; it just stores the collection of
// headers.
// - It is the responsibility of "higher level" components (HttpHeaderValueCollection, HttpRequestHeaders,
// HttpResponseHeaders) to deal with special values.
// - HttpHeaderValueCollection can be configured with an IEqualityComparer and a "special value".
//
// Example: Server sends header "Transfer-Encoding: gzip, custom, chunked" to the client.
// - HttpHeaders: HttpHeaders will have an entry in the header store for "Transfer-Encoding" with values
// "gzip", "custom", "chunked"
// - HttpGeneralHeaders:
// - Property TransferEncoding: has three values "gzip", "custom", and "chunked"
// - Property TransferEncodingChunked: is set to "true".
public sealed class HttpHeaderValueCollection<T> : ICollection<T> where T : class
{
private string _headerName;
private HttpHeaders _store;
private T _specialValue;
private Action<HttpHeaderValueCollection<T>, T> _validator;
public int Count
{
get { return GetCount(); }
}
public bool IsReadOnly
{
get { return false; }
}
internal bool IsSpecialValueSet
{
get
{
// If this collection instance has a "special value", then check whether that value was already set.
if (_specialValue == null)
{
return false;
}
return _store.ContainsParsedValue(_headerName, _specialValue);
}
}
internal HttpHeaderValueCollection(string headerName, HttpHeaders store)
: this(headerName, store, null, null)
{
}
internal HttpHeaderValueCollection(string headerName, HttpHeaders store,
Action<HttpHeaderValueCollection<T>, T> validator)
: this(headerName, store, null, validator)
{
}
internal HttpHeaderValueCollection(string headerName, HttpHeaders store, T specialValue)
: this(headerName, store, specialValue, null)
{
}
internal HttpHeaderValueCollection(string headerName, HttpHeaders store, T specialValue,
Action<HttpHeaderValueCollection<T>, T> validator)
{
Contract.Requires(headerName != null);
Contract.Requires(store != null);
_store = store;
_headerName = headerName;
_specialValue = specialValue;
_validator = validator;
}
public void Add(T item)
{
CheckValue(item);
_store.AddParsedValue(_headerName, item);
}
public void ParseAdd(string input)
{
_store.Add(_headerName, input);
}
public bool TryParseAdd(string input)
{
return _store.TryParseAndAddValue(_headerName, input);
}
public void Clear()
{
_store.Remove(_headerName);
}
public bool Contains(T item)
{
CheckValue(item);
return _store.ContainsParsedValue(_headerName, item);
}
public void CopyTo(T[] array, int arrayIndex)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
// Allow arrayIndex == array.Length in case our own collection is empty
if ((arrayIndex < 0) || (arrayIndex > array.Length))
{
throw new ArgumentOutOfRangeException(nameof(arrayIndex));
}
object storeValue = _store.GetParsedValues(_headerName);
if (storeValue == null)
{
return;
}
List<object> storeValues = storeValue as List<object>;
if (storeValues == null)
{
// We only have 1 value: If it is the "special value" just return, otherwise add the value to the
// array and return.
Debug.Assert(storeValue is T);
if (arrayIndex == array.Length)
{
throw new ArgumentException(SR.net_http_copyto_array_too_small);
}
array[arrayIndex] = storeValue as T;
}
else
{
storeValues.CopyTo(array, arrayIndex);
}
}
public bool Remove(T item)
{
CheckValue(item);
return _store.RemoveParsedValue(_headerName, item);
}
#region IEnumerable<T> Members
public IEnumerator<T> GetEnumerator()
{
object storeValue = _store.GetParsedValues(_headerName);
if (storeValue == null)
{
yield break;
}
List<object> storeValues = storeValue as List<object>;
if (storeValues == null)
{
Debug.Assert(storeValue is T);
yield return storeValue as T;
}
else
{
// We have multiple values. Iterate through the values and return them.
foreach (object item in storeValues)
{
Debug.Assert(item is T);
yield return item as T;
}
}
}
#endregion
#region IEnumerable Members
Collections.IEnumerator Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
public override string ToString()
{
return _store.GetHeaderString(_headerName);
}
internal string GetHeaderStringWithoutSpecial()
{
if (!IsSpecialValueSet)
{
return ToString();
}
return _store.GetHeaderString(_headerName, _specialValue);
}
internal void SetSpecialValue()
{
Debug.Assert(_specialValue != null,
"This method can only be used if the collection has a 'special value' set.");
if (!_store.ContainsParsedValue(_headerName, _specialValue))
{
_store.AddParsedValue(_headerName, _specialValue);
}
}
internal void RemoveSpecialValue()
{
Debug.Assert(_specialValue != null,
"This method can only be used if the collection has a 'special value' set.");
// We're not interested in the return value. It's OK if the "special value" wasn't in the store
// before calling RemoveParsedValue().
_store.RemoveParsedValue(_headerName, _specialValue);
}
private void CheckValue(T item)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
// If this instance has a custom validator for validating arguments, call it now.
if (_validator != null)
{
_validator(this, item);
}
}
private int GetCount()
{
// This is an O(n) operation.
object storeValue = _store.GetParsedValues(_headerName);
if (storeValue == null)
{
return 0;
}
List<object> storeValues = storeValue as List<object>;
if (storeValues == null)
{
return 1;
}
else
{
return storeValues.Count;
}
}
}
}
| |
// 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.Runtime.InteropServices;
using System.Threading;
using EnvDTE;
using EnvDTE90;
using EnvDTE90a;
using Microsoft.PythonTools;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.VisualStudioTools;
using TestUtilities;
using TestUtilities.Python;
using TestUtilities.UI;
using TestUtilities.UI.Python;
using Assert = Microsoft.VisualStudio.TestTools.UnitTesting.Assert;
using Thread = System.Threading.Thread;
namespace DebuggerUITests {
public class DebugProjectUITests {
#region Test Cases
/// <summary>
/// Loads the simple project and then unloads it, ensuring that the solution is created with a single project.
/// </summary>
public void DebugPythonProject(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
var pyService = app.ServiceProvider.GetUIThread().Invoke(() => app.ServiceProvider.GetPythonToolsService());
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, useLegacyDebugger: !useVsCodeDebugger)) {
StartHelloWorldAndBreak(app);
app.Dte.Debugger.Go(WaitForBreakOrEnd: true);
Assert.AreEqual(dbgDebugMode.dbgDesignMode, app.Dte.Debugger.CurrentMode);
}
}
/// <summary>
/// Loads a project with the startup file in a subdirectory, ensuring that syspath is correct when debugging.
/// </summary>
public void DebugPythonProjectSubFolderStartupFileSysPath(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
var pyService = app.ServiceProvider.GetUIThread().Invoke(() => app.ServiceProvider.GetPythonToolsService());
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, useLegacyDebugger: !useVsCodeDebugger)) {
var sln = app.CopyProjectForTest(@"TestData\SysPath.sln");
var project = app.OpenProject(sln);
ClearOutputWindowDebugPaneText(app);
app.Dte.ExecuteCommand("Debug.Start");
WaitForMode(app, dbgDebugMode.dbgDesignMode);
// sys.path should point to the startup file directory, not the project directory.
// this matches the behavior of start without debugging.
// Note: backslashes are escaped in the output
string testDataPath = Path.Combine(Path.GetDirectoryName(project.FullName), "Sub").Replace("\\", "\\\\");
WaitForDebugOutput(app, text => text.Contains(testDataPath));
}
}
/// <summary>
/// Debugs a project when clearing process-wide PYTHONPATH value.
/// If <see cref="DebugPythonProjectSubFolderStartupFileSysPath"/> fails
/// this test may also fail.
/// </summary>
public void DebugPythonProjectWithClearingPythonPath(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
var pyService = app.ServiceProvider.GetUIThread().Invoke(() => app.ServiceProvider.GetPythonToolsService());
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, useLegacyDebugger: !useVsCodeDebugger)) {
var sysPathSln = app.CopyProjectForTest(@"TestData\SysPath.sln");
var helloWorldSln = app.CopyProjectForTest(@"TestData\HelloWorld.sln");
var testDataPath = Path.Combine(PathUtils.GetParent(helloWorldSln), "HelloWorld").Replace("\\", "\\\\");
using (new EnvironmentVariableSetter("PYTHONPATH", testDataPath)) {
app.OpenProject(sysPathSln);
using (new PythonServiceGeneralOptionsSetter(pyService, clearGlobalPythonPath: true)) {
ClearOutputWindowDebugPaneText(app);
app.Dte.ExecuteCommand("Debug.Start");
WaitForMode(app, dbgDebugMode.dbgDesignMode);
var outputWindowText = WaitForDebugOutput(app, text => text.Contains("DONE"));
Assert.IsFalse(outputWindowText.Contains(testDataPath), outputWindowText);
}
}
}
}
/// <summary>
/// Debugs a project when not clearing a process-wide PYTHONPATH value.
/// If <see cref="DebugPythonProjectSubFolderStartupFileSysPath"/> fails
/// this test may also fail.
/// </summary>
public void DebugPythonProjectWithoutClearingPythonPath(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
var pyService = app.ServiceProvider.GetUIThread().Invoke(() => app.ServiceProvider.GetPythonToolsService());
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, useLegacyDebugger: !useVsCodeDebugger)) {
var sysPathSln = app.CopyProjectForTest(@"TestData\SysPath.sln");
var helloWorldSln = app.CopyProjectForTest(@"TestData\HelloWorld.sln");
var testDataPath = Path.Combine(PathUtils.GetParent(helloWorldSln), "HelloWorld").Replace("\\", "\\\\");
using (new EnvironmentVariableSetter("PYTHONPATH", testDataPath)) {
app.OpenProject(sysPathSln);
using (new PythonServiceGeneralOptionsSetter(pyService, clearGlobalPythonPath: false)) {
ClearOutputWindowDebugPaneText(app);
app.Dte.ExecuteCommand("Debug.Start");
WaitForMode(app, dbgDebugMode.dbgDesignMode);
WaitForDebugOutput(app, text => text.Contains(testDataPath));
}
}
}
}
/// <summary>
/// Tests using a custom interpreter path that is relative
/// </summary>
public void DebugPythonCustomInterpreter(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
var pyService = app.ServiceProvider.GetUIThread().Invoke(() => app.ServiceProvider.GetPythonToolsService());
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, useLegacyDebugger: !useVsCodeDebugger)) {
var sln = app.CopyProjectForTest(@"TestData\RelativeInterpreterPath.sln");
var project = app.OpenProject(sln, "Program.py");
var interpreterFolder = PathUtils.GetParent(sln);
var interpreterPath = Path.Combine(interpreterFolder, "Interpreter.exe");
var defaultInterpreter = app.OptionsService.DefaultInterpreter;
File.Copy(defaultInterpreter.Configuration.InterpreterPath, interpreterPath, true);
if (defaultInterpreter.Configuration.Version >= new Version(3, 0)) {
foreach (var sourceDll in FileUtils.EnumerateFiles(defaultInterpreter.Configuration.GetPrefixPath(), "python*.dll", recurse: false)) {
var targetDll = Path.Combine(interpreterFolder, Path.GetFileName(sourceDll));
File.Copy(sourceDll, targetDll, true);
}
}
app.Dte.Debugger.Breakpoints.Add(File: "Program.py", Line: 1);
app.Dte.ExecuteCommand("Debug.Start");
WaitForMode(app, dbgDebugMode.dbgBreakMode);
Assert.IsNotNull(app.Dte.Debugger.BreakpointLastHit);
Assert.AreEqual(1, app.Dte.Debugger.BreakpointLastHit.FileLine);
app.Dte.Debugger.Go(WaitForBreakOrEnd: true);
Assert.AreEqual(dbgDebugMode.dbgDesignMode, app.Dte.Debugger.CurrentMode);
}
}
/// <summary>
/// Tests using a custom interpreter path that doesn't exist
/// </summary>
public void DebugPythonCustomInterpreterMissing(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
var pyService = app.ServiceProvider.GetUIThread().Invoke(() => app.ServiceProvider.GetPythonToolsService());
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, useLegacyDebugger: !useVsCodeDebugger)) {
var sln = app.CopyProjectForTest(@"TestData\RelativeInterpreterPath.sln");
var project = app.OpenProject(sln, "Program.py");
var interpreterPath = Path.Combine(PathUtils.GetParent(sln), "Interpreter.exe");
app.Dte.ExecuteCommand("Debug.Start");
string expectedMissingInterpreterText = string.Format(
"The project cannot be launched because no Python interpreter is available at \"{0}\". Please check the " +
"Python Environments window and ensure the version of Python is installed and has all settings specified.",
interpreterPath);
var dialog = app.WaitForDialog();
app.CheckMessageBox(expectedMissingInterpreterText);
}
}
public void PendingBreakPointLocation(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
var pyService = app.ServiceProvider.GetUIThread().Invoke(() => app.ServiceProvider.GetPythonToolsService());
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, useLegacyDebugger: !useVsCodeDebugger)) {
var sln = app.CopyProjectForTest(@"TestData\DebuggerProject.sln");
var project = app.OpenProject(sln, "BreakpointInfo.py");
var bpInfo = project.ProjectItems.Item("BreakpointInfo.py");
// LSC
//project.GetPythonProject().GetAnalyzer().WaitForCompleteAnalysis(x => true);
var bp = app.Dte.Debugger.Breakpoints.Add(File: "BreakpointInfo.py", Line: 2);
Assert.AreEqual("Python", bp.Item(1).Language);
// FunctionName doesn't get queried for when adding the BP via EnvDTE, so we can't assert here :(
//Assert.AreEqual("BreakpointInfo.C", bp.Item(1).FunctionName);
bp = app.Dte.Debugger.Breakpoints.Add(File: "BreakpointInfo.py", Line: 3);
Assert.AreEqual("Python", bp.Item(1).Language);
//Assert.AreEqual("BreakpointInfo.C.f", bp.Item(1).FunctionName);
bp = app.Dte.Debugger.Breakpoints.Add(File: "BreakpointInfo.py", Line: 6);
Assert.AreEqual("Python", bp.Item(1).Language);
//Assert.AreEqual("BreakpointInfo", bp.Item(1).FunctionName);
bp = app.Dte.Debugger.Breakpoints.Add(File: "BreakpointInfo.py", Line: 7);
Assert.AreEqual("Python", bp.Item(1).Language);
//Assert.AreEqual("BreakpointInfo.f", bp.Item(1).FunctionName);
// https://github.com/Microsoft/PTVS/pull/630
// Make sure
}
}
public void BoundBreakpoint(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
var pyService = app.ServiceProvider.GetUIThread().Invoke(() => app.ServiceProvider.GetPythonToolsService());
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, useLegacyDebugger: !useVsCodeDebugger)) {
var project = OpenDebuggerProjectAndBreak(app, "BreakpointInfo.py", 2);
var pendingBp = (Breakpoint3)app.Dte.Debugger.Breakpoints.Item(1);
Assert.AreEqual(1, pendingBp.Children.Count);
var bp = (Breakpoint3)pendingBp.Children.Item(1);
Assert.AreEqual("Python", bp.Language);
Assert.AreEqual(Path.Combine(Path.GetDirectoryName(project.FullName), "BreakpointInfo.py"), bp.File);
Assert.AreEqual(2, bp.FileLine);
Assert.AreEqual(1, bp.FileColumn);
Assert.AreEqual(true, bp.Enabled);
Assert.AreEqual(true, bp.BreakWhenHit);
if (!useVsCodeDebugger) {
// Retreiving hit condition info for a breakpoint is not supported by VSCode protocol
// Note: this is NOT hit condition feature
Assert.AreEqual(1, bp.CurrentHits);
Assert.AreEqual(1, bp.HitCountTarget);
Assert.AreEqual(dbgHitCountType.dbgHitCountTypeNone, bp.HitCountType);
}
// Resetting BreakWhenHit without a message set throws a ComException, see
// https://stackoverflow.com/questions/27753513/visual-studio-sdk-breakpoint2-breakwhenhit-true-throws-exception-0x8971101a
pendingBp.Message = "foo";
pendingBp.BreakWhenHit = false; // causes rebind
Assert.AreEqual(1, pendingBp.Children.Count);
bp = (Breakpoint3)pendingBp.Children.Item(1);
Assert.AreEqual(false, bp.BreakWhenHit);
}
}
public void Step(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
var pyService = app.ServiceProvider.GetUIThread().Invoke(() => app.ServiceProvider.GetPythonToolsService());
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, useLegacyDebugger: !useVsCodeDebugger)) {
var project = OpenDebuggerProjectAndBreak(app, "SteppingTest.py", 1);
app.Dte.Debugger.StepOver(true);
WaitForMode(app, dbgDebugMode.dbgBreakMode);
Assert.AreEqual((uint)2, ((StackFrame2)app.Dte.Debugger.CurrentStackFrame).LineNumber);
app.Dte.Debugger.TerminateAll();
WaitForMode(app, dbgDebugMode.dbgDesignMode);
}
}
public void Step3(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
var pyService = app.ServiceProvider.GetUIThread().Invoke(() => app.ServiceProvider.GetPythonToolsService());
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, useLegacyDebugger: !useVsCodeDebugger)) {
var project = OpenDebuggerProjectAndBreak(app, "SteppingTest3.py", 2);
app.Dte.Debugger.StepOut(true);
WaitForMode(app, dbgDebugMode.dbgBreakMode);
Assert.AreEqual((uint)5, ((StackFrame2)app.Dte.Debugger.CurrentStackFrame).LineNumber);
app.Dte.Debugger.TerminateAll();
WaitForMode(app, dbgDebugMode.dbgDesignMode);
}
}
public void Step5(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
var pyService = app.ServiceProvider.GetUIThread().Invoke(() => app.ServiceProvider.GetPythonToolsService());
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, useLegacyDebugger: !useVsCodeDebugger)) {
var project = OpenDebuggerProjectAndBreak(app, "SteppingTest5.py", 5);
app.Dte.Debugger.StepInto(true);
WaitForMode(app, dbgDebugMode.dbgBreakMode);
Assert.AreEqual((uint)2, ((StackFrame2)app.Dte.Debugger.CurrentStackFrame).LineNumber);
app.Dte.Debugger.TerminateAll();
WaitForMode(app, dbgDebugMode.dbgDesignMode);
}
}
public void StepMultiProc(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
var pyService = app.ServiceProvider.GetUIThread().Invoke(() => app.ServiceProvider.GetPythonToolsService());
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, useLegacyDebugger: !useVsCodeDebugger)) {
var project = OpenDebuggerProjectAndBreak(app, "SteppingTest8.py", 14);
app.Dte.Debugger.StepOver(true);
WaitForMode(app, dbgDebugMode.dbgBreakMode);
Assert.AreEqual((uint)16, ((StackFrame2)app.Dte.Debugger.CurrentStackFrame).LineNumber);
app.Dte.Debugger.TerminateAll();
WaitForMode(app, dbgDebugMode.dbgDesignMode);
}
}
public void SetNextLine(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
var pyService = app.ServiceProvider.GetUIThread().Invoke(() => app.ServiceProvider.GetPythonToolsService());
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, useLegacyDebugger: !useVsCodeDebugger)) {
var project = OpenDebuggerProjectAndBreak(app, "SetNextLine.py", 7);
var doc = app.Dte.Documents.Item("SetNextLine.py");
((TextSelection)doc.Selection).GotoLine(8);
((TextSelection)doc.Selection).EndOfLine(false);
var curLine = ((TextSelection)doc.Selection).CurrentLine;
app.Dte.Debugger.SetNextStatement();
app.Dte.Debugger.StepOver(true);
WaitForMode(app, dbgDebugMode.dbgBreakMode);
Assert.AreEqual((uint)9, ((StackFrame2)app.Dte.Debugger.CurrentStackFrame).LineNumber);
var curFrame = app.Dte.Debugger.CurrentStackFrame;
if (useVsCodeDebugger) {
var locals = new List<Expression>();
foreach (Expression e in curFrame.Locals) {
locals.Add(e);
}
var local = locals.Single(e => e.Name == "y");
Assert.AreEqual("100", local.Value);
try {
locals.Single(e => e.Name == "x");
Assert.Fail("Expected exception, x should not be defined");
} catch {
}
} else {
var local = curFrame.Locals.Item("y");
Assert.AreEqual("100", local.Value);
try {
curFrame.Locals.Item("x");
Assert.Fail("Expected exception, x should not be defined");
} catch {
}
}
app.Dte.Debugger.TerminateAll();
WaitForMode(app, dbgDebugMode.dbgDesignMode);
}
}
/*
//[TestMethod, Priority(UITestPriority.P0)]
//[TestCategory("Installed")]
public void TestBreakAll() {
var project = OpenDebuggerProjectAndBreak("BreakAllTest.py", 1);
app.Dte.Debugger.Go(false);
WaitForMode(app, dbgDebugMode.dbgRunMode);
Thread.Sleep(2000);
app.Dte.Debugger.Break();
WaitForMode(app, dbgDebugMode.dbgBreakMode);
var lineNo = ((StackFrame2)app.Dte.Debugger.CurrentStackFrame).LineNumber;
Assert.IsTrue(lineNo == 1 || lineNo == 2);
app.Dte.Debugger.Go(false);
WaitForMode(app, dbgDebugMode.dbgRunMode);
app.Dte.Debugger.TerminateAll();
WaitForMode(app, dbgDebugMode.dbgDesignMode);
}*/
/// <summary>
/// Loads the simple project and then terminates the process while we're at a breakpoint.
/// </summary>
public void TerminateProcess(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
var pyService = app.ServiceProvider.GetUIThread().Invoke(() => app.ServiceProvider.GetPythonToolsService());
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, useLegacyDebugger: !useVsCodeDebugger)) {
StartHelloWorldAndBreak(app);
Assert.AreEqual(dbgDebugMode.dbgBreakMode, app.Dte.Debugger.CurrentMode);
Assert.AreEqual(1, app.Dte.Debugger.BreakpointLastHit.FileLine);
app.Dte.Debugger.TerminateAll();
WaitForMode(app, dbgDebugMode.dbgDesignMode);
}
}
/// <summary>
/// Loads the simple project and makes sure we get the correct module.
/// </summary>
public void EnumModules(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
var pyService = app.ServiceProvider.GetUIThread().Invoke(() => app.ServiceProvider.GetPythonToolsService());
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, useLegacyDebugger: !useVsCodeDebugger)) {
StartHelloWorldAndBreak(app);
var modules = ((Process3)app.Dte.Debugger.CurrentProcess).Modules;
Assert.IsTrue(modules.Count >= 1);
var module = modules.Item("__main__");
Assert.IsNotNull(module);
Assert.IsTrue(module.Path.EndsWith("Program.py", StringComparison.OrdinalIgnoreCase));
Assert.AreEqual("__main__", module.Name);
Assert.AreNotEqual((uint)0, module.Order);
app.Dte.Debugger.TerminateAll();
WaitForMode(app, dbgDebugMode.dbgDesignMode);
}
}
public void MainThread(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
var pyService = app.ServiceProvider.GetUIThread().Invoke(() => app.ServiceProvider.GetPythonToolsService());
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, useLegacyDebugger: !useVsCodeDebugger)) {
StartHelloWorldAndBreak(app);
var thread = ((Thread2)app.Dte.Debugger.CurrentThread);
Assert.AreEqual("MainThread", thread.Name);
Assert.AreEqual(0, thread.SuspendCount);
Assert.AreEqual("Normal", thread.Priority);
Assert.AreEqual("MainThread", thread.DisplayName);
thread.DisplayName = "Hi";
Assert.AreEqual("Hi", thread.DisplayName);
app.Dte.Debugger.TerminateAll();
WaitForMode(app, dbgDebugMode.dbgDesignMode);
}
}
public void ExpressionEvaluation(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
var pyService = app.ServiceProvider.GetUIThread().Invoke(() => app.ServiceProvider.GetPythonToolsService());
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, useLegacyDebugger: !useVsCodeDebugger)) {
OpenDebuggerProject(app, "Program.py");
app.Dte.Debugger.Breakpoints.Add(File: "Program.py", Line: 14);
app.Dte.ExecuteCommand("Debug.Start");
WaitForMode(app, dbgDebugMode.dbgBreakMode);
Assert.AreEqual(14, app.Dte.Debugger.BreakpointLastHit.FileLine);
Assert.AreEqual("i", app.Dte.Debugger.GetExpression("i").Name);
Assert.AreEqual("42", app.Dte.Debugger.GetExpression("i").Value);
Assert.AreEqual("int", app.Dte.Debugger.GetExpression("i").Type);
Assert.IsTrue(app.Dte.Debugger.GetExpression("i").IsValidValue);
Assert.AreEqual(0, app.Dte.Debugger.GetExpression("i").DataMembers.Count);
var curFrame = app.Dte.Debugger.CurrentStackFrame;
if (useVsCodeDebugger) {
var locals = new List<Expression>();
foreach (Expression e in curFrame.Locals) {
locals.Add(e);
}
var local = locals.Single(e => e.Name == "i");
Assert.AreEqual("42", local.Value);
local = locals.Single(e => e.Name == "l");
// Experimental debugger includes methods + values now, and that's different on Python 2 and 3
Assert.AreEqual(interpreter.Contains("Python27") ? 49 : 50, local.DataMembers.Count);
// TODO: re-enable this when the sorting of list members is corrected
// (right now it's methods followed by values)
//Assert.AreEqual("0", local.DataMembers.Item(1).Name);
// TODO: Uncomment line after this is done
// https://github.com/Microsoft/ptvsd/issues/316
// Assert.AreEqual("Program", ((StackFrame2)curFrame).Module);
// TODO: Experimental debugger does not support separating locals and arguments
// Assert.AreEqual(3, ((StackFrame2)curFrame).Arguments.Count);
// Assert.AreEqual("a", ((StackFrame2)curFrame).Arguments.Item(1).Name);
// Assert.AreEqual("2", ((StackFrame2)curFrame).Arguments.Item(1).Value);
// The result of invalid expressions is a error message in the experimental debugger
var invalidExpr = ((Debugger3)app.Dte.Debugger).GetExpression("invalid expression");
Assert.IsTrue(invalidExpr.Value.StartsWith("SyntaxError"));
// Experimental debugger treats the request for evalautions as succeeded. Any errors
// such as syntax errors are reported as valid results. A failure indicates that the debugger
// failed to handle the request.
Assert.IsTrue(invalidExpr.IsValidValue);
} else {
var local = curFrame.Locals.Item("i");
Assert.AreEqual("42", local.Value);
Assert.AreEqual(3, curFrame.Locals.Item("l").DataMembers.Count);
Assert.AreEqual("[0]", curFrame.Locals.Item("l").DataMembers.Item(1).Name);
Assert.AreEqual("Program", ((StackFrame2)curFrame).Module);
Assert.AreEqual(3, ((StackFrame2)curFrame).Arguments.Count);
Assert.AreEqual("a", ((StackFrame2)curFrame).Arguments.Item(1).Name);
Assert.AreEqual("2", ((StackFrame2)curFrame).Arguments.Item(1).Value);
var invalidExpr = ((Debugger3)app.Dte.Debugger).GetExpression("invalid expression");
var str = invalidExpr.Value;
Assert.IsFalse(invalidExpr.IsValidValue);
}
Assert.AreEqual("f", curFrame.FunctionName);
Assert.IsTrue(((StackFrame2)curFrame).FileName.EndsWith("Program.py"));
Assert.AreEqual((uint)14, ((StackFrame2)curFrame).LineNumber);
var expr = ((Debugger3)app.Dte.Debugger).GetExpression("l[0] + l[1]");
Assert.AreEqual("l[0] + l[1]", expr.Name);
Assert.AreEqual("5", expr.Value);
app.Dte.Debugger.ExecuteStatement("x = 2");
app.Dte.Debugger.TerminateAll();
WaitForMode(app, dbgDebugMode.dbgDesignMode);
}
}
public void SimpleException(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
var pyService = app.ServiceProvider.GetUIThread().Invoke(() => app.ServiceProvider.GetPythonToolsService());
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, useLegacyDebugger: !useVsCodeDebugger)) {
string exceptionDescription = useVsCodeDebugger ? "" : "Exception";
ExceptionTest(app, "SimpleException.py", exceptionDescription, "Exception", 3);
}
}
public void SimpleException2(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
var pyService = app.ServiceProvider.GetUIThread().Invoke(() => app.ServiceProvider.GetPythonToolsService());
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, useLegacyDebugger: !useVsCodeDebugger)) {
string exceptionDescription = useVsCodeDebugger ? "bad value" : "ValueError: bad value";
ExceptionTest(app, "SimpleException2.py", exceptionDescription, "ValueError", 3);
}
}
public void SimpleExceptionUnhandled(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, waitOnAbnormalExit: false, useLegacyDebugger: !useVsCodeDebugger)) {
string exceptionDescription = useVsCodeDebugger ? "bad value" : "ValueError: bad value";
ExceptionTest(app, "SimpleExceptionUnhandled.py", exceptionDescription, "ValueError", 2, true);
}
}
// https://github.com/Microsoft/PTVS/issues/275
public void ExceptionInImportLibNotReported(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
var pyService = app.ServiceProvider.GetUIThread().Invoke(() => app.ServiceProvider.GetPythonToolsService());
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, useLegacyDebugger: !useVsCodeDebugger))
using (new DebuggingGeneralOptionsSetter(app.Dte, enableJustMyCode: true)) {
OpenDebuggerProjectAndBreak(app, "ImportLibException.py", 2);
app.Dte.Debugger.Go(WaitForBreakOrEnd: true);
Assert.AreEqual(dbgDebugMode.dbgDesignMode, app.Dte.Debugger.CurrentMode);
}
}
public void Breakpoints(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
var pyService = app.ServiceProvider.GetUIThread().Invoke(() => app.ServiceProvider.GetPythonToolsService());
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, useLegacyDebugger: !useVsCodeDebugger)) {
OpenDebuggerProjectAndBreak(app, "BreakpointTest2.py", 3);
var debug3 = (Debugger3)app.Dte.Debugger;
Assert.AreEqual((uint)3, ((StackFrame2)debug3.CurrentThread.StackFrames.Item(1)).LineNumber);
debug3.Go(true);
Assert.AreEqual((uint)3, ((StackFrame2)debug3.CurrentThread.StackFrames.Item(1)).LineNumber);
Assert.IsTrue(debug3.Breakpoints.Item(1).Enabled);
debug3.Breakpoints.Item(1).Delete();
debug3.Go(true);
WaitForMode(app, dbgDebugMode.dbgDesignMode);
}
}
public void BreakpointsDisable(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
var pyService = app.ServiceProvider.GetUIThread().Invoke(() => app.ServiceProvider.GetPythonToolsService());
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, useLegacyDebugger: !useVsCodeDebugger)) {
OpenDebuggerProjectAndBreak(app, "BreakpointTest4.py", 2);
var debug3 = (Debugger3)app.Dte.Debugger;
Assert.AreEqual((uint)2, ((StackFrame2)debug3.CurrentThread.StackFrames.Item(1)).LineNumber);
if (useVsCodeDebugger) {
Thread.Sleep(TimeSpan.FromSeconds(1));
}
debug3.Go(true);
Assert.AreEqual((uint)2, ((StackFrame2)debug3.CurrentThread.StackFrames.Item(1)).LineNumber);
Assert.IsTrue(debug3.Breakpoints.Item(1).Enabled);
debug3.Breakpoints.Item(1).Enabled = false;
if (useVsCodeDebugger) {
Thread.Sleep(TimeSpan.FromSeconds(1));
}
debug3.Go(true);
WaitForMode(app, dbgDebugMode.dbgDesignMode);
}
}
public void BreakpointsDisableReenable(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
var pyService = app.ServiceProvider.GetUIThread().Invoke(() => app.ServiceProvider.GetPythonToolsService());
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, useLegacyDebugger: !useVsCodeDebugger)) {
var debug3 = (Debugger3)app.Dte.Debugger;
OpenDebuggerProjectAndBreak(app, "BreakpointTest4.py", 2);
Assert.AreEqual((uint)2, ((StackFrame2)debug3.CurrentThread.StackFrames.Item(1)).LineNumber);
debug3.Go(true);
Assert.AreEqual((uint)2, ((StackFrame2)debug3.CurrentThread.StackFrames.Item(1)).LineNumber);
int bpCount = debug3.Breakpoints.Count;
Assert.AreEqual(1, bpCount);
Assert.IsTrue(debug3.Breakpoints.Item(1).Enabled);
Assert.AreEqual(2, debug3.Breakpoints.Item(1).FileLine);
debug3.Breakpoints.Item(1).Enabled = false;
debug3.Breakpoints.Add(File: "BreakpointTest4.py", Line: 4);
debug3.Breakpoints.Add(File: "BreakpointTest4.py", Line: 5);
Assert.AreEqual(4, debug3.Breakpoints.Item(2).FileLine);
Assert.AreEqual(5, debug3.Breakpoints.Item(3).FileLine);
// line 4
debug3.Go(true);
WaitForMode(app, dbgDebugMode.dbgBreakMode);
Assert.AreEqual((uint)4, ((StackFrame2)debug3.CurrentThread.StackFrames.Item(1)).LineNumber);
// line 5
debug3.Go(true);
WaitForMode(app, dbgDebugMode.dbgBreakMode);
Assert.AreEqual((uint)5, ((StackFrame2)debug3.CurrentThread.StackFrames.Item(1)).LineNumber);
debug3.Breakpoints.Item(3).Enabled = false;
// back to line 4
debug3.Go(true);
WaitForMode(app, dbgDebugMode.dbgBreakMode);
Assert.AreEqual((uint)4, ((StackFrame2)debug3.CurrentThread.StackFrames.Item(1)).LineNumber);
debug3.Go(true);
WaitForMode(app, dbgDebugMode.dbgBreakMode);
Assert.AreEqual((uint)4, ((StackFrame2)debug3.CurrentThread.StackFrames.Item(1)).LineNumber);
debug3.Breakpoints.Item(2).Enabled = false;
debug3.Breakpoints.Item(3).Enabled = true;
// back to line 5
debug3.Go(true);
WaitForMode(app, dbgDebugMode.dbgBreakMode);
Assert.AreEqual((uint)5, ((StackFrame2)debug3.CurrentThread.StackFrames.Item(1)).LineNumber);
debug3.Breakpoints.Item(3).Enabled = false;
// all disabled, run to completion
debug3.Go(true);
WaitForMode(app, dbgDebugMode.dbgDesignMode);
}
}
/// <summary>
/// Make sure the presence of errors causes F5 to prevent running w/o a confirmation.
/// </summary>
public void LaunchWithErrorsDontRun(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
var pyService = app.ServiceProvider.GetUIThread().Invoke(() => app.ServiceProvider.GetPythonToolsService());
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, useLegacyDebugger: !useVsCodeDebugger, promptBeforeRunningWithBuildErrorSetting: true)) {
var sln = app.CopyProjectForTest(@"TestData\ErrorProject.sln");
var project = app.OpenProject(sln);
var projectDir = PathUtils.GetParent(project.FullName);
// Open a file with errors
string scriptFilePath = Path.Combine(projectDir, "Program.py");
app.Dte.ItemOperations.OpenFile(scriptFilePath);
app.Dte.ExecuteCommand("View.ErrorList");
var items = app.WaitForErrorListItems(7);
var debug3 = (Debugger3)app.Dte.Debugger;
debug3.Go(true);
var dialog = new PythonLaunchWithErrorsDialog(app.WaitForDialog());
dialog.No();
// make sure we don't go into debug mode
for (int i = 0; i < 10; i++) {
Assert.AreEqual(dbgDebugMode.dbgDesignMode, app.Dte.Debugger.CurrentMode);
System.Threading.Thread.Sleep(100);
}
WaitForMode(app, dbgDebugMode.dbgDesignMode);
}
}
/// <summary>
/// Start with debugging, with script but no project.
/// </summary>
public void StartWithDebuggingNoProject(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
var pyService = app.ServiceProvider.GetUIThread().Invoke(() => app.ServiceProvider.GetPythonToolsService());
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, useLegacyDebugger: !useVsCodeDebugger)) {
string scriptFilePath = TestData.GetPath(@"TestData\HelloWorld\Program.py");
app.DeleteAllBreakPoints();
app.Dte.ItemOperations.OpenFile(scriptFilePath);
app.Dte.Debugger.Breakpoints.Add(File: scriptFilePath, Line: 1);
app.Dte.ExecuteCommand("Python.StartWithDebugging");
WaitForMode(app, dbgDebugMode.dbgBreakMode);
Assert.AreEqual(dbgDebugMode.dbgBreakMode, app.Dte.Debugger.CurrentMode);
Assert.IsNotNull(app.Dte.Debugger.BreakpointLastHit);
Assert.AreEqual("Program.py, line 1 character 1", app.Dte.Debugger.BreakpointLastHit.Name);
app.Dte.Debugger.Go(WaitForBreakOrEnd: true);
Assert.AreEqual(dbgDebugMode.dbgDesignMode, app.Dte.Debugger.CurrentMode);
}
}
/// <summary>
/// Start without debugging, with script but no project.
/// </summary>
public void StartWithoutDebuggingNoProject(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
var pyService = app.ServiceProvider.GetUIThread().Invoke(() => app.ServiceProvider.GetPythonToolsService());
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, useLegacyDebugger: !useVsCodeDebugger)) {
var tempFolder = TestData.GetTempPath();
string scriptFilePath = Path.Combine(tempFolder, "CreateFile1.py");
string resultFilePath = Path.Combine(tempFolder, "File1.txt");
File.Copy(TestData.GetPath(@"TestData\CreateFile1.py"), scriptFilePath, true);
app.DeleteAllBreakPoints();
app.Dte.ItemOperations.OpenFile(scriptFilePath);
app.Dte.Debugger.Breakpoints.Add(File: scriptFilePath, Line: 1);
app.Dte.ExecuteCommand("Python.StartWithoutDebugging");
Assert.AreEqual(dbgDebugMode.dbgDesignMode, app.Dte.Debugger.CurrentMode);
WaitForFileCreatedByScript(resultFilePath);
}
}
/// <summary>
/// Start with debugging, with script not in project.
/// </summary>
public void StartWithDebuggingNotInProject(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
var pyService = app.ServiceProvider.GetUIThread().Invoke(() => app.ServiceProvider.GetPythonToolsService());
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, useLegacyDebugger: !useVsCodeDebugger)) {
string scriptFilePath = TestData.GetPath(@"TestData\HelloWorld\Program.py");
OpenDebuggerProject(app);
app.Dte.ItemOperations.OpenFile(scriptFilePath);
app.Dte.Debugger.Breakpoints.Add(File: scriptFilePath, Line: 1);
app.Dte.ExecuteCommand("Python.StartWithDebugging");
WaitForMode(app, dbgDebugMode.dbgBreakMode);
Assert.AreEqual(dbgDebugMode.dbgBreakMode, app.Dte.Debugger.CurrentMode);
Assert.AreEqual("Program.py, line 1 character 1", app.Dte.Debugger.BreakpointLastHit.Name);
app.Dte.Debugger.Go(WaitForBreakOrEnd: true);
Assert.AreEqual(dbgDebugMode.dbgDesignMode, app.Dte.Debugger.CurrentMode);
}
}
/// <summary>
/// Start without debugging, with script not in project.
/// </summary>
public void StartWithoutDebuggingNotInProject(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
var pyService = app.ServiceProvider.GetUIThread().Invoke(() => app.ServiceProvider.GetPythonToolsService());
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, useLegacyDebugger: !useVsCodeDebugger)) {
var tempFolder = TestData.GetTempPath();
string scriptFilePath = Path.Combine(tempFolder, "CreateFile2.py");
string resultFilePath = Path.Combine(tempFolder, "File2.txt");
File.Copy(TestData.GetPath(@"TestData\CreateFile2.py"), scriptFilePath, true);
OpenDebuggerProject(app);
app.Dte.ItemOperations.OpenFile(scriptFilePath);
app.Dte.Debugger.Breakpoints.Add(File: scriptFilePath, Line: 1);
app.Dte.ExecuteCommand("Python.StartWithoutDebugging");
Assert.AreEqual(dbgDebugMode.dbgDesignMode, app.Dte.Debugger.CurrentMode);
WaitForFileCreatedByScript(resultFilePath);
}
}
/// <summary>
/// Start with debuggging, with script in project.
/// </summary>
public void StartWithDebuggingInProject(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
var pyService = app.ServiceProvider.GetUIThread().Invoke(() => app.ServiceProvider.GetPythonToolsService());
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, useLegacyDebugger: !useVsCodeDebugger)) {
var proj = OpenDebuggerProject(app);
var projDir = PathUtils.GetParent(proj.FullName);
var scriptFilePath = Path.Combine(projDir, "Program.py");
app.Dte.ItemOperations.OpenFile(scriptFilePath);
app.Dte.Debugger.Breakpoints.Add(File: scriptFilePath, Line: 1);
app.Dte.ExecuteCommand("Python.StartWithDebugging");
WaitForMode(app, dbgDebugMode.dbgBreakMode);
Assert.AreEqual(dbgDebugMode.dbgBreakMode, app.Dte.Debugger.CurrentMode);
Assert.AreEqual("Program.py, line 1 character 1", app.Dte.Debugger.BreakpointLastHit.Name);
app.Dte.Debugger.Go(WaitForBreakOrEnd: true);
Assert.AreEqual(dbgDebugMode.dbgDesignMode, app.Dte.Debugger.CurrentMode);
}
}
/// <summary>
/// Start with debuggging, with script in subfolder project.
/// </summary>
public void StartWithDebuggingSubfolderInProject(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
var pyService = app.ServiceProvider.GetUIThread().Invoke(() => app.ServiceProvider.GetPythonToolsService());
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, useLegacyDebugger: !useVsCodeDebugger)) {
var proj = OpenDebuggerProject(app);
var projDir = PathUtils.GetParent(proj.FullName);
var scriptFilePath = Path.Combine(projDir, "Sub", "paths.py");
var expectedProjDir = "'" + PathUtils.TrimEndSeparator(projDir).Replace("\\", "\\\\") + "'";
app.Dte.ItemOperations.OpenFile(scriptFilePath);
app.Dte.Debugger.Breakpoints.Add(File: scriptFilePath, Line: 3);
app.Dte.ExecuteCommand("Python.StartWithDebugging");
WaitForMode(app, dbgDebugMode.dbgBreakMode);
Assert.AreEqual(dbgDebugMode.dbgBreakMode, app.Dte.Debugger.CurrentMode);
AssertUtil.ContainsAtLeast(
app.Dte.Debugger.GetExpression("sys.path").DataMembers.Cast<Expression>().Select(e => e.Value),
expectedProjDir
);
Assert.AreEqual(
expectedProjDir,
app.Dte.Debugger.GetExpression("os.path.abspath(os.curdir)").Value
);
app.Dte.Debugger.Go(WaitForBreakOrEnd: true);
Assert.AreEqual(dbgDebugMode.dbgDesignMode, app.Dte.Debugger.CurrentMode);
}
}
/// <summary>
/// Start without debuggging, with script in project.
/// </summary>
public void StartWithoutDebuggingInProject(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
var pyService = app.ServiceProvider.GetUIThread().Invoke(() => app.ServiceProvider.GetPythonToolsService());
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, useLegacyDebugger: !useVsCodeDebugger)) {
var proj = OpenDebuggerProject(app);
var projDir = PathUtils.GetParent(proj.FullName);
var scriptFilePath = Path.Combine(projDir, "CreateFile3.py");
var resultFilePath = Path.Combine(projDir, "File3.txt");
app.Dte.ItemOperations.OpenFile(scriptFilePath);
app.Dte.Debugger.Breakpoints.Add(File: scriptFilePath, Line: 1);
app.Dte.ExecuteCommand("Python.StartWithoutDebugging");
Assert.AreEqual(dbgDebugMode.dbgDesignMode, app.Dte.Debugger.CurrentMode);
WaitForFileCreatedByScript(resultFilePath);
}
}
/// <summary>
/// Start with debugging, no script.
/// </summary>
public void StartWithDebuggingNoScript(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
var pyService = app.ServiceProvider.GetUIThread().Invoke(() => app.ServiceProvider.GetPythonToolsService());
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, useLegacyDebugger: !useVsCodeDebugger)) {
try {
app.ExecuteCommand("Python.StartWithDebugging");
} catch (COMException e) {
// Requires an opened python file with focus
Assert.IsTrue(e.ToString().Contains("is not available"));
}
}
}
/// <summary>
/// Start without debugging, no script.
/// </summary>
public void StartWithoutDebuggingNoScript(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
var pyService = app.ServiceProvider.GetUIThread().Invoke(() => app.ServiceProvider.GetPythonToolsService());
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, useLegacyDebugger: !useVsCodeDebugger)) {
try {
app.ExecuteCommand("Python.StartWithoutDebugging");
} catch (COMException e) {
// Requires an opened python file with focus
Assert.IsTrue(e.ToString().Contains("is not available"));
}
}
}
public void WebProjectLauncherNoStartupFile(PythonVisualStudioApp app, bool useVsCodeDebugger, string interpreter, DotNotWaitOnNormalExit optionSetter) {
var pyService = app.ServiceProvider.GetUIThread().Invoke(() => app.ServiceProvider.GetPythonToolsService());
using (SelectDefaultInterpreter(app, interpreter))
using (new PythonOptionsSetter(app.Dte, useLegacyDebugger: !useVsCodeDebugger)) {
var project = app.CreateProject(
PythonVisualStudioApp.TemplateLanguageName,
PythonVisualStudioApp.EmptyWebProjectTemplate,
TestData.GetTempPath(),
"NewWebProject"
);
foreach (var cmd in new[] { "Debug.Start", "Debug.StartWithoutDebugging" }) {
app.Dte.ExecuteCommand(cmd);
app.CheckMessageBox("The project cannot be launched because the startup file is not specified.");
}
}
}
#endregion
#region Helpers
public class DotNotWaitOnNormalExit : PythonOptionsSetter {
public DotNotWaitOnNormalExit(DTE dte) :
base(dte, waitOnNormalExit: false) {
}
}
private static void WaitForFileCreatedByScript(string createdFilePath) {
bool exists = false;
for (int i = 0; i < 10; i++) {
exists = File.Exists(createdFilePath);
if (exists) {
break;
}
System.Threading.Thread.Sleep(250);
}
Assert.IsTrue(exists, "Python script was expected to create file '{0}'.", createdFilePath);
}
private static void ExceptionTest(PythonVisualStudioApp app, string filename, string expectedDescription, string exceptionType, int expectedLine, bool isUnhandled=false) {
var debug3 = (Debugger3)app.Dte.Debugger;
using (new DebuggingGeneralOptionsSetter(app.Dte, enableJustMyCode: true)) {
OpenDebuggerProject(app, filename);
var exceptionSettings = debug3.ExceptionGroups.Item("Python Exceptions");
if (!isUnhandled) {
exceptionSettings.SetBreakWhenThrown(true, exceptionSettings.Item(exceptionType));
}
app.Dte.ExecuteCommand("Debug.Start");
WaitForMode(app, dbgDebugMode.dbgBreakMode);
exceptionSettings.SetBreakWhenThrown(false, exceptionSettings.Item(exceptionType));
exceptionSettings.SetBreakWhenThrown(true, exceptionSettings.Item(exceptionType));
debug3.ExceptionGroups.ResetAll();
var excepAdorner = app.WaitForExceptionAdornment();
AutomationWrapper.DumpElement(excepAdorner.Element);
Assert.AreEqual(expectedDescription, excepAdorner.Description.TrimEnd());
Assert.AreEqual((uint)expectedLine, ((StackFrame2)debug3.CurrentThread.StackFrames.Item(1)).LineNumber);
debug3.Go(WaitForBreakOrEnd: true);
WaitForMode(app, dbgDebugMode.dbgDesignMode);
}
}
internal static Project OpenDebuggerProject(VisualStudioApp app, string startItem = null) {
var solutionPath = app.CopyProjectForTest(@"TestData\DebuggerProject.sln");
return app.OpenProject(solutionPath, startItem);
}
private static Project OpenDebuggerProjectAndBreak(VisualStudioApp app, string startItem, int lineNo, bool setStartupItem = true) {
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("PTVS_TEST_DEBUGADAPTER_LOGGING_ENABLED"))) {
app.ExecuteCommand("DebugAdapterHost.Logging /On");
}
return OpenProjectAndBreak(app, @"TestData\DebuggerProject.sln", startItem, lineNo);
}
private static void ClearOutputWindowDebugPaneText(VisualStudioApp app) {
OutputWindow window = ((EnvDTE80.DTE2)app.Dte).ToolWindows.OutputWindow;
OutputWindowPane debugPane = window.OutputWindowPanes.Item("Debug");
debugPane.Clear();
}
private static string WaitForDebugOutput(VisualStudioApp app, Predicate<string> condition) {
var uiThread = app.ServiceProvider.GetUIThread();
var text = uiThread.Invoke(() => app.GetOutputWindowText("Debug"));
for (int i = 0; i < 50 && !condition(text); i++) {
Thread.Sleep(100);
text = uiThread.Invoke(() => app.GetOutputWindowText("Debug"));
}
Assert.IsTrue(condition(text));
return text;
}
private static void StartHelloWorldAndBreak(VisualStudioApp app) {
OpenProjectAndBreak(app, @"TestData\HelloWorld.sln", "Program.py", 1);
}
internal static Project OpenProjectAndBreak(VisualStudioApp app, string projName, string filename, int lineNo, bool setStartupItem = true) {
var projectPath = app.CopyProjectForTest(projName);
var project = app.OpenProject(projectPath, filename, setStartupItem: setStartupItem);
app.Dte.Debugger.Breakpoints.Add(File: filename, Line: lineNo);
app.Dte.ExecuteCommand("Debug.Start");
WaitForMode(app, dbgDebugMode.dbgBreakMode);
Assert.IsNotNull(app.Dte.Debugger.BreakpointLastHit);
Assert.AreEqual(lineNo, app.Dte.Debugger.BreakpointLastHit.FileLine);
return project;
}
internal static void WaitForMode(VisualStudioApp app, dbgDebugMode mode) {
for (int i = 0; i < 30 && app.Dte.Debugger.CurrentMode != mode; i++) {
Thread.Sleep(1000);
}
Assert.AreEqual(mode, app.Dte.Debugger.CurrentMode);
}
class EmptyDisposable : IDisposable {
public void Dispose() {
}
}
private static IDisposable SelectDefaultInterpreter(PythonVisualStudioApp app, string pythonVersion) {
if (string.IsNullOrEmpty(pythonVersion)) {
// Test wants to use the existing global default
return new EmptyDisposable();
}
return app.SelectDefaultInterpreter(FindInterpreter(pythonVersion));
}
private static PythonVersion FindInterpreter(string pythonVersion) {
var interpreter = PythonPaths.GetVersionsByName(pythonVersion).FirstOrDefault();
if (interpreter == null) {
Assert.Inconclusive($"Interpreter '{pythonVersion}' not installed.");
}
return interpreter;
}
#endregion
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections;
using System.Globalization;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Cache;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using OpenLiveWriter.CoreServices.Diagnostics;
using OpenLiveWriter.CoreServices.HTML;
namespace OpenLiveWriter.CoreServices
{
/// <summary>
/// Delegate for augmenting and HTTP request.
/// </summary>
public delegate void HttpRequestFilter(HttpWebRequest request);
/// <summary>
/// Utility class for doing HTTP requests -- uses the Feeds Proxy settings (if any) for requests
/// </summary>
public class HttpRequestHelper
{
static HttpRequestHelper()
{
// This is necessary to avoid problems connecting to Blogger server from behind a proxy.
ServicePointManager.Expect100Continue = false;
try
{
// Add WSSE support everywhere.
AuthenticationManager.Register(new WsseAuthenticationModule());
}
catch (InvalidOperationException)
{
// See http://blogs.msdn.com/shawnfa/archive/2005/05/16/417975.aspx
Trace.WriteLine("Warning: WSSE support disabled");
}
if (ApplicationDiagnostics.AllowUnsafeCertificates)
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
}
}
private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors != SslPolicyErrors.None)
{
Trace.WriteLine("SSL Policy error " + sslPolicyErrors);
}
return true;
}
public static void TrackResponseClosing(ref HttpWebRequest req)
{
CloseTrackingHttpWebRequest.Wrap(ref req);
}
/// <summary>
/// Download a file and return a path to it -- returns null if the file
/// could not be found or any other error occurs
/// </summary>
/// <param name="fileUrl">file url</param>
/// <returns>path to file or null if it could not be downloaded</returns>
public static Stream SafeDownloadFile(string fileUrl)
{
string responseUri;
return SafeDownloadFile(fileUrl, out responseUri, null);
}
public static Stream SafeDownloadFile(string fileUrl, out string responseUri)
{
return SafeDownloadFile(fileUrl, out responseUri, null);
}
public static Stream SafeDownloadFile(string fileUrl, out string responseUri, HttpRequestFilter filter)
{
responseUri = null;
try
{
HttpWebResponse response = SafeSendRequest(fileUrl, filter);
if (response != null)
{
responseUri = UrlHelper.SafeToAbsoluteUri(response.ResponseUri);
return response.GetResponseStream();
}
else
return null;
}
catch (Exception ex)
{
Trace.WriteLine("Unable to download file \"" + fileUrl + "\" during Blog service detection: " + ex.ToString());
return null;
}
}
public static HttpWebResponse SendRequest(string requestUri)
{
return SendRequest(requestUri, null);
}
public static HttpWebResponse SendRequest(string requestUri, HttpRequestFilter filter)
{
HttpWebRequest request = CreateHttpWebRequest(requestUri, true, null, null);
if (filter != null)
filter(request);
// get the response
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//hack: For some reason, disabling auto-redirects also disables throwing WebExceptions for 300 status codes,
//so if we detect a non-2xx error code here, throw a web exception.
int statusCode = (int)response.StatusCode;
if (statusCode > 299)
throw new WebException(response.StatusCode.ToString() + ": " + response.StatusDescription, null, WebExceptionStatus.UnknownError, response);
return response;
}
catch (WebException e)
{
if (e.Status == WebExceptionStatus.Timeout)
{
//throw a typed exception that lets callers know that the response timed out after the request was sent
throw new WebResponseTimeoutException(e);
}
else
throw;
}
}
public static void ApplyLanguage(HttpWebRequest request)
{
string acceptLang = CultureInfo.CurrentUICulture.Name.Split('/')[0];
if (acceptLang.ToUpperInvariant() == "SR-SP-LATN")
acceptLang = "sr-Latn-CS";
if (acceptLang != "en-US")
acceptLang += ", en-US";
acceptLang += ", en, *";
request.Headers["Accept-Language"] = acceptLang;
}
public static HttpWebResponse SafeSendRequest(string requestUri, HttpRequestFilter filter)
{
try
{
return SendRequest(requestUri, filter);
}
catch (WebException we)
{
if (ApplicationDiagnostics.TestMode)
LogException(we);
return null;
}
}
public static void ApplyProxyOverride(WebRequest request)
{
WebProxy proxy = GetProxyOverride();
if (proxy != null)
request.Proxy = proxy;
}
/// <summary>
/// Returns the default proxy for an HTTP request.
///
/// Consider using ApplyProxyOverride instead.
/// </summary>
/// <returns></returns>
public static WebProxy GetProxyOverride()
{
WebProxy proxy = null;
if (WebProxySettings.ProxyEnabled)
{
string proxyServerUrl = WebProxySettings.Hostname;
if (proxyServerUrl.IndexOf("://", StringComparison.OrdinalIgnoreCase) == -1)
proxyServerUrl = "http://" + proxyServerUrl;
if (WebProxySettings.Port > 0)
proxyServerUrl += ":" + WebProxySettings.Port;
ICredentials proxyCredentials = CreateHttpCredentials(WebProxySettings.Username, WebProxySettings.Password, proxyServerUrl);
proxy = new WebProxy(proxyServerUrl, false, new string[0], proxyCredentials);
}
return proxy;
}
public static ICredentials CreateHttpCredentials(string username, string password, string url)
{
return CreateHttpCredentials(username, password, url, false);
}
/// <summary>
/// Creates a set of credentials for the specified user/pass, or returns the default credentials if user/pass is null.
/// </summary>
/// <param name="username"></param>
/// <param name="password"></param>
/// <param name="url"></param>
/// <returns></returns>
public static ICredentials CreateHttpCredentials(string username, string password, string url, bool digestOnly)
{
ICredentials credentials = CredentialCache.DefaultCredentials;
if (username != null || password != null)
{
CredentialCache credentialCache = new CredentialCache();
string userDomain = String.Empty;
if (username != null)
{
//try to parse the username string into a domain\userId
int domainIndex = username.IndexOf(@"\", StringComparison.OrdinalIgnoreCase);
if (domainIndex != -1)
{
userDomain = username.Substring(0, domainIndex);
username = username.Substring(domainIndex + 1);
}
}
credentialCache.Add(new Uri(url), "Digest", new NetworkCredential(username, password, userDomain));
if (!digestOnly)
{
credentialCache.Add(new Uri(url), "Basic", new NetworkCredential(username, password, userDomain));
credentialCache.Add(new Uri(url), "NTLM", new NetworkCredential(username, password, userDomain));
credentialCache.Add(new Uri(url), "Negotiate", new NetworkCredential(username, password, userDomain));
credentialCache.Add(new Uri(url), "Kerberos", new NetworkCredential(username, password, userDomain));
}
credentials = credentialCache;
}
return credentials;
}
public static HttpWebRequest CreateHttpWebRequest(string requestUri, bool allowAutoRedirect)
{
return CreateHttpWebRequest(requestUri, allowAutoRedirect, null, null);
}
public static HttpWebRequest CreateHttpWebRequest(string requestUri, bool allowAutoRedirect, int? connectTimeoutMs, int? readWriteTimeoutMs)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUri);
TrackResponseClosing(ref request);
// Set Accept to */* to stop Bad Behavior plugin for WordPress from
// thinking we're a spam cannon
request.Accept = "*/*";
ApplyLanguage(request);
int timeout = WebProxySettings.HttpRequestTimeout;
request.Timeout = timeout;
request.ReadWriteTimeout = timeout * 5;
if (connectTimeoutMs != null)
request.Timeout = connectTimeoutMs.Value;
if (readWriteTimeoutMs != null)
request.ReadWriteTimeout = readWriteTimeoutMs.Value;
request.AllowAutoRedirect = allowAutoRedirect;
request.UserAgent = ApplicationEnvironment.UserAgent;
ApplyProxyOverride(request);
//For robustness, we turn off keep alive and piplining by default.
//If the caller wants to override, the filter parameter can be used to adjust these settings.
//Warning: NTLM authentication requires keep-alive, so without adjusting this, NTLM-secured requests will always fail.
request.KeepAlive = false;
request.Pipelined = false;
request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.Reload);
return request;
}
public static string DumpResponse(HttpWebResponse resp)
{
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture))
{
sw.WriteLine(String.Format(CultureInfo.InvariantCulture, "{0}/{1} {2} {3}", "HTTP", resp.ProtocolVersion, (int)resp.StatusCode, resp.StatusDescription));
foreach (string key in resp.Headers.AllKeys)
{
sw.WriteLine(String.Format(CultureInfo.InvariantCulture, "{0}: {1}", key, resp.Headers[key]));
}
sw.WriteLine("");
sw.WriteLine(DecodeBody(resp));
}
return sb.ToString();
}
public static string DumpRequestHeader(HttpWebRequest req)
{
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture))
{
sw.WriteLine(String.Format(CultureInfo.InvariantCulture, "{0} {1} HTTP/{2}", req.Method, UrlHelper.SafeToAbsoluteUri(req.RequestUri), req.ProtocolVersion));
foreach (string key in req.Headers.AllKeys)
{
sw.WriteLine(String.Format(CultureInfo.InvariantCulture, "{0}: {1}", key, req.Headers[key]));
}
}
return sb.ToString();
}
public static DateTime GetExpiresHeader(HttpWebResponse response)
{
string expires = response.GetResponseHeader("Expires");
if (expires != null && expires != String.Empty && expires.Trim() != "-1")
{
try
{
DateTime expiresDate = DateTime.Parse(expires, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
return expiresDate;
}
catch (Exception ex)
{
// look for ANSI c's asctime() format as a last gasp
try
{
string asctimeFormat = "ddd' 'MMM' 'd' 'HH':'mm':'ss' 'yyyy";
DateTime expiresDate = DateTime.ParseExact(expires, asctimeFormat, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces);
return expiresDate;
}
catch
{
}
Trace.Fail("Exception parsing HTTP date - " + expires + ": " + ex.ToString());
return DateTime.MinValue;
}
}
else
{
return DateTime.MinValue;
}
}
public static string GetETagHeader(HttpWebResponse response)
{
return GetStringHeader(response, "ETag");
}
public static string GetStringHeader(HttpWebResponse response, string headerName)
{
string headerValue = response.GetResponseHeader(headerName);
if (headerValue != null)
return headerValue;
else
return String.Empty;
}
public static void LogException(WebException ex)
{
Trace.WriteLine("== BEGIN WebException =====================");
Trace.WriteLine("Status: " + ex.Status);
Trace.WriteLine(ex.ToString());
HttpWebResponse response = ex.Response as HttpWebResponse;
if (response != null)
Trace.WriteLine(DumpResponse(response));
Trace.WriteLine("== END WebException =======================");
}
public static string GetFriendlyErrorMessage(WebException we)
{
if (we.Response != null && we.Response is HttpWebResponse)
{
HttpWebResponse response = (HttpWebResponse)we.Response;
string bodyText = GetBodyText(response);
int statusCode = (int)response.StatusCode;
string statusDesc = response.StatusDescription;
return String.Format(CultureInfo.CurrentCulture,
"{0} {1}\r\n\r\n{2}",
statusCode, statusDesc,
bodyText);
}
else
{
return we.Message;
}
}
private static string GetBodyText(HttpWebResponse resp)
{
if (resp.ContentType != null && resp.ContentType.Length > 0)
{
IDictionary contentTypeData = MimeHelper.ParseContentType(resp.ContentType, true);
string mainType = (string)contentTypeData[""];
switch (mainType)
{
case "text/plain":
{
return DecodeBody(resp);
}
case "text/html":
{
return StringHelper.CompressExcessWhitespace(
HTMLDocumentHelper.HTMLToPlainText(
LightWeightHTMLThinner2.Thin(
DecodeBody(resp), true)));
}
}
}
return "";
}
private static string DecodeBody(HttpWebResponse response)
{
Stream s = response.GetResponseStream();
StreamReader sr = new StreamReader(s);
return sr.ReadToEnd();
}
}
public class HttpRequestCredentialsFilter
{
public static HttpRequestFilter Create(string username, string password, string url, bool digestOnly)
{
return new HttpRequestFilter(new HttpRequestCredentialsFilter(username, password, url, digestOnly).Filter);
}
private HttpRequestCredentialsFilter(string username, string password, string url, bool digestOnly)
{
_username = username;
_password = password;
_url = url;
_digestOnly = digestOnly;
}
private void Filter(HttpWebRequest request)
{
request.Credentials = HttpRequestHelper.CreateHttpCredentials(_username, _password, _url, _digestOnly);
}
private string _username;
private string _password;
private string _url;
private bool _digestOnly;
}
/// <summary>
/// Allow chaining together of http request filters
/// </summary>
public class CompoundHttpRequestFilter
{
public static HttpRequestFilter Create(HttpRequestFilter[] filters)
{
return new HttpRequestFilter(new CompoundHttpRequestFilter(filters).Filter);
}
private CompoundHttpRequestFilter(HttpRequestFilter[] filters)
{
_filters = filters;
}
private void Filter(HttpWebRequest request)
{
foreach (HttpRequestFilter filter in _filters)
filter(request);
}
private HttpRequestFilter[] _filters;
}
/// <summary>
/// Typed-exception that occurs when an HTTP request times out after the request has been sent, but
/// before the response is received.
/// </summary>
public class WebResponseTimeoutException : WebException
{
public WebResponseTimeoutException(WebException innerException) : base(innerException.Message, innerException, innerException.Status, innerException.Response)
{
}
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form 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.
//
using System;
using System.Collections.Generic;
using System.Text;
using Autodesk.Revit.DB;
namespace Revit.SDK.Samples.SlabShapeEditing.CS
{
/// <summary>
/// Vector4 is a homogeneous coordinate class used to store vector
/// and contain method to handle the vector
/// </summary>
public class Vector4
{
#region Class member variables and properties
private double m_x;
private double m_y;
private double m_z;
private double m_w = 1.0f;
/// <summary>
/// X property to get/set x value of Vector4
/// </summary>
public double X
{
get
{
return m_x;
}
set
{
m_x = value;
}
}
/// <summary>
/// Y property to get/set y value of Vector4
/// </summary>
public double Y
{
get
{
return m_y;
}
set
{
m_y = value;
}
}
/// <summary>
/// Z property to get/set z value of Vector4
/// </summary>
public double Z
{
get
{
return m_z;
}
set
{
m_z = value;
}
}
/// <summary>
/// W property to get/set fourth value of Vector4
/// </summary>
public double W
{
get
{
return m_w;
}
set
{
m_w = value;
}
}
#endregion
/// <summary>
/// constructor
/// </summary>
public Vector4(double x, double y, double z)
{
this.X = x; this.Y = y; this.Z = z;
}
/// <summary>
/// constructor, transfer Autodesk.Revit.DB.XYZ to vector
/// </summary>
/// <param name="v">Autodesk.Revit.DB.XYZ structure which needs to be transferred</param>
public Vector4(Autodesk.Revit.DB.XYZ v)
{
this.X = (double)v.X; this.Y = (double)v.Y; this.Z = (double)v.Z;
}
/// <summary>
/// adds two vectors
/// </summary>
/// <param name="va">first vector</param>
/// <param name="vb">second vector</param>
public static Vector4 operator+ (Vector4 va, Vector4 vb)
{
return new Vector4(va.X + vb.X, va.Y + vb.Y, va.Z + vb.Z);
}
/// <summary>
/// subtracts two vectors
/// </summary>
/// <param name="va">first vector</param>
/// <param name="vb">second vector</param>
/// <returns>subtraction of two vectors</returns>
public static Vector4 operator- (Vector4 va, Vector4 vb)
{
return new Vector4(va.X - vb.X, va.Y - vb.Y, va.Z - vb.Z);
}
/// <summary>
/// multiplies a vector by a double type value
/// </summary>
/// <param name="v">vector</param>
/// <param name="factor">multiplier of double type</param>
/// <returns> the result vector </returns>
public static Vector4 operator *(Vector4 v, double factor)
{
return new Vector4(v.X * factor, v.Y * factor, v.Z * factor);
}
/// <summary>
/// divides vector by a double type value
/// </summary>
/// <param name="v">vector</param>
/// <param name="factor">double type value</param>
/// <returns> vector divided by a double type value </returns>
public static Vector4 operator /(Vector4 v, double factor)
{
return new Vector4(v.X / factor, v.Y / factor, v.Z / factor);
}
/// <summary>
/// dot multiply vector
/// </summary>
/// <param name="v"> the result vector </param>
public double DotProduct(Vector4 v)
{
return (this.X * v.X + this.Y * v.Y + this.Z * v.Z);
}
/// <summary>
/// get normal vector of plane contains two vectors
/// </summary>
/// <param name="v">second vector</param>
/// <returns> normal vector of two vectors</returns>
public Vector4 CrossProduct(Vector4 v)
{
return new Vector4(this.Y * v.Z - this.Z * v.Y,this.Z * v.X
- this.X * v.Z,this.X * v.Y - this.Y * v.X);
}
/// <summary>
/// dot multiply two vectors
/// </summary>
/// <param name="va">first vector</param>
/// <param name="vb">second vector</param>
public static double DotProduct(Vector4 va, Vector4 vb)
{
return (va.X * vb.X + va.Y * vb.Y + va.Z * vb.Z);
}
/// <summary>
/// get normal vector of two vectors
/// </summary>
/// <param name="va">first vector</param>
/// <param name="vb">second vector</param>
/// <returns> normal vector of two vectors </returns>
public static Vector4 CrossProduct(Vector4 va, Vector4 vb)
{
return new Vector4(va.Y * vb.Z - va.Z * vb.Y, va.Z * vb.X
- va.X * vb.Z, va.X * vb.Y - va.Y * vb.X);
}
/// <summary>
/// get unit vector
/// </summary>
public void Normalize()
{
double length = Length();
if(length == 0)
{
length = 1;
}
this.X /= length;
this.Y /= length;
this.Z /= length;
}
/// <summary>
/// calculate the length of vector
/// </summary>
public double Length()
{
return (double)Math.Sqrt(this.X * this.X + this.Y * this.Y + this.Z * this.Z);
}
};
/// <summary>
/// Matrix used to transform between ucs coordinate and world coordinate.
/// </summary>
public class Matrix4
{
#region MatrixType
/// <summary>
/// Matrix Type Enum use to define function of matrix
/// </summary>
public enum MatrixType
{
Rotation, // matrix use to rotate
Translation, // matrix used to Translation
Scale, // matrix used to Scale
RotationAndTranslation, // matrix used to Rotation and Translation
Normal // normal matrix
};
private double[,] m_matrix = new double[4,4]; // an array stores the matrix
private MatrixType m_type; //type of matrix
#endregion
/// <summary>
/// X property to get/set Type of matrix
/// </summary>
public MatrixType Type
{
get
{
return m_type;
}
set
{
m_type = value;
}
}
/// <summary>
/// X property to get/set Array which store data for matrix
/// </summary>
public double[,] Matrix
{
get
{
return m_matrix;
}
set
{
m_matrix = value;
}
}
/// <summary>
/// get a matrix used to rotate object specific angle on X direction
/// </summary>
/// <param name="angle">rotate angle</param>
/// <returns>matrix which rotate object specific angle on X direction</returns>
public static Matrix4 RotateX(double angle)
{
Matrix4 rotateX = new Matrix4();
rotateX.Type = MatrixType.Rotation;
rotateX.Identity();
double sin = (double)Math.Sin(angle);
double cos = (double)Math.Cos(angle);
rotateX.Matrix[1, 1] = cos;
rotateX.Matrix[1, 2] = sin;
rotateX.Matrix[2, 1] = -sin;
rotateX.Matrix[2, 2] = cos;
return rotateX;
}
/// <summary>
/// get a matrix used to rotate object specific angle on Y direction
/// </summary>
/// <param name="angle">rotate angle</param>
/// <returns>matrix which rotate object specific angle on Y direction</returns>
public static Matrix4 RotateY(double angle)
{
Matrix4 rotateX = new Matrix4();
rotateX.Type = MatrixType.Rotation;
rotateX.Identity();
double sin = (double)Math.Sin(angle);
double cos = (double)Math.Cos(angle);
rotateX.Matrix[0, 0] = cos;
rotateX.Matrix[0, 2] = -sin;
rotateX.Matrix[2, 0] = sin;
rotateX.Matrix[2, 2] = cos;
return rotateX;
}
/// <summary>
/// get a matrix used to rotate object specific angle on Z direction
/// </summary>
/// <param name="angle">rotate angle</param>
/// <returns>matrix which rotate object specific angle on Z direction</returns>
public static Matrix4 RotateZ(double angle)
{
Matrix4 rotateX = new Matrix4();
rotateX.Type = MatrixType.Rotation;
rotateX.Identity();
double sin = (double)Math.Sin(angle);
double cos = (double)Math.Cos(angle);
rotateX.Matrix[1, 1] = cos;
rotateX.Matrix[1, 2] = sin;
rotateX.Matrix[2, 1] = -sin;
rotateX.Matrix[2, 2] = cos;
return rotateX;
}
/// <summary>
/// default constructor
/// </summary>
public Matrix4()
{
m_type = MatrixType.Normal;
Identity();
}
/// <summary>
/// ctor,rotation matrix,origin at (0,0,0)
/// </summary>
/// <param name="xAxis">identity of x axis</param>
/// <param name="yAxis">identity of y axis</param>
/// <param name="zAxis">identity of z axis</param>
public Matrix4(Vector4 xAxis,Vector4 yAxis, Vector4 zAxis)
{
m_type = MatrixType.Rotation;
Identity();
m_matrix[0, 0] = xAxis.X; m_matrix[0, 1] = xAxis.Y; m_matrix[0, 2] = xAxis.Z;
m_matrix[1, 0] = yAxis.X; m_matrix[1, 1] = yAxis.Y; m_matrix[1, 2] = yAxis.Z;
m_matrix[2, 0] = zAxis.X; m_matrix[2, 1] = zAxis.Y; m_matrix[2, 2] = zAxis.Z;
}
/// <summary>
/// ctor,translation matrix.
/// </summary>
/// <param name="origin">origin of ucs in world coordinate</param>
public Matrix4(Vector4 origin)
{
m_type = MatrixType.Translation;
Identity();
m_matrix[3, 0] = origin.X; m_matrix[3, 1] = origin.Y; m_matrix[3, 2] = origin.Z;
}
/// <summary>
/// rotation and translation matrix constructor
/// </summary>
/// <param name="xAxis">x Axis</param>
/// <param name="yAxis">y Axis</param>
/// <param name="zAxis">z Axis</param>
/// <param name="origin">origin</param>
public Matrix4(Vector4 xAxis, Vector4 yAxis, Vector4 zAxis, Vector4 origin)
{
m_type = MatrixType.RotationAndTranslation;
Identity();
m_matrix[0, 0] = xAxis.X; m_matrix[0, 1] = xAxis.Y; m_matrix[0, 2] = xAxis.Z;
m_matrix[1, 0] = yAxis.X; m_matrix[1, 1] = yAxis.Y; m_matrix[1, 2] = yAxis.Z;
m_matrix[2, 0] = zAxis.X; m_matrix[2, 1] = zAxis.Y; m_matrix[2, 2] = zAxis.Z;
m_matrix[3, 0] = origin.X; m_matrix[3, 1] = origin.Y; m_matrix[3, 2] = origin.Z;
}
/// <summary>
/// scale matrix constructor
/// </summary>
/// <param name="scale">scale factor</param>
public Matrix4(double scale)
{
m_type = MatrixType.Scale;
Identity();
m_matrix[0, 0] = scale;
m_matrix[1, 1] = scale;
m_matrix[2, 2] = scale;
}
/// <summary>
/// indexer of matrix
/// </summary>
/// <param name="row">row number</param>
/// <param name="column">column number</param>
/// <returns></returns>
public double this[int row, int column]
{
get
{
return this.m_matrix[row, column];
}
set
{
this.m_matrix[row, column] = value;
}
}
/// <summary>
/// Identity matrix
/// </summary>
public void Identity()
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
this.m_matrix[i, j] = 0.0f;
}
}
this.m_matrix[0, 0] = 1.0f;
this.m_matrix[1, 1] = 1.0f;
this.m_matrix[2, 2] = 1.0f;
this.m_matrix[3, 3] = 1.0f;
}
/// <summary>
/// multiply matrix left and right
/// </summary>
/// <param name="left">left matrix</param>
/// <param name="right">right matrix</param>
/// <returns></returns>
public static Matrix4 Multiply(Matrix4 left, Matrix4 right)
{
Matrix4 result = new Matrix4();
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
result[i, j] = left[i, 0] * right[0, j] + left[i, 1] * right[1, j]
+ left[i, 2] * right[2, j] + left[i, 3] * right[3, j];
}
}
return result;
}
/// <summary>
/// transform point using this matrix
/// </summary>
/// <param name="point">point to be transformed</param>
/// <returns>transform result</returns>
public Vector4 Transform(Vector4 point)
{
return new Vector4(point.X * this[0, 0] + point.Y * this[1, 0]
+ point.Z * this[2, 0]+ point.W * this[3, 0],
point.X * this[0, 1] + point.Y * this[1, 1]
+ point.Z * this[2, 1]+ point.W * this[3, 1],
point.X * this[0, 2] + point.Y * this[1, 2]
+ point.Z * this[2, 2]+ point.W * this[3, 2]);
}
/// <summary>
/// if m_matrix is a rotation matrix,this method can get the rotation inverse matrix.
/// </summary>
/// <returns>inverse of rotation matrix</returns>
public Matrix4 RotationInverse()
{
return new Matrix4(new Vector4(this[0, 0], this[1, 0], this[2, 0]),
new Vector4(this[0, 1], this[1, 1], this[2, 1]),
new Vector4(this[0, 2], this[1, 2], this[2, 2]));
}
/// <summary>
/// if this m_matrix is a translation matrix,
/// this method can get the translation inverse matrix.
/// </summary>
/// <returns>inverse of translation matrix</returns>
public Matrix4 TranslationInverse()
{
return new Matrix4(new Vector4(-this[3, 0], -this[3, 1], -this[3, 2]));
}
/// <summary>
/// get inverse matrix
/// </summary>
/// <returns>inverse matrix</returns>
public Matrix4 Inverse()
{
switch(m_type)
{
case MatrixType.Rotation: return RotationInverse();
case MatrixType.Translation: return TranslationInverse();
case MatrixType.RotationAndTranslation:
return Multiply(TranslationInverse(),RotationInverse());
case MatrixType.Scale: return ScaleInverse();
case MatrixType.Normal: return new Matrix4();
default: return null;
}
}
/// <summary>
/// if m_matrix is a scale matrix,this method can get the scale inverse matrix.
/// </summary>
/// <returns>inverse of scale matrix</returns>
public Matrix4 ScaleInverse()
{
return new Matrix4(1 / m_matrix[0,0]);
}
};
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.