context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
namespace SIM.Tool.Windows.UserControls.Install
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Xml;
using SIM.Adapters.SqlServer;
using SIM.Adapters.WebServer;
using SIM.Instances;
using SIM.Products;
using SIM.Tool.Base;
using SIM.Tool.Base.Pipelines;
using SIM.Tool.Base.Profiles;
using SIM.Tool.Base.Wizards;
using Sitecore.Diagnostics.Base;
using Sitecore.Diagnostics.Base.Annotations;
using Sitecore.Diagnostics.Logging;
using SIM.Extensions;
#region
#endregion
[UsedImplicitly]
public partial class InstanceDetails : IWizardStep, IFlowControl
{
#region Fields
[NotNull]
private readonly ICollection<string> allFrameworkVersions = Environment.Is64BitOperatingSystem ? new[]
{
"v2.0", "v2.0 32bit", "v4.0", "v4.0 32bit"
} : new[]
{
"v2.0", "v4.0"
};
private InstallWizardArgs installParameters = null;
private IEnumerable<Product> standaloneProducts;
#endregion
#region Constructors
public InstanceDetails()
{
this.InitializeComponent();
this.NetFramework.ItemsSource = this.allFrameworkVersions;
}
#endregion
#region Public properties
public static bool InstallEverywhere
{
get
{
return WindowsSettings.AppInstallEverywhere.Value;
}
}
#endregion
#region Public Methods
public bool OnMovingBack(WizardArgs wizardArg)
{
return true;
}
public bool OnMovingNext(WizardArgs wizardArgs)
{
var productRevision = this.ProductRevision;
Assert.IsNotNull(productRevision, nameof(productRevision));
Product product = productRevision.SelectedValue as Product;
Assert.IsNotNull(product, nameof(product));
var rootName = GetValidRootName();
var rootPath = GetValidRootPath(rootName);
if (rootPath == null)
return false;
var name = GetValidWebsiteName();
if (name == null)
return false;
var hostNames = GetValidHostNames();
var sqlPrefix = GetValidSqlPrefix();
var attachSql = this.attachSql.IsChecked ?? true;
var connectionString = ProfileManager.GetConnectionString();
SqlServerManager.Instance.ValidateConnectionString(connectionString);
var licensePath = ProfileManager.Profile.License;
Assert.IsNotNull(licensePath, @"The license file isn't set in the Settings window");
FileSystem.FileSystem.Local.File.AssertExists(licensePath, "The {0} file is missing".FormatWith(licensePath));
var appPoolInfo = GetAppPoolInfo();
var args = (InstallWizardArgs)wizardArgs;
args.InstanceName = name;
args.InstanceHostNames = hostNames;
args.InstanceSqlPrefix = sqlPrefix;
args.InstanceAttachSql = attachSql;
args.InstanceWebRootPath = GetWebRootPath(rootPath);
args.InstanceRootName = rootName;
args.InstanceRootPath = rootPath;
args.InstanceProduct = product;
args.InstanceConnectionString = connectionString;
args.LicenseFileInfo = new FileInfo(licensePath);
args.InstanceAppPoolInfo = appPoolInfo;
args.Product = product;
return true;
}
[NotNull]
private AppPoolInfo GetAppPoolInfo()
{
var netFramework = this.NetFramework;
Assert.IsNotNull(netFramework, nameof(netFramework));
var framework = netFramework.SelectedValue.ToString();
var frameworkArr = framework.Split(' ');
Assert.IsTrue(frameworkArr.Length > 0, "impossible");
var force32Bit = frameworkArr.Length == 2;
var mode = this.Mode;
Assert.IsNotNull(mode, nameof(mode));
var modeItem = (ListBoxItem) mode.SelectedValue;
Assert.IsNotNull(modeItem, nameof(modeItem));
var isClassic = ((string) modeItem.Content).EqualsIgnoreCase("Classic");
var appPoolInfo = new AppPoolInfo
{
FrameworkVersion = Extensions.EmptyToNull(frameworkArr[0]) ?? "v2.0",
Enable32BitAppOnWin64 = force32Bit,
ManagedPipelineMode = !isClassic
};
return appPoolInfo;
}
private static string GetWebRootPath(string rootPath)
{
var webRootPath = Path.Combine(rootPath, "Website");
return webRootPath;
}
[NotNull]
private string GetValidRootName()
{
var rootName = this.RootName;
Assert.IsNotNull(rootName, nameof(rootName));
var root = rootName.Text.EmptyToNull();
Assert.IsNotNull(rootName, "Root folder name must not be emoty");
return root;
}
[CanBeNull]
private string GetValidRootPath(string root)
{
var location = this.locationFolder.Text.EmptyToNull();
Assert.IsNotNull(location, @"The location folder isn't set");
var rootPath = Path.Combine(location, root);
var locationIsPhysical = FileSystem.FileSystem.Local.Directory.HasDriveLetter(rootPath);
Assert.IsTrue(locationIsPhysical, "The location folder path must be physical i.e. contain a drive letter. Please choose another location folder");
var webRootPath = GetWebRootPath(rootPath);
var rootFolderExists = FileSystem.FileSystem.Local.Directory.Exists(rootPath);
if (!rootFolderExists || InstanceManager.Instances == null)
return rootPath;
if (InstanceManager.Instances.Any(i => i != null && i.WebRootPath.EqualsIgnoreCase(webRootPath)))
{
Alert("There is another instance with the same root path, please choose another folder");
return null;
}
if (WindowHelper.ShowMessage("The folder with the same name already exists. Would you like to delete it?", MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.OK) != MessageBoxResult.OK)
{
return null;
}
FileSystem.FileSystem.Local.Directory.DeleteIfExists(rootPath);
return rootPath;
}
[CanBeNull]
private string GetValidWebsiteName()
{
var instanceName = this.InstanceName;
Assert.IsNotNull(instanceName, nameof(instanceName));
var name = instanceName.Text.EmptyToNull();
Assert.IsNotNull(name, @"Instance name isn't set");
var websiteExists = WebServerManager.WebsiteExists(name);
if (websiteExists)
{
using (var context = WebServerManager.CreateContext("InstanceDetails.OnMovingNext('{0}')".FormatWith(name)))
{
var site = context.Sites.Single(s => s != null && Extensions.EqualsIgnoreCase(s.Name, name));
var path = WebServerManager.GetWebRootPath(site);
if (FileSystem.FileSystem.Local.Directory.Exists(path))
{
this.Alert("The website with the same name already exists, please choose another instance name.");
return null;
}
if (
WindowHelper.ShowMessage(
"A website with the name " + name + " already exists. Would you like to remove it?",
MessageBoxButton.OKCancel, MessageBoxImage.Asterisk) != MessageBoxResult.OK)
{
return null;
}
site.Delete();
context.CommitChanges();
}
}
websiteExists = WebServerManager.WebsiteExists(name);
Assert.IsTrue(!websiteExists, "The website with the same name already exists, please choose another instance name.");
return name;
}
[NotNull]
private string GetValidSqlPrefix()
{
var sqlPrefix = this.sqlPrefix;
Assert.IsNotNull(sqlPrefix, nameof(sqlPrefix));
var prefix = sqlPrefix.Text.EmptyToNull();
Assert.IsNotNull(prefix, @"Sql prefix isn't set");
return prefix;
}
[NotNull]
private string[] GetValidHostNames()
{
var hostName = this.HostNames;
Assert.IsNotNull(hostName, "HostNames is null");
var hostNamesString = hostName.Text.EmptyToNull();
Assert.IsNotNull(hostNamesString, "Host names can not be empty");
var hostNames = hostNamesString.Split(new[] { '\r', '\n', ',', '|', ';' }, StringSplitOptions.RemoveEmptyEntries);
Assert.IsTrue(hostNames.Any(), "Host names can not be empty");
foreach (var host in hostNames)
{
var hostExists = WebServerManager.HostBindingExists(host);
Assert.IsTrue(!hostExists, $"Website with the host name '{host}' already exists");
}
return hostNames;
}
#endregion
#region Methods
#region Protected methods
protected void Alert([NotNull] string message, [NotNull] params object[] args)
{
Assert.ArgumentNotNull(message, nameof(message));
Assert.ArgumentNotNull(args, nameof(args));
WindowHelper.ShowMessage(message.FormatWith(args), "Conflict is found", MessageBoxButton.OK, MessageBoxImage.Stop);
}
#endregion
#region Private methods
private void Init()
{
using (new ProfileSection("Initializing InstanceDetails", this))
{
this.DataContext = new Model();
this.standaloneProducts = ProductManager.StandaloneProducts;
}
}
private void InstanceNameTextChanged([CanBeNull] object sender, [CanBeNull] TextChangedEventArgs e)
{
using (new ProfileSection("Instance name text changed", this))
{
var name = this.InstanceName.Text;
this.RootName.Text = name;
this.sqlPrefix.Text = name;
this.HostNames.Text = GenerateHostName(name);
}
}
[NotNull]
private string GenerateHostName([NotNull]string name)
{
var hostName = name;
if (ProductHelper.Settings.CoreProductReverseHostName.Value)
{
// convert example.cm1 into cm1.example
hostName = string.Join(".", hostName.Split(".".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Reverse());
}
if (ProductHelper.Settings.CoreProductHostNameEndsWithLocal.Value && !hostName.EndsWith(".local", StringComparison.InvariantCultureIgnoreCase))
{
// convert to cm1.example.local
hostName = hostName + (ProductHelper.Settings.CoreProductHostNameEndsWithLocal.Value ? ".local" : "");
}
return hostName;
}
private void PickLocationFolder([CanBeNull] object sender, [CanBeNull] RoutedEventArgs e)
{
WindowHelper.PickFolder("Choose location folder", this.locationFolder, null);
}
private void ProductNameChanged([CanBeNull] object sender, [CanBeNull] SelectionChangedEventArgs e)
{
var productName = this.ProductName;
Assert.IsNotNull(productName, nameof(productName));
var grouping = productName.SelectedValue as IGrouping<string, Product>;
if (grouping == null)
{
return;
}
var productVersion = this.ProductVersion;
Assert.IsNotNull(productVersion, nameof(productVersion));
productVersion.DataContext = grouping.Where(x => x != null).GroupBy(p => p.ShortVersion).Where(x => x != null).OrderBy(p => p.Key);
this.SelectFirst(productVersion);
}
private void ProductRevisionChanged([CanBeNull] object sender, [CanBeNull] SelectionChangedEventArgs e)
{
using (new ProfileSection("Product revision changed", this))
{
var product = this.ProductRevision.SelectedValue as Product;
if (product == null)
{
return;
}
var name = product.DefaultInstanceName;
this.InstanceName.Text = name;
var frameworkVersions = new ObservableCollection<string>(this.allFrameworkVersions);
var m = product.Manifest;
if (m != null)
{
var node = (XmlElement)m.SelectSingleNode("/manifest/*/limitations");
if (node != null)
{
foreach (XmlElement limitation in node.ChildNodes)
{
var lname = limitation.Name;
switch (lname.ToLower())
{
case "framework":
{
var supportedVersions = limitation.SelectElements("supportedVersion");
if (supportedVersions != null)
{
ICollection<string> supportedVersionNames = supportedVersions.Select(supportedVersion => supportedVersion.InnerText).ToArray();
for (int i = frameworkVersions.Count - 1; i >= 0; i--)
{
if (!supportedVersionNames.Contains(frameworkVersions[i]))
{
frameworkVersions.RemoveAt(i);
}
}
}
break;
}
}
}
}
}
var netFramework = this.NetFramework;
Assert.IsNotNull(netFramework, nameof(netFramework));
netFramework.ItemsSource = frameworkVersions;
netFramework.SelectedIndex = 0;
}
}
private void ProductVersionChanged([CanBeNull] object sender, [CanBeNull] SelectionChangedEventArgs e)
{
var productVersion = this.ProductVersion;
Assert.IsNotNull(productVersion, nameof(productVersion));
var grouping = productVersion.SelectedValue as IGrouping<string, Product>;
if (grouping == null)
{
return;
}
this.ProductRevision.DataContext = grouping.OrderBy(p => p.Revision);
this.SelectLast(this.ProductRevision);
}
private void Select([NotNull] Selector element, [NotNull] string value)
{
Assert.ArgumentNotNull(element, nameof(element));
Assert.ArgumentNotNull(value, nameof(value));
if (element.Items.Count <= 0)
{
return;
}
for (int i = 0; i < element.Items.Count; ++i)
{
object item0 = element.Items[i];
IGrouping<string, Product> item1 = item0 as IGrouping<string, Product>;
if (item1 != null)
{
var key = item1.Key;
if (key.EqualsIgnoreCase(value))
{
element.SelectedIndex = i;
break;
}
}
else
{
Product item2 = item0 as Product;
if (item2 != null)
{
var key = item2.Revision;
if (key.EqualsIgnoreCase(value))
{
element.SelectedIndex = i;
break;
}
}
}
}
}
private void SelectByValue([NotNull] Selector element, string value)
{
Assert.ArgumentNotNull(element, nameof(element));
if (string.IsNullOrEmpty(value))
{
this.SelectLast(element);
return;
}
if (element.Items.Count > 0)
{
if (element.Items[0].GetType() == typeof(Product))
{
foreach (Product item in element.Items)
{
if (item.Name.EqualsIgnoreCase(value, true))
{
element.SelectedItem = item;
break;
}
if (item.Revision.EqualsIgnoreCase(value, true))
{
element.SelectedItem = item;
break;
}
}
}
else
{
foreach (var item in element.Items)
{
if (item is ContentControl)
{
if ((item as ContentControl).Content.ToString().EqualsIgnoreCase(value, true))
{
element.SelectedItem = item;
break;
}
}
if (item is string)
{
if ((item as string).EqualsIgnoreCase(value, true))
{
element.SelectedItem = item;
break;
}
}
}
}
}
}
private void SelectFirst([NotNull] Selector element)
{
Assert.ArgumentNotNull(element, nameof(element));
if (element.Items.Count > 0)
{
element.SelectedIndex = 0;
}
}
private void SelectLast([NotNull] Selector element)
{
Assert.ArgumentNotNull(element, nameof(element));
if (element.Items.Count > 0)
{
element.SelectedIndex = element.Items.Count - 1;
}
}
private void SelectProductByValue([CanBeNull] Selector element, [NotNull] string value)
{
Assert.ArgumentNotNull(value, nameof(value));
if (element == null)
{
return;
}
if (string.IsNullOrEmpty(value))
{
this.SelectLast(element);
return;
}
var items = element.Items;
Assert.IsNotNull(items, nameof(items));
if (items.Count > 0)
{
foreach (IGrouping<string, Product> item in items)
{
if (item.First().Name.EqualsIgnoreCase(value, true))
{
element.SelectedItem = item;
break;
}
if (item.First().Version.EqualsIgnoreCase(value, true))
{
element.SelectedItem = item;
break;
}
}
}
}
private void WindowLoaded(object sender, RoutedEventArgs e)
{
using (new ProfileSection("Window loaded", this))
{
var args = this.installParameters;
Assert.IsNotNull(args, nameof(args));
var product = args.Product;
if (product != null)
{
return;
}
this.SelectProductByValue(this.ProductName, WindowsSettings.AppInstallationDefaultProduct.Value);
this.SelectProductByValue(this.ProductVersion, WindowsSettings.AppInstallationDefaultProductVersion.Value);
this.SelectByValue(this.ProductRevision, WindowsSettings.AppInstallationDefaultProductRevision.Value);
var netFramework = this.NetFramework;
Assert.IsNotNull(netFramework, nameof(netFramework));
if (string.IsNullOrEmpty(WindowsSettings.AppInstallationDefaultFramework.Value))
{
netFramework.SelectedIndex = 0;
}
else
{
this.SelectByValue(netFramework, WindowsSettings.AppInstallationDefaultFramework.Value);
}
var mode = this.Mode;
Assert.IsNotNull(mode, nameof(mode));
if (string.IsNullOrEmpty(WindowsSettings.AppInstallationDefaultPoolMode.Value))
{
mode.SelectedIndex = 0;
}
else
{
this.SelectByValue(mode, WindowsSettings.AppInstallationDefaultPoolMode.Value);
}
}
}
#endregion
#endregion
#region Nested type: Model
public class Model
{
#region Fields
[CanBeNull]
[UsedImplicitly]
public readonly Product[] Products = ProductManager.StandaloneProducts.ToArray();
[NotNull]
private string name;
#endregion
#region Properties
[NotNull]
[UsedImplicitly]
public string Name
{
get
{
return this.name;
}
set
{
Assert.IsNotNull(value.EmptyToNull(), "Name must not be empty");
this.name = value;
}
}
[UsedImplicitly]
public IGrouping<string, Product> SelectedProductGroup1 { get; set; }
#endregion
}
#endregion
#region IWizardStep Members
void IWizardStep.InitializeStep(WizardArgs wizardArgs)
{
this.Init();
this.locationFolder.Text = ProfileManager.Profile.InstancesFolder;
this.ProductName.DataContext = this.standaloneProducts.GroupBy(p => p.Name);
var args = (InstallWizardArgs)wizardArgs;
this.installParameters = args;
Product product = args.Product;
if (product != null)
{
this.Select(this.ProductName, product.Name);
this.Select(this.ProductVersion, product.ShortVersion);
this.Select(this.ProductRevision, product.Revision);
}
else
{
this.SelectFirst(this.ProductName);
}
AppPoolInfo info = args.InstanceAppPoolInfo;
if (info != null)
{
var frameworkValue = info.FrameworkVersion + " " + (info.Enable32BitAppOnWin64 ? "32bit" : string.Empty);
this.SelectByValue(this.NetFramework, frameworkValue);
this.SelectByValue(this.Mode, info.ManagedPipelineMode ? "Integrated" : "Classic");
}
var name = args.InstanceName;
if (!string.IsNullOrEmpty(name))
{
this.InstanceName.Text = name;
}
var rootName = args.InstanceRootName;
if (!string.IsNullOrEmpty(rootName))
{
this.RootName.Text = rootName;
}
var hostNames = args.InstanceHostNames;
if (hostNames != null && hostNames.Any())
{
this.HostNames.Text = hostNames.Join("\r\n");
}
if (rootName == null)
return;
var location = args.InstanceRootPath.TrimEnd(rootName).Trim('/', '\\');
if (!string.IsNullOrEmpty(location))
{
this.locationFolder.Text = location;
}
}
bool IWizardStep.SaveChanges(WizardArgs wizardArgs)
{
return true;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Globalization;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Microsoft.Build.Tasks.Hosting;
using Microsoft.CodeAnalysis.CommandLine;
namespace Microsoft.CodeAnalysis.BuildTasks
{
/// <summary>
/// This class defines the "Vbc" XMake task, which enables building assemblies from VB
/// source files by invoking the VB compiler. This is the new Roslyn XMake task,
/// meaning that the code is compiled by using the Roslyn compiler server, rather
/// than vbc.exe. The two should be functionally identical, but the compiler server
/// should be significantly faster with larger projects and have a smaller memory
/// footprint.
/// </summary>
public class Vbc : ManagedCompiler
{
private bool _useHostCompilerIfAvailable;
// The following 1 fields are used, set and re-set in LogEventsFromTextOutput()
/// <summary>
/// This stores the original lines and error priority together in the order in which they were received.
/// </summary>
private readonly Queue<VBError> _vbErrorLines = new Queue<VBError>();
// Used when parsing vbc output to determine the column number of an error
private bool _isDoneOutputtingErrorMessage;
private int _numberOfLinesInErrorMessage;
internal override RequestLanguage Language => RequestLanguage.VisualBasicCompile;
#region Properties
// Please keep these alphabetized. These are the parameters specific to Vbc. The
// ones shared between Vbc and Csc are defined in ManagedCompiler.cs, which is
// the base class.
public string BaseAddress
{
set { _store[nameof(BaseAddress)] = value; }
get { return (string)_store[nameof(BaseAddress)]; }
}
public string DisabledWarnings
{
set { _store[nameof(DisabledWarnings)] = value; }
get { return (string)_store[nameof(DisabledWarnings)]; }
}
public string DocumentationFile
{
set { _store[nameof(DocumentationFile)] = value; }
get { return (string)_store[nameof(DocumentationFile)]; }
}
public string ErrorReport
{
set { _store[nameof(ErrorReport)] = value; }
get { return (string)_store[nameof(ErrorReport)]; }
}
public bool GenerateDocumentation
{
set { _store[nameof(GenerateDocumentation)] = value; }
get { return _store.GetOrDefault(nameof(GenerateDocumentation), false); }
}
public ITaskItem[] Imports
{
set { _store[nameof(Imports)] = value; }
get { return (ITaskItem[])_store[nameof(Imports)]; }
}
public string LangVersion
{
set { _store[nameof(LangVersion)] = value; }
get { return (string)_store[nameof(LangVersion)]; }
}
public string ModuleAssemblyName
{
set { _store[nameof(ModuleAssemblyName)] = value; }
get { return (string)_store[nameof(ModuleAssemblyName)]; }
}
public bool NoStandardLib
{
set { _store[nameof(NoStandardLib)] = value; }
get { return _store.GetOrDefault(nameof(NoStandardLib), false); }
}
// This is not a documented switch. It prevents the automatic reference to Microsoft.VisualBasic.dll.
// The VB team believes the only scenario for this is when you are building that assembly itself.
// We have to support the switch here so that we can build the SDE and VB trees, which need to build this assembly.
// Although undocumented, it cannot be wrapped with #if BUILDING_DF_LKG because this would prevent dogfood builds
// within VS, which must use non-LKG msbuild bits.
public bool NoVBRuntimeReference
{
set { _store[nameof(NoVBRuntimeReference)] = value; }
get { return _store.GetOrDefault(nameof(NoVBRuntimeReference), false); }
}
public bool NoWarnings
{
set { _store[nameof(NoWarnings)] = value; }
get { return _store.GetOrDefault(nameof(NoWarnings), false); }
}
public string OptionCompare
{
set { _store[nameof(OptionCompare)] = value; }
get { return (string)_store[nameof(OptionCompare)]; }
}
public bool OptionExplicit
{
set { _store[nameof(OptionExplicit)] = value; }
get { return _store.GetOrDefault(nameof(OptionExplicit), true); }
}
public bool OptionStrict
{
set { _store[nameof(OptionStrict)] = value; }
get { return _store.GetOrDefault(nameof(OptionStrict), false); }
}
public bool OptionInfer
{
set { _store[nameof(OptionInfer)] = value; }
get { return _store.GetOrDefault(nameof(OptionInfer), false); }
}
// Currently only /optionstrict:custom
public string OptionStrictType
{
set { _store[nameof(OptionStrictType)] = value; }
get { return (string)_store[nameof(OptionStrictType)]; }
}
public bool RemoveIntegerChecks
{
set { _store[nameof(RemoveIntegerChecks)] = value; }
get { return _store.GetOrDefault(nameof(RemoveIntegerChecks), false); }
}
public string RootNamespace
{
set { _store[nameof(RootNamespace)] = value; }
get { return (string)_store[nameof(RootNamespace)]; }
}
public string SdkPath
{
set { _store[nameof(SdkPath)] = value; }
get { return (string)_store[nameof(SdkPath)]; }
}
/// <summary>
/// Name of the language passed to "/preferreduilang" compiler option.
/// </summary>
/// <remarks>
/// If set to null, "/preferreduilang" option is omitted, and vbc.exe uses its default setting.
/// Otherwise, the value is passed to "/preferreduilang" as is.
/// </remarks>
public string PreferredUILang
{
set { _store[nameof(PreferredUILang)] = value; }
get { return (string)_store[nameof(PreferredUILang)]; }
}
public string VsSessionGuid
{
set { _store[nameof(VsSessionGuid)] = value; }
get { return (string)_store[nameof(VsSessionGuid)]; }
}
public bool TargetCompactFramework
{
set { _store[nameof(TargetCompactFramework)] = value; }
get { return _store.GetOrDefault(nameof(TargetCompactFramework), false); }
}
public bool UseHostCompilerIfAvailable
{
set { _useHostCompilerIfAvailable = value; }
get { return _useHostCompilerIfAvailable; }
}
public string VBRuntimePath
{
set { _store[nameof(VBRuntimePath)] = value; }
get { return (string)_store[nameof(VBRuntimePath)]; }
}
public string Verbosity
{
set { _store[nameof(Verbosity)] = value; }
get { return (string)_store[nameof(Verbosity)]; }
}
public string WarningsAsErrors
{
set { _store[nameof(WarningsAsErrors)] = value; }
get { return (string)_store[nameof(WarningsAsErrors)]; }
}
public string WarningsNotAsErrors
{
set { _store[nameof(WarningsNotAsErrors)] = value; }
get { return (string)_store[nameof(WarningsNotAsErrors)]; }
}
public string VBRuntime
{
set { _store[nameof(VBRuntime)] = value; }
get { return (string)_store[nameof(VBRuntime)]; }
}
public string PdbFile
{
set { _store[nameof(PdbFile)] = value; }
get { return (string)_store[nameof(PdbFile)]; }
}
#endregion
#region Tool Members
private static readonly string[] s_separator = { "\r\n" };
internal override void LogMessages(string output, MessageImportance messageImportance)
{
var lines = output.Split(s_separator, StringSplitOptions.None);
foreach (string line in lines)
{
//Code below will parse the set of four lines that comprise a VB
//error message into a single object. The four-line format contains
//a second line that is blank. This must be passed to the code below
//to satisfy the parser. The parser needs to work with output from
//old compilers as well.
LogEventsFromTextOutput(line, messageImportance);
}
}
/// <summary>
/// Return the name of the tool to execute.
/// </summary>
override protected string ToolName
{
get
{
return "vbc.exe";
}
}
/// <summary>
/// Override Execute so that we can moved the PDB file if we need to,
/// after the compiler is done.
/// </summary>
public override bool Execute()
{
if (!base.Execute())
{
return false;
}
if (!SkipCompilerExecution)
{
MovePdbFileIfNecessary(OutputAssembly.ItemSpec);
}
return !Log.HasLoggedErrors;
}
/// <summary>
/// Move the PDB file if the PDB file that was generated by the compiler
/// is not at the specified path, or if it is newer than the one there.
/// VBC does not have a switch to specify the PDB path, so we are essentially implementing that for it here.
/// We need make this possible to avoid colliding with the PDB generated by WinMDExp.
///
/// If at some future point VBC.exe offers a /pdbfile switch, this function can be removed.
/// </summary>
internal void MovePdbFileIfNecessary(string outputAssembly)
{
// Get the name of the output assembly because the pdb will be written beside it and will have the same name
if (String.IsNullOrEmpty(PdbFile) || String.IsNullOrEmpty(outputAssembly))
{
return;
}
try
{
string actualPdb = Path.ChangeExtension(outputAssembly, ".pdb"); // This is the pdb that the compiler generated
FileInfo actualPdbInfo = new FileInfo(actualPdb);
string desiredLocation = PdbFile;
if (!desiredLocation.EndsWith(".pdb", StringComparison.OrdinalIgnoreCase))
{
desiredLocation += ".pdb";
}
FileInfo desiredPdbInfo = new FileInfo(desiredLocation);
// If the compiler generated a pdb..
if (actualPdbInfo.Exists)
{
// .. and the desired one does not exist or it's older...
if (!desiredPdbInfo.Exists || (desiredPdbInfo.Exists && actualPdbInfo.LastWriteTime > desiredPdbInfo.LastWriteTime))
{
// Delete the existing one if it's already there, as Move would otherwise fail
if (desiredPdbInfo.Exists)
{
Utilities.DeleteNoThrow(desiredPdbInfo.FullName);
}
// Move the file to where we actually wanted VBC to put it
File.Move(actualPdbInfo.FullName, desiredLocation);
}
}
}
catch (Exception e) when (Utilities.IsIoRelatedException(e))
{
Log.LogErrorWithCodeFromResources("VBC_RenamePDB", PdbFile, e.Message);
}
}
/// <summary>
/// vbc.exe only takes the BaseAddress in hexadecimal format. But we allow the caller
/// of the task to pass in the BaseAddress in either decimal or hexadecimal format.
/// Examples of supported hex formats include "0x10000000" or "&H10000000".
/// </summary>
internal string GetBaseAddressInHex()
{
string originalBaseAddress = this.BaseAddress;
if (originalBaseAddress != null)
{
if (originalBaseAddress.Length > 2)
{
string twoLetterPrefix = originalBaseAddress.Substring(0, 2);
if (
(0 == String.Compare(twoLetterPrefix, "0x", StringComparison.OrdinalIgnoreCase)) ||
(0 == String.Compare(twoLetterPrefix, "&h", StringComparison.OrdinalIgnoreCase))
)
{
// The incoming string is already in hex format ... we just need to
// remove the 0x or &H from the beginning.
return originalBaseAddress.Substring(2);
}
}
// The incoming BaseAddress is not in hexadecimal format, so we need to
// convert it to hex.
try
{
uint baseAddressDecimal = UInt32.Parse(originalBaseAddress, CultureInfo.InvariantCulture);
return baseAddressDecimal.ToString("X", CultureInfo.InvariantCulture);
}
catch (FormatException e)
{
throw Utilities.GetLocalizedArgumentException(e,
ErrorString.Vbc_ParameterHasInvalidValue, "BaseAddress", originalBaseAddress);
}
}
return null;
}
/// <summary>
/// Looks at all the parameters that have been set, and builds up the string
/// containing all the command-line switches.
/// </summary>
protected internal override void AddResponseFileCommands(CommandLineBuilderExtension commandLine)
{
commandLine.AppendSwitchIfNotNull("/baseaddress:", this.GetBaseAddressInHex());
commandLine.AppendSwitchIfNotNull("/libpath:", this.AdditionalLibPaths, ",");
commandLine.AppendSwitchIfNotNull("/imports:", this.Imports, ",");
// Make sure this /doc+ switch comes *before* the /doc:<file> switch (which is handled in the
// ManagedCompiler.cs base class). /doc+ is really just an alias for /doc:<assemblyname>.xml,
// and the last /doc switch on the command-line wins. If the user provided a specific doc filename,
// we want that one to win.
commandLine.AppendPlusOrMinusSwitch("/doc", this._store, "GenerateDocumentation");
commandLine.AppendSwitchIfNotNull("/optioncompare:", this.OptionCompare);
commandLine.AppendPlusOrMinusSwitch("/optionexplicit", this._store, "OptionExplicit");
// Make sure this /optionstrict+ switch appears *before* the /optionstrict:xxxx switch below
/* twhitney: In Orcas a change was made for devdiv bug 16889 that set Option Strict-, whenever this.DisabledWarnings was
* empty. That was clearly the wrong thing to do and we found it when we had a project with all the warning configuration
* entries set to WARNING. Because this.DisabledWarnings was empty in that case we would end up sending /OptionStrict-
* effectively silencing all the warnings that had been selected.
*
* Now what we do is:
* If option strict+ is specified, that trumps everything and we just set option strict+
* Otherwise, just set option strict:custom.
* You may wonder why we don't try to set Option Strict- The reason is that Option Strict- just implies a certain
* set of warnings that should be disabled (there's ten of them today) You get the same effect by sending
* option strict:custom on along with the correct list of disabled warnings.
* Rather than make this code know the current set of disabled warnings that comprise Option strict-, we just send
* option strict:custom on with the understanding that we'll get the same behavior as option strict- since we are passing
* the /nowarn line on that contains all the warnings OptionStrict- would disable anyway. The IDE knows what they are
* and puts them in the project file so we are good. And by not making this code aware of which warnings comprise
* Option Strict-, we have one less place we have to keep up to date in terms of what comprises option strict-
*/
// Decide whether we are Option Strict+ or Option Strict:custom
object optionStrictSetting = this._store["OptionStrict"];
bool optionStrict = optionStrictSetting != null ? (bool)optionStrictSetting : false;
if (optionStrict)
{
commandLine.AppendSwitch("/optionstrict+");
}
else // OptionStrict+ wasn't specified so use :custom.
{
commandLine.AppendSwitch("/optionstrict:custom");
}
commandLine.AppendSwitchIfNotNull("/optionstrict:", this.OptionStrictType);
commandLine.AppendWhenTrue("/nowarn", this._store, "NoWarnings");
commandLine.AppendSwitchWithSplitting("/nowarn:", this.DisabledWarnings, ",", ';', ',');
commandLine.AppendPlusOrMinusSwitch("/optioninfer", this._store, "OptionInfer");
commandLine.AppendWhenTrue("/nostdlib", this._store, "NoStandardLib");
commandLine.AppendWhenTrue("/novbruntimeref", this._store, "NoVBRuntimeReference");
commandLine.AppendSwitchIfNotNull("/errorreport:", this.ErrorReport);
commandLine.AppendSwitchIfNotNull("/platform:", this.PlatformWith32BitPreference);
commandLine.AppendPlusOrMinusSwitch("/removeintchecks", this._store, "RemoveIntegerChecks");
commandLine.AppendSwitchIfNotNull("/rootnamespace:", this.RootNamespace);
commandLine.AppendSwitchIfNotNull("/sdkpath:", this.SdkPath);
commandLine.AppendSwitchIfNotNull("/langversion:", this.LangVersion);
commandLine.AppendSwitchIfNotNull("/moduleassemblyname:", this.ModuleAssemblyName);
commandLine.AppendWhenTrue("/netcf", this._store, "TargetCompactFramework");
commandLine.AppendSwitchIfNotNull("/preferreduilang:", this.PreferredUILang);
commandLine.AppendPlusOrMinusSwitch("/highentropyva", this._store, "HighEntropyVA");
if (0 == String.Compare(this.VBRuntimePath, this.VBRuntime, StringComparison.OrdinalIgnoreCase))
{
commandLine.AppendSwitchIfNotNull("/vbruntime:", this.VBRuntimePath);
}
else if (this.VBRuntime != null)
{
string vbRuntimeSwitch = this.VBRuntime;
if (0 == String.Compare(vbRuntimeSwitch, "EMBED", StringComparison.OrdinalIgnoreCase))
{
commandLine.AppendSwitch("/vbruntime*");
}
else if (0 == String.Compare(vbRuntimeSwitch, "NONE", StringComparison.OrdinalIgnoreCase))
{
commandLine.AppendSwitch("/vbruntime-");
}
else if (0 == String.Compare(vbRuntimeSwitch, "DEFAULT", StringComparison.OrdinalIgnoreCase))
{
commandLine.AppendSwitch("/vbruntime+");
}
else
{
commandLine.AppendSwitchIfNotNull("/vbruntime:", vbRuntimeSwitch);
}
}
// Verbosity
if (
(this.Verbosity != null) &&
(
(0 == String.Compare(this.Verbosity, "quiet", StringComparison.OrdinalIgnoreCase)) ||
(0 == String.Compare(this.Verbosity, "verbose", StringComparison.OrdinalIgnoreCase))
)
)
{
commandLine.AppendSwitchIfNotNull("/", this.Verbosity);
}
commandLine.AppendSwitchIfNotNull("/doc:", this.DocumentationFile);
commandLine.AppendSwitchUnquotedIfNotNull("/define:", Vbc.GetDefineConstantsSwitch(this.DefineConstants));
AddReferencesToCommandLine(commandLine);
commandLine.AppendSwitchIfNotNull("/win32resource:", this.Win32Resource);
// Special case for "Sub Main" (See VSWhidbey 381254)
if (0 != String.Compare("Sub Main", this.MainEntryPoint, StringComparison.OrdinalIgnoreCase))
{
commandLine.AppendSwitchIfNotNull("/main:", this.MainEntryPoint);
}
base.AddResponseFileCommands(commandLine);
// This should come after the "TreatWarningsAsErrors" flag is processed (in managedcompiler.cs).
// Because if TreatWarningsAsErrors=false, then we'll have a /warnaserror- on the command-line,
// and then any specific warnings that should be treated as errors should be specified with
// /warnaserror+:<list> after the /warnaserror- switch. The order of the switches on the command-line
// does matter.
//
// Note that
// /warnaserror+
// is just shorthand for:
// /warnaserror+:<all possible warnings>
//
// Similarly,
// /warnaserror-
// is just shorthand for:
// /warnaserror-:<all possible warnings>
commandLine.AppendSwitchWithSplitting("/warnaserror+:", this.WarningsAsErrors, ",", ';', ',');
commandLine.AppendSwitchWithSplitting("/warnaserror-:", this.WarningsNotAsErrors, ",", ';', ',');
// If not design time build and the globalSessionGuid property was set then add a -globalsessionguid:<guid>
bool designTime = false;
if (this.HostObject != null)
{
var vbHost = this.HostObject as IVbcHostObject;
designTime = vbHost.IsDesignTime();
}
if (!designTime)
{
if (!string.IsNullOrWhiteSpace(this.VsSessionGuid))
{
commandLine.AppendSwitchIfNotNull("/sqmsessionguid:", this.VsSessionGuid);
}
}
// It's a good idea for the response file to be the very last switch passed, just
// from a predictability perspective. It also solves the problem that a dogfooder
// ran into, which is described in an email thread attached to bug VSWhidbey 146883.
// See also bugs 177762 and 118307 for additional bugs related to response file position.
if (this.ResponseFiles != null)
{
foreach (ITaskItem response in this.ResponseFiles)
{
commandLine.AppendSwitchIfNotNull("@", response.ItemSpec);
}
}
}
private void AddReferencesToCommandLine(CommandLineBuilderExtension commandLine)
{
if ((this.References == null) || (this.References.Length == 0))
{
return;
}
var references = new List<ITaskItem>(this.References.Length);
var links = new List<ITaskItem>(this.References.Length);
foreach (ITaskItem reference in this.References)
{
bool embed = Utilities.TryConvertItemMetadataToBool(reference, "EmbedInteropTypes");
if (embed)
{
links.Add(reference);
}
else
{
references.Add(reference);
}
}
if (links.Count > 0)
{
commandLine.AppendSwitchIfNotNull("/link:", links.ToArray(), ",");
}
if (references.Count > 0)
{
commandLine.AppendSwitchIfNotNull("/reference:", references.ToArray(), ",");
}
}
/// <summary>
/// Validate parameters, log errors and warnings and return true if
/// Execute should proceed.
/// </summary>
protected override bool ValidateParameters()
{
if (!base.ValidateParameters())
{
return false;
}
// Validate that the "Verbosity" parameter is one of "quiet", "normal", or "verbose".
if (this.Verbosity != null)
{
if ((0 != String.Compare(Verbosity, "normal", StringComparison.OrdinalIgnoreCase)) &&
(0 != String.Compare(Verbosity, "quiet", StringComparison.OrdinalIgnoreCase)) &&
(0 != String.Compare(Verbosity, "verbose", StringComparison.OrdinalIgnoreCase)))
{
Log.LogErrorWithCodeFromResources("Vbc_EnumParameterHasInvalidValue", "Verbosity", this.Verbosity, "Quiet, Normal, Verbose");
return false;
}
}
return true;
}
/// <summary>
/// This method intercepts the lines to be logged coming from STDOUT from VBC.
/// Once we see a standard vb warning or error, then we capture it and grab the next 3
/// lines so we can transform the string form the form of FileName.vb(line) to FileName.vb(line,column)
/// which will allow us to report the line and column to the IDE, and thus filter the error
/// in the duplicate case for multi-targeting, or just squiggle the appropriate token
/// instead of the entire line.
/// </summary>
/// <param name="singleLine">A single line from the STDOUT of the vbc compiler</param>
/// <param name="messageImportance">High,Low,Normal</param>
protected override void LogEventsFromTextOutput(string singleLine, MessageImportance messageImportance)
{
// We can return immediately if this was not called by the out of proc compiler
if (!this.UsedCommandLineTool)
{
base.LogEventsFromTextOutput(singleLine, messageImportance);
return;
}
// We can also return immediately if the current string is not a warning or error
// and we have not seen a warning or error yet. 'Error' and 'Warning' are not localized.
if (_vbErrorLines.Count == 0 &&
singleLine.IndexOf("warning", StringComparison.OrdinalIgnoreCase) == -1 &&
singleLine.IndexOf("error", StringComparison.OrdinalIgnoreCase) == -1)
{
base.LogEventsFromTextOutput(singleLine, messageImportance);
return;
}
ParseVBErrorOrWarning(singleLine, messageImportance);
}
/// <summary>
/// Given a string, parses it to find out whether it's an error or warning and, if so,
/// make sure it's validated properly.
/// </summary>
/// <comments>
/// INTERNAL FOR UNITTESTING ONLY
/// </comments>
/// <param name="singleLine">The line to parse</param>
/// <param name="messageImportance">The MessageImportance to use when reporting the error.</param>
internal void ParseVBErrorOrWarning(string singleLine, MessageImportance messageImportance)
{
// if this string is empty then we haven't seen the first line of an error yet
if (_vbErrorLines.Count > 0)
{
// vbc separates the error message from the source text with an empty line, so
// we can check for an empty line to see if vbc finished outputting the error message
if (!_isDoneOutputtingErrorMessage && singleLine.Length == 0)
{
_isDoneOutputtingErrorMessage = true;
_numberOfLinesInErrorMessage = _vbErrorLines.Count;
}
_vbErrorLines.Enqueue(new VBError(singleLine, messageImportance));
// We are looking for the line that indicates the column (contains the '~'),
// which vbc outputs 3 lines below the error message:
//
// <error message>
// <blank line>
// <line with the source text>
// <line with the '~'>
if (_isDoneOutputtingErrorMessage &&
_vbErrorLines.Count == _numberOfLinesInErrorMessage + 3)
{
// Once we have the 4th line (error line + 3), then parse it for the first ~
// which will correspond to the column of the token with the error because
// VBC respects the users's indentation settings in the file it is compiling
// and only outputs SPACE chars to STDOUT.
// The +1 is to translate the index into user columns which are 1 based.
VBError originalVBError = _vbErrorLines.Dequeue();
string originalVBErrorString = originalVBError.Message;
int column = singleLine.IndexOf('~') + 1;
int endParenthesisLocation = originalVBErrorString.IndexOf(')');
// If for some reason the line does not contain any ~ then something went wrong
// so abort and return the original string.
if (column < 0 || endParenthesisLocation < 0)
{
// we need to output all of the original lines we ate.
Log.LogMessageFromText(originalVBErrorString, originalVBError.MessageImportance);
foreach (VBError vberror in _vbErrorLines)
{
base.LogEventsFromTextOutput(vberror.Message, vberror.MessageImportance);
}
_vbErrorLines.Clear();
return;
}
string newLine = null;
newLine = originalVBErrorString.Substring(0, endParenthesisLocation) + "," + column + originalVBErrorString.Substring(endParenthesisLocation);
// Output all of the lines of the error, but with the modified first line as well.
Log.LogMessageFromText(newLine, originalVBError.MessageImportance);
foreach (VBError vberror in _vbErrorLines)
{
base.LogEventsFromTextOutput(vberror.Message, vberror.MessageImportance);
}
_vbErrorLines.Clear();
}
}
else
{
CanonicalError.Parts parts = CanonicalError.Parse(singleLine);
if (parts == null)
{
base.LogEventsFromTextOutput(singleLine, messageImportance);
}
else if ((parts.category == CanonicalError.Parts.Category.Error ||
parts.category == CanonicalError.Parts.Category.Warning) &&
parts.column == CanonicalError.Parts.numberNotSpecified)
{
if (parts.line != CanonicalError.Parts.numberNotSpecified)
{
// If we got here, then this is a standard VBC error or warning.
_vbErrorLines.Enqueue(new VBError(singleLine, messageImportance));
_isDoneOutputtingErrorMessage = false;
_numberOfLinesInErrorMessage = 0;
}
else
{
// Project-level errors don't have line numbers -- just output now.
base.LogEventsFromTextOutput(singleLine, messageImportance);
}
}
}
}
#endregion
/// <summary>
/// Many VisualStudio VB projects have values for the DefineConstants property that
/// contain quotes and spaces. Normally we don't allow parameters passed into the
/// task to contain quotes, because if we weren't careful, we might accidentally
/// allow a parameter injection attach. But for "DefineConstants", we have to allow
/// it.
/// So this method prepares the string to be passed in on the /define: command-line
/// switch. It does that by quoting the entire string, and escaping the embedded
/// quotes.
/// </summary>
internal static string GetDefineConstantsSwitch
(
string originalDefineConstants
)
{
if ((originalDefineConstants == null) || (originalDefineConstants.Length == 0))
{
return null;
}
StringBuilder finalDefineConstants = new StringBuilder(originalDefineConstants);
// Replace slash-quote with slash-slash-quote.
finalDefineConstants.Replace("\\\"", "\\\\\"");
// Replace quote with slash-quote.
finalDefineConstants.Replace("\"", "\\\"");
// Surround the whole thing with a pair of double-quotes.
finalDefineConstants.Insert(0, '"');
finalDefineConstants.Append('"');
// Now it's ready to be passed in to the /define: switch.
return finalDefineConstants.ToString();
}
/// <summary>
/// This method will initialize the host compiler object with all the switches,
/// parameters, resources, references, sources, etc.
///
/// It returns true if everything went according to plan. It returns false if the
/// host compiler had a problem with one of the parameters that was passed in.
///
/// This method also sets the "this.HostCompilerSupportsAllParameters" property
/// accordingly.
///
/// Example:
/// If we attempted to pass in Platform="foobar", then this method would
/// set HostCompilerSupportsAllParameters=true, but it would throw an
/// exception because the host compiler fully supports
/// the Platform parameter, but "foobar" is an illegal value.
///
/// Example:
/// If we attempted to pass in NoConfig=false, then this method would set
/// HostCompilerSupportsAllParameters=false, because while this is a legal
/// thing for csc.exe, the IDE compiler cannot support it. In this situation
/// the return value will also be false.
/// </summary>
/// <owner>RGoel</owner>
private bool InitializeHostCompiler(IVbcHostObject vbcHostObject)
{
this.HostCompilerSupportsAllParameters = this.UseHostCompilerIfAvailable;
string param = "Unknown";
try
{
param = nameof(vbcHostObject.BeginInitialization);
vbcHostObject.BeginInitialization();
CheckHostObjectSupport(param = nameof(AdditionalLibPaths), vbcHostObject.SetAdditionalLibPaths(AdditionalLibPaths));
CheckHostObjectSupport(param = nameof(AddModules), vbcHostObject.SetAddModules(AddModules));
// For host objects which support them, set the analyzers, ruleset and additional files.
IAnalyzerHostObject analyzerHostObject = vbcHostObject as IAnalyzerHostObject;
if (analyzerHostObject != null)
{
CheckHostObjectSupport(param = nameof(Analyzers), analyzerHostObject.SetAnalyzers(Analyzers));
CheckHostObjectSupport(param = nameof(CodeAnalysisRuleSet), analyzerHostObject.SetRuleSet(CodeAnalysisRuleSet));
CheckHostObjectSupport(param = nameof(AdditionalFiles), analyzerHostObject.SetAdditionalFiles(AdditionalFiles));
}
CheckHostObjectSupport(param = nameof(BaseAddress), vbcHostObject.SetBaseAddress(TargetType, GetBaseAddressInHex()));
CheckHostObjectSupport(param = nameof(CodePage), vbcHostObject.SetCodePage(CodePage));
CheckHostObjectSupport(param = nameof(DebugType), vbcHostObject.SetDebugType(EmitDebugInformation, DebugType));
CheckHostObjectSupport(param = nameof(DefineConstants), vbcHostObject.SetDefineConstants(DefineConstants));
CheckHostObjectSupport(param = nameof(DelaySign), vbcHostObject.SetDelaySign(DelaySign));
CheckHostObjectSupport(param = nameof(DocumentationFile), vbcHostObject.SetDocumentationFile(DocumentationFile));
CheckHostObjectSupport(param = nameof(FileAlignment), vbcHostObject.SetFileAlignment(FileAlignment));
CheckHostObjectSupport(param = nameof(GenerateDocumentation), vbcHostObject.SetGenerateDocumentation(GenerateDocumentation));
CheckHostObjectSupport(param = nameof(Imports), vbcHostObject.SetImports(Imports));
CheckHostObjectSupport(param = nameof(KeyContainer), vbcHostObject.SetKeyContainer(KeyContainer));
CheckHostObjectSupport(param = nameof(KeyFile), vbcHostObject.SetKeyFile(KeyFile));
CheckHostObjectSupport(param = nameof(LinkResources), vbcHostObject.SetLinkResources(LinkResources));
CheckHostObjectSupport(param = nameof(MainEntryPoint), vbcHostObject.SetMainEntryPoint(MainEntryPoint));
CheckHostObjectSupport(param = nameof(NoConfig), vbcHostObject.SetNoConfig(NoConfig));
CheckHostObjectSupport(param = nameof(NoStandardLib), vbcHostObject.SetNoStandardLib(NoStandardLib));
CheckHostObjectSupport(param = nameof(NoWarnings), vbcHostObject.SetNoWarnings(NoWarnings));
CheckHostObjectSupport(param = nameof(Optimize), vbcHostObject.SetOptimize(Optimize));
CheckHostObjectSupport(param = nameof(OptionCompare), vbcHostObject.SetOptionCompare(OptionCompare));
CheckHostObjectSupport(param = nameof(OptionExplicit), vbcHostObject.SetOptionExplicit(OptionExplicit));
CheckHostObjectSupport(param = nameof(OptionStrict), vbcHostObject.SetOptionStrict(OptionStrict));
CheckHostObjectSupport(param = nameof(OptionStrictType), vbcHostObject.SetOptionStrictType(OptionStrictType));
CheckHostObjectSupport(param = nameof(OutputAssembly), vbcHostObject.SetOutputAssembly(OutputAssembly?.ItemSpec));
// For host objects which support them, set platform with 32BitPreference, HighEntropyVA, and SubsystemVersion
IVbcHostObject5 vbcHostObject5 = vbcHostObject as IVbcHostObject5;
if (vbcHostObject5 != null)
{
CheckHostObjectSupport(param = nameof(PlatformWith32BitPreference), vbcHostObject5.SetPlatformWith32BitPreference(PlatformWith32BitPreference));
CheckHostObjectSupport(param = nameof(HighEntropyVA), vbcHostObject5.SetHighEntropyVA(HighEntropyVA));
CheckHostObjectSupport(param = nameof(SubsystemVersion), vbcHostObject5.SetSubsystemVersion(SubsystemVersion));
}
else
{
CheckHostObjectSupport(param = nameof(Platform), vbcHostObject.SetPlatform(Platform));
}
IVbcHostObject6 vbcHostObject6 = vbcHostObject as IVbcHostObject6;
if (vbcHostObject6 != null)
{
CheckHostObjectSupport(param = nameof(ErrorLog), vbcHostObject6.SetErrorLog(ErrorLog));
CheckHostObjectSupport(param = nameof(ReportAnalyzer), vbcHostObject6.SetReportAnalyzer(ReportAnalyzer));
}
CheckHostObjectSupport(param = nameof(References), vbcHostObject.SetReferences(References));
CheckHostObjectSupport(param = nameof(RemoveIntegerChecks), vbcHostObject.SetRemoveIntegerChecks(RemoveIntegerChecks));
CheckHostObjectSupport(param = nameof(Resources), vbcHostObject.SetResources(Resources));
CheckHostObjectSupport(param = nameof(ResponseFiles), vbcHostObject.SetResponseFiles(ResponseFiles));
CheckHostObjectSupport(param = nameof(RootNamespace), vbcHostObject.SetRootNamespace(RootNamespace));
CheckHostObjectSupport(param = nameof(SdkPath), vbcHostObject.SetSdkPath(SdkPath));
CheckHostObjectSupport(param = nameof(Sources), vbcHostObject.SetSources(Sources));
CheckHostObjectSupport(param = nameof(TargetCompactFramework), vbcHostObject.SetTargetCompactFramework(TargetCompactFramework));
CheckHostObjectSupport(param = nameof(TargetType), vbcHostObject.SetTargetType(TargetType));
CheckHostObjectSupport(param = nameof(TreatWarningsAsErrors), vbcHostObject.SetTreatWarningsAsErrors(TreatWarningsAsErrors));
CheckHostObjectSupport(param = nameof(WarningsAsErrors), vbcHostObject.SetWarningsAsErrors(WarningsAsErrors));
CheckHostObjectSupport(param = nameof(WarningsNotAsErrors), vbcHostObject.SetWarningsNotAsErrors(WarningsNotAsErrors));
// DisabledWarnings needs to come after WarningsAsErrors and WarningsNotAsErrors, because
// of the way the host object works, and the fact that DisabledWarnings trump Warnings[Not]AsErrors.
CheckHostObjectSupport(param = nameof(DisabledWarnings), vbcHostObject.SetDisabledWarnings(DisabledWarnings));
CheckHostObjectSupport(param = nameof(Win32Icon), vbcHostObject.SetWin32Icon(Win32Icon));
CheckHostObjectSupport(param = nameof(Win32Resource), vbcHostObject.SetWin32Resource(Win32Resource));
// In order to maintain compatibility with previous host compilers, we must
// light-up for IVbcHostObject2
if (vbcHostObject is IVbcHostObject2)
{
IVbcHostObject2 vbcHostObject2 = (IVbcHostObject2)vbcHostObject;
CheckHostObjectSupport(param = nameof(ModuleAssemblyName), vbcHostObject2.SetModuleAssemblyName(ModuleAssemblyName));
CheckHostObjectSupport(param = nameof(OptionInfer), vbcHostObject2.SetOptionInfer(OptionInfer));
CheckHostObjectSupport(param = nameof(Win32Manifest), vbcHostObject2.SetWin32Manifest(GetWin32ManifestSwitch(NoWin32Manifest, Win32Manifest)));
// initialize option Infer
CheckHostObjectSupport(param = nameof(OptionInfer), vbcHostObject2.SetOptionInfer(OptionInfer));
}
else
{
// If we have been given a property that the host compiler doesn't support
// then we need to state that we are falling back to the command line compiler
if (!String.IsNullOrEmpty(ModuleAssemblyName))
{
CheckHostObjectSupport(param = nameof(ModuleAssemblyName), resultFromHostObjectSetOperation: false);
}
if (_store.ContainsKey(nameof(OptionInfer)))
{
CheckHostObjectSupport(param = nameof(OptionInfer), resultFromHostObjectSetOperation: false);
}
if (!String.IsNullOrEmpty(Win32Manifest))
{
CheckHostObjectSupport(param = nameof(Win32Manifest), resultFromHostObjectSetOperation: false);
}
}
// Check for support of the LangVersion property
if (vbcHostObject is IVbcHostObject3)
{
IVbcHostObject3 vbcHostObject3 = (IVbcHostObject3)vbcHostObject;
CheckHostObjectSupport(param = nameof(LangVersion), vbcHostObject3.SetLanguageVersion(LangVersion));
}
else if (!String.IsNullOrEmpty(LangVersion) && !UsedCommandLineTool)
{
CheckHostObjectSupport(param = nameof(LangVersion), resultFromHostObjectSetOperation: false);
}
if (vbcHostObject is IVbcHostObject4)
{
IVbcHostObject4 vbcHostObject4 = (IVbcHostObject4)vbcHostObject;
CheckHostObjectSupport(param = nameof(VBRuntime), vbcHostObject4.SetVBRuntime(VBRuntime));
}
// Support for NoVBRuntimeReference was added to this task after IVbcHostObject was frozen. That doesn't matter much because the host
// compiler doesn't support it, and almost nobody uses it anyway. But if someone has set it, we need to hard code falling back to
// the command line compiler here.
if (NoVBRuntimeReference)
{
CheckHostObjectSupport(param = nameof(NoVBRuntimeReference), resultFromHostObjectSetOperation: false);
}
InitializeHostObjectSupportForNewSwitches(vbcHostObject, ref param);
// In general, we don't support preferreduilang with the in-proc compiler. It will always use the same locale as the
// host process, so in general, we have to fall back to the command line compiler if this option is specified.
// However, we explicitly allow two values (mostly for parity with C#):
// Null is supported because it means that option should be omitted, and compiler default used - obviously always valid.
// Explicitly specified name of current locale is also supported, since it is effectively a no-op.
if (!String.IsNullOrEmpty(PreferredUILang) && !String.Equals(PreferredUILang, System.Globalization.CultureInfo.CurrentUICulture.Name, StringComparison.OrdinalIgnoreCase))
{
CheckHostObjectSupport(param = nameof(PreferredUILang), resultFromHostObjectSetOperation: false);
}
}
catch (Exception e)
{
Log.LogErrorWithCodeFromResources("General_CouldNotSetHostObjectParameter", param, e.Message);
return false;
}
finally
{
// In the case of the VB host compiler, the EndInitialization method will
// throw (due to FAILED HRESULT) if there was a bad value for one of the
// parameters.
vbcHostObject.EndInitialization();
}
return true;
}
/// <summary>
/// This method will get called during Execute() if a host object has been passed into the Vbc
/// task. Returns one of the following values to indicate what the next action should be:
/// UseHostObjectToExecute Host compiler exists and was initialized.
/// UseAlternateToolToExecute Host compiler doesn't exist or was not appropriate.
/// NoActionReturnSuccess Host compiler was already up-to-date, and we're done.
/// NoActionReturnFailure Bad parameters were passed into the task.
/// </summary>
/// <owner>RGoel</owner>
protected override HostObjectInitializationStatus InitializeHostObject()
{
if (this.HostObject != null)
{
// When the host object was passed into the task, it was passed in as a generic
// "Object" (because ITask interface obviously can't have any Vbc-specific stuff
// in it, and each task is going to want to communicate with its host in a unique
// way). Now we cast it to the specific type that the Vbc task expects. If the
// host object does not match this type, the host passed in an invalid host object
// to Vbc, and we error out.
// NOTE: For compat reasons this must remain IVbcHostObject
// we can dynamically test for smarter interfaces later..
using (RCWForCurrentContext<IVbcHostObject> hostObject = new RCWForCurrentContext<IVbcHostObject>(this.HostObject as IVbcHostObject))
{
IVbcHostObject vbcHostObject = hostObject.RCW;
if (vbcHostObject != null)
{
bool hostObjectSuccessfullyInitialized = InitializeHostCompiler(vbcHostObject);
// If we're currently only in design-time (as opposed to build-time),
// then we're done. We've initialized the host compiler as best we
// can, and we certainly don't want to actually do the final compile.
// So return true, saying we're done and successful.
if (vbcHostObject.IsDesignTime())
{
// If we are design-time then we do not want to continue the build at
// this time.
return hostObjectSuccessfullyInitialized ?
HostObjectInitializationStatus.NoActionReturnSuccess :
HostObjectInitializationStatus.NoActionReturnFailure;
}
if (!this.HostCompilerSupportsAllParameters)
{
// Since the host compiler has refused to take on the responsibility for this compilation,
// we're about to shell out to the command-line compiler to handle it. If some of the
// references don't exist on disk, we know the command-line compiler will fail, so save
// the trouble, and just throw a consistent error ourselves. This allows us to give
// more information than the compiler would, and also make things consistent across
// Vbc / Csc / etc. Actually, the real reason is bug 275726 (ddsuites\src\vs\env\vsproject\refs\ptp3).
// This suite behaves differently in localized builds than on English builds because
// VBC.EXE doesn't localize the word "error" when they emit errors and so we can't scan for it.
if (!CheckAllReferencesExistOnDisk())
{
return HostObjectInitializationStatus.NoActionReturnFailure;
}
// The host compiler doesn't support some of the switches/parameters
// being passed to it. Therefore, we resort to using the command-line compiler
// in this case.
UsedCommandLineTool = true;
return HostObjectInitializationStatus.UseAlternateToolToExecute;
}
// Ok, by now we validated that the host object supports the necessary switches
// and parameters. Last thing to check is whether the host object is up to date,
// and in that case, we will inform the caller that no further action is necessary.
if (hostObjectSuccessfullyInitialized)
{
return vbcHostObject.IsUpToDate() ?
HostObjectInitializationStatus.NoActionReturnSuccess :
HostObjectInitializationStatus.UseHostObjectToExecute;
}
else
{
return HostObjectInitializationStatus.NoActionReturnFailure;
}
}
else
{
Log.LogErrorWithCodeFromResources("General_IncorrectHostObject", "Vbc", "IVbcHostObject");
}
}
}
// No appropriate host object was found.
UsedCommandLineTool = true;
return HostObjectInitializationStatus.UseAlternateToolToExecute;
}
/// <summary>
/// This method will get called during Execute() if a host object has been passed into the Vbc
/// task. Returns true if an appropriate host object was found, it was called to do the compile,
/// and the compile succeeded. Otherwise, we return false.
/// </summary>
/// <owner>RGoel</owner>
protected override bool CallHostObjectToExecute()
{
Debug.Assert(this.HostObject != null, "We should not be here if the host object has not been set.");
IVbcHostObject vbcHostObject = this.HostObject as IVbcHostObject;
Debug.Assert(vbcHostObject != null, "Wrong kind of host object passed in!");
IVbcHostObject5 vbcHostObject5 = vbcHostObject as IVbcHostObject5;
Debug.Assert(vbcHostObject5 != null, "Wrong kind of host object passed in!");
// IVbcHostObjectFreeThreaded::Compile is the preferred way to compile the host object
// because while it is still synchronous it does its waiting on our BG thread
// (as opposed to the UI thread for IVbcHostObject::Compile)
if (vbcHostObject5 != null)
{
IVbcHostObjectFreeThreaded freeThreadedHostObject = vbcHostObject5.GetFreeThreadedHostObject();
return freeThreadedHostObject.Compile();
}
else
{
// If for some reason we can't get to IVbcHostObject5 we just fall back to the old
// Compile method. This method unfortunately allows for reentrancy on the UI thread.
return vbcHostObject.Compile();
}
}
/// <summary>
/// private class that just holds together name, value pair for the vbErrorLines Queue
/// </summary>
private class VBError
{
public string Message { get; }
public MessageImportance MessageImportance { get; }
public VBError(string message, MessageImportance importance)
{
this.Message = message;
this.MessageImportance = importance;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using Verse;
namespace CommunityCoreLibrary.Controller
{
/// <summary>
/// This controller handles advanced research (validation, initialization, updates)
/// </summary>
internal class ResearchSubController : SubController
{
// These are used to optimize the process so the same data
// isn't constantly reprocessed with every itteration.
private static List< ThingDef > buildingCache;
private static List< HelpCategoryDef > helpCategoryCache;
private static List< AdvancedResearchMod > researchModCache;
// Was god-mode on the last update?
private bool wasGodMode;
public override string Name
{
get
{
return "Advanced Research";
}
}
// Override sequence priorities
public override int ValidationPriority
{
get
{
return 50;
}
}
public override int InitializationPriority
{
get
{
return 90;
}
}
public override int UpdatePriority
{
get
{
return 50;
}
}
public override bool ReinitializeOnGameLoad
{
get
{
return true;
}
}
// Validate ...research...?
public override bool Validate ()
{
// Hopefully...
var stringBuilder = new StringBuilder();
var rVal = true;
CCL_Log.CaptureBegin( stringBuilder );
var AdvancedResearchDefs = Controller.Data.AdvancedResearchDefs;
// Make sure the hidden research exists
if( CommunityCoreLibrary.Research.Locker == null )
{
CCL_Log.Trace( Verbosity.FatalErrors, "Missing research locker!" );
rVal = false;
}
// Validate each advanced research def
for( int index = AdvancedResearchDefs.Count - 1; index >= 0; index-- )
{
var advancedResearchDef = AdvancedResearchDefs[ index ];
if( !advancedResearchDef.IsValid() )
{
// Remove projects with errors from list of usable projects
AdvancedResearchDefs.Remove( advancedResearchDef );
rVal = false;
continue;
}
if( advancedResearchDef.IsLockedOut() )
{
// Remove locked out projects
CCL_Log.TraceMod(
advancedResearchDef,
Verbosity.Warnings,
"Def is locked out by one or more research prerequisites" );
AdvancedResearchDefs.Remove( advancedResearchDef );
continue;
}
}
#if DEBUG
if( rVal == true )
{
var allMods = Controller.Data.Mods;
foreach( var mod in allMods )
{
if( !Find_Extensions.DefListOfTypeForMod<AdvancedResearchDef>( mod ).NullOrEmpty() )
{
CCL_Log.TraceMod(
mod,
Verbosity.Validation,
"Passed validation"
);
}
}
}
#endif
// Should be empty or a laundry list
CCL_Log.CaptureEnd(
stringBuilder,
rVal ? "Validated" : "Errors during validation"
);
strReturn = stringBuilder.ToString();
// Return true if all mods OK, false if any failed validation
State = rVal ? SubControllerState.Validated : SubControllerState.ValidationError;
return rVal;
}
public override bool Initialize ()
{
if( Data.AdvancedResearchDefs.NullOrEmpty() )
{
// No advanced research, hybernate
strReturn = "No advanced research defined, hybernating...";
State = Controller.SubControllerState.Hybernating;
return true;
}
// Create caches
InitializeCaches();
// Set the initial state
SetInitialState( true );
// Upgrade system state
strReturn = "Initialized";
State = Controller.SubControllerState.Ok;
return true;
}
public override bool Update()
{
// Don't display an update message
strReturn = string.Empty;
// Everything is good, do some work
wasGodMode |= DebugSettings.godMode;
CheckAdvancedResearch();
return true;
}
#region Cache Processing
private void InitializeCaches()
{
buildingCache = new List< ThingDef >();
helpCategoryCache = new List<HelpCategoryDef>();
researchModCache = new List< AdvancedResearchMod >();
}
private void PrepareCaches()
{
// Prepare the caches
buildingCache.Clear();
researchModCache.Clear();
helpCategoryCache.Clear();
}
private void ProcessCaches( bool setInitialState = false )
{
// Process the caches
// Recache the buildings recipes
if ( buildingCache.Count > 0 )
{
foreach ( var building in buildingCache )
{
building.RecacheRecipes( !setInitialState );
}
}
// Apply all the research mods
if ( researchModCache.Count > 0 )
{
foreach ( var researchMod in researchModCache )
{
researchMod.Invoke( !setInitialState );
}
}
// Recache the help system
if ( helpCategoryCache.Count > 0 )
{
foreach ( var helpCategory in helpCategoryCache )
{
helpCategory.Recache();
}
MainTabWindow_ModHelp.Recache();
}
}
#endregion Cache Processing
#region Research Processing
public void CheckAdvancedResearch()
{
if (
( !DebugSettings.godMode )&&
( wasGodMode )
)
{
// Reset everything
SetInitialState();
wasGodMode = false;
}
// Prepare for some work
PrepareCaches();
// Scan advanced research for newly completed projects
foreach ( var Advanced in Data.AdvancedResearchDefs )
{
if ( Advanced.ResearchState != ResearchEnableMode.Complete )
{
var enableMode = Advanced.EnableMode;
if ( enableMode != Advanced.ResearchState )
{
// Enable this project
Advanced.Enable( enableMode );
}
}
}
// Process caches
ProcessCaches();
}
private void SetInitialState( bool firstTimeRun = false )
{
// Set the initial state of the advanced research
PrepareCaches();
// Process each advanced research def in reverse order
for ( int i = Data.AdvancedResearchDefs.Count - 1; i >= 0; i-- )
{
var Advanced = Data.AdvancedResearchDefs[i];
// Reset the project
Advanced.Disable( firstTimeRun );
}
// Now do the work!
ProcessCaches( firstTimeRun );
}
#endregion Research Processing
#region Recache/Process Interface
public static void RecacheBuildingRecipes( ThingDef def )
{
buildingCache.AddUnique( def );
}
public static void RecacheHelpCategory( HelpCategoryDef def )
{
helpCategoryCache.AddUnique( def );
}
public static void ProcessResearchMod( AdvancedResearchMod mod )
{
researchModCache.AddUnique( mod );
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Security.Principal;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Cats.Areas.EarlyWarning.Controllers;
using Cats.Areas.EarlyWarning.Models;
using Cats.Models;
using Cats.Models.Constant;
using Cats.Models.Security;
using Cats.Services.Administration;
using Cats.Services.Common;
using Cats.Services.EarlyWarning;
using Cats.Services.PSNP;
using Cats.Services.Security;
using Kendo.Mvc.UI;
using Moq;
using NUnit.Framework;
using log4net;
using IAdminUnitService = Cats.Services.EarlyWarning.IAdminUnitService;
using IFDPService = Cats.Services.EarlyWarning.IFDPService;
using UserProfile = Cats.Models.UserProfile;
namespace Cats.Tests.ControllersTests
{
[TestFixture]
public class RequestControllerTests
{
#region SetUp / TearDown
private RequestController _requestController;
[SetUp]
public void Init()
{
var requestDetailCommodity = new List<RequestDetailCommodity>()
{
new RequestDetailCommodity
{
CommodityID = 1,
Amount = 20,
RequestCommodityID = 1,
RegionalRequestDetailID = 1,
Commodity=new Commodity(){CommodityID=1,Name="CSB"}
},
};
var regionalRequests = new List<RegionalRequest>()
{
new RegionalRequest
{
ProgramId = 1
,
Month = 1
,
RegionID = 1
,
RegionalRequestID = 1
,
RequistionDate = DateTime.Parse("7/3/2013")
,
Year = DateTime.Today.Year
,
Status=1,
RequestedBy = 1,
ApprovedBy = 2,
Program = new Program(){
Name="Program1",
ProgramID = 1
},
AdminUnit=new AdminUnit
{
Name="Region",
AdminUnitID=1
},
Ration=new Ration()
{
RationID=1,
RefrenceNumber="RE1",
},
RegionalRequestDetails = new List<RegionalRequestDetail>
{
new RegionalRequestDetail
{
Beneficiaries = 100
,
Fdpid = 1,
Fdp = new FDP{FDPID=1,Name="FDP1",AdminUnit=new AdminUnit{AdminUnitID=1,Name="Admin1",AdminUnit2=new AdminUnit{AdminUnitID=2,Name="Admin2"}}}
,
RegionalRequestID = 1
,
RegionalRequestDetailID = 1,
RequestDetailCommodities=requestDetailCommodity
},
new RegionalRequestDetail
{
Beneficiaries = 100
,
Fdpid = 2,
Fdp = new FDP{FDPID=2,Name="FDP1",AdminUnit=new AdminUnit{AdminUnitID=1,Name="Admin1",AdminUnit2=new AdminUnit{AdminUnitID=2,Name="Admin2"}}}
,
RegionalRequestID = 1
,
RegionalRequestDetailID = 2,
RequestDetailCommodities=requestDetailCommodity
}
}
}
};
// regionalRequests[0].RegionalRequestDetails.First().RequestDetailCommodities = requestDetailCommodity;
var adminUnit = new List<AdminUnit>()
{
new AdminUnit
{
Name = "Temp Admin uni",
AdminUnitID = 1
}
};
var plan = new List<Plan>
{
new Plan {PlanID = 1,PlanName = "Plan1",ProgramID = 1,StartDate = new DateTime(12/12/12),EndDate =new DateTime(12/12/12) }
};
var _status = new List<Cats.Models.WorkflowStatus>()
{
new WorkflowStatus()
{
Description = "Draft",
StatusID = 1,
WorkflowID = 1
},
new WorkflowStatus()
{
Description = "Approved",
StatusID = 2,
WorkflowID = 1
},
new WorkflowStatus()
{
Description = "Closed",
StatusID = 3,
WorkflowID = 1
}
};
var userAccountService = new Mock<IUserAccountService>();
userAccountService.Setup(t => t.GetUserInfo(It.IsAny<string>())).Returns(new UserInfo()
{
UserName = "x",
DatePreference = "en",
PreferedWeightMeasurment = "mt",
UserProfileID = 80
});
var transactionService = new Mock<Cats.Services.Transaction.ITransactionService>();
var commonService = new Mock<ICommonService>();
commonService.Setup(t => t.GetAminUnits(It.IsAny<Expression<Func<AdminUnit, bool>>>(),
It.IsAny<Func<IQueryable<AdminUnit>, IOrderedQueryable<AdminUnit>>>(),
It.IsAny<string>())).Returns(adminUnit);
commonService.Setup(t => t.GetStatus(It.IsAny<WORKFLOW>())).Returns(_status);
commonService.Setup(t => t.GetPlan(plan.First().ProgramID)).Returns(plan);
var mockRegionalRequestService = new Mock<IRegionalRequestService>();
mockRegionalRequestService.Setup(
t => t.GetSubmittedRequest(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<int>())).Returns(
(int region, int month, int status) =>
{
return regionalRequests.FindAll(
t => t.RegionID == region && t.RequistionDate.Month == month && t.Status == status).ToList();
});
mockRegionalRequestService.Setup(
t =>
t.Get(It.IsAny<Expression<Func<RegionalRequest, bool>>>(),
It.IsAny<Func<IQueryable<RegionalRequest>, IOrderedQueryable<RegionalRequest>>>(),
It.IsAny<string>())).Returns(
(Expression<Func<RegionalRequest, bool>> filter,
Func<IQueryable<RegionalRequest>, IOrderedQueryable<RegionalRequest>> sort, string includes)
=>
{
return regionalRequests.AsQueryable().Where(filter);
;
});
mockRegionalRequestService.Setup(t => t.FindById(It.IsAny<int>())).Returns(
(int requestId) => regionalRequests.Find(t => t.RegionalRequestID == requestId));
mockRegionalRequestService.Setup(t => t.ApproveRequest(It.IsAny<int>(),It.IsAny<UserInfo>() )).Returns((int reqId, UserInfo user) =>
{
regionalRequests.
Find
(t =>
t.
RegionalRequestID
== reqId).
Status
=
(int)
RegionalRequestStatus
.Approved;
return true;
});
mockRegionalRequestService.Setup(t => t.AddRegionalRequest(It.IsAny<RegionalRequest>())).Returns(
(RegionalRequest rRequest) =>
{
regionalRequests.Add(rRequest);
return true;
});
mockRegionalRequestService.Setup(t => t.GetAllRegionalRequest()).Returns(regionalRequests);
mockRegionalRequestService.Setup(t => t.PlanToRequest(It.IsAny<HRDPSNPPlan>())).Returns(new HRDPSNPPlanInfo()
{
BeneficiaryInfos
=
new List
<
BeneficiaryInfo
>()
{
new BeneficiaryInfo
()
{
Beneficiaries
=
1,
FDPID
=
1,
FDPName
=
"F1",
Selected
=
true
}
}
,
HRDPSNPPlan
=
new HRDPSNPPlan
{
DonorID
=
1,
Month
=
1,
PlanID
=
1,
ProgramID
=
1,
PSNPPlanID
=
1,
RationID
=
1,
RegionID
=
1,
Round
=
1,
SeasonID
=
1,
Year
=
1
}
});
var mockAdminUnitService = new Mock<IAdminUnitService>();
mockAdminUnitService.Setup(t => t.FindBy(It.IsAny<Expression<Func<AdminUnit, bool>>>())).Returns(adminUnit);
mockAdminUnitService.Setup(t => t.GetRegions()).Returns(adminUnit);
var workflowService = new Mock<IWorkflowStatusService>();
workflowService.Setup(t => t.GetStatus(It.IsAny<Cats.Models.Constant.WORKFLOW>())).Returns(_status);
workflowService.Setup(t => t.GetStatusName(It.IsAny<Cats.Models.Constant.WORKFLOW>(), It.IsAny<int>())).
Returns((Cats.Models.Constant.WORKFLOW workflow, int statusId) =>
{
return _status.Find(t => t.StatusID == statusId && t.WorkflowID == (int)workflow).Description;
});
commonService.Setup(t => t.GetPrograms(It.IsAny<Expression<Func<Program, bool>>>(),
It.IsAny<Func<IQueryable<Program>, IOrderedQueryable<Program>>>(),
It.IsAny<string>())).Returns(new List<Program>()
{
new Program()
{ProgramID = 1, Description = "Relief"}
});
commonService.Setup(t => t.GetRations(It.IsAny<Expression<Func<Ration, bool>>>(),
It.IsAny<Func<IQueryable<Ration>, IOrderedQueryable<Ration>>>(),
It.IsAny<string>())).Returns(new List<Ration>()
{
new Ration
{RationID = 1, RefrenceNumber = "R-00983"}
});
var fdpService = new Mock<IFDPService>();
fdpService.Setup(t => t.FindBy(It.IsAny<Expression<Func<FDP, bool>>>())).Returns(new List<FDP>()
{
new FDP()
{
FDPID = 1,
Name = "FDP1",
AdminUnitID = 1
}
});
var requestDetailService = new Mock<IRegionalRequestDetailService>();
requestDetailService.Setup(t => t.Get(It.IsAny<Expression<Func<RegionalRequestDetail, bool>>>(), null, It.IsAny<string>())).Returns(regionalRequests.First().RegionalRequestDetails);
var fakeContext = new Mock<HttpContextBase>();
var identity = new GenericIdentity("User");
var principal = new GenericPrincipal(identity, null);
fakeContext.Setup(t => t.User).Returns(principal);
var controllerContext = new Mock<ControllerContext>();
controllerContext.Setup(t => t.HttpContext).Returns(fakeContext.Object);
commonService.Setup(t => t.GetCommodities(It.IsAny<Expression<Func<Commodity, bool>>>(),
It.IsAny<Func<IQueryable<Commodity>, IOrderedQueryable<Commodity>>>(),
It.IsAny<string>())).Returns(new List<Commodity>() { new Commodity { CommodityID = 1, Name = "CSB" } });
var hrds = new List<HRD>
{
new HRD()
{
Year = 2013,
Season = new Season() {Name = "Mehere", SeasonID = 1},
RationID = 1,
HRDDetails =
new List<HRDDetail>()
{
new HRDDetail()
{
DurationOfAssistance = 2,
HRDDetailID = 1,
NumberOfBeneficiaries = 300,
WoredaID = 1,
AdminUnit =
new AdminUnit()
{
Name = "Woreda",
AdminUnitID = 2,
AdminUnit2 =
new AdminUnit()
{
Name = "Zone",
AdminUnitID = 3,
AdminUnit2 =
new AdminUnit()
{
Name = "Region",
AdminUnitID = 6
}
}
}
}
}
}
};
var hrdService = new Mock<IHRDService>();
var appService = new Mock<IApplicationSettingService>();
hrdService.Setup(
t =>
t.Get(It.IsAny<Expression<Func<HRD, bool>>>(), It.IsAny<Func<IQueryable<HRD>, IOrderedQueryable<HRD>>>(),
It.IsAny<string>())).Returns(hrds);
var log = new Mock<ILog>();
log.Setup(t => t.Error(It.IsAny<object>()));
var hrdServiceDetail = new Mock<IHRDDetailService>();
var RegionalPSNPPlanDetailService = new Mock<IRegionalPSNPPlanDetailService>();
var RegionalPSNPPlanService = new Mock<IRegionalPSNPPlanService>();
var Notification = new Mock<INotificationService>();
var userProfile = new Mock<IUserProfileService>();
_requestController = new RequestController(
mockRegionalRequestService.Object,
fdpService.Object, requestDetailService.Object,
commonService.Object, hrdService.Object,
appService.Object, userAccountService.Object,
log.Object, hrdServiceDetail.Object,
RegionalPSNPPlanDetailService.Object,
RegionalPSNPPlanService.Object, null, null, null, transactionService.Object, Notification.Object, userProfile.Object);
_requestController.ControllerContext = controllerContext.Object;
}
[TearDown]
public void Dispose()
{
_requestController.Dispose();
}
#endregion
#region Tests
[Test]
public void ShouldListOnlySubmittedRequests()
{
var view = _requestController.SubmittedRequest((int)RegionalRequestStatus.Approved);
Assert.AreEqual(0, ((IEnumerable<RegionalRequestViewModel>)view.Model).Count());
}
[Test]
public void CanApproveDraftRequest()
{
//Act
_requestController.ApproveRequest(1);
var noCommdodityOrBeneficiary = _requestController.CheckBeneficiaryNoAndCommodity(1);
// var reqStatus = regionalRequests[0].Status;
var resut = (ViewResult)_requestController.Edit(1);
//Assert
Assert.IsInstanceOf<RegionalRequest>(resut.Model);
Assert.IsFalse(noCommdodityOrBeneficiary);
//Assert.AreEqual((int)RegionalRequestStatus.Approved, ((RegionalRequest)resut.Model).Status);
}
[Test]
public void CanGetRequestForEdit()
{
//Act
var result = (ViewResult)_requestController.Edit(1);
var regionalRequest = (RegionalRequest)result.Model;
//Assert
Assert.IsInstanceOf<RegionalRequest>(result.Model);
// Assert.AreEqual(1, regionalRequest.RegionalRequestID);
}
[Test]
public void CanCreateNewRegionalRequest()
{
int ProgramId = 1;
/*
var newRegionalRequest = new RegionalRequest
{
ProgramId = 1
,
Month = 2
,
RegionID = 2
,
RegionalRequestID = 4
,
RequistionDate = DateTime.Parse("7/3/2013")
,
Year = DateTime.Today.Year
,
Status = 1,
Program = new Program()
{
Name = "Program1",
ProgramID = 1
},
AdminUnit = new AdminUnit
{
Name = "Region",
AdminUnitID = 1
},
Ration = new Ration()
{
RationID = 1,
RefrenceNumber = "RE1",
},
Plan = new Plan()
{
PlanID = 1,
PlanName = "Plan1",
StartDate = DateTime.Parse("7/3/2013"),
EndDate = DateTime.Parse("7/3/2013")
},
RegionalRequestDetails = new List<RegionalRequestDetail>
{
new RegionalRequestDetail
{
Beneficiaries = 100
,
Fdpid = 1
,
RegionalRequestID = 1
,
RegionalRequestDetailID = 1
},
new RegionalRequestDetail
{
Beneficiaries = 100
,
Fdpid = 2
,
RegionalRequestID = 1
,
RegionalRequestDetailID = 2
}
}
};
/*
//Act
var plan = new HRDPSNPPlan(){PlanID=1,DonorID=1,Month=1,ProgramID=1,PSNPPlanID=1,RationID=1,RegionID=1,Round=1,SeasonID=1,Year=1};
_requestController.New(plan);
var request = new DataSourceRequest();
var result = (JsonResult)_requestController.Request_Read(request);
* */
//Assert
// Assert.IsInstanceOf<JsonResult>(result);
Assert.AreEqual(1, ProgramId);
}
[Test]
public void ShouldListAllRegionalRequests()
{
//Act
var request = new DataSourceRequest();
request.Page = 1;
request.PageSize = 5;
var result = (JsonResult)_requestController.Request_Read(request,-1);
//Assert
Assert.IsNotNull(result);
Assert.AreEqual(1, (((DataSourceResult)result.Data).Total));
}
[Test]
public void AllocationModelShouldContainRegionalRequest()
{
//Arrange
//Act
var result = (ViewResult)_requestController.Allocation2(1);
//Assert
Assert.IsInstanceOf<RegionalRequestViewModel>(result.Model);
}
[Test]
public void ShouldPrepareReginalRequestForEdit()
{
//Act
var result = (ViewResult)_requestController.Edit(1);
//Assert
Assert.IsInstanceOf<RegionalRequest>(result.Model);
}
[Test]
public void ShouldRaiseHttpNotFound()
{
//Act
var result = _requestController.Edit(10);
//Assert
Assert.IsInstanceOf<HttpNotFoundResult>(result);
}
[Test]
public void ShouldUpdateRegionalRequest()
{
//Arrange
var request = new RegionalRequest
{
ProgramId = 1
,
Month = 1
,
RegionID = 2
,
RegionalRequestID = 1
,
RequistionDate = DateTime.Parse("7/3/2013")
,
Year = DateTime.Today.Year
,
Status = 1,
};
//Act
var result = _requestController.Edit(request);
var result2 = (ViewResult)_requestController.Edit(1);
//Assert
Assert.IsInstanceOf<RedirectToRouteResult>(result);
// Assert.AreEqual(2, ((RegionalRequest)result2.Model).RegionID);
}
[Test]
public void ShouldDisplayRequestDetails()
{
//Act
var result = (ViewResult)_requestController.Details(1);
var resultMainRequest = _requestController.ViewData["Request_main_data"];
//Assert
Assert.IsInstanceOf<DataTable>(result.Model);
Assert.IsInstanceOf<RegionalRequestViewModel>(resultMainRequest);
}
#endregion
}
}
| |
/*
*
* (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.Web;
using ASC.Core;
using ASC.Core.Users;
namespace ASC.Web.Studio.Core.Users
{
public sealed class ProfileHelper
{
public UserInfo UserInfo { get; private set; }
public ProfileHelper(string userNameOrUserId)
{
if (string.IsNullOrEmpty(userNameOrUserId) && SecurityContext.IsAuthenticated)
{
UserInfo = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);
}
if (!String.IsNullOrEmpty(userNameOrUserId))
{
UserInfo = CoreContext.UserManager.GetUserByUserName(userNameOrUserId);
}
if (UserInfo == null || UserInfo.Equals(Constants.LostUser))
{
var userID = Guid.Empty;
if (!String.IsNullOrEmpty(userNameOrUserId))
{
try
{
userID = new Guid(userNameOrUserId);
}
catch
{
userID = SecurityContext.CurrentAccount.ID;
}
}
if (!CoreContext.UserManager.UserExists(userID))
{
userID = SecurityContext.CurrentAccount.ID;
}
UserInfo = CoreContext.UserManager.GetUsers(userID);
}
}
public List<MyContact> Phones
{
get
{
if (_phones != null) return _phones;
_phones = GetPhones();
return _phones;
}
}
public List<MyContact> Emails
{
get
{
if (_emails != null) return _emails;
_emails = GetEmails();
return _emails;
}
}
public List<MyContact> Messengers
{
get
{
if (_messengers != null) return _messengers;
_messengers = GetMessengers();
return _messengers;
}
}
public List<MyContact> Contacts
{
get
{
if (_socialContacts != null) return _socialContacts;
_socialContacts = GetSocialContacts();
return _socialContacts;
}
}
private List<MyContact> _phones;
private List<MyContact> _emails;
private List<MyContact> _messengers;
private List<MyContact> _socialContacts;
private List<MyContact> _contacts;
private static MyContact GetSocialContact(String type, String value)
{
var node = SocialContactsManager.xmlSocialContacts.GetElementById(type);
var title = node != null ? node.Attributes["title"].Value : type;
var template = node != null ? node.GetElementsByTagName("template")[0].InnerXml : "{0}";
return new MyContact
{
type = type,
classname = type,
label = title,
text = HttpUtility.HtmlEncode(value),
link = String.Format(template, HttpUtility.HtmlEncode(value))
};
}
private List<MyContact> GetContacts()
{
if (_contacts != null) return _contacts;
var userInfoContacts = UserInfo.Contacts;
_contacts = new List<MyContact>();
for (int i = 0, n = userInfoContacts.Count; i < n; i += 2)
{
if (i + 1 < userInfoContacts.Count)
{
_contacts.Add(GetSocialContact(userInfoContacts[i], userInfoContacts[i + 1]));
}
}
return _contacts;
}
private List<MyContact> GetPhones()
{
var contacts = GetContacts();
var phones = new List<MyContact>();
for (int i = 0, n = contacts.Count; i < n; i++)
{
switch (contacts[i].type)
{
case "phone":
case "extphone":
case "mobphone":
case "extmobphone":
phones.Add(contacts[i]);
break;
}
}
return phones;
}
private List<MyContact> GetEmails()
{
var contacts = GetContacts();
var emails = new List<MyContact>();
for (int i = 0, n = contacts.Count; i < n; i++)
{
switch (contacts[i].type)
{
case "mail":
case "extmail":
case "gmail":
emails.Add(contacts[i]);
break;
}
}
return emails;
}
private List<MyContact> GetMessengers()
{
var contacts = GetContacts();
var messengers = new List<MyContact>();
for (int i = 0, n = contacts.Count; i < n; i++)
{
switch (contacts[i].type)
{
case "jabber":
case "skype":
case "extskype":
case "msn":
case "aim":
case "icq":
case "gtalk":
messengers.Add(contacts[i]);
break;
}
}
return messengers;
}
private List<MyContact> GetSocialContacts()
{
var contacts = GetContacts();
var soccontacts = new List<MyContact>();
for (int i = 0, n = contacts.Count; i < n; i++)
{
switch (contacts[i].type)
{
case "mail":
case "extmail":
case "gmail":
case "phone":
case "extphone":
case "mobphone":
case "extmobphone":
case "jabber":
case "skype":
case "extskype":
case "msn":
case "aim":
case "icq":
case "gtalk":
continue;
}
soccontacts.Add(contacts[i]);
}
return soccontacts;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.Rendering
{
public class HtmlHelperPartialExtensionsTest
{
// Func<IHtmlHelper, IHtmlContent>, expected Model, expected ViewDataDictionary
public static TheoryData<Func<IHtmlHelper, IHtmlContent>, object, ViewDataDictionary> PartialExtensionMethods
{
get
{
var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider());
var model = new object();
return new TheoryData<Func<IHtmlHelper, IHtmlContent>, object, ViewDataDictionary>
{
{ helper => helper.Partial("test"), null, null },
{ helper => helper.Partial("test", model), model, null },
{ helper => helper.Partial("test", viewData), null, viewData },
{ helper => helper.Partial("test", model, viewData), model, viewData },
};
}
}
[Theory]
[MemberData(nameof(PartialExtensionMethods))]
public void PartialMethods_CallHtmlHelperWithExpectedArguments(
Func<IHtmlHelper, IHtmlContent> partialMethod,
object expectedModel,
ViewDataDictionary expectedViewData)
{
// Arrange
var htmlContent = Mock.Of<IHtmlContent>();
var helper = new Mock<IHtmlHelper>(MockBehavior.Strict);
if (expectedModel == null)
{
// Extension methods without model parameter use ViewData.Model to get Model.
var viewData = expectedViewData ?? new ViewDataDictionary(new EmptyModelMetadataProvider());
helper
.SetupGet(h => h.ViewData)
.Returns(viewData)
.Verifiable();
}
helper
.Setup(h => h.PartialAsync("test", expectedModel, expectedViewData))
.Returns(Task.FromResult(htmlContent))
.Verifiable();
// Act
var result = partialMethod(helper.Object);
// Assert
Assert.Same(htmlContent, result);
helper.VerifyAll();
}
[Theory]
[MemberData(nameof(PartialExtensionMethods))]
public void PartialMethods_DoesNotWrapThrownException(
Func<IHtmlHelper, IHtmlContent> partialMethod,
object unusedModel,
ViewDataDictionary unusedViewData)
{
// Arrange
var expected = new InvalidOperationException();
var helper = new Mock<IHtmlHelper>();
helper.Setup(h => h.PartialAsync("test", It.IsAny<object>(), It.IsAny<ViewDataDictionary>()))
.Callback(() =>
{
// Workaround for compilation issue with Moq.
helper.ToString();
throw expected;
});
helper.SetupGet(h => h.ViewData)
.Returns(new ViewDataDictionary(new EmptyModelMetadataProvider()));
// Act and Assert
var actual = Assert.Throws<InvalidOperationException>(() => partialMethod(helper.Object));
Assert.Same(expected, actual);
}
// Func<IHtmlHelper, IHtmlContent>, expected Model, expected ViewDataDictionary
public static TheoryData<Func<IHtmlHelper, Task<IHtmlContent>>, object, ViewDataDictionary> PartialAsyncExtensionMethods
{
get
{
var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider());
var model = new object();
return new TheoryData<Func<IHtmlHelper, Task<IHtmlContent>>, object, ViewDataDictionary>
{
{ helper => helper.PartialAsync("test"), null, null },
{ helper => helper.PartialAsync("test", model), model, null },
{ helper => helper.PartialAsync("test", viewData), null, viewData },
};
}
}
[Theory]
[MemberData(nameof(PartialAsyncExtensionMethods))]
public async Task PartialAsyncMethods_CallHtmlHelperWithExpectedArguments(
Func<IHtmlHelper, Task<IHtmlContent>> partialAsyncMethod,
object expectedModel,
ViewDataDictionary expectedViewData)
{
// Arrange
var htmlContent = Mock.Of<IHtmlContent>();
var helper = new Mock<IHtmlHelper>(MockBehavior.Strict);
if (expectedModel == null)
{
// Extension methods without model parameter use ViewData.Model to get Model.
var viewData = expectedViewData ?? new ViewDataDictionary(new EmptyModelMetadataProvider());
helper
.SetupGet(h => h.ViewData)
.Returns(viewData)
.Verifiable();
}
helper
.Setup(h => h.PartialAsync("test", expectedModel, expectedViewData))
.Returns(Task.FromResult(htmlContent))
.Verifiable();
// Act
var result = await partialAsyncMethod(helper.Object);
// Assert
Assert.Same(htmlContent, result);
helper.VerifyAll();
}
// Func<IHtmlHelper, IHtmlContent>, expected Model, expected ViewDataDictionary
public static TheoryData<Action<IHtmlHelper>, object, ViewDataDictionary> RenderPartialExtensionMethods
{
get
{
var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider());
var model = new object();
return new TheoryData<Action<IHtmlHelper>, object, ViewDataDictionary>
{
{ helper => helper.RenderPartial("test"), null, null },
{ helper => helper.RenderPartial("test", model), model, null },
{ helper => helper.RenderPartial("test", viewData), null, viewData },
{ helper => helper.RenderPartial("test", model, viewData), model, viewData },
};
}
}
[Theory]
[MemberData(nameof(RenderPartialExtensionMethods))]
public void RenderPartialMethods_DoesNotWrapThrownException(
Action<IHtmlHelper> partialMethod,
object unusedModel,
ViewDataDictionary unusedViewData)
{
// Arrange
var expected = new InvalidOperationException();
var helper = new Mock<IHtmlHelper>();
helper.Setup(h => h.RenderPartialAsync("test", It.IsAny<object>(), It.IsAny<ViewDataDictionary>()))
.Callback(() =>
{
// Workaround for compilation issue with Moq.
helper.ToString();
throw expected;
});
helper.SetupGet(h => h.ViewData)
.Returns(new ViewDataDictionary(new EmptyModelMetadataProvider()));
// Act and Assert
var actual = Assert.Throws<InvalidOperationException>(() => partialMethod(helper.Object));
Assert.Same(expected, actual);
}
[Theory]
[MemberData(nameof(RenderPartialAsyncExtensionMethods))]
public async Task RenderPartialMethods_CallHtmlHelperWithExpectedArguments(
Func<IHtmlHelper, Task> renderPartialAsyncMethod,
object expectedModel,
ViewDataDictionary expectedViewData)
{
// Arrange
var htmlContent = Mock.Of<IHtmlContent>();
var helper = new Mock<IHtmlHelper>(MockBehavior.Strict);
if (expectedModel == null)
{
// Extension methods without model parameter use ViewData.Model to get Model.
var viewData = expectedViewData ?? new ViewDataDictionary(new EmptyModelMetadataProvider());
helper
.SetupGet(h => h.ViewData)
.Returns(viewData)
.Verifiable();
}
helper
.Setup(h => h.RenderPartialAsync("test", expectedModel, expectedViewData))
.Returns(Task.FromResult(true))
.Verifiable();
// Act
await renderPartialAsyncMethod(helper.Object);
// Assert
helper.VerifyAll();
}
// Func<IHtmlHelper, IHtmlContent>, expected Model, expected ViewDataDictionary
public static TheoryData<Func<IHtmlHelper, Task>, object, ViewDataDictionary> RenderPartialAsyncExtensionMethods
{
get
{
var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider());
var model = new object();
return new TheoryData<Func<IHtmlHelper, Task>, object, ViewDataDictionary>
{
{ helper => helper.RenderPartialAsync("test"), null, null },
{ helper => helper.RenderPartialAsync("test", model), model, null },
{ helper => helper.RenderPartialAsync("test", viewData), null, viewData },
};
}
}
[Theory]
[MemberData(nameof(RenderPartialAsyncExtensionMethods))]
public async Task RenderPartialAsyncMethods_CallHtmlHelperWithExpectedArguments(
Func<IHtmlHelper, Task> renderPartialAsyncMethod,
object expectedModel,
ViewDataDictionary expectedViewData)
{
// Arrange
var htmlContent = Mock.Of<IHtmlContent>();
var helper = new Mock<IHtmlHelper>(MockBehavior.Strict);
if (expectedModel == null)
{
// Extension methods without model parameter use ViewData.Model to get Model.
var viewData = expectedViewData ?? new ViewDataDictionary(new EmptyModelMetadataProvider());
helper
.SetupGet(h => h.ViewData)
.Returns(viewData)
.Verifiable();
}
helper
.Setup(h => h.RenderPartialAsync("test", expectedModel, expectedViewData))
.Returns(Task.FromResult(true))
.Verifiable();
// Act
await renderPartialAsyncMethod(helper.Object);
// Assert
helper.VerifyAll();
}
[Fact]
public void Partial_InvokesPartialAsyncWithCurrentModel()
{
// Arrange
var expected = new HtmlString("value");
var model = new object();
var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider())
{
Model = model
};
var helper = new Mock<IHtmlHelper>(MockBehavior.Strict);
helper.Setup(h => h.PartialAsync("test", model, null))
.Returns(Task.FromResult((IHtmlContent)expected))
.Verifiable();
helper.SetupGet(h => h.ViewData)
.Returns(viewData);
// Act
var actual = helper.Object.Partial("test");
// Assert
Assert.Same(expected, actual);
helper.Verify();
}
[Fact]
public void PartialWithModel_InvokesPartialAsyncWithPassedInModel()
{
// Arrange
var expected = new HtmlString("value");
var model = new object();
var helper = new Mock<IHtmlHelper>(MockBehavior.Strict);
helper.Setup(h => h.PartialAsync("test", model, null))
.Returns(Task.FromResult((IHtmlContent)expected))
.Verifiable();
// Act
var actual = helper.Object.Partial("test", model);
// Assert
Assert.Same(expected, actual);
helper.Verify();
}
[Fact]
public void PartialWithViewData_InvokesPartialAsyncWithPassedInViewData()
{
// Arrange
var expected = new HtmlString("value");
var model = new object();
var passedInViewData = new ViewDataDictionary(new EmptyModelMetadataProvider());
var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider())
{
Model = model
};
var helper = new Mock<IHtmlHelper>(MockBehavior.Strict);
helper.Setup(h => h.PartialAsync("test", model, passedInViewData))
.Returns(Task.FromResult((IHtmlContent)expected))
.Verifiable();
helper.SetupGet(h => h.ViewData)
.Returns(viewData);
// Act
var actual = helper.Object.Partial("test", passedInViewData);
// Assert
Assert.Same(expected, actual);
helper.Verify();
}
[Fact]
public void PartialWithViewDataAndModel_InvokesPartialAsyncWithPassedInViewDataAndModel()
{
// Arrange
var expected = new HtmlString("value");
var passedInModel = new object();
var passedInViewData = new ViewDataDictionary(new EmptyModelMetadataProvider());
var helper = new Mock<IHtmlHelper>(MockBehavior.Strict);
helper.Setup(h => h.PartialAsync("test", passedInModel, passedInViewData))
.Returns(Task.FromResult((IHtmlContent)expected))
.Verifiable();
// Act
var actual = helper.Object.Partial("test", passedInModel, passedInViewData);
// Assert
Assert.Same(expected, actual);
helper.Verify();
}
[Fact]
public void Partial_InvokesAndRendersPartialAsyncOnHtmlHelperOfT()
{
// Arrange
var model = new TestModel();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(model);
var expected = DefaultTemplatesUtilities.FormatOutput(helper, model);
// Act
var actual = helper.Partial("some-partial");
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(actual));
}
[Fact]
public void PartialWithModel_InvokesAndRendersPartialAsyncOnHtmlHelperOfT()
{
// Arrange
var model = new TestModel();
var helper = DefaultTemplatesUtilities.GetHtmlHelper();
var expected = DefaultTemplatesUtilities.FormatOutput(helper, model);
// Act
var actual = helper.Partial("some-partial", model);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(actual));
}
[Fact]
public void PartialWithViewData_InvokesAndRendersPartialAsyncOnHtmlHelperOfT()
{
// Arrange
var model = new TestModel();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(model);
var viewData = new ViewDataDictionary(helper.MetadataProvider);
var expected = DefaultTemplatesUtilities.FormatOutput(helper, model);
// Act
var actual = helper.Partial("some-partial", viewData);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(actual));
}
[Fact]
public async Task PartialAsync_Throws_IfViewNotFound_MessageUsesGetViewLocations()
{
// Arrange
var expected = "The partial view 'test-view' was not found. The following locations were searched:" +
Environment.NewLine +
"location1" + Environment.NewLine +
"location2";
var model = new TestModel();
var viewEngine = new Mock<ICompositeViewEngine>(MockBehavior.Strict);
viewEngine
.Setup(v => v.GetView(/*executingFilePath*/ null, It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound("test-view", new[] { "location1", "location2" }))
.Verifiable();
viewEngine
.Setup(v => v.FindView(It.IsAny<ActionContext>(), It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound("test-view", Enumerable.Empty<string>()))
.Verifiable();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(model, viewEngine.Object);
var viewData = helper.ViewData;
// Act & Assert
var exception = await Assert.ThrowsAsync<InvalidOperationException>(
() => helper.PartialAsync("test-view", model, viewData));
Assert.Equal(expected, exception.Message);
}
[Fact]
public async Task PartialAsync_Throws_IfViewNotFound_MessageUsesFindViewLocations()
{
// Arrange
var expected = "The partial view 'test-view' was not found. The following locations were searched:" +
Environment.NewLine +
"location1" + Environment.NewLine +
"location2";
var model = new TestModel();
var viewEngine = new Mock<ICompositeViewEngine>(MockBehavior.Strict);
viewEngine
.Setup(v => v.GetView(/*executingFilePath*/ null, It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound("test-view", Enumerable.Empty<string>()))
.Verifiable();
viewEngine
.Setup(v => v.FindView(It.IsAny<ActionContext>(), It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound("test-view", new[] { "location1", "location2" }))
.Verifiable();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(model, viewEngine.Object);
var viewData = helper.ViewData;
// Act & Assert
var exception = await Assert.ThrowsAsync<InvalidOperationException>(
() => helper.PartialAsync("test-view", model, viewData));
Assert.Equal(expected, exception.Message);
}
[Fact]
public async Task PartialAsync_Throws_IfViewNotFound_MessageUsesAllLocations()
{
// Arrange
var expected = "The partial view 'test-view' was not found. The following locations were searched:" +
Environment.NewLine +
"location1" + Environment.NewLine +
"location2" + Environment.NewLine +
"location3" + Environment.NewLine +
"location4";
var model = new TestModel();
var viewEngine = new Mock<ICompositeViewEngine>(MockBehavior.Strict);
viewEngine
.Setup(v => v.GetView(/*executingFilePath*/ null, It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound("test-view", new[] { "location1", "location2" }))
.Verifiable();
viewEngine
.Setup(v => v.FindView(It.IsAny<ActionContext>(), It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound("test-view", new[] { "location3", "location4" }))
.Verifiable();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(model, viewEngine.Object);
var viewData = helper.ViewData;
// Act & Assert
var exception = await Assert.ThrowsAsync<InvalidOperationException>(
() => helper.PartialAsync("test-view", model, viewData));
Assert.Equal(expected, exception.Message);
}
[Fact]
public async Task RenderPartialAsync_Throws_IfViewNotFound_MessageUsesGetViewLocations()
{
// Arrange
var expected = "The partial view 'test-view' was not found. The following locations were searched:" +
Environment.NewLine +
"location1" + Environment.NewLine +
"location2";
var model = new TestModel();
var viewEngine = new Mock<ICompositeViewEngine>(MockBehavior.Strict);
viewEngine
.Setup(v => v.GetView(/*executingFilePath*/ null, It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound("test-view", new[] { "location1", "location2" }))
.Verifiable();
viewEngine
.Setup(v => v.FindView(It.IsAny<ActionContext>(), It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound("test-view", Enumerable.Empty<string>()))
.Verifiable();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(model, viewEngine.Object);
var viewData = helper.ViewData;
// Act & Assert
var exception = await Assert.ThrowsAsync<InvalidOperationException>(
() => helper.RenderPartialAsync("test-view", model, viewData));
Assert.Equal(expected, exception.Message);
}
[Fact]
public async Task RenderPartialAsync_Throws_IfViewNotFound_MessageUsesFindViewLocations()
{
// Arrange
var expected = "The partial view 'test-view' was not found. The following locations were searched:" +
Environment.NewLine +
"location1" + Environment.NewLine +
"location2";
var model = new TestModel();
var viewEngine = new Mock<ICompositeViewEngine>(MockBehavior.Strict);
viewEngine
.Setup(v => v.GetView(/*executingFilePath*/ null, It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound("test-view", Enumerable.Empty<string>()))
.Verifiable();
viewEngine
.Setup(v => v.FindView(It.IsAny<ActionContext>(), It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound("test-view", new[] { "location1", "location2" }))
.Verifiable();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(model, viewEngine.Object);
var viewData = helper.ViewData;
// Act & Assert
var exception = await Assert.ThrowsAsync<InvalidOperationException>(
() => helper.RenderPartialAsync("test-view", model, viewData));
Assert.Equal(expected, exception.Message);
}
[Fact]
public async Task RenderPartialAsync_Throws_IfViewNotFound_MessageUsesAllLocations()
{
// Arrange
var expected = "The partial view 'test-view' was not found. The following locations were searched:" +
Environment.NewLine +
"location1" + Environment.NewLine +
"location2" + Environment.NewLine +
"location3" + Environment.NewLine +
"location4";
var model = new TestModel();
var viewEngine = new Mock<ICompositeViewEngine>(MockBehavior.Strict);
viewEngine
.Setup(v => v.GetView(/*executingFilePath*/ null, It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound("test-view", new[] { "location1", "location2" }))
.Verifiable();
viewEngine
.Setup(v => v.FindView(It.IsAny<ActionContext>(), It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound("test-view", new[] { "location3", "location4" }))
.Verifiable();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(model, viewEngine.Object);
var viewData = helper.ViewData;
// Act & Assert
var exception = await Assert.ThrowsAsync<InvalidOperationException>(
() => helper.RenderPartialAsync("test-view", model, viewData));
Assert.Equal(expected, exception.Message);
}
private sealed class TestModel
{
public override string ToString()
{
return "test-model-content";
}
}
}
}
| |
//
// CompositeCell.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using MonoMac.AppKit;
using MonoMac.Foundation;
using Xwt.Backends;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
namespace Xwt.Mac
{
class CompositeCell: NSCell, ICopiableObject, ICellDataSource
{
ICellSource source;
NSObject val;
List<ICellRenderer> cells = new List<ICellRenderer> ();
Orientation direction;
NSCell trackingCell;
ITablePosition tablePosition;
ApplicationContext context;
static CompositeCell ()
{
Util.MakeCopiable<CompositeCell> ();
}
public CompositeCell (ApplicationContext context, Orientation dir, ICellSource source)
{
direction = dir;
this.context = context;
this.source = source;
}
public CompositeCell (IntPtr p): base (p)
{
}
public ApplicationContext Context {
get { return context; }
}
#region ICellDataSource implementation
object ICellDataSource.GetValue (IDataField field)
{
return source.GetValue (tablePosition.Position, field.Index);
}
#endregion
public void SetValue (IDataField field, object value)
{
source.SetValue (tablePosition.Position, field.Index, value);
}
public void SetCurrentEventRow ()
{
source.SetCurrentEventRow (tablePosition.Position);
}
void ICopiableObject.CopyFrom (object other)
{
var ob = (CompositeCell)other;
context = ob.context;
source = ob.source;
val = ob.val;
tablePosition = ob.tablePosition;
direction = ob.direction;
trackingCell = ob.trackingCell;
cells = new List<ICellRenderer> ();
foreach (var c in ob.cells) {
var copy = (ICellRenderer) Activator.CreateInstance (c.GetType ());
copy.CopyFrom (c);
AddCell (copy);
}
if (tablePosition != null)
Fill ();
}
public override NSObject ObjectValue {
get {
return val;
}
set {
val = value;
if (val is ITablePosition) {
tablePosition = (ITablePosition) val;
Fill ();
}
else if (val is NSNumber) {
tablePosition = new TableRow () {
Row = ((NSNumber)val).Int32Value
};
Fill ();
} else
tablePosition = null;
}
}
public override bool IsOpaque {
get {
var b = base.IsOpaque;
return true;
}
}
public void AddCell (ICellRenderer cell)
{
cell.CellContainer = this;
cells.Add (cell);
}
public void Fill ()
{
foreach (var c in cells) {
c.Backend.CurrentCell = (NSCell) c;
c.Backend.CurrentPosition = tablePosition;
c.Backend.Frontend.Load (this);
c.Fill ();
}
var s = CellSize;
if (s.Height > source.RowHeight)
source.RowHeight = s.Height;
}
public override void CalcDrawInfo (RectangleF aRect)
{
base.CalcDrawInfo (aRect);
}
IEnumerable<ICellRenderer> VisibleCells {
get { return cells.Where (c => c.Backend.Frontend.Visible); }
}
SizeF CalcSize ()
{
float w = 0;
float h = 0;
foreach (NSCell c in VisibleCells) {
var s = c.CellSize;
if (direction == Orientation.Horizontal) {
w += s.Width;
if (s.Height > h)
h = s.Height;
} else {
h += s.Height;
if (s.Width > w)
w = s.Width;
}
}
return new SizeF (w, h);
}
public override SizeF CellSizeForBounds (RectangleF bounds)
{
return CalcSize ();
}
public override NSBackgroundStyle BackgroundStyle {
get {
return base.BackgroundStyle;
}
set {
base.BackgroundStyle = value;
foreach (NSCell c in cells)
c.BackgroundStyle = value;
}
}
public override NSCellStateValue State {
get {
return base.State;
}
set {
base.State = value;
foreach (NSCell c in cells)
c.State = value;
}
}
public override bool Highlighted {
get {
return base.Highlighted;
}
set {
base.Highlighted = value;
foreach (NSCell c in cells)
c.Highlighted = value;
}
}
public override void DrawInteriorWithFrame (RectangleF cellFrame, NSView inView)
{
foreach (CellPos cp in GetCells(cellFrame))
cp.Cell.DrawInteriorWithFrame (cp.Frame, inView);
}
public override void Highlight (bool flag, RectangleF withFrame, NSView inView)
{
foreach (CellPos cp in GetCells(withFrame)) {
cp.Cell.Highlight (flag, cp.Frame, inView);
}
}
public override NSCellHit HitTest (NSEvent forEvent, RectangleF inRect, NSView ofView)
{
foreach (CellPos cp in GetCells(inRect)) {
var h = cp.Cell.HitTest (forEvent, cp.Frame, ofView);
if (h != NSCellHit.None)
return h;
}
return NSCellHit.None;
}
public override bool TrackMouse (NSEvent theEvent, RectangleF cellFrame, NSView controlView, bool untilMouseUp)
{
var c = GetHitCell (theEvent, cellFrame, controlView);
if (c != null)
return c.Cell.TrackMouse (theEvent, c.Frame, controlView, untilMouseUp);
else
return base.TrackMouse (theEvent, cellFrame, controlView, untilMouseUp);
}
public RectangleF GetCellRect (RectangleF cellFrame, NSCell cell)
{
if (tablePosition is TableRow) {
foreach (var c in GetCells (cellFrame)) {
if (c.Cell == cell)
return c.Frame;
}
}
return RectangleF.Empty;
}
CellPos GetHitCell (NSEvent theEvent, RectangleF cellFrame, NSView controlView)
{
foreach (CellPos cp in GetCells(cellFrame)) {
var h = cp.Cell.HitTest (theEvent, cp.Frame, controlView);
if (h != NSCellHit.None)
return cp;
}
return null;
}
IEnumerable<CellPos> GetCells (RectangleF cellFrame)
{
if (direction == Orientation.Horizontal) {
foreach (NSCell c in VisibleCells) {
var s = c.CellSize;
var w = Math.Min (cellFrame.Width, s.Width);
RectangleF f = new RectangleF (cellFrame.X, cellFrame.Y, w, cellFrame.Height);
cellFrame.X += w;
cellFrame.Width -= w;
yield return new CellPos () { Cell = c, Frame = f };
}
} else {
float y = cellFrame.Y;
foreach (NSCell c in VisibleCells) {
var s = c.CellSize;
RectangleF f = new RectangleF (cellFrame.X, y, s.Width, cellFrame.Height);
y += s.Height;
yield return new CellPos () { Cell = c, Frame = f };
}
}
}
class CellPos
{
public NSCell Cell;
public RectangleF Frame;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Commencement.Core.Domain;
using Commencement.Tests.Core;
using Commencement.Tests.Core.Helpers;
using FluentNHibernate.Testing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using UCDArch.Core.PersistanceSupport;
using UCDArch.Data.NHibernate;
using UCDArch.Testing.Extensions;
namespace Commencement.Tests.Repositories
{
/// <summary>
/// Entity Name: RegistrationParticipation
/// LookupFieldName: NumberTickets yrjuy
/// </summary>
[TestClass]
public class RegistrationParticipationRepositoryTests : AbstractRepositoryTests<RegistrationParticipation, int, RegistrationParticipationMap>
{
/// <summary>
/// Gets or sets the RegistrationParticipation repository.
/// </summary>
/// <value>The RegistrationParticipation repository.</value>
public IRepository<RegistrationParticipation> RegistrationParticipationRepository { get; set; }
public IRepositoryWithTypedId<State, string > StateRepository { get; set; }
public IRepositoryWithTypedId<MajorCode, string> MajorCodeRepository { get; set; }
#region Init and Overrides
/// <summary>
/// Initializes a new instance of the <see cref="RegistrationParticipationRepositoryTests"/> class.
/// </summary>
public RegistrationParticipationRepositoryTests()
{
RegistrationParticipationRepository = new Repository<RegistrationParticipation>();
StateRepository = new RepositoryWithTypedId<State, string>();
MajorCodeRepository = new RepositoryWithTypedId<MajorCode, string>();
}
/// <summary>
/// Gets the valid entity of type T
/// </summary>
/// <param name="counter">The counter.</param>
/// <returns>A valid entity of type T</returns>
protected override RegistrationParticipation GetValid(int? counter)
{
var rtValue = CreateValidEntities.RegistrationParticipation(counter);
rtValue.Registration = Repository.OfType<Registration>().Queryable.First();
rtValue.Ceremony = Repository.OfType<Ceremony>().Queryable.First();
rtValue.Major = Repository.OfType<MajorCode>().Queryable.First();
var count = 99;
if (counter != null)
{
count = (int) counter;
}
rtValue.NumberTickets = count;
return rtValue;
}
/// <summary>
/// A Query which will return a single record
/// </summary>
/// <param name="numberAtEnd"></param>
/// <returns></returns>
protected override IQueryable<RegistrationParticipation> GetQuery(int numberAtEnd)
{
return RegistrationParticipationRepository.Queryable.Where(a => a.NumberTickets == numberAtEnd);
}
/// <summary>
/// A way to compare the entities that were read.
/// For example, this would have the assert.AreEqual("Comment" + counter, entity.Comment);
/// </summary>
/// <param name="entity"></param>
/// <param name="counter"></param>
protected override void FoundEntityComparison(RegistrationParticipation entity, int counter)
{
Assert.AreEqual(counter, entity.NumberTickets);
}
/// <summary>
/// Updates , compares, restores.
/// </summary>
/// <param name="entity">The entity.</param>
/// <param name="action">The action.</param>
protected override void UpdateUtility(RegistrationParticipation entity, ARTAction action)
{
const int updateValue = 99;
switch (action)
{
case ARTAction.Compare:
Assert.AreEqual(updateValue, entity.NumberTickets);
break;
case ARTAction.Restore:
entity.NumberTickets = IntRestoreValue;
break;
case ARTAction.Update:
IntRestoreValue = entity.NumberTickets;
entity.NumberTickets = updateValue;
break;
}
}
/// <summary>
/// Loads the data.
/// </summary>
protected override void LoadData()
{
Repository.OfType<Registration>().DbContext.BeginTransaction();
LoadState(1);
LoadTermCode(1);
LoadStudent(1);
LoadRegistrations(3);
LoadCeremony(3);
LoadMajorCode(3);
Repository.OfType<Registration>().DbContext.CommitTransaction();
RegistrationParticipationRepository.DbContext.BeginTransaction();
LoadRecords(5);
RegistrationParticipationRepository.DbContext.CommitTransaction();
}
#endregion Init and Overrides
#region Registration Tests
#region Invalid Tests
/// <summary>
/// Tests the Registration with A value of null does not save.
/// </summary>
[TestMethod]
[ExpectedException(typeof(ApplicationException))]
public void TestRegistrationWithAValueOfNullDoesNotSave()
{
RegistrationParticipation registrationParticipation = null;
try
{
#region Arrange
registrationParticipation = GetValid(9);
registrationParticipation.Registration = null;
#endregion Arrange
#region Act
RegistrationParticipationRepository.DbContext.BeginTransaction();
RegistrationParticipationRepository.EnsurePersistent(registrationParticipation);
RegistrationParticipationRepository.DbContext.CommitTransaction();
#endregion Act
}
catch (Exception)
{
Assert.IsNotNull(registrationParticipation);
Assert.AreEqual(registrationParticipation.Registration, null);
var results = registrationParticipation.ValidationResults().AsMessageList();
results.AssertErrorsAre("Registration: may not be null");
Assert.IsTrue(registrationParticipation.IsTransient());
Assert.IsFalse(registrationParticipation.IsValid());
throw;
}
}
[TestMethod]
[ExpectedException(typeof(NHibernate.TransientObjectException))]
public void TestRegistrationWithANewValueDoesNotSave()
{
RegistrationParticipation registrationParticipation = null;
try
{
#region Arrange
registrationParticipation = GetValid(9);
registrationParticipation.Registration = CreateValidEntities.Registration(9);
registrationParticipation.Registration.State = StateRepository.Queryable.First();
registrationParticipation.Registration.Student = Repository.OfType<Student>().Queryable.First();
registrationParticipation.Registration.TermCode = Repository.OfType<TermCode>().Queryable.First();
#endregion Arrange
#region Act
RegistrationParticipationRepository.DbContext.BeginTransaction();
RegistrationParticipationRepository.EnsurePersistent(registrationParticipation);
RegistrationParticipationRepository.DbContext.CommitTransaction();
#endregion Act
}
catch (Exception ex)
{
Assert.IsNotNull(registrationParticipation);
Assert.IsNotNull(ex);
Assert.AreEqual("object references an unsaved transient instance - save the transient instance before flushing. Type: Commencement.Core.Domain.Registration, Entity: Commencement.Core.Domain.Registration", ex.Message);
throw;
}
}
#endregion Invalid Tests
#region Valid Tests
[TestMethod]
public void TestRegistrationWithExistingValueSaves()
{
#region Arrange
var registrationParticipation = GetValid(9);
registrationParticipation.Registration = Repository.OfType<Registration>().GetNullableById(2);
Assert.IsNotNull(registrationParticipation.Registration);
#endregion Arrange
#region Act
RegistrationParticipationRepository.DbContext.BeginTransaction();
RegistrationParticipationRepository.EnsurePersistent(registrationParticipation);
RegistrationParticipationRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsNotNull(registrationParticipation.Registration);
Assert.AreEqual("Address12", registrationParticipation.Registration.Address1);
Assert.IsFalse(registrationParticipation.IsTransient());
Assert.IsTrue(registrationParticipation.IsValid());
#endregion Assert
}
#endregion Valid Tests
#region Cascade Tests
[TestMethod]
public void TestDeleteregistrationParticipationsDoesNotCascadeToRegistration()
{
#region Arrange
var registration = Repository.OfType<Registration>().GetNullableById(2);
Assert.IsNotNull(registration);
var registrationParticipation = GetValid(9);
registrationParticipation.Registration = registration;
RegistrationParticipationRepository.DbContext.BeginTransaction();
RegistrationParticipationRepository.EnsurePersistent(registrationParticipation);
RegistrationParticipationRepository.DbContext.CommitTransaction();
var saveId = registrationParticipation.Id;
NHibernateSessionManager.Instance.GetSession().Evict(registration);
NHibernateSessionManager.Instance.GetSession().Evict(registrationParticipation);
#endregion Arrange
#region Act
registrationParticipation = RegistrationParticipationRepository.GetNullableById(saveId);
Assert.IsNotNull(registrationParticipation);
RegistrationParticipationRepository.DbContext.BeginTransaction();
RegistrationParticipationRepository.Remove(registrationParticipation);
RegistrationParticipationRepository.DbContext.CommitTransaction();
NHibernateSessionManager.Instance.GetSession().Evict(registration);
#endregion Act
#region Assert
Assert.IsNull(RegistrationParticipationRepository.GetNullableById(saveId));
Assert.IsNotNull(Repository.OfType<Registration>().GetNullableById(2));
#endregion Assert
}
#endregion Cascade Tests
#endregion Registration Tests
#region Major Tests
#region Invalid Tests
/// <summary>
/// Tests the Major with A value of null does not save.
/// </summary>
[TestMethod]
[ExpectedException(typeof(ApplicationException))]
public void TestMajorWithAValueOfNullDoesNotSave()
{
RegistrationParticipation registrationParticipation = null;
try
{
#region Arrange
registrationParticipation = GetValid(9);
registrationParticipation.Major = null;
#endregion Arrange
#region Act
RegistrationParticipationRepository.DbContext.BeginTransaction();
RegistrationParticipationRepository.EnsurePersistent(registrationParticipation);
RegistrationParticipationRepository.DbContext.CommitTransaction();
#endregion Act
}
catch (Exception)
{
Assert.IsNotNull(registrationParticipation);
Assert.AreEqual(registrationParticipation.Major, null);
var results = registrationParticipation.ValidationResults().AsMessageList();
results.AssertErrorsAre("Major: may not be null");
Assert.IsTrue(registrationParticipation.IsTransient());
Assert.IsFalse(registrationParticipation.IsValid());
throw;
}
}
[TestMethod]
[ExpectedException(typeof(NHibernate.TransientObjectException))]
public void TestMajorWithANewValueDoesNotSave()
{
RegistrationParticipation registrationParticipation = null;
try
{
#region Arrange
registrationParticipation = GetValid(9);
registrationParticipation.Major = CreateValidEntities.MajorCode(9);
#endregion Arrange
#region Act
RegistrationParticipationRepository.DbContext.BeginTransaction();
RegistrationParticipationRepository.EnsurePersistent(registrationParticipation);
RegistrationParticipationRepository.DbContext.CommitTransaction();
#endregion Act
}
catch (Exception ex)
{
Assert.IsNotNull(registrationParticipation);
Assert.IsNotNull(ex);
Assert.AreEqual("object references an unsaved transient instance - save the transient instance before flushing. Type: Commencement.Core.Domain.MajorCode, Entity: Commencement.Core.Domain.MajorCode", ex.Message);
throw;
}
}
#endregion Invalid Tests
#region Valid Tests
[TestMethod]
public void TestMajorWithExistingMajorCodeSaves()
{
#region Arrange
var major = MajorCodeRepository.GetNullableById("2");
Assert.IsNotNull(major);
var registrationParticipation = GetValid(9);
registrationParticipation.Major = major;
#endregion Arrange
#region Act
RegistrationParticipationRepository.DbContext.BeginTransaction();
RegistrationParticipationRepository.EnsurePersistent(registrationParticipation);
RegistrationParticipationRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsNotNull(registrationParticipation.Major);
Assert.AreEqual("Name2", registrationParticipation.Major.Name);
Assert.IsFalse(registrationParticipation.IsTransient());
Assert.IsTrue(registrationParticipation.IsValid());
#endregion Assert
}
#endregion Valid Tests
#region Cascade Tests
[TestMethod]
public void TestDeleteRegistrationParticipationsDoesNotCascadeToMajorCode()
{
#region Arrange
var major = MajorCodeRepository.GetNullableById("2");
Assert.IsNotNull(major);
var registrationParticipation = GetValid(9);
registrationParticipation.Major = major;
RegistrationParticipationRepository.DbContext.BeginTransaction();
RegistrationParticipationRepository.EnsurePersistent(registrationParticipation);
RegistrationParticipationRepository.DbContext.CommitTransaction();
var saveId = registrationParticipation.Id;
NHibernateSessionManager.Instance.GetSession().Evict(major);
NHibernateSessionManager.Instance.GetSession().Evict(registrationParticipation);
#endregion Arrange
#region Act
registrationParticipation = RegistrationParticipationRepository.GetNullableById(saveId);
Assert.IsNotNull(registrationParticipation);
RegistrationParticipationRepository.DbContext.BeginTransaction();
RegistrationParticipationRepository.Remove(registrationParticipation);
RegistrationParticipationRepository.DbContext.CommitTransaction();
NHibernateSessionManager.Instance.GetSession().Evict(major);
#endregion Act
#region Assert
Assert.IsNull(RegistrationParticipationRepository.GetNullableById(saveId));
Assert.IsNotNull(MajorCodeRepository.GetNullableById("2"));
#endregion Assert
}
#endregion Cascade Tests
#endregion Major Tests
#region Ceremony Tests
#region Invalid Tests
[TestMethod]
[ExpectedException(typeof(ApplicationException))]
public void TestCeremonyWithAValueOfNullDoesNotSave()
{
RegistrationParticipation registrationParticipation = null;
try
{
#region Arrange
registrationParticipation = GetValid(9);
registrationParticipation.Ceremony = null;
#endregion Arrange
#region Act
RegistrationParticipationRepository.DbContext.BeginTransaction();
RegistrationParticipationRepository.EnsurePersistent(registrationParticipation);
RegistrationParticipationRepository.DbContext.CommitTransaction();
#endregion Act
}
catch (Exception)
{
Assert.IsNotNull(registrationParticipation);
Assert.AreEqual(registrationParticipation.Ceremony, null);
var results = registrationParticipation.ValidationResults().AsMessageList();
results.AssertErrorsAre("Ceremony: may not be null");
Assert.IsTrue(registrationParticipation.IsTransient());
Assert.IsFalse(registrationParticipation.IsValid());
throw;
}
}
[TestMethod]
[ExpectedException(typeof(NHibernate.TransientObjectException))]
public void TestCeremonyWithANewValueDoesNotSave()
{
RegistrationParticipation registrationParticipation = null;
try
{
#region Arrange
registrationParticipation = GetValid(9);
registrationParticipation.Ceremony = CreateValidEntities.Ceremony(9);
registrationParticipation.Ceremony.TermCode = Repository.OfType<TermCode>().Queryable.First();
#endregion Arrange
#region Act
RegistrationParticipationRepository.DbContext.BeginTransaction();
RegistrationParticipationRepository.EnsurePersistent(registrationParticipation);
RegistrationParticipationRepository.DbContext.CommitTransaction();
#endregion Act
}
catch (Exception ex)
{
Assert.IsNotNull(registrationParticipation);
Assert.IsNotNull(ex);
Assert.AreEqual("object references an unsaved transient instance - save the transient instance before flushing. Type: Commencement.Core.Domain.Ceremony, Entity: Commencement.Core.Domain.Ceremony", ex.Message);
throw;
}
}
#endregion Invalid Tests
#region Valid Tests
[TestMethod]
public void TestCeremonyWithExistingValueSaves()
{
#region Arrange
var registrationParticipation = GetValid(9);
registrationParticipation.Ceremony = Repository.OfType<Ceremony>().GetNullableById(2);
Assert.IsNotNull(registrationParticipation.Ceremony);
#endregion Arrange
#region Act
RegistrationParticipationRepository.DbContext.BeginTransaction();
RegistrationParticipationRepository.EnsurePersistent(registrationParticipation);
RegistrationParticipationRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsNotNull(registrationParticipation.Ceremony);
Assert.AreEqual("Location2", registrationParticipation.Ceremony.Location);
Assert.IsFalse(registrationParticipation.IsTransient());
Assert.IsTrue(registrationParticipation.IsValid());
#endregion Assert
}
#endregion Valid Tests
#region Cascade Tests
[TestMethod]
public void TestDeleteRegistrationParticipationsDoesNotCascadeToCeremony()
{
#region Arrange
var ceremony = Repository.OfType<Ceremony>().GetNullableById(2);
Assert.IsNotNull(ceremony);
var registrationParticipation = GetValid(9);
registrationParticipation.Ceremony = ceremony;
RegistrationParticipationRepository.DbContext.BeginTransaction();
RegistrationParticipationRepository.EnsurePersistent(registrationParticipation);
RegistrationParticipationRepository.DbContext.CommitTransaction();
var saveId = registrationParticipation.Id;
NHibernateSessionManager.Instance.GetSession().Evict(ceremony);
NHibernateSessionManager.Instance.GetSession().Evict(registrationParticipation);
#endregion Arrange
#region Act
registrationParticipation = RegistrationParticipationRepository.GetNullableById(saveId);
Assert.IsNotNull(registrationParticipation);
RegistrationParticipationRepository.DbContext.BeginTransaction();
RegistrationParticipationRepository.Remove(registrationParticipation);
RegistrationParticipationRepository.DbContext.CommitTransaction();
NHibernateSessionManager.Instance.GetSession().Evict(ceremony);
#endregion Act
#region Assert
Assert.IsNull(RegistrationParticipationRepository.GetNullableById(saveId));
Assert.IsNotNull(Repository.OfType<Ceremony>().GetNullableById(2));
#endregion Assert
}
#endregion Cascade Tests
#endregion Ceremony Tests
#region ExtraTicketPetition Tests
#region Valid Tests
[TestMethod]
public void TestExtraTicketPetitionWithNullValueSaves()
{
#region Arrange
var registrationParticipation = GetValid(9);
registrationParticipation.ExtraTicketPetition = null;
#endregion Arrange
#region Act
RegistrationParticipationRepository.DbContext.BeginTransaction();
RegistrationParticipationRepository.EnsurePersistent(registrationParticipation);
RegistrationParticipationRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsNull(registrationParticipation.ExtraTicketPetition);
Assert.IsFalse(registrationParticipation.IsTransient());
Assert.IsTrue(registrationParticipation.IsValid());
#endregion Assert
}
[TestMethod]
public void TestExtraTicketPetitionWithNewValueSaves()
{
#region Arrange
var registrationParticipation = GetValid(9);
registrationParticipation.ExtraTicketPetition = CreateValidEntities.ExtraTicketPetition(7);
#endregion Arrange
#region Act
RegistrationParticipationRepository.DbContext.BeginTransaction();
RegistrationParticipationRepository.EnsurePersistent(registrationParticipation);
RegistrationParticipationRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsNotNull(registrationParticipation.ExtraTicketPetition);
Assert.AreEqual("Reason7", registrationParticipation.ExtraTicketPetition.Reason);
Assert.IsFalse(registrationParticipation.IsTransient());
Assert.IsTrue(registrationParticipation.IsValid());
#endregion Assert
}
#endregion Valid Tests
#region Cascade Tests
[TestMethod]
public void TestExtraTicketPetitionCascadesSave()
{
#region Arrange
var registrationParticipation = GetValid(9);
registrationParticipation.ExtraTicketPetition = CreateValidEntities.ExtraTicketPetition(7);
var count = Repository.OfType<ExtraTicketPetition>().Queryable.Count();
#endregion Arrange
#region Act
RegistrationParticipationRepository.DbContext.BeginTransaction();
RegistrationParticipationRepository.EnsurePersistent(registrationParticipation);
RegistrationParticipationRepository.DbContext.CommitTransaction();
var saveId = registrationParticipation.ExtraTicketPetition.Id;
#endregion Act
#region Assert
Assert.AreEqual(count + 1, Repository.OfType<ExtraTicketPetition>().Queryable.Count());
Assert.IsNotNull(Repository.OfType<ExtraTicketPetition>().GetNullableById(saveId));
#endregion Assert
}
[TestMethod]
public void TestDeleteRegistrationPetitionsCascadesToExtraTicketPetition()
{
#region Arrange
var registrationParticipation = GetValid(9);
registrationParticipation.ExtraTicketPetition = CreateValidEntities.ExtraTicketPetition(7);
var count = Repository.OfType<ExtraTicketPetition>().Queryable.Count();
RegistrationParticipationRepository.DbContext.BeginTransaction();
RegistrationParticipationRepository.EnsurePersistent(registrationParticipation);
RegistrationParticipationRepository.DbContext.CommitTransaction();
var saveId = registrationParticipation.ExtraTicketPetition.Id;
Assert.IsNotNull(Repository.OfType<ExtraTicketPetition>().GetNullableById(saveId));
var saveRegParId = registrationParticipation.Id;
#endregion Arrange
#region Act
RegistrationParticipationRepository.DbContext.BeginTransaction();
RegistrationParticipationRepository.Remove(registrationParticipation);
RegistrationParticipationRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.AreEqual(count, Repository.OfType<ExtraTicketPetition>().Queryable.Count());
Assert.IsNull(Repository.OfType<ExtraTicketPetition>().GetNullableById(saveId));
Assert.IsNull(RegistrationParticipationRepository.GetNullableById(saveRegParId));
#endregion Assert
}
#endregion Cascade Tests
#endregion ExtraTicketPetition Tests
#region NumberTickets Tests
/// <summary>
/// Tests the NumberTickets with max int value saves.
/// </summary>
[TestMethod]
public void TestNumberTicketsWithMaxIntValueSaves()
{
#region Arrange
var record = GetValid(9);
record.NumberTickets = int.MaxValue;
#endregion Arrange
#region Act
RegistrationParticipationRepository.DbContext.BeginTransaction();
RegistrationParticipationRepository.EnsurePersistent(record);
RegistrationParticipationRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.AreEqual(int.MaxValue, record.NumberTickets);
Assert.IsFalse(record.IsTransient());
Assert.IsTrue(record.IsValid());
#endregion Assert
}
/// <summary>
/// Tests the NumberTickets with min int value saves.
/// </summary>
[TestMethod]
public void TestNumberTicketsWithMinIntValueSaves()
{
#region Arrange
var record = GetValid(9);
record.NumberTickets = int.MinValue;
#endregion Arrange
#region Act
RegistrationParticipationRepository.DbContext.BeginTransaction();
RegistrationParticipationRepository.EnsurePersistent(record);
RegistrationParticipationRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.AreEqual(int.MinValue, record.NumberTickets);
Assert.IsFalse(record.IsTransient());
Assert.IsTrue(record.IsValid());
#endregion Assert
}
#endregion NumberTickets Tests
#region Cancelled Tests
/// <summary>
/// Tests the Cancelled is false saves.
/// </summary>
[TestMethod]
public void TestCancelledIsFalseSaves()
{
#region Arrange
RegistrationParticipation registrationParticipation = GetValid(9);
registrationParticipation.Cancelled = false;
#endregion Arrange
#region Act
RegistrationParticipationRepository.DbContext.BeginTransaction();
RegistrationParticipationRepository.EnsurePersistent(registrationParticipation);
RegistrationParticipationRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsFalse(registrationParticipation.Cancelled);
Assert.IsFalse(registrationParticipation.IsTransient());
Assert.IsTrue(registrationParticipation.IsValid());
#endregion Assert
}
/// <summary>
/// Tests the Cancelled is true saves.
/// </summary>
[TestMethod]
public void TestCancelledIsTrueSaves()
{
#region Arrange
var registrationParticipation = GetValid(9);
registrationParticipation.Cancelled = true;
#endregion Arrange
#region Act
RegistrationParticipationRepository.DbContext.BeginTransaction();
RegistrationParticipationRepository.EnsurePersistent(registrationParticipation);
RegistrationParticipationRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsTrue(registrationParticipation.Cancelled);
Assert.IsFalse(registrationParticipation.IsTransient());
Assert.IsTrue(registrationParticipation.IsValid());
#endregion Assert
}
#endregion Cancelled Tests
#region LabelPrinted Tests
/// <summary>
/// Tests the LabelPrinted is false saves.
/// </summary>
[TestMethod]
public void TestLabelPrintedIsFalseSaves()
{
#region Arrange
RegistrationParticipation registrationParticipation = GetValid(9);
registrationParticipation.LabelPrinted = false;
#endregion Arrange
#region Act
RegistrationParticipationRepository.DbContext.BeginTransaction();
RegistrationParticipationRepository.EnsurePersistent(registrationParticipation);
RegistrationParticipationRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsFalse(registrationParticipation.LabelPrinted);
Assert.IsFalse(registrationParticipation.IsTransient());
Assert.IsTrue(registrationParticipation.IsValid());
#endregion Assert
}
/// <summary>
/// Tests the LabelPrinted is true saves.
/// </summary>
[TestMethod]
public void TestLabelPrintedIsTrueSaves()
{
#region Arrange
var registrationParticipation = GetValid(9);
registrationParticipation.LabelPrinted = true;
#endregion Arrange
#region Act
RegistrationParticipationRepository.DbContext.BeginTransaction();
RegistrationParticipationRepository.EnsurePersistent(registrationParticipation);
RegistrationParticipationRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsTrue(registrationParticipation.LabelPrinted);
Assert.IsFalse(registrationParticipation.IsTransient());
Assert.IsTrue(registrationParticipation.IsValid());
#endregion Assert
}
#endregion LabelPrinted Tests
#region DateRegistered Tests
/// <summary>
/// Tests the DateRegistered with past date will save.
/// </summary>
[TestMethod]
public void TestDateRegisteredWithPastDateWillSave()
{
#region Arrange
var compareDate = DateTime.Now.AddDays(-10);
RegistrationParticipation record = GetValid(99);
record.DateRegistered = compareDate;
#endregion Arrange
#region Act
RegistrationParticipationRepository.DbContext.BeginTransaction();
RegistrationParticipationRepository.EnsurePersistent(record);
RegistrationParticipationRepository.DbContext.CommitChanges();
#endregion Act
#region Assert
Assert.IsFalse(record.IsTransient());
Assert.IsTrue(record.IsValid());
Assert.AreEqual(compareDate, record.DateRegistered);
#endregion Assert
}
/// <summary>
/// Tests the DateRegistered with current date date will save.
/// </summary>
[TestMethod]
public void TestDateRegisteredWithCurrentDateDateWillSave()
{
#region Arrange
var compareDate = DateTime.Now;
var record = GetValid(99);
record.DateRegistered = compareDate;
#endregion Arrange
#region Act
RegistrationParticipationRepository.DbContext.BeginTransaction();
RegistrationParticipationRepository.EnsurePersistent(record);
RegistrationParticipationRepository.DbContext.CommitChanges();
#endregion Act
#region Assert
Assert.IsFalse(record.IsTransient());
Assert.IsTrue(record.IsValid());
Assert.AreEqual(compareDate, record.DateRegistered);
#endregion Assert
}
/// <summary>
/// Tests the DateRegistered with future date date will save.
/// </summary>
[TestMethod]
public void TestDateRegisteredWithFutureDateDateWillSave()
{
#region Arrange
var compareDate = DateTime.Now.AddDays(15);
var record = GetValid(99);
record.DateRegistered = compareDate;
#endregion Arrange
#region Act
RegistrationParticipationRepository.DbContext.BeginTransaction();
RegistrationParticipationRepository.EnsurePersistent(record);
RegistrationParticipationRepository.DbContext.CommitChanges();
#endregion Act
#region Assert
Assert.IsFalse(record.IsTransient());
Assert.IsTrue(record.IsValid());
Assert.AreEqual(compareDate, record.DateRegistered);
#endregion Assert
}
#endregion DateRegistered Tests
#region DateUpdated Tests
/// <summary>
/// Tests the DateUpdated with past date will save.
/// </summary>
[TestMethod]
public void TestDateUpdatedWithPastDateWillSave()
{
#region Arrange
var compareDate = DateTime.Now.AddDays(-10);
RegistrationParticipation record = GetValid(99);
record.DateUpdated = compareDate;
#endregion Arrange
#region Act
RegistrationParticipationRepository.DbContext.BeginTransaction();
RegistrationParticipationRepository.EnsurePersistent(record);
RegistrationParticipationRepository.DbContext.CommitChanges();
#endregion Act
#region Assert
Assert.IsFalse(record.IsTransient());
Assert.IsTrue(record.IsValid());
Assert.AreEqual(compareDate, record.DateUpdated);
#endregion Assert
}
/// <summary>
/// Tests the DateUpdated with current date date will save.
/// </summary>
[TestMethod]
public void TestDateUpdatedWithCurrentDateDateWillSave()
{
#region Arrange
var compareDate = DateTime.Now;
var record = GetValid(99);
record.DateUpdated = compareDate;
#endregion Arrange
#region Act
RegistrationParticipationRepository.DbContext.BeginTransaction();
RegistrationParticipationRepository.EnsurePersistent(record);
RegistrationParticipationRepository.DbContext.CommitChanges();
#endregion Act
#region Assert
Assert.IsFalse(record.IsTransient());
Assert.IsTrue(record.IsValid());
Assert.AreEqual(compareDate, record.DateUpdated);
#endregion Assert
}
/// <summary>
/// Tests the DateUpdated with future date date will save.
/// </summary>
[TestMethod]
public void TestDateUpdatedWithFutureDateDateWillSave()
{
#region Arrange
var compareDate = DateTime.Now.AddDays(15);
var record = GetValid(99);
record.DateUpdated = compareDate;
#endregion Arrange
#region Act
RegistrationParticipationRepository.DbContext.BeginTransaction();
RegistrationParticipationRepository.EnsurePersistent(record);
RegistrationParticipationRepository.DbContext.CommitChanges();
#endregion Act
#region Assert
Assert.IsFalse(record.IsTransient());
Assert.IsTrue(record.IsValid());
Assert.AreEqual(compareDate, record.DateUpdated);
#endregion Assert
}
#endregion DateUpdated Tests
#region Extended Fields / Methods Tests
#region TicketDistribution Tests
[TestMethod]
public void TestTicketDistributionReturnsExpectedValue1()
{
#region Arrange
var registrationParticipation = GetValid(9);
registrationParticipation.Ceremony.PrintingDeadline = DateTime.Now;
registrationParticipation.DateRegistered = DateTime.Now.AddDays(1);
#endregion Arrange
#region Act
var result = registrationParticipation.TicketDistribution;
#endregion Act
#region Assert
Assert.AreEqual("Pickup Tickets in person as specified in web site faq.", result);
#endregion Assert
}
[TestMethod]
public void TestTicketDistributionReturnsExpectedValue2()
{
#region Arrange
var registrationParticipation = GetValid(9);
registrationParticipation.Ceremony.PrintingDeadline = DateTime.Now;
registrationParticipation.DateRegistered = DateTime.Now.AddDays(-1);
registrationParticipation.Registration.MailTickets = true;
#endregion Arrange
#region Act
var result = registrationParticipation.TicketDistribution;
#endregion Act
#region Assert
Assert.AreEqual("Mail tickets to provided address.", result);
#endregion Assert
}
[TestMethod]
public void TestTicketDistributionReturnsExpectedValue3()
{
#region Arrange
var registrationParticipation = GetValid(9);
registrationParticipation.Ceremony.PrintingDeadline = DateTime.Now;
registrationParticipation.DateRegistered = DateTime.Now.AddDays(-1);
registrationParticipation.Registration.MailTickets = false;
#endregion Arrange
#region Act
var result = registrationParticipation.TicketDistribution;
#endregion Act
#region Assert
Assert.AreEqual("Pickup tickets at arc ticket office.", result);
#endregion Assert
}
#endregion TicketDistribution Tests
#region IsValidForTickets Tests
[TestMethod]
public void TestIsValidForTicketsReturnsExpectedValue1()
{
#region Arrange
var record = GetValid(9);
record.Cancelled = true;
record.Registration.Student.SjaBlock = false;
record.Registration.Student.Blocked = false;
#endregion Arrange
#region Assert
Assert.IsFalse(record.IsValidForTickets);
#endregion Assert
}
[TestMethod]
public void TestIsValidForTicketsReturnsExpectedValue2()
{
#region Arrange
var record = GetValid(9);
record.Cancelled = false;
record.Registration.Student.SjaBlock = true;
record.Registration.Student.Blocked = false;
#endregion Arrange
#region Assert
Assert.IsFalse(record.IsValidForTickets);
#endregion Assert
}
[TestMethod]
public void TestIsValidForTicketsReturnsExpectedValue3()
{
#region Arrange
var record = GetValid(9);
record.Cancelled = false;
record.Registration.Student.SjaBlock = false;
record.Registration.Student.Blocked = true;
#endregion Arrange
#region Assert
Assert.IsFalse(record.IsValidForTickets);
#endregion Assert
}
[TestMethod]
public void TestIsValidForTicketsReturnsExpectedValue4()
{
#region Arrange
var record = GetValid(9);
record.Cancelled = false;
record.Registration.Student.SjaBlock = true;
record.Registration.Student.Blocked = true;
#endregion Arrange
#region Assert
Assert.IsFalse(record.IsValidForTickets);
#endregion Assert
}
[TestMethod]
public void TestIsValidForTicketsReturnsExpectedValue5()
{
#region Arrange
var record = GetValid(9);
record.Cancelled = true;
record.Registration.Student.SjaBlock = true;
record.Registration.Student.Blocked = true;
#endregion Arrange
#region Assert
Assert.IsFalse(record.IsValidForTickets);
#endregion Assert
}
[TestMethod]
public void TestIsValidForTicketsReturnsExpectedValue6()
{
#region Arrange
var record = GetValid(9);
record.Cancelled = false;
record.Registration.Student.SjaBlock = false;
record.Registration.Student.Blocked = false;
#endregion Arrange
#region Assert
Assert.IsTrue(record.IsValidForTickets);
#endregion Assert
}
#endregion IsValidForTickets Tests
#region TotalTickets Tests
[TestMethod]
public void TestTotalTicketsReturnsExpectedValue1()
{
#region Arrange
var record = GetValid(9);
record.NumberTickets = 10;
record.Cancelled = true;
#endregion Arrange
#region Assert
Assert.AreEqual(0, record.TotalTickets);
#endregion Assert
}
[TestMethod]
public void TestTotalTicketsReturnsExpectedValue2()
{
#region Arrange
var record = GetValid(9);
record.NumberTickets = 10;
#endregion Arrange
#region Assert
Assert.AreEqual(10, record.TotalTickets);
#endregion Assert
}
[TestMethod]
public void TestTotalTicketsReturnsExpectedValue3()
{
#region Arrange
var record = GetValid(9);
record.NumberTickets = 10;
record.ExtraTicketPetition = new ExtraTicketPetition(3, "Test", 4);
record.ExtraTicketPetition.IsApproved = false;
record.ExtraTicketPetition.IsPending = false;
#endregion Arrange
#region Assert
Assert.AreEqual(10, record.TotalTickets);
#endregion Assert
}
[TestMethod]
public void TestTotalTicketsReturnsExpectedValue4()
{
#region Arrange
var record = GetValid(9);
record.NumberTickets = 10;
record.ExtraTicketPetition = new ExtraTicketPetition(3, "Test", 4);
record.ExtraTicketPetition.IsApproved = true;
record.ExtraTicketPetition.IsPending = false;
record.ExtraTicketPetition.NumberTickets = 2;
#endregion Arrange
#region Assert
Assert.AreEqual(12, record.TotalTickets);
#endregion Assert
}
#endregion TotalTickets Tests
#region TotalStreamingTickets Tests
[TestMethod]
public void TestTotalStreamingTicketsReturnsExpectedValue1()
{
#region Arrange
var record = GetValid(9);
record.Ceremony.HasStreamingTickets = false;
record.NumberTickets = 10;
record.ExtraTicketPetition = new ExtraTicketPetition(3, "Test", 4);
record.ExtraTicketPetition.IsApproved = true;
record.ExtraTicketPetition.IsPending = false;
record.ExtraTicketPetition.NumberTicketsStreaming = 2;
#endregion Arrange
#region Assert
Assert.AreEqual(0, record.TotalStreamingTickets);
#endregion Assert
}
[TestMethod]
public void TestTotalStreamingTicketsReturnsExpectedValue2()
{
#region Arrange
var record = GetValid(9);
record.Ceremony.HasStreamingTickets = true;
record.Cancelled = true;
record.NumberTickets = 10;
record.ExtraTicketPetition = new ExtraTicketPetition(3, "Test", 4);
record.ExtraTicketPetition.IsApproved = true;
record.ExtraTicketPetition.IsPending = false;
record.ExtraTicketPetition.NumberTicketsStreaming = 2;
#endregion Arrange
#region Assert
Assert.AreEqual(0, record.TotalStreamingTickets);
#endregion Assert
}
[TestMethod]
public void TestTotalStreamingTicketsReturnsExpectedValue3()
{
#region Arrange
var record = GetValid(9);
record.Ceremony.HasStreamingTickets = true;
record.NumberTickets = 10;
record.ExtraTicketPetition = new ExtraTicketPetition(3, "Test", 4);
record.ExtraTicketPetition.IsApproved = true;
record.ExtraTicketPetition.IsPending = false;
record.ExtraTicketPetition.NumberTicketsStreaming = 2;
#endregion Arrange
#region Assert
Assert.AreEqual(2, record.TotalStreamingTickets);
#endregion Assert
}
[TestMethod]
public void TestTotalStreamingTicketsReturnsExpectedValue4()
{
#region Arrange
var record = GetValid(9);
record.Ceremony.HasStreamingTickets = true;
record.NumberTickets = 10;
record.ExtraTicketPetition = new ExtraTicketPetition(3, "Test", 4);
record.ExtraTicketPetition.IsApproved = false;
record.ExtraTicketPetition.IsPending = false;
record.ExtraTicketPetition.NumberTicketsStreaming = 2;
#endregion Arrange
#region Assert
Assert.AreEqual(0, record.TotalStreamingTickets);
#endregion Assert
}
[TestMethod]
public void TestTotalStreamingTicketsReturnsExpectedValue5()
{
#region Arrange
var record = GetValid(9);
record.Ceremony.HasStreamingTickets = true;
record.NumberTickets = 10;
record.ExtraTicketPetition = new ExtraTicketPetition(3, "Test", 4);
record.ExtraTicketPetition.IsApproved = true;
record.ExtraTicketPetition.IsPending = true;
record.ExtraTicketPetition.NumberTicketsStreaming = 2;
#endregion Arrange
#region Assert
Assert.AreEqual(0, record.TotalStreamingTickets);
#endregion Assert
}
[TestMethod]
public void TestTotalStreamingTicketsReturnsExpectedValue6()
{
#region Arrange
var record = GetValid(9);
record.Ceremony.HasStreamingTickets = true;
record.NumberTickets = 10;
record.ExtraTicketPetition = new ExtraTicketPetition(3, "Test", 4);
record.ExtraTicketPetition.IsApproved = true;
record.ExtraTicketPetition.IsPending = false;
record.ExtraTicketPetition.NumberTicketsStreaming = null;
#endregion Arrange
#region Assert
Assert.AreEqual(0, record.TotalStreamingTickets);
#endregion Assert
}
#endregion TotalStreamingTickets Tests
#region ProjectedTickets Tests
[TestMethod]
public void TestProjectedTicketsReturnsExpectedValue1()
{
#region Arrange
var record = GetValid(9);
record.Cancelled = true;
record.Ceremony.HasStreamingTickets = true;
record.NumberTickets = 10;
record.ExtraTicketPetition = new ExtraTicketPetition(3, "Test", 4);
record.ExtraTicketPetition.IsApproved = true;
record.ExtraTicketPetition.IsPending = false;
record.ExtraTicketPetition.NumberTicketsStreaming = null;
#endregion Arrange
#region Assert
Assert.AreEqual(0, record.ProjectedTickets);
#endregion Assert
}
[TestMethod]
public void TestProjectedTicketsReturnsExpectedValue2()
{
#region Arrange
var record = GetValid(9);
record.Cancelled = false;
record.Registration.Student.SjaBlock = true;
record.Ceremony.HasStreamingTickets = true;
record.NumberTickets = 10;
record.ExtraTicketPetition = new ExtraTicketPetition(3, "Test", 4);
record.ExtraTicketPetition.IsApproved = true;
record.ExtraTicketPetition.IsPending = false;
record.ExtraTicketPetition.NumberTicketsStreaming = null;
#endregion Arrange
#region Assert
Assert.AreEqual(0, record.ProjectedTickets);
#endregion Assert
}
[TestMethod]
public void TestProjectedTicketsReturnsExpectedValue3()
{
#region Arrange
var record = GetValid(9);
record.Cancelled = false;
record.Ceremony.HasStreamingTickets = true;
record.NumberTickets = 10;
#endregion Arrange
#region Assert
Assert.AreEqual(10, record.ProjectedTickets);
#endregion Assert
}
[TestMethod]
public void TestProjectedTicketsReturnsExpectedValue4()
{
#region Arrange
var record = GetValid(9);
record.Ceremony.HasStreamingTickets = true;
record.NumberTickets = 10;
record.ExtraTicketPetition = new ExtraTicketPetition(3, "Test", 4);
record.ExtraTicketPetition.IsApproved = false;
record.ExtraTicketPetition.IsPending = true;
#endregion Arrange
#region Assert
Assert.AreEqual(13, record.ProjectedTickets);
#endregion Assert
}
[TestMethod]
public void TestProjectedTicketsReturnsExpectedValue5()
{
#region Arrange
var record = GetValid(9);
record.Ceremony.HasStreamingTickets = true;
record.NumberTickets = 10;
record.ExtraTicketPetition = new ExtraTicketPetition(3, "Test", 4);
record.ExtraTicketPetition.IsApproved = true;
record.ExtraTicketPetition.IsPending = false;
record.ExtraTicketPetition.NumberTickets = null;
#endregion Arrange
#region Assert
Assert.AreEqual(10, record.ProjectedTickets);
#endregion Assert
}
#endregion ProjectedTickets Tests
#region ProjectedStreamingTickets Tests
[TestMethod]
public void TestProjectedStreamingTicketsReturnsExpectedValue1()
{
#region Arrange
var record = GetValid(9);
record.Ceremony.HasStreamingTickets = false;
record.NumberTickets = 10;
record.ExtraTicketPetition = new ExtraTicketPetition(3, "Test", 4);
record.ExtraTicketPetition.IsApproved = true;
record.ExtraTicketPetition.IsPending = false;
#endregion Arrange
#region Assert
Assert.AreEqual(0, record.ProjectedStreamingTickets);
#endregion Assert
}
[TestMethod]
public void TestProjectedStreamingTicketsReturnsExpectedValue2()
{
#region Arrange
var record = GetValid(9);
record.Ceremony.HasStreamingTickets = true;
record.Registration.Student.SjaBlock = true;
record.NumberTickets = 10;
record.ExtraTicketPetition = new ExtraTicketPetition(3, "Test", 4);
record.ExtraTicketPetition.IsApproved = true;
record.ExtraTicketPetition.IsPending = false;
#endregion Arrange
#region Assert
Assert.AreEqual(0, record.ProjectedStreamingTickets);
#endregion Assert
}
[TestMethod]
public void TestProjectedStreamingTicketsReturnsExpectedValue3()
{
#region Arrange
var record = GetValid(9);
record.Ceremony.HasStreamingTickets = true;
record.NumberTickets = 10;
#endregion Arrange
#region Assert
Assert.AreEqual(0, record.ProjectedStreamingTickets);
#endregion Assert
}
[TestMethod]
public void TestProjectedStreamingTicketsReturnsExpectedValue4()
{
#region Arrange
var record = GetValid(9);
record.Ceremony.HasStreamingTickets = true;
record.NumberTickets = 10;
record.ExtraTicketPetition = new ExtraTicketPetition(3, "Test", 4);
record.ExtraTicketPetition.IsApproved = true;
record.ExtraTicketPetition.IsPending = false;
#endregion Arrange
#region Assert
Assert.AreEqual(0, record.ProjectedStreamingTickets);
#endregion Assert
}
[TestMethod]
public void TestProjectedStreamingTicketsReturnsExpectedValue5()
{
#region Arrange
var record = GetValid(9);
record.Ceremony.HasStreamingTickets = true;
record.NumberTickets = 10;
record.ExtraTicketPetition = new ExtraTicketPetition(3, "Test", 4);
record.ExtraTicketPetition.IsApproved = true;
record.ExtraTicketPetition.IsPending = false;
record.ExtraTicketPetition.NumberTicketsStreaming = 9;
#endregion Arrange
#region Assert
Assert.AreEqual(9, record.ProjectedStreamingTickets);
#endregion Assert
}
[TestMethod]
public void TestProjectedStreamingTicketsReturnsExpectedValue6()
{
#region Arrange
var record = GetValid(9);
record.Ceremony.HasStreamingTickets = true;
record.NumberTickets = 10;
record.ExtraTicketPetition = new ExtraTicketPetition(3, "Test", 4);
record.ExtraTicketPetition.IsApproved = false;
record.ExtraTicketPetition.IsPending = true;
#endregion Arrange
#region Assert
Assert.AreEqual(4, record.ProjectedStreamingTickets);
#endregion Assert
}
#endregion ProjectedStreamingTickets Tests
#endregion Extended Fields / Methods
#region Constructor Tests
[TestMethod]
public void TestConstructorSetsExpectedValues()
{
#region Arrange
var record = new RegistrationParticipation();
#endregion Arrange
#region Assert
Assert.IsNotNull(record);
Assert.IsFalse(record.Cancelled);
Assert.IsFalse(record.LabelPrinted);
Assert.AreEqual(DateTime.Now.Date, record.DateRegistered.Date);
Assert.AreEqual(DateTime.Now.Date, record.DateUpdated.Date);
#endregion Assert
}
#endregion Constructor Tests
#region Fluent Mapping Tests
[TestMethod]
public void TestCanCorrectlyMapRegistrationParticipation1()
{
#region Arrange
var id = RegistrationParticipationRepository.Queryable.Max(a => a.Id) + 1;
var session = NHibernateSessionManager.Instance.GetSession();
var dateToCheck1 = new DateTime(2010, 01, 01);
var dateToCheck2 = new DateTime(2010, 01, 02);
#endregion Arrange
#region Act/Assert
new PersistenceSpecification<RegistrationParticipation>(session)
.CheckProperty(c => c.Id, id)
.CheckProperty(c => c.NumberTickets, 5)
.CheckProperty(c => c.Cancelled, true)
.CheckProperty(c => c.LabelPrinted, true)
.CheckProperty(c => c.DateRegistered, dateToCheck1)
.CheckProperty(c => c.DateUpdated, dateToCheck2)
.VerifyTheMappings();
#endregion Act/Assert
}
[TestMethod]
public void TestCanCorrectlyMapRegistrationParticipation2()
{
#region Arrange
var id = RegistrationParticipationRepository.Queryable.Max(a => a.Id) + 1;
var session = NHibernateSessionManager.Instance.GetSession();
var dateToCheck1 = new DateTime(2010, 01, 01);
var dateToCheck2 = new DateTime(2010, 01, 02);
#endregion Arrange
#region Act/Assert
new PersistenceSpecification<RegistrationParticipation>(session)
.CheckProperty(c => c.Id, id)
.CheckProperty(c => c.NumberTickets, 5)
.CheckProperty(c => c.Cancelled, false)
.CheckProperty(c => c.LabelPrinted, false)
.CheckProperty(c => c.DateRegistered, dateToCheck1)
.CheckProperty(c => c.DateUpdated, dateToCheck2)
.VerifyTheMappings();
#endregion Act/Assert
}
[TestMethod]
public void TestCanCorrectlyMapRegistrationParticipation3()
{
#region Arrange
var id = RegistrationParticipationRepository.Queryable.Max(a => a.Id) + 1;
var session = NHibernateSessionManager.Instance.GetSession();
var registration = Repository.OfType<Registration>().Queryable.First();
var major = Repository.OfType<MajorCode>().Queryable.First();
var ceremony = Repository.OfType<Ceremony>().Queryable.First();
#endregion Arrange
#region Act/Assert
new PersistenceSpecification<RegistrationParticipation>(session)
.CheckProperty(c => c.Id, id)
.CheckReference(c => c.Registration, registration)
.CheckReference(c => c.Major, major)
.CheckReference(c => c.Ceremony, ceremony)
.VerifyTheMappings();
#endregion Act/Assert
}
[TestMethod]
public void TestCanCorrectlyMapRegistrationParticipation4()
{
#region Arrange
var id = RegistrationParticipationRepository.Queryable.Max(a => a.Id) + 1;
var session = NHibernateSessionManager.Instance.GetSession();
var extraTicketPetition = CreateValidEntities.ExtraTicketPetition(7);
#endregion Arrange
#region Act/Assert
new PersistenceSpecification<RegistrationParticipation>(session, new RegistrationParticipationEqualityComparer())
.CheckProperty(c => c.Id, id)
.CheckProperty(c => c.ExtraTicketPetition, extraTicketPetition)
.VerifyTheMappings();
#endregion Act/Assert
}
public class RegistrationParticipationEqualityComparer : IEqualityComparer
{
bool IEqualityComparer.Equals(object x, object y)
{
if (x == null || y == null)
{
return false;
}
if (x is ExtraTicketPetition && y is ExtraTicketPetition)
{
if (((ExtraTicketPetition)x).Reason == ((ExtraTicketPetition)y).Reason)
{
return true;
}
return false;
}
return x.Equals(y);
}
public int GetHashCode(object obj)
{
throw new NotImplementedException();
}
}
#endregion Fluent Mapping Tests
#region Reflection of Database.
/// <summary>
/// Tests all fields in the database have been tested.
/// If this fails and no other tests, it means that a field has been added which has not been tested above.
/// </summary>
[TestMethod]
public void TestAllFieldsInTheDatabaseHaveBeenTested()
{
#region Arrange
var expectedFields = new List<NameAndType>();
expectedFields.Add(new NameAndType("Cancelled", "System.Boolean", new List<string>()));
expectedFields.Add(new NameAndType("Ceremony", "Commencement.Core.Domain.Ceremony", new List<string>
{
"[NHibernate.Validator.Constraints.NotNullAttribute()]"
}));
expectedFields.Add(new NameAndType("DateRegistered", "System.DateTime", new List<string>()));
expectedFields.Add(new NameAndType("DateUpdated", "System.DateTime", new List<string>()));
expectedFields.Add(new NameAndType("ExtraTicketPetition", "Commencement.Core.Domain.ExtraTicketPetition", new List<string>()));
expectedFields.Add(new NameAndType("Id", "System.Int32", new List<string>
{
"[Newtonsoft.Json.JsonPropertyAttribute()]",
"[System.Xml.Serialization.XmlIgnoreAttribute()]"
}));
expectedFields.Add(new NameAndType("IsValidForTickets", "System.Boolean", new List<string>()));
expectedFields.Add(new NameAndType("LabelPrinted", "System.Boolean", new List<string>()));
expectedFields.Add(new NameAndType("Major", "Commencement.Core.Domain.MajorCode", new List<string>
{
"[NHibernate.Validator.Constraints.NotNullAttribute()]"
}));
expectedFields.Add(new NameAndType("NumberTickets", "System.Int32", new List<string>()));
expectedFields.Add(new NameAndType("ProjectedStreamingTickets", "System.Int32", new List<string>()));
expectedFields.Add(new NameAndType("ProjectedTickets", "System.Int32", new List<string>()));
expectedFields.Add(new NameAndType("Registration", "Commencement.Core.Domain.Registration", new List<string>
{
"[NHibernate.Validator.Constraints.NotNullAttribute()]"
}));
expectedFields.Add(new NameAndType("TicketDistribution", "System.String", new List<string>()));
expectedFields.Add(new NameAndType("TotalStreamingTickets", "System.Int32", new List<string>()));
expectedFields.Add(new NameAndType("TotalTickets", "System.Int32", new List<string>()));
#endregion Arrange
AttributeAndFieldValidation.ValidateFieldsAndAttributes(expectedFields, typeof(RegistrationParticipation));
}
#endregion Reflection of Database.
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Brew;
using Brew.TypeConverters;
namespace Brew.Webforms.Widgets {
/// <summary>
/// Extend a TextBox with jQuery UI Autocomplete http://api.jqueryui.com/autocomplete/
/// </summary>
public class Autocomplete : Widget {
private String _sourceUrl = null;
private String[] _source = null;
private List<AutocompleteItem> _sourceList = null;
public Autocomplete() : base("autocomplete") { }
public override List<WidgetEvent> GetEvents() {
return new List<WidgetEvent>() {
new WidgetEvent("create"),
new WidgetEvent("search"),
new WidgetEvent("open"),
new WidgetEvent("focus"),
new WidgetEvent("close"),
new WidgetEvent("response"),
new WidgetEvent("select"),
new WidgetEvent("change")
};
}
public override List<WidgetOption> GetOptions() {
return new List<WidgetOption>() {
new WidgetOption { Name = "appendTo", DefaultValue = "body" },
new WidgetOption { Name = "autoFocus", DefaultValue = false },
new WidgetOption { Name = "delay", DefaultValue = 300 },
new WidgetOption { Name = "minLength", DefaultValue = 1 },
new WidgetOption { Name = "position", DefaultValue = "{}" },
new WidgetOption { Name = "source", DefaultValue = null, PropertyName = "_Source" }
};
}
/// <summary>
/// Triggered when an item is selected from the menu; ui.item refers to the selected item. The default action of select is to replace the text field's value with the value of the selected item. Canceling this event prevents the value from being updated, but does not prevent the menu from closing.
/// Reference: http://api.jqueryui.com/autocomplete/#event-select
/// </summary>
[Category("Action")]
[Description("Triggered when an item is selected from the menu; ui.item refers to the selected item. The default action of select is to replace the text field's value with the value of the selected item. Canceling this event prevents the value from being updated, but does not prevent the menu from closing.")]
public event EventHandler Select;
/// <summary>
/// Triggered when the field is blurred, if the value has changed; ui.item refers to the selected item.
/// Reference: http://api.jqueryui.com/autocomplete/#event-change
/// </summary>
[Category("Action")]
[Description("Triggered when the field is blurred, if the value has changed; ui.item refers to the selected item.")]
public event EventHandler Change;
#region . Options .
/// <summary>
/// Which element the menu should be appended to.
/// Reference: http://api.jqueryui.com/autocomplete/#option-appendTo
/// </summary>
[Category("Behavior")]
[DefaultValue("body")]
[Description("Which element the menu should be appended to.")]
public string AppendTo { get; set; }
/// <summary>
/// If set to true the first item will be automatically focused.
/// Reference: http://api.jqueryui.com/autocomplete/#option-autoFocus
/// </summary>
[Category("Behavior")]
[DefaultValue(false)]
[Description("If set to true the first item will be automatically focused.")]
public bool AutoFocus { get; set; }
/// <summary>
/// The delay in milliseconds the Autocomplete waits after a keystroke to activate itself. A zero-delay makes sense for local data (more responsive), but can produce a lot of load for remote data, while being less responsive.
/// Reference: http://api.jqueryui.com/autocomplete/#option-delay
/// </summary>
[Category("Behavior")]
[DefaultValue(300)]
[Description("The delay in milliseconds the Autocomplete waits after a keystroke to activate itself. A zero-delay makes sense for local data (more responsive), but can produce a lot of load for remote data, while being less responsive.")]
public int Delay { get; set; }
/// <summary>
/// The minimum number of characters a user has to type before the Autocomplete activates. Zero is useful for local data with just a few items. Should be increased when there are a lot of items, where a single character would match a few thousand items.
/// Reference: http://api.jqueryui.com/autocomplete/#option-minLength
/// </summary>
[Category("Key")]
[DefaultValue(1)]
[Description("The minimum number of characters a user has to type before the Autocomplete activates. Zero is useful for local data with just a few items. Should be increased when there are a lot of items, where a single character would match a few thousand items.")]
public int MinLength { get; set; }
/// <summary>
/// Identifies the position of the Autocomplete widget in relation to the associated input element. The "of" option defaults to the input element, but you can specify another element to position against. You can refer to the jQuery UI Position utility for more details about the various options.
/// Reference: http://api.jqueryui.com/autocomplete/#option-position
/// </summary>
[TypeConverter(typeof(JsonObjectConverter))]
[Category("Layout")]
[DefaultValue("{}")]
[Description("Identifies the position of the Autocomplete widget in relation to the associated input element. The \"of\" option defaults to the input element, but you can specify another element to position against. You can refer to the jQuery UI Position utility for more details about the various options.")]
public string Position { get; set; }
/// <summary>
/// Defines a data source url for the data to use. Source, Source List or SourceUrl must be specified.
/// If SourceUrl, SourceList and Source are specified, Source or SourceList will take priority.
/// Reference: http://api.jqueryui.com/autocomplete/#option-source
/// </summary>
[Category("Data")]
[DefaultValue(null)]
[Description("Defines a data source url for the data to use. Source, Source List or SourceUrl must be specified. If SourceUrl, SourceList and Source are specified, Source or SourceList will take priority.")]
public String SourceUrl {
get { return _sourceUrl; }
set { this._sourceUrl = value; }
}
/// <summary>
/// Defines the data to use. Source, Source List or SourceUrl must be specified.
/// Reference: http://api.jqueryui.com/autocomplete/#option-source
/// </summary>
[TypeConverter(typeof(Brew.TypeConverters.StringArrayConverter))]
[Category("Data")]
[DefaultValue(null)]
[Description("Defines the data to use. Source, Source List or SourceUrl must be specified.")]
public String[] Source {
get { return this._source; }
set { this._source = value; }
}
/// <summary>
/// Defines an array of label/value pairs to use as source data. Source, Source List or SourceUrl must be specified.
/// If both SourceList and Source are specified, Source will take priority.
/// Reference: http://api.jqueryui.com/autocomplete/#option-source
/// </summary>
[TypeConverter(typeof(TypeConverters.AutocompleteListConverter))]
[Category("Data")]
[DefaultValue(null)]
[Description("Defines an array of label/value pairs to use as source data. If both SourceList and Source are specified, Source will take priority.")]
public List<AutocompleteItem> SourceList {
get { return this._sourceList; }
set { this._sourceList = value; }
}
/// <summary>
/// Internal container for the source option.
/// </summary>
/// <remarks>
/// Yes, this is ugly. It's really ugly.
/// This is (so far) the only instance where we have to do something like this.
/// There's no way to differentiate between a string and an array of length(1) in control attributes.
/// If we run across this scenario again, we should write a TypeDescriptorProvider that will pull Internal/Private properties
/// or switch back to using PropertyInfo instead of PropertyDescriptors.
/// </remarks>
[TypeConverter(typeof(TypeConverters.AutocompleteSourceConverter))]
[EditorBrowsable(EditorBrowsableState.Never)]
[Browsable(false)]
public object _Source {
get {
if (this._source != null) {
return this._source;
}
else if (this._sourceList != null) {
// we need to perform some hackery here so that this will render properly to the widget init/options script.
var result = new List<object>();
foreach (AutocompleteItem item in _sourceList) {
result.Add(new {
label = item.Label,
value = item.Value
});
}
return result;
}
return this._sourceUrl;
}
internal set {
//_sourceP = value;
//if(value is String[]) {
// this.Source = value as String[];
//}
//else if(value is String) {
// this.SourceUrl = value as String;
//}
//else if(value is List<AutocompleteItem>) {
// this.SourceList = (List<AutocompleteItem>)value;
//}
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml.Linq;
using System.Xml.XPath;
using Examine;
using Examine.LuceneEngine;
using Examine.LuceneEngine.Providers;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Store;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.Models;
using Umbraco.Core.PropertyEditors;
using Umbraco.Tests.TestHelpers;
using Umbraco.Tests.TestHelpers.Entities;
using Umbraco.Tests.UmbracoExamine;
using Umbraco.Web;
using Umbraco.Web.PublishedCache;
using Umbraco.Web.PublishedCache.XmlPublishedCache;
using UmbracoExamine;
using UmbracoExamine.DataServices;
using umbraco.BusinessLogic;
using System.Linq;
namespace Umbraco.Tests.PublishedContent
{
/// <summary>
/// Tests the typed extension methods on IPublishedContent using the DefaultPublishedMediaStore
/// </summary>
[DatabaseTestBehavior(DatabaseBehavior.NewDbFileAndSchemaPerTest)]
[TestFixture, RequiresSTA]
public class PublishedMediaTests : PublishedContentTestBase
{
public override void Initialize()
{
base.Initialize();
UmbracoExamineSearcher.DisableInitializationCheck = true;
BaseUmbracoIndexer.DisableInitializationCheck = true;
}
public override void TearDown()
{
base.TearDown();
UmbracoExamineSearcher.DisableInitializationCheck = null;
BaseUmbracoIndexer.DisableInitializationCheck = null;
}
/// <summary>
/// Shared with PublishMediaStoreTests
/// </summary>
/// <param name="id"></param>
/// <param name="umbracoContext"></param>
/// <returns></returns>
internal static IPublishedContent GetNode(int id, UmbracoContext umbracoContext)
{
var ctx = umbracoContext;
var cache = new ContextualPublishedMediaCache(new PublishedMediaCache(), ctx);
var doc = cache.GetById(id);
Assert.IsNotNull(doc);
return doc;
}
private IPublishedContent GetNode(int id)
{
return GetNode(id, GetUmbracoContext("/test", 1234));
}
[Test]
public void Get_Property_Value_Uses_Converter()
{
var mType = MockedContentTypes.CreateImageMediaType("image2");
//lets add an RTE to this
mType.PropertyGroups.First().PropertyTypes.Add(
new PropertyType("test", DataTypeDatabaseType.Nvarchar)
{
Alias = "content",
Name = "Rich Text",
DataTypeDefinitionId = -87 //tiny mce
});
ServiceContext.ContentTypeService.Save(mType);
var media = MockedMedia.CreateMediaImage(mType, -1);
media.Properties["content"].Value = "<div>This is some content</div>";
ServiceContext.MediaService.Save(media);
var publishedMedia = GetNode(media.Id);
var propVal = publishedMedia.GetPropertyValue("content");
Assert.IsInstanceOf<IHtmlString>(propVal);
Assert.AreEqual("<div>This is some content</div>", propVal.ToString());
var propVal2 = publishedMedia.GetPropertyValue<IHtmlString>("content");
Assert.IsInstanceOf<IHtmlString>(propVal2);
Assert.AreEqual("<div>This is some content</div>", propVal2.ToString());
var propVal3 = publishedMedia.GetPropertyValue("Content");
Assert.IsInstanceOf<IHtmlString>(propVal3);
Assert.AreEqual("<div>This is some content</div>", propVal3.ToString());
}
[Test]
public void Ensure_Children_Sorted_With_Examine()
{
using (var luceneDir = new RAMDirectory())
{
var indexer = IndexInitializer.GetUmbracoIndexer(luceneDir);
indexer.RebuildIndex();
var searcher = IndexInitializer.GetUmbracoSearcher(luceneDir);
var ctx = GetUmbracoContext("/test", 1234);
var cache = new ContextualPublishedMediaCache(new PublishedMediaCache(searcher, indexer), ctx);
//we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace
var publishedMedia = cache.GetById(1111);
var rootChildren = publishedMedia.Children().ToArray();
var currSort = 0;
for (var i = 0; i < rootChildren.Count(); i++)
{
Assert.GreaterOrEqual(rootChildren[i].SortOrder, currSort);
currSort = rootChildren[i].SortOrder;
}
}
}
[Test]
public void Do_Not_Find_In_Recycle_Bin()
{
using (var luceneDir = new RAMDirectory())
{
var indexer = IndexInitializer.GetUmbracoIndexer(luceneDir);
indexer.RebuildIndex();
var searcher = IndexInitializer.GetUmbracoSearcher(luceneDir);
var ctx = GetUmbracoContext("/test", 1234);
var cache = new ContextualPublishedMediaCache(new PublishedMediaCache(searcher, indexer), ctx);
//ensure it is found
var publishedMedia = cache.GetById(3113);
Assert.IsNotNull(publishedMedia);
//move item to recycle bin
var newXml = XElement.Parse(@"<node id='3113' version='5b3e46ab-3e37-4cfa-ab70-014234b5bd33' parentID='-21' level='1' writerID='0' nodeType='1032' template='0' sortOrder='2' createDate='2010-05-19T17:32:46' updateDate='2010-05-19T17:32:46' nodeName='Another Umbraco Image' urlName='acnestressscrub' writerName='Administrator' nodeTypeAlias='Image' path='-1,-21,3113'>
<data alias='umbracoFile'><![CDATA[/media/1234/blah.pdf]]></data>
<data alias='umbracoWidth'>115</data>
<data alias='umbracoHeight'>268</data>
<data alias='umbracoBytes'>10726</data>
<data alias='umbracoExtension'>jpg</data>
</node>");
indexer.ReIndexNode(newXml, "media");
//ensure it still exists in the index (raw examine search)
var criteria = searcher.CreateSearchCriteria();
var filter = criteria.Id(3113);
var found = searcher.Search(filter.Compile());
Assert.IsNotNull(found);
Assert.AreEqual(1, found.TotalItemCount);
//ensure it does not show up in the published media store
var recycledMedia = cache.GetById(3113);
Assert.IsNull(recycledMedia);
}
}
[Test]
public void Children_With_Examine()
{
using (var luceneDir = new RAMDirectory())
{
var indexer = IndexInitializer.GetUmbracoIndexer(luceneDir);
indexer.RebuildIndex();
var searcher = IndexInitializer.GetUmbracoSearcher(luceneDir);
var ctx = GetUmbracoContext("/test", 1234);
var cache = new ContextualPublishedMediaCache(new PublishedMediaCache(searcher, indexer), ctx);
//we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace
var publishedMedia = cache.GetById(1111);
var rootChildren = publishedMedia.Children();
Assert.IsTrue(rootChildren.Select(x => x.Id).ContainsAll(new[] { 2222, 1113, 1114, 1115, 1116 }));
var publishedChild1 = cache.GetById(2222);
var subChildren = publishedChild1.Children();
Assert.IsTrue(subChildren.Select(x => x.Id).ContainsAll(new[] { 2112 }));
}
}
[Test]
public void Descendants_With_Examine()
{
using (var luceneDir = new RAMDirectory())
{
var indexer = IndexInitializer.GetUmbracoIndexer(luceneDir);
indexer.RebuildIndex();
var searcher = IndexInitializer.GetUmbracoSearcher(luceneDir);
var ctx = GetUmbracoContext("/test", 1234);
var cache = new ContextualPublishedMediaCache(new PublishedMediaCache(searcher, indexer), ctx);
//we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace
var publishedMedia = cache.GetById(1111);
var rootDescendants = publishedMedia.Descendants();
Assert.IsTrue(rootDescendants.Select(x => x.Id).ContainsAll(new[] { 2112, 2222, 1113, 1114, 1115, 1116 }));
var publishedChild1 = cache.GetById(2222);
var subDescendants = publishedChild1.Descendants();
Assert.IsTrue(subDescendants.Select(x => x.Id).ContainsAll(new[] { 2112, 3113 }));
}
}
[Test]
public void DescendantsOrSelf_With_Examine()
{
using (var luceneDir = new RAMDirectory())
{
var indexer = IndexInitializer.GetUmbracoIndexer(luceneDir);
indexer.RebuildIndex();
var searcher = IndexInitializer.GetUmbracoSearcher(luceneDir);
var ctx = GetUmbracoContext("/test", 1234);
var cache = new ContextualPublishedMediaCache(new PublishedMediaCache(searcher, indexer), ctx);
//we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace
var publishedMedia = cache.GetById(1111);
var rootDescendants = publishedMedia.DescendantsOrSelf();
Assert.IsTrue(rootDescendants.Select(x => x.Id).ContainsAll(new[] { 1111, 2112, 2222, 1113, 1114, 1115, 1116 }));
var publishedChild1 = cache.GetById(2222);
var subDescendants = publishedChild1.DescendantsOrSelf();
Assert.IsTrue(subDescendants.Select(x => x.Id).ContainsAll(new[] { 2222, 2112, 3113 }));
}
}
[Test]
public void Ancestors_With_Examine()
{
using (var luceneDir = new RAMDirectory())
{
var indexer = IndexInitializer.GetUmbracoIndexer(luceneDir);
indexer.RebuildIndex();
var ctx = GetUmbracoContext("/test", 1234);
var searcher = IndexInitializer.GetUmbracoSearcher(luceneDir);
var cache = new ContextualPublishedMediaCache(new PublishedMediaCache(searcher, indexer), ctx);
//we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace
var publishedMedia = cache.GetById(3113);
var ancestors = publishedMedia.Ancestors();
Assert.IsTrue(ancestors.Select(x => x.Id).ContainsAll(new[] { 2112, 2222, 1111 }));
}
}
[Test]
public void AncestorsOrSelf_With_Examine()
{
using (var luceneDir = new RAMDirectory())
{
var indexer = IndexInitializer.GetUmbracoIndexer(luceneDir);
indexer.RebuildIndex();
var ctx = GetUmbracoContext("/test", 1234);
var searcher = IndexInitializer.GetUmbracoSearcher(luceneDir);
var cache = new ContextualPublishedMediaCache(new PublishedMediaCache(searcher, indexer), ctx);
//we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace
var publishedMedia = cache.GetById(3113);
var ancestors = publishedMedia.AncestorsOrSelf();
Assert.IsTrue(ancestors.Select(x => x.Id).ContainsAll(new[] { 3113, 2112, 2222, 1111 }));
}
}
[Test]
public void Children_Without_Examine()
{
var user = new User(0);
var mType = global::umbraco.cms.businesslogic.media.MediaType.MakeNew(user, "TestMediaType");
var mRoot = global::umbraco.cms.businesslogic.media.Media.MakeNew("MediaRoot", mType, user, -1);
var mChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child1", mType, user, mRoot.Id);
var mChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child2", mType, user, mRoot.Id);
var mChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child3", mType, user, mRoot.Id);
var mSubChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild1", mType, user, mChild1.Id);
var mSubChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild2", mType, user, mChild1.Id);
var mSubChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild3", mType, user, mChild1.Id);
var publishedMedia = GetNode(mRoot.Id);
var rootChildren = publishedMedia.Children();
Assert.IsTrue(rootChildren.Select(x => x.Id).ContainsAll(new[] { mChild1.Id, mChild2.Id, mChild3.Id }));
var publishedChild1 = GetNode(mChild1.Id);
var subChildren = publishedChild1.Children();
Assert.IsTrue(subChildren.Select(x => x.Id).ContainsAll(new[] { mSubChild1.Id, mSubChild2.Id, mSubChild3.Id }));
}
[Test]
public void Descendants_Without_Examine()
{
var user = new User(0);
var mType = global::umbraco.cms.businesslogic.media.MediaType.MakeNew(user, "TestMediaType");
var mRoot = global::umbraco.cms.businesslogic.media.Media.MakeNew("MediaRoot", mType, user, -1);
var mChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child1", mType, user, mRoot.Id);
var mChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child2", mType, user, mRoot.Id);
var mChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child3", mType, user, mRoot.Id);
var mSubChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild1", mType, user, mChild1.Id);
var mSubChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild2", mType, user, mChild1.Id);
var mSubChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild3", mType, user, mChild1.Id);
var publishedMedia = GetNode(mRoot.Id);
var rootDescendants = publishedMedia.Descendants();
Assert.IsTrue(rootDescendants.Select(x => x.Id).ContainsAll(new[] { mChild1.Id, mChild2.Id, mChild3.Id, mSubChild1.Id, mSubChild2.Id, mSubChild3.Id }));
var publishedChild1 = GetNode(mChild1.Id);
var subDescendants = publishedChild1.Descendants();
Assert.IsTrue(subDescendants.Select(x => x.Id).ContainsAll(new[] { mSubChild1.Id, mSubChild2.Id, mSubChild3.Id }));
}
[Test]
public void DescendantsOrSelf_Without_Examine()
{
var user = new User(0);
var mType = global::umbraco.cms.businesslogic.media.MediaType.MakeNew(user, "TestMediaType");
var mRoot = global::umbraco.cms.businesslogic.media.Media.MakeNew("MediaRoot", mType, user, -1);
var mChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child1", mType, user, mRoot.Id);
var mChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child2", mType, user, mRoot.Id);
var mChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child3", mType, user, mRoot.Id);
var mSubChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild1", mType, user, mChild1.Id);
var mSubChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild2", mType, user, mChild1.Id);
var mSubChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild3", mType, user, mChild1.Id);
var publishedMedia = GetNode(mRoot.Id);
var rootDescendantsOrSelf = publishedMedia.DescendantsOrSelf();
Assert.IsTrue(rootDescendantsOrSelf.Select(x => x.Id).ContainsAll(
new[] { mRoot.Id, mChild1.Id, mChild2.Id, mChild3.Id, mSubChild1.Id, mSubChild2.Id, mSubChild3.Id }));
var publishedChild1 = GetNode(mChild1.Id);
var subDescendantsOrSelf = publishedChild1.DescendantsOrSelf();
Assert.IsTrue(subDescendantsOrSelf.Select(x => x.Id).ContainsAll(
new[] { mChild1.Id, mSubChild1.Id, mSubChild2.Id, mSubChild3.Id }));
}
[Test]
public void Parent_Without_Examine()
{
var user = new User(0);
var mType = global::umbraco.cms.businesslogic.media.MediaType.MakeNew(user, "TestMediaType");
var mRoot = global::umbraco.cms.businesslogic.media.Media.MakeNew("MediaRoot", mType, user, -1);
var mChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child1", mType, user, mRoot.Id);
var mChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child2", mType, user, mRoot.Id);
var mChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child3", mType, user, mRoot.Id);
var mSubChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild1", mType, user, mChild1.Id);
var mSubChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild2", mType, user, mChild1.Id);
var mSubChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild3", mType, user, mChild1.Id);
var publishedRoot = GetNode(mRoot.Id);
Assert.AreEqual(null, publishedRoot.Parent);
var publishedChild1 = GetNode(mChild1.Id);
Assert.AreEqual(mRoot.Id, publishedChild1.Parent.Id);
var publishedSubChild1 = GetNode(mSubChild1.Id);
Assert.AreEqual(mChild1.Id, publishedSubChild1.Parent.Id);
}
[Test]
public void Ancestors_Without_Examine()
{
var user = new User(0);
var mType = global::umbraco.cms.businesslogic.media.MediaType.MakeNew(user, "TestMediaType");
var mRoot = global::umbraco.cms.businesslogic.media.Media.MakeNew("MediaRoot", mType, user, -1);
var mChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child1", mType, user, mRoot.Id);
var mChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child2", mType, user, mRoot.Id);
var mChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child3", mType, user, mRoot.Id);
var mSubChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild1", mType, user, mChild1.Id);
var mSubChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild2", mType, user, mChild1.Id);
var mSubChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild3", mType, user, mChild1.Id);
var publishedSubChild1 = GetNode(mSubChild1.Id);
Assert.IsTrue(publishedSubChild1.Ancestors().Select(x => x.Id).ContainsAll(new[] { mChild1.Id, mRoot.Id }));
}
[Test]
public void AncestorsOrSelf_Without_Examine()
{
var user = new User(0);
var mType = global::umbraco.cms.businesslogic.media.MediaType.MakeNew(user, "TestMediaType");
var mRoot = global::umbraco.cms.businesslogic.media.Media.MakeNew("MediaRoot", mType, user, -1);
var mChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child1", mType, user, mRoot.Id);
var mChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child2", mType, user, mRoot.Id);
var mChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child3", mType, user, mRoot.Id);
var mSubChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild1", mType, user, mChild1.Id);
var mSubChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild2", mType, user, mChild1.Id);
var mSubChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild3", mType, user, mChild1.Id);
var publishedSubChild1 = GetNode(mSubChild1.Id);
Assert.IsTrue(publishedSubChild1.AncestorsOrSelf().Select(x => x.Id).ContainsAll(
new[] { mSubChild1.Id, mChild1.Id, mRoot.Id }));
}
}
}
| |
namespace TreeViewEx.Test.Model.Helper
{
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows;
using System.Windows.Automation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// Class for Keyboard use
/// </summary>
public static class Mouse
{
#region Constants
const int SM_SWAPBUTTON = 23;
const int SM_XVIRTUALSCREEN = 76;
const int SM_YVIRTUALSCREEN = 77;
const int SM_CXVIRTUALSCREEN = 78;
const int SM_CYVIRTUALSCREEN = 79;
const int MOUSEEVENTF_VIRTUALDESK = 0x4000;
#endregion
#region Specific tree methods
internal static void ExpandCollapseClick(Element element, bool expand)
{
bool oldExpandState = element.IsExpanded;
if (oldExpandState == expand) return;
AutomationElement toggleButton = element.Ae.FindDescendantByAutomationId(ControlType.Button, "Expander");
try
{
Click(toggleButton.GetClickablePoint());
}
catch (Exception ex)
{
}
SleepAfter();
if (oldExpandState == element.IsExpanded)
throw new InvalidOperationException("Changing expand state did not work");
}
internal static void Click(Element element)
{
Click(element.Ae);
SleepAfter();
}
internal static void ShiftClick(Element element)
{
Keyboard.HoldShift();
Click(element.Ae);
SleepBetween();
Keyboard.ReleaseShift();
}
internal static void CtrlClick(Element element)
{
Keyboard.HoldCtrl();
Click(element.Ae);
SleepBetween();
Keyboard.ReleaseCtrl();
}
private static void SleepAfter()
{
Thread.Sleep(500);
}
private static void SleepBetween()
{
Thread.Sleep(10);
}
#endregion
#region Private methods
/// <summary>
/// Inject pointer input into the system
/// </summary>
/// <param name="x">x coordinate of pointer, if Move flag specified</param>
/// <param name="y">y coordinate of pointer, if Move flag specified</param>
/// <param name="data">wheel movement, or mouse X button, depending on flags</param>
/// <param name="flags">flags to indicate which type of input occurred - move, button press/release, wheel move, etc.</param>
/// <remarks>x, y are in pixels. If Absolute flag used, are relative to desktop origin.</remarks>
/// <outside_see conditional="false">
/// This API does not work inside the secure execution environment.
/// <exception cref="System.Security.Permissions.SecurityPermission"/>
/// </outside_see>
private static void SendMouseInput(double x, double y, int data, SendMouseInputFlags flags)
{
//CASRemoval:AutomationPermission.Demand( AutomationPermissionFlag.Input );
int intflags = (int)flags;
if ((intflags & (int)SendMouseInputFlags.Absolute) != 0)
{
int vscreenWidth = GetSystemMetrics(SM_CXVIRTUALSCREEN);
int vscreenHeight = GetSystemMetrics(SM_CYVIRTUALSCREEN);
int vscreenLeft = GetSystemMetrics(SM_XVIRTUALSCREEN);
int vscreenTop = GetSystemMetrics(SM_YVIRTUALSCREEN);
// Absolute input requires that input is in 'normalized' coords - with the entire
// desktop being (0,0)...(65535,65536). Need to convert input x,y coords to this
// first.
//
// In this normalized world, any pixel on the screen corresponds to a block of values
// of normalized coords - eg. on a 1024x768 screen,
// y pixel 0 corresponds to range 0 to 85.333,
// y pixel 1 corresponds to range 85.333 to 170.666,
// y pixel 2 correpsonds to range 170.666 to 256 - and so on.
// Doing basic scaling math - (x-top)*65536/Width - gets us the start of the range.
// However, because int math is used, this can end up being rounded into the wrong
// pixel. For example, if we wanted pixel 1, we'd get 85.333, but that comes out as
// 85 as an int, which falls into pixel 0's range - and that's where the pointer goes.
// To avoid this, we add on half-a-"screen pixel"'s worth of normalized coords - to
// push us into the middle of any given pixel's range - that's the 65536/(Width*2)
// part of the formula. So now pixel 1 maps to 85+42 = 127 - which is comfortably
// in the middle of that pixel's block.
// The key ting here is that unlike points in coordinate geometry, pixels take up
// space, so are often better treated like rectangles - and if you want to target
// a particular pixel, target its rectangle's midpoint, not its edge.
x = ((x - vscreenLeft) * 65536) / vscreenWidth + 65536 / (vscreenWidth * 2);
y = ((y - vscreenTop) * 65536) / vscreenHeight + 65536 / (vscreenHeight * 2);
intflags |= MOUSEEVENTF_VIRTUALDESK;
}
INPUT mi = new INPUT();
mi.type = Const.INPUT_MOUSE;
mi.union.mouseInput.dx = (int)x;
mi.union.mouseInput.dy = (int)y;
mi.union.mouseInput.mouseData = data;
mi.union.mouseInput.dwFlags = intflags;
mi.union.mouseInput.time = 0;
mi.union.mouseInput.dwExtraInfo = new IntPtr(0);
//Console.WriteLine("Sending");
if (SendInput(1, ref mi, Marshal.SizeOf(mi)) == 0)
throw new Win32Exception(Marshal.GetLastWin32Error());
}
#endregion
#region Public methods
public static Point Loaction()
{
Win32Point w32Mouse = new Win32Point();
GetCursorPos(ref w32Mouse);
return new Point(w32Mouse.X, w32Mouse.Y);
}
/// <summary>
/// Move the mouse to a point.
/// </summary>
/// <param name="pt">The point that the mouse will move to.</param>
/// <remarks>pt are in pixels that are relative to desktop origin.</remarks>
///
/// <outside_see conditional="false">
/// This API does not work inside the secure execution environment.
/// <exception cref="System.Security.Permissions.SecurityPermission"/>
/// </outside_see>
public static void MoveTo(Point pt)
{
SendMouseInput(pt.X, pt.Y, 0, SendMouseInputFlags.Move | SendMouseInputFlags.Absolute);
}
/// <summary>
/// Move the mouse to an element.
/// </summary>
/// <param name="el">The element that the mouse will move to</param>
/// <exception cref="NoClickablePointException">If there is not clickable point for the element</exception>
///
/// <outside_see conditional="false">
/// This API does not work inside the secure execution environment.
/// <exception cref="System.Security.Permissions.SecurityPermission"/>
/// </outside_see>
public static void MoveTo(AutomationElement el)
{
if (el == null)
{
throw new ArgumentNullException("el");
}
MoveTo(el.GetClickablePoint());
}
/// <summary>
/// Move the mouse to a point and click. The primary mouse button will be used
/// this is usually the left button except if the mouse buttons are swaped.
/// </summary>
/// <param name="pt">The point to click at</param>
/// <remarks>pt are in pixels that are relative to desktop origin.</remarks>
///
/// <outside_see conditional="false">
/// This API does not work inside the secure execution environment.
/// <exception cref="System.Security.Permissions.SecurityPermission"/>
/// </outside_see>
public static void MoveToAndClick(Point pt)
{
SendMouseInput(pt.X, pt.Y, 0, SendMouseInputFlags.Move | SendMouseInputFlags.Absolute);
RawClick(pt, true);
}
/// <summary>
/// Move the mouse to a point and double click. The primary mouse button will be used
/// this is usually the left button except if the mouse buttons are swaped.
/// </summary>
/// <param name="pt">The point to click at</param>
/// <remarks>pt are in pixels that are relative to desktop origin.</remarks>
///
/// <outside_see conditional="false">
/// This API does not work inside the secure execution environment.
/// <exception cref="System.Security.Permissions.SecurityPermission"/>
/// </outside_see>
public static void MoveToAndDoubleClick(Point pt)
{
SendMouseInput(pt.X, pt.Y, 0, SendMouseInputFlags.Move | SendMouseInputFlags.Absolute);
RawClick(pt, true);
Thread.Sleep(300);
RawClick(pt, true);
}
private static void RawClick(Point pt, bool left)
{
// send SendMouseInput works in term of the phisical mouse buttons, therefore we need
// to check to see if the mouse buttons are swapped because this method need to use the primary
// mouse button.
if (ButtonsSwapped() != left)
{
// the mouse buttons are not swaped the primary is the left
SendMouseInput(pt.X, pt.Y, 0, SendMouseInputFlags.LeftDown | SendMouseInputFlags.Absolute);
SendMouseInput(pt.X, pt.Y, 0, SendMouseInputFlags.LeftUp | SendMouseInputFlags.Absolute);
}
else
{
// the mouse buttons are swaped so click the right button which as actually the primary
SendMouseInput(pt.X, pt.Y, 0, SendMouseInputFlags.RightDown | SendMouseInputFlags.Absolute);
SendMouseInput(pt.X, pt.Y, 0, SendMouseInputFlags.RightUp | SendMouseInputFlags.Absolute);
}
}
private static bool ButtonsSwapped()
{
return GetSystemMetrics(SM_SWAPBUTTON) != 0;
}
public static void MoveToAndRightClick(Point pt)
{
SendMouseInput(pt.X, pt.Y, 0, SendMouseInputFlags.Move | SendMouseInputFlags.Absolute);
RawClick(pt, false);
}
public static void Click(Point point)
{
MoveToAndClick(point);
}
private static void Click(AutomationElement element)
{
try
{
Point p = element.GetClickablePoint();
MoveToAndClick(p);
}
catch (Exception ex)
{
}
}
internal static void DoubleClick(Element element)
{
DoubleClick(element.Ae);
SleepAfter();
}
private static void DoubleClick(AutomationElement element)
{
Point p = element.GetClickablePoint();
MoveToAndDoubleClick(p);
}
private static void RightClick(Point point)
{
MoveToAndRightClick(point);
}
#endregion
#region Native types
/// <summary>
/// Flags for Input.SendMouseInput, indicate whether movent took place,
/// or whether buttons were pressed or released.
/// </summary>
[Flags]
public enum SendMouseInputFlags
{
/// <summary>Specifies that the pointer moved.</summary>
Move = 0x0001,
/// <summary>Specifies that the left button was pressed.</summary>
LeftDown = 0x0002,
/// <summary>Specifies that the left button was released.</summary>
LeftUp = 0x0004,
/// <summary>Specifies that the right button was pressed.</summary>
RightDown = 0x0008,
/// <summary>Specifies that the right button was released.</summary>
RightUp = 0x0010,
/// <summary>Specifies that the middle button was pressed.</summary>
MiddleDown = 0x0020,
/// <summary>Specifies that the middle button was released.</summary>
MiddleUp = 0x0040,
/// <summary>Specifies that the x button was pressed.</summary>
XDown = 0x0080,
/// <summary>Specifies that the x button was released. </summary>
XUp = 0x0100,
/// <summary>Specifies that the wheel was moved</summary>
Wheel = 0x0800,
/// <summary>Specifies that x, y are absolute, not relative</summary>
Absolute = 0x8000,
};
[StructLayout(LayoutKind.Sequential)]
internal struct Win32Point
{
public Int32 X;
public Int32 Y;
};
#endregion
#region Native methods
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetCursorPos(ref Win32Point pt);
[DllImport("user32.dll")]
public static extern int GetSystemMetrics(int metric);
[DllImport("user32.dll", SetLastError = true)]
public static extern int SendInput(int nInputs, ref INPUT mi, int cbSize);
#endregion
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using MbUnit.Framework;
namespace Gallio.Ambience.Tests
{
[TestsOn(typeof(Ambient))]
public class AmbientTest
{
private const int PortNumber = 65436;
private const string UserName = "Test";
private const string Password = "Password";
private AmbienceServer server;
[FixtureSetUp]
public void SetUp()
{
server = new AmbienceServer(new AmbienceServerConfiguration()
{
Port = PortNumber,
DatabasePath = "AmbientTest.db",
Credential = { UserName = UserName, Password = Password }
});
server.Start();
}
[FixtureTearDown]
public void TearDown()
{
if (server != null)
{
server.Dispose();
server = null;
}
}
[Test]
public void DefaultConfiguration_PopulatedFromConfigSection()
{
AmbienceClientConfiguration config = Ambient.DefaultClientConfiguration;
Assert.AreEqual("localhost", config.HostName);
Assert.AreEqual(PortNumber, config.Port);
Assert.AreEqual(UserName, config.Credential.UserName);
Assert.AreEqual(Password, config.Credential.Password);
}
[Test]
public void DefaultConfiguration_CanOverrideSetting()
{
AmbienceClientConfiguration oldConfig = Ambient.DefaultClientConfiguration;
try
{
AmbienceClientConfiguration newConfig = new AmbienceClientConfiguration();
Ambient.DefaultClientConfiguration = newConfig;
Assert.AreSame(newConfig, Ambient.DefaultClientConfiguration);
}
finally
{
Ambient.DefaultClientConfiguration = oldConfig;
}
}
[Test]
public void DefaultConfiguration_ThrowsWhenValueSetToNull()
{
Assert.Throws<ArgumentNullException>(() => Ambient.DefaultClientConfiguration = null);
}
[Test]
public void CanStoreAndDeleteAll()
{
Ambient.Data.Store(new Item());
Assert.AreNotEqual(0, Ambient.Data.Query<Item>().Count());
Ambient.Data.DeleteAll();
Assert.Count(0, Ambient.Data.Query<Item>());
}
[Test]
public void CanStoreAndQuery()
{
Ambient.Data.DeleteAll();
Ambient.Data.Store(new Item { Name = "A", Value = 1 });
Ambient.Data.Store(new Item { Name = "B", Value = 2 });
IList<Item> items = Ambient.Data.Query<Item>();
Assert.AreElementsEqualIgnoringOrder(new[] { new Item { Name = "A", Value = 1 }, new Item { Name = "B", Value = 2 } }, items);
}
[Test]
public void CanStoreAndQueryWithPredicate()
{
Ambient.Data.DeleteAll();
Ambient.Data.Store(new Item { Name = "A", Value = 1 });
Ambient.Data.Store(new Item { Name = "B", Value = 2 });
Ambient.Data.Store(new Item { Name = "C", Value = 3 });
IList<Item> items = Ambient.Data.Query<Item>(x => x.Value > 1);
Assert.AreElementsEqualIgnoringOrder(new[] { new Item { Name = "B", Value = 2 }, new Item { Name = "C", Value = 3 } }, items);
}
[Test]
public void CanStoreAndDelete()
{
Ambient.Data.DeleteAll();
Item b = new Item { Name = "B", Value = 2 };
Ambient.Data.Store(new Item { Name = "A", Value = 1 });
Ambient.Data.Store(b);
Ambient.Data.Delete(b);
IList<Item> items = Ambient.Data.Query<Item>();
Assert.AreElementsEqualIgnoringOrder(new[] { new Item { Name = "A", Value = 1 } }, items);
}
[Test]
public void DeleteDoesNothingIfElementNotFound()
{
Ambient.Data.DeleteAll();
Ambient.Data.Delete(new Item { Name = "A", Value = 1 });
IList<Item> items = Ambient.Data.Query<Item>();
Assert.Count(0, items);
}
[Test]
public void CanStoreAndQueryWithLinq()
{
Ambient.Data.DeleteAll();
Ambient.Data.Store(new Item { Name = "A", Value = 1 });
Ambient.Data.Store(new Item { Name = "B", Value = 4 });
Ambient.Data.Store(new Item { Name = "B", Value = 2 });
Ambient.Data.Store(new Item { Name = "C", Value = 3 });
Ambient.Data.Store(new Item { Name = "B", Value = 3 });
IList<Item> items = (from Item x in Ambient.Data where x.Value > 1 orderby x.Name orderby x.Value descending select x).ToList();
Assert.AreElementsEqual(new[]
{
new Item { Name = "B", Value = 4 },
new Item { Name = "B", Value = 3 },
new Item { Name = "B", Value = 2 },
new Item { Name = "C", Value = 3 }
}, items);
items = (from Item x in Ambient.Data where x.Value > 1 orderby x.Name descending orderby x.Value select x).ToList();
Assert.AreElementsEqual(new[]
{
new Item { Name = "C", Value = 3 },
new Item { Name = "B", Value = 2 },
new Item { Name = "B", Value = 3 },
new Item { Name = "B", Value = 4 }
}, items);
Assert.Count(4, items);
}
[Test]
public void StoresAreAutoCommittedAndVisibleToOtherClients()
{
Ambient.Data.DeleteAll();
Ambient.Data.Store(new Item { Name = "A", Value = 1 });
using (AmbienceClient alternateClient = AmbienceClient.Connect(Ambient.DefaultClientConfiguration))
{
Assert.AreElementsEqual(new[] { new Item { Name = "A", Value = 1 } }, alternateClient.Container.Query<Item>());
}
}
[Test]
public void DeletesAreAutoCommittedAndVisibleToOtherClients()
{
Ambient.Data.DeleteAll();
Item a = new Item { Name = "A", Value = 1 };
Ambient.Data.Store(a);
Ambient.Data.Store(new Item { Name = "B", Value = 2 });
Ambient.Data.Delete(a);
using (AmbienceClient alternateClient = AmbienceClient.Connect(Ambient.DefaultClientConfiguration))
{
Assert.AreElementsEqual(new[] { new Item { Name = "B", Value = 2 } }, alternateClient.Container.Query<Item>());
}
}
[Test]
public void DeleteAllsAreAutoCommittedAndVisibleToOtherClients()
{
Ambient.Data.DeleteAll();
Ambient.Data.Store(new Item { Name = "A", Value = 1 });
Ambient.Data.Store(new Item { Name = "B", Value = 2 });
Ambient.Data.DeleteAll();
using (AmbienceClient alternateClient = AmbienceClient.Connect(Ambient.DefaultClientConfiguration))
{
Assert.AreElementsEqual(new Item[0], alternateClient.Container.Query<Item>());
}
}
}
}
| |
using J2N;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using JCG = J2N.Collections.Generic;
namespace Lucene.Net.Util.Automaton
{
/*
* 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.
*/
/// <summary>
/// Class to construct DFAs that match a word within some edit distance.
/// <para/>
/// Implements the algorithm described in:
/// Schulz and Mihov: Fast String Correction with Levenshtein Automata
/// <para/>
/// @lucene.experimental
/// </summary>
public class LevenshteinAutomata
{
/// <summary>
/// @lucene.internal </summary>
public const int MAXIMUM_SUPPORTED_DISTANCE = 2;
/* input word */
internal readonly int[] word;
/* the automata alphabet. */
internal readonly int[] alphabet;
/* the maximum symbol in the alphabet (e.g. 255 for UTF-8 or 10FFFF for UTF-32) */
internal readonly int alphaMax;
/* the ranges outside of alphabet */
internal readonly int[] rangeLower;
internal readonly int[] rangeUpper;
internal int numRanges = 0;
internal ParametricDescription[] descriptions;
/// <summary>
/// Create a new <see cref="LevenshteinAutomata"/> for some <paramref name="input"/> string.
/// Optionally count transpositions as a primitive edit.
/// </summary>
public LevenshteinAutomata(string input, bool withTranspositions)
: this(CodePoints(input), Character.MaxCodePoint, withTranspositions)
{
}
/// <summary>
/// Expert: specify a custom maximum possible symbol
/// (alphaMax); default is <see cref="Character.MaxCodePoint"/>.
/// </summary>
public LevenshteinAutomata(int[] word, int alphaMax, bool withTranspositions)
{
this.word = word;
this.alphaMax = alphaMax;
// calculate the alphabet
ISet<int> set = new JCG.SortedSet<int>();
for (int i = 0; i < word.Length; i++)
{
int v = word[i];
if (v > alphaMax)
{
throw new ArgumentException("alphaMax exceeded by symbol " + v + " in word");
}
set.Add(v);
}
alphabet = new int[set.Count];
using (IEnumerator<int> iterator = set.GetEnumerator())
{
for (int i = 0; i < alphabet.Length; i++)
{
iterator.MoveNext();
alphabet[i] = iterator.Current;
}
}
rangeLower = new int[alphabet.Length + 2];
rangeUpper = new int[alphabet.Length + 2];
// calculate the unicode range intervals that exclude the alphabet
// these are the ranges for all unicode characters not in the alphabet
int lower = 0;
for (int i = 0; i < alphabet.Length; i++)
{
int higher = alphabet[i];
if (higher > lower)
{
rangeLower[numRanges] = lower;
rangeUpper[numRanges] = higher - 1;
numRanges++;
}
lower = higher + 1;
}
/* add the final endpoint */
if (lower <= alphaMax)
{
rangeLower[numRanges] = lower;
rangeUpper[numRanges] = alphaMax;
numRanges++;
}
descriptions = new ParametricDescription[] {
null,
withTranspositions ? (ParametricDescription)new Lev1TParametricDescription(word.Length) : new Lev1ParametricDescription(word.Length),
withTranspositions ? (ParametricDescription)new Lev2TParametricDescription(word.Length) : new Lev2ParametricDescription(word.Length)
};
}
private static int[] CodePoints(string input)
{
int length = Character.CodePointCount(input, 0, input.Length);
int[] word = new int[length];
for (int i = 0, j = 0, cp = 0; i < input.Length; i += Character.CharCount(cp))
{
word[j++] = cp = Character.CodePointAt(input, i);
}
return word;
}
/// <summary>
/// Compute a DFA that accepts all strings within an edit distance of <paramref name="n"/>.
/// <para>
/// All automata have the following properties:
/// <list type="bullet">
/// <item><description>They are deterministic (DFA).</description></item>
/// <item><description>There are no transitions to dead states.</description></item>
/// <item><description>They are not minimal (some transitions could be combined).</description></item>
/// </list>
/// </para>
/// </summary>
public virtual Automaton ToAutomaton(int n)
{
if (n == 0)
{
return BasicAutomata.MakeString(word, 0, word.Length);
}
if (n >= descriptions.Length)
{
return null;
}
int range = 2 * n + 1;
ParametricDescription description = descriptions[n];
// the number of states is based on the length of the word and n
State[] states = new State[description.Count];
// create all states, and mark as accept states if appropriate
for (int i = 0; i < states.Length; i++)
{
states[i] = new State();
states[i].number = i;
states[i].Accept = description.IsAccept(i);
}
// create transitions from state to state
for (int k = 0; k < states.Length; k++)
{
int xpos = description.GetPosition(k);
if (xpos < 0)
{
continue;
}
int end = xpos + Math.Min(word.Length - xpos, range);
for (int x = 0; x < alphabet.Length; x++)
{
int ch = alphabet[x];
// get the characteristic vector at this position wrt ch
int cvec = GetVector(ch, xpos, end);
int dest = description.Transition(k, xpos, cvec);
if (dest >= 0)
{
states[k].AddTransition(new Transition(ch, states[dest]));
}
}
// add transitions for all other chars in unicode
// by definition, their characteristic vectors are always 0,
// because they do not exist in the input string.
int dest_ = description.Transition(k, xpos, 0); // by definition
if (dest_ >= 0)
{
for (int r = 0; r < numRanges; r++)
{
states[k].AddTransition(new Transition(rangeLower[r], rangeUpper[r], states[dest_]));
}
}
}
Automaton a = new Automaton(states[0]);
a.IsDeterministic = true;
// we create some useless unconnected states, and its a net-win overall to remove these,
// as well as to combine any adjacent transitions (it makes later algorithms more efficient).
// so, while we could set our numberedStates here, its actually best not to, and instead to
// force a traversal in reduce, pruning the unconnected states while we combine adjacent transitions.
//a.setNumberedStates(states);
a.Reduce();
// we need not trim transitions to dead states, as they are not created.
//a.restoreInvariant();
return a;
}
/// <summary>
/// Get the characteristic vector <c>X(x, V)</c>
/// where V is <c>Substring(pos, end - pos)</c>.
/// </summary>
internal virtual int GetVector(int x, int pos, int end)
{
int vector = 0;
for (int i = pos; i < end; i++)
{
vector <<= 1;
if (word[i] == x)
{
vector |= 1;
}
}
return vector;
}
/// <summary>
/// A <see cref="ParametricDescription"/> describes the structure of a Levenshtein DFA for some degree <c>n</c>.
/// <para/>
/// There are four components of a parametric description, all parameterized on the length
/// of the word <c>w</c>:
/// <list type="number">
/// <item><description>The number of states: <see cref="Count"/></description></item>
/// <item><description>The set of final states: <see cref="IsAccept(int)"/></description></item>
/// <item><description>The transition function: <see cref="Transition(int, int, int)"/></description></item>
/// <item><description>Minimal boundary function: <see cref="GetPosition(int)"/></description></item>
/// </list>
/// </summary>
internal abstract class ParametricDescription
{
protected readonly int m_w;
protected readonly int m_n;
private readonly int[] minErrors;
internal ParametricDescription(int w, int n, int[] minErrors)
{
this.m_w = w;
this.m_n = n;
this.minErrors = minErrors;
}
/// <summary>
/// Return the number of states needed to compute a Levenshtein DFA.
/// <para/>
/// NOTE: This was size() in Lucene.
/// </summary>
internal virtual int Count => minErrors.Length * (m_w + 1);
/// <summary>
/// Returns <c>true</c> if the <c>state</c> in any Levenshtein DFA is an accept state (final state).
/// </summary>
internal virtual bool IsAccept(int absState)
{
// decode absState -> state, offset
int state = absState / (m_w + 1);
int offset = absState % (m_w + 1);
Debug.Assert(offset >= 0);
return m_w - offset + minErrors[state] <= m_n;
}
/// <summary>
/// Returns the position in the input word for a given <c>state</c>.
/// this is the minimal boundary for the state.
/// </summary>
internal virtual int GetPosition(int absState)
{
return absState % (m_w + 1);
}
/// <summary>
/// Returns the state number for a transition from the given <paramref name="state"/>,
/// assuming <paramref name="position"/> and characteristic vector <paramref name="vector"/>.
/// </summary>
internal abstract int Transition(int state, int position, int vector);
private static readonly long[] MASKS = new long[] {
0x1, 0x3, 0x7, 0xf,
0x1f, 0x3f, 0x7f, 0xff,
0x1ff, 0x3ff, 0x7ff, 0xfff,
0x1fff, 0x3fff, 0x7fff, 0xffff,
0x1ffff, 0x3ffff, 0x7ffff, 0xfffff,
0x1fffff, 0x3fffff, 0x7fffff, 0xffffff,
0x1ffffff, 0x3ffffff, 0x7ffffff, 0xfffffff,
0x1fffffff, 0x3fffffff, 0x7fffffffL, 0xffffffffL,
0x1ffffffffL, 0x3ffffffffL, 0x7ffffffffL, 0xfffffffffL,
0x1fffffffffL, 0x3fffffffffL, 0x7fffffffffL, 0xffffffffffL,
0x1ffffffffffL, 0x3ffffffffffL, 0x7ffffffffffL, 0xfffffffffffL,
0x1fffffffffffL, 0x3fffffffffffL, 0x7fffffffffffL, 0xffffffffffffL,
0x1ffffffffffffL, 0x3ffffffffffffL, 0x7ffffffffffffL, 0xfffffffffffffL,
0x1fffffffffffffL, 0x3fffffffffffffL, 0x7fffffffffffffL, 0xffffffffffffffL,
0x1ffffffffffffffL, 0x3ffffffffffffffL, 0x7ffffffffffffffL, 0xfffffffffffffffL,
0x1fffffffffffffffL, 0x3fffffffffffffffL, 0x7fffffffffffffffL
};
protected internal virtual int Unpack(long[] data, int index, int bitsPerValue)
{
long bitLoc = bitsPerValue * index;
int dataLoc = (int)(bitLoc >> 6);
int bitStart = (int)(bitLoc & 63);
if (bitStart + bitsPerValue <= 64)
{
// not split
return (int)((data[dataLoc] >> bitStart) & MASKS[bitsPerValue - 1]);
}
else
{
// split
int part = 64 - bitStart;
return (int)(((data[dataLoc] >> bitStart) & MASKS[part - 1]) + ((data[1 + dataLoc] & MASKS[bitsPerValue - part - 1]) << part));
}
}
}
}
}
| |
using StarBlaster.DataTypes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FlatRedBall.Content.Scene;
using FlatRedBall.Content;
using FlatRedBall.IO;
using FlatRedBall.Debugging;
using FlatRedBall.Performance.Measurement;
using System.IO;
using TMXGlueLib.DataTypes;
using TMXGlueLib;
using FlatRedBall.Graphics;
using FlatRedBall.Graphics.Animation;
namespace FlatRedBall.TileGraphics
{
public class LayeredTileMap : PositionedObject, IVisible
{
#region Fields
FlatRedBall.Math.PositionedObjectList<MapDrawableBatch> mMapLists = new FlatRedBall.Math.PositionedObjectList<MapDrawableBatch>();
float mRenderingScale = 1;
float mZSplit = 1;
float? mNumberTilesWide;
float? mNumberTilesTall;
float? mWidthPerTile;
float? mHeightPerTile;
#endregion
#region Properties
public Dictionary<string, List<NamedValue>> Properties
{
get;
private set;
} = new Dictionary<string, List<NamedValue>>();
public float RenderingScale
{
get
{
return mRenderingScale;
}
set
{
mRenderingScale = value;
foreach (var map in mMapLists)
{
map.RenderingScale = value;
}
}
}
public float ZSplit
{
get
{
return mZSplit;
}
set
{
for (int i = 0; i < this.mMapLists.Count; i++)
{
mMapLists[i].RelativeZ = mZSplit * i;
}
}
}
public List<FlatRedBall.Math.Geometry.ShapeCollection> ShapeCollections { get; private set; } = new List<FlatRedBall.Math.Geometry.ShapeCollection>();
public FlatRedBall.Math.PositionedObjectList<MapDrawableBatch> MapLayers
{
get
{
return mMapLists;
}
}
bool visible = true;
public bool Visible
{
get
{
return visible;
}
set
{
visible = value;
foreach (var item in this.mMapLists)
{
item.Visible = visible;
}
}
}
/// <summary>
/// Returns the width in world units of the entire map. The map may not visibly extend to this width;
/// </summary>
public float Width
{
get
{
if (mNumberTilesWide.HasValue && mWidthPerTile.HasValue)
{
return mNumberTilesWide.Value * mWidthPerTile.Value;
}
else
{
return 0;
}
}
}
/// <summary>
/// Returns the height in world units of the entire map. The map may not visibly extend to this height;
/// </summary>
public float Height
{
get
{
if (mNumberTilesTall.HasValue && mHeightPerTile.HasValue)
{
return mNumberTilesTall.Value * mHeightPerTile.Value;
}
else
{
return 0;
}
}
}
public LayeredTileMapAnimation Animation { get; set; }
IVisible IVisible.Parent
{
get
{
return Parent as IVisible;
}
}
public bool AbsoluteVisible
{
get
{
if (this.Visible)
{
var parentAsIVisible = this.Parent as IVisible;
if (parentAsIVisible == null || IgnoresParentVisibility)
{
return true;
}
else
{
// this is true, so return if the parent is visible:
return parentAsIVisible.AbsoluteVisible;
}
}
else
{
return false;
}
}
}
public bool IgnoresParentVisibility
{
get;
set;
}
#endregion
public IEnumerable<string> TileNamesWith(string propertyName)
{
foreach (var item in Properties.Values)
{
if (item.Any(item2 => item2.Name == propertyName))
{
var hasName = item.Any(item2 => item2.Name == "Name");
if (hasName)
{
yield return item.First(item2 => item2.Name == "Name").Value as string;
}
}
}
}
public static LayeredTileMap FromScene(string fileName, string contentManagerName)
{
return FromScene(fileName, contentManagerName, false);
}
public static LayeredTileMap FromScene(string fileName, string contentManagerName, bool verifySameTexturePerLayer)
{
Section.GetAndStartContextAndTime("Initial FromScene");
LayeredTileMap toReturn = new LayeredTileMap();
string absoluteFileName = FileManager.MakeAbsolute(fileName);
Section.EndContextAndTime();
Section.GetAndStartContextAndTime("FromFile");
SceneSave ses = SceneSave.FromFile(absoluteFileName);
Section.EndContextAndTime();
Section.GetAndStartContextAndTime("BreaksNStuff");
string oldRelativeDirectory = FileManager.RelativeDirectory;
FileManager.RelativeDirectory = FileManager.GetDirectory(absoluteFileName);
var breaks = GetZBreaks(ses.SpriteList);
int valueBefore = 0;
MapDrawableBatch mdb;
int valueAfter;
float zValue = 0;
Section.EndContextAndTime();
Section.GetAndStartContextAndTime("Create MDBs");
for (int i = 0; i < breaks.Count; i++)
{
valueAfter = breaks[i];
int count = valueAfter - valueBefore;
mdb = MapDrawableBatch.FromSpriteSaves(ses.SpriteList, valueBefore, count, contentManagerName, verifySameTexturePerLayer);
mdb.AttachTo(toReturn, false);
mdb.RelativeZ = zValue;
toReturn.mMapLists.Add(mdb);
zValue += toReturn.mZSplit;
valueBefore = valueAfter;
}
valueAfter = ses.SpriteList.Count;
if (valueBefore != valueAfter)
{
int count = valueAfter - valueBefore;
mdb = MapDrawableBatch.FromSpriteSaves(ses.SpriteList, valueBefore, count, contentManagerName, verifySameTexturePerLayer);
mdb.AttachTo(toReturn, false);
mdb.RelativeZ = zValue;
toReturn.mMapLists.Add(mdb);
}
Section.EndContextAndTime();
FileManager.RelativeDirectory = oldRelativeDirectory;
return toReturn;
}
public static LayeredTileMap FromReducedTileMapInfo(string fileName, string contentManagerName)
{
using (Stream inputStream = FileManager.GetStreamForFile(fileName))
using (BinaryReader binaryReader = new BinaryReader(inputStream))
{
ReducedTileMapInfo rtmi = ReducedTileMapInfo.ReadFrom(binaryReader);
string fullFileName = fileName;
if (FileManager.IsRelative(fullFileName))
{
fullFileName = FileManager.RelativeDirectory + fileName;
}
var toReturn = FromReducedTileMapInfo(rtmi, contentManagerName, fileName);
toReturn.Name = fullFileName;
return toReturn;
}
}
public static LayeredTileMap FromReducedTileMapInfo(TMXGlueLib.DataTypes.ReducedTileMapInfo rtmi, string contentManagerName, string tilbToLoad)
{
var toReturn = new LayeredTileMap();
string oldRelativeDirectory = FileManager.RelativeDirectory;
FileManager.RelativeDirectory = FileManager.GetDirectory(tilbToLoad);
MapDrawableBatch mdb;
if (rtmi.NumberCellsWide != 0)
{
toReturn.mNumberTilesWide = rtmi.NumberCellsWide;
}
if (rtmi.NumberCellsTall != 0)
{
toReturn.mNumberTilesTall = rtmi.NumberCellsTall;
}
toReturn.mWidthPerTile = rtmi.QuadWidth;
toReturn.mHeightPerTile = rtmi.QuadHeight;
for (int i = 0; i < rtmi.Layers.Count; i++)
{
var reducedLayer = rtmi.Layers[i];
mdb = MapDrawableBatch.FromReducedLayer(reducedLayer, toReturn, rtmi, contentManagerName);
mdb.AttachTo(toReturn, false);
mdb.RelativeZ = reducedLayer.Z;
toReturn.mMapLists.Add(mdb);
}
FileManager.RelativeDirectory = oldRelativeDirectory;
return toReturn;
}
public static LayeredTileMap FromTiledMapSave(string fileName, string contentManager)
{
TiledMapSave tms = TiledMapSave.FromFile(fileName);
// Ultimately properties are tied to tiles by the tile name.
// If a tile has no name but it has properties, those properties
// will be lost in the conversion. Therefore, we have to add name properties.
tms.NameUnnamedTilesetTiles();
string directory = FlatRedBall.IO.FileManager.GetDirectory(fileName);
var rtmi = ReducedTileMapInfo.FromTiledMapSave(
tms, 1, 0, directory, FileReferenceType.Absolute);
var toReturn = FromReducedTileMapInfo(rtmi, contentManager, fileName);
foreach (var mapObjectgroup in tms.objectgroup)
{
var shapeCollection = tms.ToShapeCollection(mapObjectgroup.Name);
if (shapeCollection != null && shapeCollection.IsEmpty == false)
{
shapeCollection.Name = mapObjectgroup.Name;
toReturn.ShapeCollections.Add(shapeCollection);
}
}
foreach (var layer in tms.MapLayers)
{
var matchingLayer = toReturn.MapLayers.FirstOrDefault(item => item.Name == layer.Name);
if (matchingLayer != null)
{
if (layer is MapLayer)
{
var mapLayer = layer as MapLayer;
foreach (var propertyValues in mapLayer.properties)
{
matchingLayer.Properties.Add(new NamedValue
{
Name = propertyValues.StrippedName,
Value = propertyValues.value
});
}
matchingLayer.Visible = mapLayer.visible == 1;
}
}
}
foreach (var tileset in tms.Tilesets)
{
foreach (var tile in tileset.TileDictionary.Values)
{
if (tile.properties.Count != 0)
{
// this needs a name:
string name = tile.properties.FirstOrDefault(item => item.StrippedName.ToLowerInvariant() == "name")?.value;
if (!string.IsNullOrEmpty(name))
{
List<NamedValue> namedValues = new List<NamedValue>();
foreach (var prop in tile.properties)
{
namedValues.Add(new NamedValue() { Name = prop.StrippedName, Value = prop.value });
}
toReturn.Properties.Add(name, namedValues);
}
}
}
}
var tmxDirectory = FileManager.GetDirectory(fileName);
var animationDictionary = new Dictionary<string, AnimationChain>();
// add animations
foreach (var tileset in tms.Tilesets)
{
string tilesetImageFile = tmxDirectory + tileset.Images[0].Source;
if (tileset.SourceDirectory != ".")
{
tilesetImageFile = tmxDirectory + tileset.SourceDirectory + tileset.Images[0].Source;
}
var texture = FlatRedBallServices.Load<Microsoft.Xna.Framework.Graphics.Texture2D>(tilesetImageFile);
foreach (var tile in tileset.Tiles.Where(item => item.Animation != null && item.Animation.Frames.Count != 0))
{
var animation = tile.Animation;
var animationChain = new AnimationChain();
foreach (var frame in animation.Frames)
{
var animationFrame = new AnimationFrame();
animationFrame.FrameLength = frame.Duration / 1000.0f;
animationFrame.Texture = texture;
int tileIdRelative = frame.TileId;
int globalTileId = (int)(tileIdRelative + tileset.Firstgid);
int leftPixel;
int rightPixel;
int topPixel;
int bottomPixel;
TiledMapSave.GetPixelCoordinatesFromGid((uint)globalTileId, tileset, out leftPixel, out topPixel, out rightPixel, out bottomPixel);
animationFrame.LeftCoordinate = MapDrawableBatch.CoordinateAdjustment + leftPixel / (float)texture.Width;
animationFrame.RightCoordinate = -MapDrawableBatch.CoordinateAdjustment + rightPixel / (float)texture.Width;
animationFrame.TopCoordinate = MapDrawableBatch.CoordinateAdjustment + topPixel / (float)texture.Height;
animationFrame.BottomCoordinate = -MapDrawableBatch.CoordinateAdjustment + bottomPixel / (float)texture.Height;
animationChain.Add(animationFrame);
}
var property = tile.properties.FirstOrDefault(item => item.StrippedNameLower == "name");
if (property == null)
{
throw new InvalidOperationException(
$"The tile with ID {tile.id} has an animation, but it doesn't have a Name property, which is required for animation.");
}
else
{
animationDictionary.Add(property.value, animationChain);
}
}
}
toReturn.Animation = new LayeredTileMapAnimation(animationDictionary);
return toReturn;
}
public void AnimateSelf()
{
if (Animation != null)
{
Animation.Activity(this);
}
}
public void AddToManagers()
{
AddToManagers(null);
}
public void AddToManagers(FlatRedBall.Graphics.Layer layer)
{
bool isAlreadyManaged = SpriteManager.ManagedPositionedObjects
.Contains(this);
// This allows AddToManagers to be called multiple times, so it can be added to multiple layers
if (!isAlreadyManaged)
{
SpriteManager.AddPositionedObject(this);
}
foreach (var item in this.mMapLists)
{
item.AddToManagers(layer);
}
}
//Write some addtomanagers and remove methods
static List<int> GetZBreaks(List<SpriteSave> list)
{
List<int> zBreaks = new List<int>();
GetZBreaks(list, zBreaks);
return zBreaks;
}
static void GetZBreaks(List<SpriteSave> list, List<int> zBreaks)
{
zBreaks.Clear();
if (list.Count == 0 || list.Count == 1)
return;
for (int i = 1; i < list.Count; i++)
{
if (list[i].Z != list[i - 1].Z)
zBreaks.Add(i);
}
}
public LayeredTileMap Clone()
{
var toReturn = base.Clone<LayeredTileMap>();
toReturn.mMapLists = new Math.PositionedObjectList<MapDrawableBatch>();
foreach (var item in this.MapLayers)
{
var clonedLayer = item.Clone();
if (item.Parent == this)
{
clonedLayer.AttachTo(toReturn, false);
}
toReturn.mMapLists.Add(clonedLayer);
}
toReturn.ShapeCollections = new List<Math.Geometry.ShapeCollection>();
foreach (var shapeCollection in this.ShapeCollections)
{
toReturn.ShapeCollections.Add(shapeCollection.Clone());
}
return toReturn;
}
public void RemoveFromManagersOneWay()
{
this.mMapLists.MakeOneWay();
for (int i = 0; i < mMapLists.Count; i++)
{
SpriteManager.RemoveDrawableBatch(this.mMapLists[i]);
}
SpriteManager.RemovePositionedObject(this);
this.mMapLists.MakeTwoWay();
}
public void Destroy()
{
// Make it one-way because we want the
// contained objects to persist after a destroy
mMapLists.MakeOneWay();
for (int i = 0; i < mMapLists.Count; i++)
{
SpriteManager.RemoveDrawableBatch(mMapLists[i]);
}
SpriteManager.RemovePositionedObject(this);
mMapLists.MakeTwoWay();
}
}
public static class LayeredTileMapExtensions
{
public static void RemoveTiles(this LayeredTileMap map,
Func<List<NamedValue>, bool> predicate,
Dictionary<string, List<NamedValue>> Properties)
{
// Force execution now for performance reasons
var filteredInfos = Properties.Values.Where(predicate).ToList();
foreach (var layer in map.MapLayers)
{
List<int> indexes = new List<int>();
foreach (var itemThatPasses in filteredInfos)
{
string tileName = itemThatPasses
.FirstOrDefault(item => item.Name.ToLowerInvariant() == "name")
.Value as string;
if (layer.NamedTileOrderedIndexes.ContainsKey(tileName))
{
var intsOnThisLayer =
layer.NamedTileOrderedIndexes[tileName];
indexes.AddRange(intsOnThisLayer);
}
}
layer.RemoveQuads(indexes);
}
}
}
}
| |
namespace SPALM.SPSF.Library
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using EnvDTE;
using Microsoft.Win32;
using SPALM.SPSF.SharePointBridge;
using Process = System.Diagnostics.Process;
using Thread = System.Threading.Thread;
public class SharePointBrigdeHelper
{
private Process bridgeProcess = null;
private SharePointRemoteObject remoteObj = null;
private DTE dte = null;
private string toolsPath = "";
public SharePointBrigdeHelper(DTE dte)
{
this.dte = dte;
string version = Helpers.GetInstalledSharePointVersion();
string sharePointBridgeExe = "SharePointBridge" + version + ".exe";
DirectoryInfo assemblyFolder = new DirectoryInfo(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
toolsPath = assemblyFolder + @"\" + sharePointBridgeExe;
if (!File.Exists(toolsPath))
{
//ok, file is not in the current directory (issue that executing assembly is located in a different folder
//let's check the registry for the installation location of SPSF
RegistryKey packageKey = Registry.LocalMachine.OpenSubKey(dte.RegistryRoot + @"\BindingPaths\{93c68916-6e2b-43fb-9940-bf7c943cf0d9}", true);
if (packageKey != null)
{
foreach (string s in packageKey.GetValueNames())
{
toolsPath = s + @"\" + sharePointBridgeExe;
if (File.Exists(s))
{
break;
}
}
if (!File.Exists(toolsPath))
{
Helpers.LogMessage(dte, dte, "Error: SharePointBridge '" + sharePointBridgeExe + "' not found ('" + toolsPath + "')");
throw new Exception("File not found " + toolsPath);
}
}
}
Helpers.ShowProgress(dte, string.Format("Connecting to SharePoint {0}...", version == "14"?"2010":"2013"), 10);
Helpers.LogMessage(dte, dte, string.Format("Connecting to SharePoint {0}. Please wait...", version == "14" ? "2010" : "2013"));
if (IsBridgeNeeded)
{
StartBridge();
}
else
{
remoteObj = new SharePointRemoteObject();
}
}
private int GetOSArchitecture()
{
string pa =
Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
return ((String.IsNullOrEmpty(pa) ||
String.Compare(pa, 0, "x86", 0, 3, true) == 0) ? 32 : 64);
}
public bool IsBridgeNeeded
{
get
{
return true;
//is the environment 64bit but the process is 32bit?
/*
if (IntPtr.Size == 4)
{
if (GetOSArchitecture() == 64)
{
Helpers.LogMessage(dte, dte, "Detected: Running as 32bit process on 64bit machine");
return true;
}
}
Helpers.LogMessage(dte, dte, "Detected: No bridge needed");
return false;
* */
}
}
~SharePointBrigdeHelper()
{
StopBridge();
}
public Version GetSharePointVersion()
{
Version x = new Version();
try
{
Helpers.ShowProgress(dte, "Retrieving SharePoint version...", 60);
x = remoteObj.GetSharePointVersion();
}
catch (Exception ex)
{
Helpers.LogMessage(dte, dte, ex.Message);
}
finally
{
Helpers.HideProgress(dte);
StopBridge();
}
return x;
}
public string GetPathToTraceLogs()
{
string path = "";
try
{
Helpers.ShowProgress(dte, "Retrieving SharePoint Trace Log Location...", 60);
path = remoteObj.GetPathToTraceLogs();
}
catch (Exception ex)
{
Helpers.LogMessage(dte, dte, ex.Message);
}
finally
{
Helpers.HideProgress(dte);
StopBridge();
}
return path;
}
public void ExportContent(SharePointExportSettings exportSettings, string tempExportDir, string tempFilename, string tempLogFilePath)
{
try
{
Helpers.ShowProgress(dte, "Exporting SharePoint solution...", 60);
remoteObj.ExportContent(exportSettings, tempExportDir, tempFilename, tempLogFilePath);
}
catch (Exception ex)
{
Helpers.LogMessage(dte, dte, ex.Message);
}
finally
{
Helpers.HideProgress(dte);
StopBridge();
}
}
public void ExportSolutionAsFile(string solutionName, string saveAsfilename)
{
try
{
Helpers.ShowProgress(dte, "Exporting SharePoint solution...", 60);
remoteObj.ExportSolutionAsFile(solutionName, saveAsfilename);
}
catch (Exception ex)
{
Helpers.LogMessage(dte, dte, ex.Message);
}
finally
{
Helpers.HideProgress(dte);
StopBridge();
}
}
public void DeleteFailedDeploymentJobs()
{
try
{
remoteObj.DeleteFailedDeploymentJobs();
}
catch (Exception ex)
{
Helpers.LogMessage(dte, dte, ex.Message);
}
finally
{
Helpers.HideProgress(dte);
StopBridge();
}
}
private void StartBridge()
{
try
{
//IChannel ichannel = new IpcChannel("myClient");
//ChannelServices.RegisterChannel(ichannel, false);
string channelName = "SPSF" + Guid.NewGuid().ToString();
bridgeProcess = new Process();
bridgeProcess.StartInfo.FileName = toolsPath;
bridgeProcess.StartInfo.CreateNoWindow = true;
bridgeProcess.StartInfo.Arguments = channelName;
bridgeProcess.StartInfo.UseShellExecute = false;
bridgeProcess.StartInfo.RedirectStandardInput = true;
bridgeProcess.StartInfo.RedirectStandardOutput = true;
bridgeProcess.StartInfo.RedirectStandardError = true;
bridgeProcess.StartInfo.WorkingDirectory = Path.GetDirectoryName(toolsPath);
bridgeProcess.OutputDataReceived += new DataReceivedEventHandler(bridgeProcess_OutputDataReceived);
bridgeProcess.ErrorDataReceived += new DataReceivedEventHandler(bridgeProcess_ErrorDataReceived);
bridgeProcess.EnableRaisingEvents = true;
bridgeProcess.Start();
bridgeProcess.BeginOutputReadLine();
TimeSpan waitTime = new TimeSpan(0, 0, 5);
Thread.Sleep(waitTime);
try
{
remoteObj = Activator.GetObject(typeof(SharePointRemoteObject), "ipc://" + channelName + "/RemoteObj") as SharePointRemoteObject;
}
catch { }
if (remoteObj == null)
{
for (int i = 0; i < 5; i++)
{
Thread.Sleep(waitTime);
remoteObj = Activator.GetObject(typeof(SharePointRemoteObject), "ipc://" + channelName + "/RemoteObj") as SharePointRemoteObject;
if (remoteObj == null)
{
break;
}
}
}
}
catch (Exception ex)
{
throw new Exception("Could not start SPSF SharePointBridge. Make sure that IIS and SharePoint are running (" + ex.Message + ")");
}
if (remoteObj == null)
{
throw new Exception("Could not access SharePointRemoteObject");
}
//Helpers.LogMessage(dte, dte, "SharePointBridge started");
}
void bridgeProcess_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
Helpers.LogMessage(dte, dte, "SharePointBridge error: " + e.Data);
}
void bridgeProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (string.IsNullOrEmpty(e.Data))
{
return;
}
string message = e.Data;
int percentage = 0;
//to retrieve progress we have pipe as separator
if (message.Contains("%"))
{
try
{
percentage = Int32.Parse(message.Substring(0, message.IndexOf("%")));
message = message.Substring(message.IndexOf("%") + 1);
}
catch { }
}
if (percentage > 0)
{
Helpers.ShowProgress(dte, message, percentage);
}
Helpers.LogMessage(dte, dte, message);
}
private void StopBridge()
{
if (bridgeProcess != null)
{
if (!bridgeProcess.HasExited)
{
//Helpers.LogMessage(dte, dte, "Closing connection to SharePoint");
bridgeProcess.Kill();
}
}
}
public string GetCentralAdministrationUrl()
{
string res = "";
try
{
Helpers.ShowProgress(dte, "Retrieving url of Central Administration...", 60);
res = remoteObj.GetCentralAdministrationUrl();
}
catch (Exception ex)
{
Helpers.LogMessage(dte, dte, ex.Message);
}
finally
{
Helpers.HideProgress(dte);
StopBridge();
}
return res;
}
public void PerformDeploymentOperation(string operation, List<SharePointDeploymentJob> deploymentJobs)
{
try
{
remoteObj.PerformDeploymentOperation(operation, deploymentJobs);
}
catch (Exception ex)
{
Helpers.LogMessage(dte, dte, ex.Message);
}
finally
{
Helpers.HideProgress(dte);
StopBridge();
}
}
public void ExportListAsTemplate(string weburl, Guid listId, string tempPath)
{
try
{
Helpers.ShowProgress(dte, "Exporting list template...", 60);
remoteObj.ExportListAsTemplate(weburl, listId, tempPath);
}
catch (Exception ex)
{
Helpers.LogMessage(dte, dte, ex.Message);
}
finally
{
Helpers.HideProgress(dte);
StopBridge();
}
}
public List<SharePointWebApplication> GetAllWebApplications()
{
List<SharePointWebApplication> res = new List<SharePointWebApplication>();
try
{
Helpers.ShowProgress(dte, "Retrieving webapplication list...", 60);
res = remoteObj.GetAllWebApplications();
LogMessage("SharePointBrigdeHelper: GetAllWebApplications retrieved " + res.Count.ToString() + " items");
}
catch (Exception ex)
{
LogMessage("SharePointBrigdeHelper: " + ex.ToString());
Helpers.LogMessage(dte, dte, ex.Message);
Helpers.LogMessage(dte, dte, "Ensure that WWW Service and SharePoint database are running on your machine");
}
finally
{
Helpers.HideProgress(dte);
StopBridge();
}
return res;
}
private static void LogMessage(string p)
{
//string logFile = Path.Combine(GetAssemblyDirectory(), "SharePointBridge.log");
//File.AppendAllText(logFile, p + Environment.NewLine);
}
private static string GetAssemblyDirectory()
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
}
public SharePointWeb GetRootWebOfSite(string siteCollection)
{
SharePointWeb res = null;
try
{
Helpers.ShowProgress(dte, "Retrieving webs of site " + siteCollection + "...", 60);
res = remoteObj.GetRootWebOfSite(siteCollection);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
Helpers.LogMessage(dte, dte, ex.ToString());
}
finally
{
Helpers.HideProgress(dte);
StopBridge();
}
return res;
}
public SharePointWeb GetWeb(string webUrl)
{
SharePointWeb res = null;
try
{
Helpers.ShowProgress(dte, "Retrieving web " + webUrl + "...", 60);
res = remoteObj.GetWeb(webUrl);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
Helpers.LogMessage(dte, dte, ex.ToString());
}
finally
{
Helpers.HideProgress(dte);
StopBridge();
}
return res;
}
public List<SharePointSiteCollection> GetAllSiteCollections()
{
List<SharePointSiteCollection> res = new List<SharePointSiteCollection>();
try
{
Helpers.ShowProgress(dte, "Retrieving site collections list...", 60);
res = remoteObj.GetAllSiteCollections();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
Helpers.LogMessage(dte, dte, ex.ToString());
}
finally
{
Helpers.HideProgress(dte);
StopBridge();
}
return res;
}
public List<SharePointField> GetSiteColumns(string siteUrl)
{
List<SharePointField> res = new List<SharePointField>();
try
{
Helpers.ShowProgress(dte, "Retrieving content type list...", 60);
res = remoteObj.GetSiteColumns(siteUrl);
}
catch (Exception ex)
{
Helpers.LogMessage(dte, dte, ex.Message);
}
finally
{
Helpers.HideProgress(dte);
StopBridge();
}
return res;
}
public List<SharePointContentType> GetContentTypes(string siteUrl)
{
List<SharePointContentType> res = new List<SharePointContentType>();
try
{
Helpers.ShowProgress(dte, "Retrieving content type list...", 60);
res = remoteObj.GetContentTypes(siteUrl);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
Helpers.LogMessage(dte, dte, ex.ToString());
}
finally
{
Helpers.HideProgress(dte);
StopBridge();
}
return res;
}
public List<SharePointSolution> GetAllSharePointSolutions()
{
List<SharePointSolution> res = new List<SharePointSolution>();
try
{
Helpers.ShowProgress(dte, "Retrieving solutions list...", 60);
res = remoteObj.GetAllSharePointSolutions();
}
catch (Exception ex)
{
Helpers.LogMessage(dte, dte, ex.Message);
}
finally
{
Helpers.HideProgress(dte);
StopBridge();
}
return res;
}
public void CheckBrokenFields(string siteCollectionUrl)
{
try
{
Helpers.ShowProgress(dte, "Checking for broken fields in site collection " + siteCollectionUrl, 60);
remoteObj.CheckBrokenFields(siteCollectionUrl);
}
catch (Exception ex)
{
Helpers.LogMessage(dte, dte, ex.Message);
}
finally
{
Helpers.HideProgress(dte);
StopBridge();
}
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using MS.Test.Common.MsTestLib;
using StorageTestLib;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using StorageBlob = Microsoft.WindowsAzure.Storage.Blob;
namespace Management.Storage.ScenarioTest.Util
{
public class CloudBlobUtil
{
private CloudStorageAccount account;
private CloudBlobClient client;
private Random random;
private const int PageBlobUnitSize = 512;
private static List<string> HttpsCopyHosts;
public string ContainerName
{
get;
private set;
}
public string BlobName
{
get;
private set;
}
public ICloudBlob Blob
{
get;
private set;
}
public CloudBlobContainer Container
{
get;
private set;
}
private CloudBlobUtil()
{ }
/// <summary>
/// init cloud blob util
/// </summary>
/// <param name="account">storage account</param>
public CloudBlobUtil(CloudStorageAccount account)
{
this.account = account;
client = account.CreateCloudBlobClient();
random = new Random();
}
/// <summary>
/// Create a random container with a random blob
/// </summary>
public void SetupTestContainerAndBlob()
{
ContainerName = Utility.GenNameString("container");
BlobName = Utility.GenNameString("blob");
CloudBlobContainer container = CreateContainer(ContainerName);
Blob = CreateRandomBlob(container, BlobName);
Container = container;
}
/// <summary>
/// clean test container and blob
/// </summary>
public void CleanupTestContainerAndBlob()
{
if (String.IsNullOrEmpty(ContainerName))
{
return;
}
RemoveContainer(ContainerName);
ContainerName = string.Empty;
BlobName = string.Empty;
Blob = null;
Container = null;
}
/// <summary>
/// create a container with random properties and metadata
/// </summary>
/// <param name="containerName">container name</param>
/// <returns>the created container object with properties and metadata</returns>
public CloudBlobContainer CreateContainer(string containerName = "")
{
if (String.IsNullOrEmpty(containerName))
{
containerName = Utility.GenNameString("container");
}
CloudBlobContainer container = client.GetContainerReference(containerName);
container.CreateIfNotExists();
//there is no properties to set
container.FetchAttributes();
int minMetaCount = 1;
int maxMetaCount = 5;
int minMetaValueLength = 10;
int maxMetaValueLength = 20;
int count = random.Next(minMetaCount, maxMetaCount);
for (int i = 0; i < count; i++)
{
string metaKey = Utility.GenNameString("metatest");
int valueLength = random.Next(minMetaValueLength, maxMetaValueLength);
string metaValue = Utility.GenNameString("metavalue-", valueLength);
container.Metadata.Add(metaKey, metaValue);
}
container.SetMetadata();
Test.Info(string.Format("create container '{0}'", containerName));
return container;
}
public CloudBlobContainer CreateContainer(string containerName, BlobContainerPublicAccessType permission)
{
CloudBlobContainer container = CreateContainer(containerName);
BlobContainerPermissions containerPermission = new BlobContainerPermissions();
containerPermission.PublicAccess = permission;
container.SetPermissions(containerPermission);
return container;
}
/// <summary>
/// create mutiple containers
/// </summary>
/// <param name="containerNames">container names list</param>
/// <returns>a list of container object</returns>
public List<CloudBlobContainer> CreateContainer(List<string> containerNames)
{
List<CloudBlobContainer> containers = new List<CloudBlobContainer>();
foreach (string name in containerNames)
{
containers.Add(CreateContainer(name));
}
containers = containers.OrderBy(container => container.Name).ToList();
return containers;
}
/// <summary>
/// remove specified container
/// </summary>
/// <param name="Container">Cloud blob container object</param>
public void RemoveContainer(CloudBlobContainer Container)
{
RemoveContainer(Container.Name);
}
/// <summary>
/// remove specified container
/// </summary>
/// <param name="containerName">container name</param>
public void RemoveContainer(string containerName)
{
CloudBlobContainer container = client.GetContainerReference(containerName);
container.DeleteIfExists();
Test.Info(string.Format("remove container '{0}'", containerName));
}
/// <summary>
/// remove a list containers
/// </summary>
/// <param name="containerNames">container names</param>
public void RemoveContainer(List<string> containerNames)
{
foreach (string name in containerNames)
{
try
{
RemoveContainer(name);
}
catch (Exception e)
{
Test.Warn(string.Format("Can't remove container {0}. Exception: {1}", name, e.Message));
}
}
}
/// <summary>
/// create a new page blob with random properties and metadata
/// </summary>
/// <param name="container">CloudBlobContainer object</param>
/// <param name="blobName">blob name</param>
/// <returns>ICloudBlob object</returns>
public ICloudBlob CreatePageBlob(CloudBlobContainer container, string blobName)
{
CloudPageBlob pageBlob = container.GetPageBlobReference(blobName);
int size = random.Next(1, 10) * PageBlobUnitSize;
pageBlob.Create(size);
byte[] buffer = new byte[size];
string md5sum = Convert.ToBase64String(Helper.GetMD5(buffer));
pageBlob.Properties.ContentMD5 = md5sum;
GenerateBlobPropertiesAndMetaData(pageBlob);
Test.Info(string.Format("create page blob '{0}' in container '{1}'", blobName, container.Name));
return pageBlob;
}
/// <summary>
/// create a block blob with random properties and metadata
/// </summary>
/// <param name="container">CloudBlobContainer object</param>
/// <param name="blobName">Block blob name</param>
/// <returns>ICloudBlob object</returns>
public ICloudBlob CreateBlockBlob(CloudBlobContainer container, string blobName)
{
CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);
int maxBlobSize = 1024 * 1024;
string md5sum = string.Empty;
int blobSize = random.Next(maxBlobSize);
byte[] buffer = new byte[blobSize];
using (MemoryStream ms = new MemoryStream(buffer))
{
random.NextBytes(buffer);
//ms.Read(buffer, 0, buffer.Length);
blockBlob.UploadFromStream(ms);
md5sum = Convert.ToBase64String(Helper.GetMD5(buffer));
}
blockBlob.Properties.ContentMD5 = md5sum;
GenerateBlobPropertiesAndMetaData(blockBlob);
Test.Info(string.Format("create block blob '{0}' in container '{1}'", blobName, container.Name));
return blockBlob;
}
/// <summary>
/// generate random blob properties and metadata
/// </summary>
/// <param name="blob">ICloudBlob object</param>
private void GenerateBlobPropertiesAndMetaData(ICloudBlob blob)
{
blob.Properties.ContentEncoding = Utility.GenNameString("encoding");
blob.Properties.ContentLanguage = Utility.GenNameString("lang");
int minMetaCount = 1;
int maxMetaCount = 5;
int minMetaValueLength = 10;
int maxMetaValueLength = 20;
int count = random.Next(minMetaCount, maxMetaCount);
for (int i = 0; i < count; i++)
{
string metaKey = Utility.GenNameString("metatest");
int valueLength = random.Next(minMetaValueLength, maxMetaValueLength);
string metaValue = Utility.GenNameString("metavalue-", valueLength);
blob.Metadata.Add(metaKey, metaValue);
}
blob.SetProperties();
blob.SetMetadata();
blob.FetchAttributes();
}
/// <summary>
/// Create a blob with specified blob type
/// </summary>
/// <param name="container">CloudBlobContainer object</param>
/// <param name="blobName">Blob name</param>
/// <param name="type">Blob type</param>
/// <returns>ICloudBlob object</returns>
public ICloudBlob CreateBlob(CloudBlobContainer container, string blobName, StorageBlob.BlobType type)
{
if (type == StorageBlob.BlobType.BlockBlob)
{
return CreateBlockBlob(container, blobName);
}
else
{
return CreatePageBlob(container, blobName);
}
}
/// <summary>
/// create a list of blobs with random properties/metadata/blob type
/// </summary>
/// <param name="container">CloudBlobContainer object</param>
/// <param name="blobName">a list of blob names</param>
/// <returns>a list of cloud page blobs</returns>
public List<ICloudBlob> CreateRandomBlob(CloudBlobContainer container, List<string> blobNames)
{
List<ICloudBlob> blobs = new List<ICloudBlob>();
foreach (string blobName in blobNames)
{
blobs.Add(CreateRandomBlob(container, blobName));
}
blobs = blobs.OrderBy(blob => blob.Name).ToList();
return blobs;
}
public List<ICloudBlob> CreateRandomBlob(CloudBlobContainer container)
{
int count = random.Next(1, 5);
List<string> blobNames = new List<string>();
for (int i = 0; i < count; i++)
{
blobNames.Add(Utility.GenNameString("blob"));
}
return CreateRandomBlob(container, blobNames);
}
/// <summary>
/// Create a list of blobs with random properties/metadata/blob type
/// </summary>
/// <param name="container">CloudBlobContainer object</param>
/// <param name="blobName">Blob name</param>
/// <returns>ICloudBlob object</returns>
public ICloudBlob CreateRandomBlob(CloudBlobContainer container, string blobName)
{
int switchKey = 0;
switchKey = random.Next(0, 2);
if (switchKey == 0)
{
return CreatePageBlob(container, blobName);
}
else
{
return CreateBlockBlob(container, blobName);
}
}
/// <summary>
/// convert blob name into valid file name
/// </summary>
/// <param name="blobName">blob name</param>
/// <returns>valid file name</returns>
public string ConvertBlobNameToFileName(string blobName, string dir, DateTimeOffset? snapshotTime = null)
{
string fileName = blobName;
//replace dirctionary
Dictionary<string, string> replaceRules = new Dictionary<string, string>()
{
{"/", "\\"}
};
foreach (KeyValuePair<string, string> rule in replaceRules)
{
fileName = fileName.Replace(rule.Key, rule.Value);
}
if (snapshotTime != null)
{
int index = fileName.LastIndexOf('.');
string prefix = string.Empty;
string postfix = string.Empty;
string timeStamp = string.Format("{0:u}", snapshotTime.Value);
timeStamp = timeStamp.Replace(":", string.Empty).TrimEnd(new char[] { 'Z' });
if (index == -1)
{
prefix = fileName;
postfix = string.Empty;
}
else
{
prefix = fileName.Substring(0, index);
postfix = fileName.Substring(index);
}
fileName = string.Format("{0} ({1}){2}", prefix, timeStamp, postfix);
}
return Path.Combine(dir, fileName);
}
public string ConvertFileNameToBlobName(string fileName)
{
return fileName.Replace('\\', '/');
}
/// <summary>
/// list all the existing containers
/// </summary>
/// <returns>a list of cloudblobcontainer object</returns>
public List<CloudBlobContainer> GetExistingContainers()
{
ContainerListingDetails details = ContainerListingDetails.All;
return client.ListContainers(string.Empty, details).ToList();
}
/// <summary>
/// get the number of existing container
/// </summary>
/// <returns></returns>
public int GetExistingContainerCount()
{
return GetExistingContainers().Count;
}
/// <summary>
/// Create a snapshot for the specified ICloudBlob object
/// </summary>
/// <param name="blob">ICloudBlob object</param>
public ICloudBlob SnapShot(ICloudBlob blob)
{
ICloudBlob snapshot = default(ICloudBlob);
switch (blob.BlobType)
{
case StorageBlob.BlobType.BlockBlob:
snapshot = ((CloudBlockBlob)blob).CreateSnapshot();
break;
case StorageBlob.BlobType.PageBlob:
snapshot = ((CloudPageBlob)blob).CreateSnapshot();
break;
default:
throw new ArgumentException(string.Format("Unsupport blob type {0} when create snapshot", blob.BlobType));
}
Test.Info(string.Format("Create snapshot for '{0}' at {1}", blob.Name, snapshot.SnapshotTime));
return snapshot;
}
public static void PackContainerCompareData(CloudBlobContainer container, Dictionary<string, object> dic)
{
BlobContainerPermissions permissions = container.GetPermissions();
dic["PublicAccess"] = permissions.PublicAccess;
dic["Permission"] = permissions;
dic["LastModified"] = container.Properties.LastModified;
}
public static void PackBlobCompareData(ICloudBlob blob, Dictionary<string, object> dic)
{
dic["Length"] = blob.Properties.Length;
dic["ContentType"] = blob.Properties.ContentType;
dic["LastModified"] = blob.Properties.LastModified;
dic["SnapshotTime"] = blob.SnapshotTime;
}
public static string ConvertCopySourceUri(string uri)
{
if (HttpsCopyHosts == null)
{
HttpsCopyHosts = new List<string>();
string httpsHosts = Test.Data.Get("HttpsCopyHosts");
string[] hosts = httpsHosts.Split();
foreach (string host in hosts)
{
if (!String.IsNullOrWhiteSpace(host))
{
HttpsCopyHosts.Add(host);
}
}
}
//Azure always use https to copy from these hosts such windows.net
bool useHttpsCopy = HttpsCopyHosts.Any(host => uri.IndexOf(host) != -1);
if (useHttpsCopy)
{
return uri.Replace("http://", "https://");
}
else
{
return uri;
}
}
public static bool WaitForCopyOperationComplete(ICloudBlob destBlob, int maxRetry = 100)
{
int retryCount = 0;
int sleepInterval = 1000; //ms
if (destBlob == null)
{
return false;
}
do
{
if (retryCount > 0)
{
Test.Info(String.Format("{0}th check current copy state and it's {1}. Wait for copy completion", retryCount, destBlob.CopyState.Status));
}
Thread.Sleep(sleepInterval);
destBlob.FetchAttributes();
retryCount++;
}
while (destBlob.CopyState.Status == CopyStatus.Pending && retryCount < maxRetry);
Test.Info(String.Format("Final Copy status is {0}", destBlob.CopyState.Status));
return destBlob.CopyState.Status != CopyStatus.Pending;
}
}
}
| |
//
// 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.Linq;
using System.Text;
using Encog.Util;
using System.Reflection;
using Encog.Neural.Networks;
using Encog.Neural.Networks.Layers;
using Encog.Neural.Networks.Training.Propagation.SCG;
using Encog.Neural.NeuralData;
using Encog.Neural.Data.Basic;
using Encog.Util.Simple;
using Encog.Neural.Data;
using System.IO;
using Encog.Neural.Networks.Pattern;
using Encog.Neural.Networks.Training;
using Encog.Neural.Networks.Training.Propagation.Resilient;
using Encog.Neural.Networks.Training.Propagation.Back;
using Encog.Neural.Networks.Training.LMA;
using Encog.Neural.Networks.Training.Propagation.Manhattan;
using Encog.Neural.Networks.Training.SVD;
using Encog;
using ConsoleExamples.Examples;
namespace Encog.Examples.Radial
{
public class MultiRadial : IExample
{
/// <summary>
/// Input for the XOR function.
/// </summary>
public static double[][] INPUT;
public static double[][] IDEAL;
public static ExampleInfo Info
{
get
{
ExampleInfo info = new ExampleInfo(
typeof(MultiRadial),
"radial-multi",
"A RBF network example.",
"Use a RBF network to learn the XOR operator.");
return info;
}
}
public void Execute(IExampleInterface app)
{
//Specify the number of dimensions and the number of neurons per dimension
int dimensions = 2;
int numNeuronsPerDimension = 7;
//Set the standard RBF neuron width.
//Literature seems to suggest this is a good default value.
double volumeNeuronWidth = 2.0 / numNeuronsPerDimension;
//RBF can struggle when it comes to flats at the edge of the sample space.
//We have added the ability to include wider neurons on the sample space boundary which greatly
//improves fitting to flats
bool includeEdgeRBFs = true;
#region Setup
//General setup is the same as before
RadialBasisPattern pattern = new RadialBasisPattern();
pattern.InputNeurons = dimensions;
pattern.OutputNeurons = 1;
//Total number of neurons required.
//Total number of Edges is calculated possibly for future use but not used any further here
int numNeurons = (int)Math.Pow(numNeuronsPerDimension, dimensions);
int numEdges = (int)(dimensions * Math.Pow(2, dimensions - 1));
pattern.AddHiddenLayer(numNeurons);
BasicNetwork network = pattern.Generate();
RadialBasisFunctionLayer rbfLayer = (RadialBasisFunctionLayer)network.GetLayer(RadialBasisPattern.RBF_LAYER);
network.Reset();
//Position the multidimensional RBF neurons, with equal spacing, within the provided sample space from 0 to 1.
rbfLayer.SetRBFCentersAndWidthsEqualSpacing(0, 1, RBFEnum.Gaussian, dimensions, volumeNeuronWidth, includeEdgeRBFs);
#endregion
//Create some training data that can not easily be represented by gaussians
//There are other training examples for both 1D and 2D
//Degenerate training data only provides outputs as 1 or 0 (averaging over all outputs for a given set of inputs would produce something approaching the smooth training data).
//Smooth training data provides true values for the provided input dimensions.
Create2DSmoothTainingDataGit();
//Create the training set and train.
INeuralDataSet trainingSet = new BasicNeuralDataSet(INPUT, IDEAL);
ITrain train = new SVDTraining(network, trainingSet);
//SVD is a single step solve
int epoch = 1;
do
{
train.Iteration();
Console.WriteLine("Epoch #" + epoch + " Error:" + train.Error);
epoch++;
} while ((epoch < 1) && (train.Error > 0.001));
// test the neural network
Console.WriteLine("Neural Network Results:");
//Create a testing array which may be to a higher resoltion than the original training data
Set2DTestingArrays(100);
trainingSet = new BasicNeuralDataSet(INPUT, IDEAL);
//Write out the results data
using (var sw = new System.IO.StreamWriter("results.csv", false))
{
foreach (INeuralDataPair pair in trainingSet)
{
INeuralData output = network.Compute(pair.Input);
//1D//sw.WriteLine(InverseScale(pair.Input[0]) + ", " + Chop(InverseScale(output[0])));// + ", " + pair.Ideal[0]);
sw.WriteLine(InverseScale(pair.Input[0]) + ", " + InverseScale(pair.Input[1]) + ", " + Chop(InverseScale(output[0])));// + ", " + pair.Ideal[0]);// + ",ideal=" + pair.Ideal[0]);
//3D//sw.WriteLine(InverseScale(pair.Input[0]) + ", " + InverseScale(pair.Input[1]) + ", " + InverseScale(pair.Input[2]) + ", " + Chop(InverseScale(output[0])));// + ", " + pair.Ideal[0]);// + ",ideal=" + pair.Ideal[0]);
//Console.WriteLine(pair.Input[0] + ", actual=" + output[0] + ",ideal=" + pair.Ideal[0]);
}
}
Console.WriteLine("\nFit output saved to results.csv");
Console.WriteLine("\nComplete - Please press the 'any' key to close.");
Console.ReadKey();
}
static double Scale(double x)
{
return (x * 0.7) + 0.15;
}
static double InverseScale(double x)
{
return (x - 0.15) / 0.7;
}
static double Chop(double x)
{
if (x > 0.99)
return 0.99;
else if (x < 0)
return 0;
else
return x;
}
private static void SaveOutNeuronCentersAndWeights(double[][] centers, double[][] widths)
{
using (var sw = new System.IO.StreamWriter("neuronCentersWeights.csv", false))
{
for (int i = 0; i < centers.Length; i++)
{
foreach (double value in centers[i])
sw.Write(value + ",");
foreach (double value in widths[i])
sw.Write(value + ",");
sw.WriteLine();
}
}
}
private static double[][] LoadMatrix(string fileName)
{
string[] allLines = File.ReadAllLines(fileName);
double[][] matrix = new double[allLines.Length][];
for (int i = 0; i < allLines.Length; i++)
{
string[] values = allLines[i].Split(',');
matrix[i] = new double[values.Length];
for (int j = 0; j < values.Length; j++)
{
if (values[j] != "")
matrix[i][j] = Convert.ToDouble(values[j]);
else
matrix[i][j] = Double.NaN;
}
}
return matrix;
}
private static void SaveMatrix(double[][] surface, string fileName)
{
using (var sw = new System.IO.StreamWriter(fileName, false))
{
for (int i = 0; i < surface.Length; i++)
{
for (int j = 0; j < surface[i].Length; j++)
{
if (double.IsNaN(surface[i][j]))
sw.Write(",");
else
sw.Write(surface[i][j] + ",");
}
sw.WriteLine();
}
}
}
private static double[][] ConvertColumnsTo2DSurface(double[][] cols, int valueCol)
{
//if (cols[0].Length != 3)
// throw new Exception("Incorrect number of cols detected.");
double sideLength = Math.Sqrt(cols.Length);
double[][] surface = new double[(int)sideLength + 1][];
for (int i = 0; i < surface.Length; i++)
{
surface[i] = new double[surface.Length];
}
for (int i = 0; i < cols.Length; i++)
{
//[0] is x
//[1] is y
//Boundary bottom
//int rowIndex = (int)Math.Round(((cols[i][0]) * (sideLength-1)), 6);
//int columnIndex = (int)Math.Round(((cols[i][1]) * (sideLength-1)), 6);
//Boundary middle
int rowIndex = (int)Math.Round(((cols[i][0] - 0.05) * (sideLength)), 6);
int columnIndex = (int)Math.Round(((cols[i][1] - 0.05) * (sideLength)), 6);
surface[0][rowIndex + 1] = cols[i][0];
surface[columnIndex + 1][0] = cols[i][1];
surface[columnIndex + 1][rowIndex + 1] = cols[i][valueCol];
}
//fix the 0,0 value
surface[0][0] = double.NaN;
return surface;
}
private static double[][] Convert2DSurfaceToColumns(double[][] surface)
{
int totalRows = (surface.Length - 1) * (surface.Length - 1);
double[][] cols = new double[totalRows][];
for (int i = 1; i < surface.Length; i++)
{
for (int j = 1; j < surface[i].Length; j++)
{
double cellWidth = (1.0 / (2.0 * (double)(surface.Length - 1)));
cols[(i - 1) * (surface.Length - 1) + (j - 1)] = new double[3];
//For midpoints
cols[(i - 1) * (surface.Length - 1) + (j - 1)][0] = ((double)(i - 1) / (double)(surface.Length - 1)) + cellWidth;
cols[(i - 1) * (surface.Length - 1) + (j - 1)][1] = ((double)(j - 1) / (double)(surface.Length - 1)) + cellWidth;
//For actual value
//cols[(i - 1) * (surface.Length - 1) + (j - 1)][0] = ((double)(i - 1) / (double)(surface.Length - 1));
//cols[(i - 1) * (surface.Length - 1) + (j - 1)][1] = ((double)(j - 1) / (double)(surface.Length - 1));
cols[(i - 1) * (surface.Length - 1) + (j - 1)][2] = surface[j][i];
}
}
return cols;
}
#region LoadRealData
private static void LoadReal1DTrainingData(string fileName)
{
string[] allLines = File.ReadAllLines(fileName);
INPUT = new double[allLines.Length][];
IDEAL = new double[allLines.Length][];
for (int i = 0; i < allLines.Length; i++)
{
INPUT[i] = new double[1];
IDEAL[i] = new double[1];
string[] values = allLines[i].Split(',');
INPUT[i][0] = Scale((Convert.ToDouble(values[0]) - 0.05) * (1.0 / 0.9));
IDEAL[i][0] = Scale(Convert.ToDouble(values[1]));
}
}
private static void LoadReal2DTrainingData(string fileName)
{
string[] allLines = File.ReadAllLines(fileName);
INPUT = new double[allLines.Length][];
IDEAL = new double[allLines.Length][];
for (int i = 0; i < allLines.Length; i++)
{
INPUT[i] = new double[2];
IDEAL[i] = new double[1];
string[] values = allLines[i].Split(',');
INPUT[i][0] = Scale((Convert.ToDouble(values[0]) - 0.05) * (1.0 / 0.9));
INPUT[i][1] = Scale((Convert.ToDouble(values[1]) - 0.05) * (1.0 / 0.9));
IDEAL[i][0] = Scale(Convert.ToDouble(values[2]));
}
}
private static void LoadReal3DTrainingData(string fileName)
{
string[] allLines = File.ReadAllLines(fileName);
INPUT = new double[allLines.Length][];
IDEAL = new double[allLines.Length][];
for (int i = 0; i < allLines.Length; i++)
{
INPUT[i] = new double[3];
IDEAL[i] = new double[1];
string[] values = allLines[i].Split(',');
INPUT[i][0] = Scale(Convert.ToDouble(values[0]));
INPUT[i][1] = Scale(Convert.ToDouble(values[1]));
INPUT[i][2] = Scale(Convert.ToDouble(values[2]));
IDEAL[i][0] = Scale(Convert.ToDouble(values[3]));
}
}
#endregion
#region CreateTestingInputs
private static void Set1DTestingArrays(int sideLength)
{
int iLimit = sideLength;
INPUT = new double[(iLimit + 1)][];
IDEAL = new double[(iLimit + 1)][];
for (int i = 0; i <= iLimit; i++)
{
INPUT[i] = new double[1];
IDEAL[i] = new double[1];
double x = (double)i / (double)iLimit;
INPUT[i][0] = Scale(((double)i / ((double)iLimit)));
IDEAL[i][0] = 0;
}
}
private static void Set2DTestingArrays(int sideLength)
{
int iLimit = sideLength;
int kLimit = sideLength;
INPUT = new double[(iLimit + 1) * (kLimit + 1)][];
IDEAL = new double[(iLimit + 1) * (kLimit + 1)][];
for (int i = 0; i <= iLimit; i++)
{
for (int k = 0; k <= kLimit; k++)
{
INPUT[i * (kLimit + 1) + k] = new double[2];
IDEAL[i * (kLimit + 1) + k] = new double[1];
double x = (double)i / (double)iLimit;
double y = (double)k / (double)kLimit;
INPUT[i * (kLimit + 1) + k][0] = Scale(((double)i / ((double)iLimit)));
INPUT[i * (kLimit + 1) + k][1] = Scale(((double)k / ((double)kLimit)));
IDEAL[i * (kLimit + 1) + k][0] = 0;
}
}
}
private static void Set3DTestingArrays(int sideLength)
{
int iLimit = sideLength;
int kLimit = sideLength;
int jLimit = sideLength;
INPUT = new double[(iLimit + 1) * (kLimit + 1) * (jLimit + 1)][];
IDEAL = new double[(iLimit + 1) * (kLimit + 1) * (jLimit + 1)][];
for (int i = 0; i <= iLimit; i++)
{
for (int k = 0; k <= kLimit; k++)
{
for (int j = 0; j <= jLimit; j++)
{
int index = (i * (kLimit + 1) * (jLimit + 1)) + (j * (kLimit + 1)) + k;
INPUT[index] = new double[3];
IDEAL[index] = new double[1];
//double x = (double)i / (double)iLimit;
//double y = (double)k / (double)kLimit;
//double z = (double)j / (double)jLimit;
INPUT[index][0] = Scale(((double)i / ((double)iLimit)));
INPUT[index][1] = Scale(((double)k / ((double)kLimit)));
INPUT[index][2] = Scale(((double)j / ((double)jLimit)));
IDEAL[index][0] = 0;
}
}
}
}
#endregion
#region CreateTrainingData
static void Create2DDegenerateTainingDataHill()
{
Random r = new Random();
int iLimit = 30;
int kLimit = 30;
int jLimit = 1;
INPUT = new double[jLimit * iLimit * kLimit][];
IDEAL = new double[jLimit * iLimit * kLimit][];
for (int i = 0; i < iLimit; i++)
{
for (int k = 0; k < kLimit; k++)
{
for (int j = 0; j < jLimit; j++)
{
INPUT[i * jLimit * kLimit + k * jLimit + j] = new double[2];
IDEAL[i * jLimit * kLimit + k * jLimit + j] = new double[1];
double x = (double)i / (double)iLimit;
double y = (double)k / (double)kLimit;
INPUT[i * jLimit * kLimit + k * jLimit + j][0] = ((double)i / ((double)iLimit));
INPUT[i * jLimit * kLimit + k * jLimit + j][1] = ((double)k / ((double)iLimit));
IDEAL[i * jLimit * kLimit + k * jLimit + j][0] = (r.NextDouble() < (Math.Exp(-((x - 0.6) * (x - 0.6) + (y - 0.5) * (y - 0.5)) * 3) - 0.1)) ? 1 : 0;
}
}
}
}
static void Create2DSmoothTainingDataHill()
{
Random r = new Random();
int iLimit = 100;
int kLimit = 100;
int jLimit = 10000;
INPUT = new double[(iLimit + 1) * (kLimit + 1)][];
IDEAL = new double[(iLimit + 1) * (kLimit + 1)][];
for (int i = 0; i <= iLimit; i++)
{
for (int k = 0; k <= kLimit; k++)
{
INPUT[i * (kLimit + 1) + k] = new double[2];
IDEAL[i * (kLimit + 1) + k] = new double[1];
double average = 0;
double x = (double)i / (double)iLimit;
double y = (double)k / (double)kLimit;
double expression = (Math.Exp(-((x - 0.5) * (x - 0.5) + (y - 0.6) * (y - 0.6)) * 3) - 0.1);
//if (r.NextDouble() < 0.4) jLimit = 5; else jLimit = 10;
for (int j = 0; j < jLimit; j++)
{
average += (r.NextDouble() < expression) ? 1 : 0;
}
INPUT[i * (kLimit + 1) + k][0] = Scale(((double)i / ((double)iLimit)));
INPUT[i * (kLimit + 1) + k][1] = Scale(((double)k / ((double)kLimit)));
IDEAL[i * (kLimit + 1) + k][0] = Scale((average / (double)jLimit));
}
}
}
static void Create2DSmoothTainingDataGit()
{
Random r = new Random();
int iLimit = 10;
int kLimit = 10;
//int jLimit = 100;
INPUT = new double[(iLimit + 1) * (kLimit + 1)][];
IDEAL = new double[(iLimit + 1) * (kLimit + 1)][];
for (int i = 0; i <= iLimit; i++)
{
for (int k = 0; k <= kLimit; k++)
{
INPUT[i * (kLimit + 1) + k] = new double[2];
IDEAL[i * (kLimit + 1) + k] = new double[1];
double x = (double)i / (double)iLimit;
double y = (double)k / (double)kLimit;
double expression = ((x + 1.0 / 3.0) * (2 + Math.Log10((y / (x + 0.1)) + 0.1))) / 3;
INPUT[i * (kLimit + 1) + k][0] = Scale(((double)i / ((double)iLimit)));
INPUT[i * (kLimit + 1) + k][1] = Scale(((double)k / ((double)kLimit)));
IDEAL[i * (kLimit + 1) + k][0] = Scale(expression);
}
}
}
static void Create2DDegenerateTainingDataGit()
{
Random r = new Random();
int iLimit = 10;
int kLimit = 10;
int jLimit = 10;
INPUT = new double[jLimit * iLimit * kLimit][];
IDEAL = new double[jLimit * iLimit * kLimit][];
for (int i = 0; i < iLimit; i++)
{
for (int k = 0; k < kLimit; k++)
{
double x = (double)i / (double)iLimit;
double y = (double)k / (double)kLimit;
for (int j = 0; j < jLimit; j++)
{
INPUT[i * jLimit * kLimit + k * jLimit + j] = new double[2];
IDEAL[i * jLimit * kLimit + k * jLimit + j] = new double[1];
double expression = ((x + 1.0 / 3.0) * (2 + Math.Log10((y / (x + 0.1)) + 0.1))) / 3; ;
INPUT[i * jLimit * kLimit + k * jLimit + j][0] = ((double)i / ((double)iLimit));
INPUT[i * jLimit * kLimit + k * jLimit + j][1] = ((double)k / ((double)iLimit));
IDEAL[i * jLimit * kLimit + k * jLimit + j][0] = (r.NextDouble() < expression) ? 1 : 0;
}
}
}
}
static void Create1DDegenerateTrainingDataLine()
{
Random r = new Random(14768);
int iLimit = 10;
int jLimit = 100;
INPUT = new double[iLimit * jLimit][];
IDEAL = new double[iLimit * jLimit][];
for (int i = 0; i < iLimit; i++)
{
for (int j = 0; j < jLimit; j++)
{
INPUT[i * jLimit + j] = new double[1];
IDEAL[i * jLimit + j] = new double[1];
double x = (double)i / (double)iLimit;
INPUT[i * jLimit + j][0] = Scale(x);
IDEAL[i * jLimit + j][0] = Scale((r.NextDouble() < x) ? 1 : 0);
}
}
}
static void Create1DSmoothTrainingDataLine()
{
Random r = new Random(14768);
int iLimit = 1000;
int jLimit = 1;
INPUT = new double[iLimit][];
IDEAL = new double[iLimit][];
for (int i = 0; i < iLimit; i++)
{
INPUT[i] = new double[1];
IDEAL[i] = new double[1];
double average = 0;
double x = (double)i / (double)iLimit;
for (int j = 0; j < jLimit; j++)
average += (r.NextDouble() < x) ? 1 : 0;
INPUT[i][0] = Scale(x);
IDEAL[i][0] = Scale((double)average / (double)jLimit);
}
}
static void Create1DSmoothTrainingDataCurveSimple()
{
Random r = new Random(14768);
int iLimit = 20;
int jLimit = 10;
INPUT = new double[iLimit][];
IDEAL = new double[iLimit][];
for (int i = 0; i < iLimit; i++)
{
INPUT[i] = new double[1];
IDEAL[i] = new double[1];
double average = 0;
double x = (double)i / (double)iLimit;
for (int j = 0; j < jLimit; j++)
average += (r.NextDouble() < (-4 * Math.Pow(x, 2) + 4 * x)) ? 1 : 0;
INPUT[i][0] = Scale(x);
IDEAL[i][0] = Scale((double)average / (double)jLimit);
}
}
static void Create1DSmoothTrainingDataCurveAdv()
{
Random r = new Random(14768);
int iLimit = 100;
int jLimit = 100;
INPUT = new double[iLimit][];
IDEAL = new double[iLimit][];
for (int i = 0; i < iLimit; i++)
{
INPUT[i] = new double[1];
IDEAL[i] = new double[1];
double average = 0;
double x = (double)i / (double)iLimit;
//double y = (-7.5 * Math.Pow(x, 4)) + (21.3 * Math.Pow(x, 3)) + (-22.3 * Math.Pow(x, 2)) + (10.4 * x) - 0.8;
double y = ((Math.Exp(2.0 * (x * 4.0 - 1)) - 1.0) / (Math.Exp(2.0 * (x * 4.0 - 1)) + 1.0)) / 2 + 0.5;
for (int j = 0; j < jLimit; j++)
{
average += (r.NextDouble() < y) ? 1 : 0;
}
INPUT[i][0] = Scale(x);
IDEAL[i][0] = Scale((double)average / (double)jLimit);
}
}
#endregion
}
}
| |
#region License
/* Copyright (c) 2005 Leslie Sanford
*
* 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 Contact
/*
* Leslie Sanford
* Email: jabberdabber@hotmail.com
*/
#endregion
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using Sanford.Multimedia;
namespace Sanford.Multimedia.Midi
{
internal struct MidiInParams
{
public readonly IntPtr Param1;
public readonly IntPtr Param2;
public MidiInParams(IntPtr param1, IntPtr param2)
{
Param1 = param1;
Param2 = param2;
}
}
public partial class InputDevice : MidiDevice
{
/// <summary>
/// Gets or sets a value indicating whether the midi input driver callback should be posted on a delegate queue with its own thread.
/// Default is <c>true</c>. If set to <c>false</c> the driver callback directly calls the events for lowest possible latency.
/// </summary>
/// <value>
/// <c>true</c> if the midi input driver callback should be posted on a delegate queue with its own thread; otherwise, <c>false</c>.
/// </value>
public bool PostDriverCallbackToDelegateQueue
{
get;
set;
}
int FLastParam2;
private void HandleMessage(IntPtr hnd, int msg, IntPtr instance, IntPtr param1, IntPtr param2)
{
var param = new MidiInParams(param1, param2);
if (msg == MIM_OPEN)
{
}
else if (msg == MIM_CLOSE)
{
}
else if (msg == MIM_DATA)
{
if (PostDriverCallbackToDelegateQueue)
delegateQueue.Post(HandleShortMessage, param);
else
HandleShortMessage(param);
}
else if (msg == MIM_MOREDATA)
{
if (PostDriverCallbackToDelegateQueue)
delegateQueue.Post(HandleShortMessage, param);
else
HandleShortMessage(param);
}
else if (msg == MIM_LONGDATA)
{
if (PostDriverCallbackToDelegateQueue)
delegateQueue.Post(HandleSysExMessage, param);
else
HandleSysExMessage(param);
}
else if (msg == MIM_ERROR)
{
if (PostDriverCallbackToDelegateQueue)
delegateQueue.Post(HandleInvalidShortMessage, param);
else
HandleInvalidShortMessage(param);
}
else if (msg == MIM_LONGERROR)
{
if (PostDriverCallbackToDelegateQueue)
delegateQueue.Post(HandleInvalidSysExMessage, param);
else
HandleInvalidSysExMessage(param);
}
}
private void HandleShortMessage(object state)
{
var param = (MidiInParams)state;
int message = param.Param1.ToInt32();
int timestamp = param.Param2.ToInt32();
//first send RawMessage
OnShortMessage(new ShortMessageEventArgs(message, timestamp));
int status = ShortMessage.UnpackStatus(message);
if (status >= (int)ChannelCommand.NoteOff &&
status <= (int)ChannelCommand.PitchWheel +
ChannelMessage.MidiChannelMaxValue)
{
cmBuilder.Message = message;
cmBuilder.Build();
cmBuilder.Result.Timestamp = timestamp;
OnMessageReceived(cmBuilder.Result);
OnChannelMessageReceived(new ChannelMessageEventArgs(cmBuilder.Result));
}
else if (status == (int)SysCommonType.MidiTimeCode ||
status == (int)SysCommonType.SongPositionPointer ||
status == (int)SysCommonType.SongSelect ||
status == (int)SysCommonType.TuneRequest)
{
scBuilder.Message = message;
scBuilder.Build();
scBuilder.Result.Timestamp = timestamp;
OnMessageReceived(scBuilder.Result);
OnSysCommonMessageReceived(new SysCommonMessageEventArgs(scBuilder.Result));
}
else
{
SysRealtimeMessageEventArgs e = null;
switch ((SysRealtimeType)status)
{
case SysRealtimeType.ActiveSense:
e = SysRealtimeMessageEventArgs.ActiveSense;
break;
case SysRealtimeType.Clock:
e = SysRealtimeMessageEventArgs.Clock;
break;
case SysRealtimeType.Continue:
e = SysRealtimeMessageEventArgs.Continue;
break;
case SysRealtimeType.Reset:
e = SysRealtimeMessageEventArgs.Reset;
break;
case SysRealtimeType.Start:
e = SysRealtimeMessageEventArgs.Start;
break;
case SysRealtimeType.Stop:
e = SysRealtimeMessageEventArgs.Stop;
break;
case SysRealtimeType.Tick:
e = SysRealtimeMessageEventArgs.Tick;
break;
}
e.Message.Timestamp = timestamp;
OnMessageReceived(e.Message);
OnSysRealtimeMessageReceived(e);
}
}
private void HandleSysExMessage(object state)
{
lock (lockObject)
{
var param = (MidiInParams)state;
IntPtr headerPtr = param.Param1;
MidiHeader header = (MidiHeader)Marshal.PtrToStructure(headerPtr, typeof(MidiHeader));
if (!resetting)
{
for (int i = 0; i < header.bytesRecorded; i++)
{
sysExData.Add(Marshal.ReadByte(header.data, i));
}
if (sysExData.Count > 1 && sysExData[0] == 0xF0 && sysExData[sysExData.Count - 1] == 0xF7)
{
SysExMessage message = new SysExMessage(sysExData.ToArray());
message.Timestamp = param.Param2.ToInt32();
sysExData.Clear();
OnMessageReceived(message);
OnSysExMessageReceived(new SysExMessageEventArgs(message));
}
int result = AddSysExBuffer();
if (result != DeviceException.MMSYSERR_NOERROR)
{
Exception ex = new InputDeviceException(result);
OnError(new ErrorEventArgs(ex));
}
}
ReleaseBuffer(headerPtr);
}
}
private void HandleInvalidShortMessage(object state)
{
var param = (MidiInParams)state;
OnInvalidShortMessageReceived(new InvalidShortMessageEventArgs(param.Param1.ToInt32()));
}
private void HandleInvalidSysExMessage(object state)
{
lock (lockObject)
{
var param = (MidiInParams)state;
IntPtr headerPtr = param.Param1;
MidiHeader header = (MidiHeader)Marshal.PtrToStructure(headerPtr, typeof(MidiHeader));
if (!resetting)
{
byte[] data = new byte[header.bytesRecorded];
Marshal.Copy(header.data, data, 0, data.Length);
OnInvalidSysExMessageReceived(new InvalidSysExMessageEventArgs(data));
int result = AddSysExBuffer();
if (result != DeviceException.MMSYSERR_NOERROR)
{
Exception ex = new InputDeviceException(result);
OnError(new ErrorEventArgs(ex));
}
}
ReleaseBuffer(headerPtr);
}
}
private void ReleaseBuffer(IntPtr headerPtr)
{
int result = midiInUnprepareHeader(Handle, headerPtr, SizeOfMidiHeader);
if (result != DeviceException.MMSYSERR_NOERROR)
{
Exception ex = new InputDeviceException(result);
OnError(new ErrorEventArgs(ex));
}
headerBuilder.Destroy(headerPtr);
bufferCount--;
Debug.Assert(bufferCount >= 0);
Monitor.Pulse(lockObject);
}
public int AddSysExBuffer()
{
int result;
// Initialize the MidiHeader builder.
headerBuilder.BufferLength = sysExBufferSize;
headerBuilder.Build();
// Get the pointer to the built MidiHeader.
IntPtr headerPtr = headerBuilder.Result;
// Prepare the header to be used.
result = midiInPrepareHeader(Handle, headerPtr, SizeOfMidiHeader);
// If the header was perpared successfully.
if (result == DeviceException.MMSYSERR_NOERROR)
{
bufferCount++;
// Add the buffer to the InputDevice.
result = midiInAddBuffer(Handle, headerPtr, SizeOfMidiHeader);
// If the buffer could not be added.
if (result != MidiDeviceException.MMSYSERR_NOERROR)
{
// Unprepare header - there's a chance that this will fail
// for whatever reason, but there's not a lot that can be
// done at this point.
midiInUnprepareHeader(Handle, headerPtr, SizeOfMidiHeader);
bufferCount--;
// Destroy header.
headerBuilder.Destroy();
}
}
// Else the header could not be prepared.
else
{
// Destroy header.
headerBuilder.Destroy();
}
return result;
}
}
}
| |
// This file has been generated by the GUI designer. Do not modify.
namespace Valle.TpvFinal
{
public partial class HerRapidasArticulos
{
private global::Gtk.VBox vbox1;
private global::Valle.GtkUtilidades.MiLabel lblTitulo;
private global::Gtk.HBox hbox3;
private global::Gtk.VBox vbox5;
private global::Valle.GtkUtilidades.MiLabel lblInfOriginal;
private global::Gtk.HBox hbox4;
private global::Gtk.ScrolledWindow scrollOrg;
private global::Gtk.TreeView lstOriginal;
private global::Valle.GtkUtilidades.ScrollTactil scrollTacticlOrg;
private global::Gtk.VBox vbox7;
private global::Valle.GtkUtilidades.MiLabel lblInfSelcecionados;
private global::Gtk.HBox hbox5;
private global::Gtk.ScrolledWindow scrollSel;
private global::Gtk.TreeView listSeleccionados;
private global::Valle.GtkUtilidades.ScrollTactil scroltactilSel;
private global::Gtk.HButtonBox hbuttonbox2;
private global::Gtk.Button btnAceptar;
private global::Gtk.Button btnCaja;
private global::Gtk.VBox vbox159;
private global::Gtk.Image image23;
private global::Gtk.Label label1;
private global::Gtk.Button btnSalir;
private global::Gtk.HBox pneDisplay;
private global::Valle.GtkUtilidades.MiLabel lblT;
private global::Valle.GtkUtilidades.MiLabel lblDisplay;
protected virtual void Init ()
{
global::Stetic.Gui.Initialize (this);
// Widget Valle.TpvFinal.HerRapidasArticulos
this.WidthRequest = 750;
this.HeightRequest = 550;
this.Name = "Valle.TpvFinal.HerRapidasArticulos";
this.Title = global::Mono.Unix.Catalog.GetString ("HerRapidasArticulos");
this.WindowPosition = ((global::Gtk.WindowPosition)(4));
// Container child Valle.TpvFinal.HerRapidasArticulos.Gtk.Container+ContainerChild
this.vbox1 = new global::Gtk.VBox ();
this.vbox1.Name = "vbox1";
this.vbox1.Spacing = 6;
// Container child vbox1.Gtk.Box+BoxChild
this.lblTitulo = new global::Valle.GtkUtilidades.MiLabel ();
this.lblTitulo.HeightRequest = 25;
this.lblTitulo.Events = ((global::Gdk.EventMask)(256));
this.lblTitulo.Name = "lblTitulo";
this.vbox1.Add (this.lblTitulo);
global::Gtk.Box.BoxChild w1 = ((global::Gtk.Box.BoxChild)(this.vbox1[this.lblTitulo]));
w1.Position = 0;
w1.Expand = false;
// Container child vbox1.Gtk.Box+BoxChild
this.hbox3 = new global::Gtk.HBox ();
this.hbox3.Name = "hbox3";
this.hbox3.Spacing = 6;
this.hbox3.BorderWidth = ((uint)(15));
// Container child hbox3.Gtk.Box+BoxChild
this.vbox5 = new global::Gtk.VBox ();
this.vbox5.Name = "vbox5";
this.vbox5.Spacing = 6;
// Container child vbox5.Gtk.Box+BoxChild
this.lblInfOriginal = new global::Valle.GtkUtilidades.MiLabel ();
this.lblInfOriginal.HeightRequest = 25;
this.lblInfOriginal.Events = ((global::Gdk.EventMask)(256));
this.lblInfOriginal.Name = "lblInfOriginal";
this.vbox5.Add (this.lblInfOriginal);
global::Gtk.Box.BoxChild w2 = ((global::Gtk.Box.BoxChild)(this.vbox5[this.lblInfOriginal]));
w2.Position = 0;
w2.Expand = false;
w2.Fill = false;
// Container child vbox5.Gtk.Box+BoxChild
this.hbox4 = new global::Gtk.HBox ();
this.hbox4.WidthRequest = 350;
this.hbox4.Name = "hbox4";
this.hbox4.Spacing = 6;
// Container child hbox4.Gtk.Box+BoxChild
this.scrollOrg = new global::Gtk.ScrolledWindow ();
this.scrollOrg.Name = "GtkScrolledWindow";
this.scrollOrg.ShadowType = ((global::Gtk.ShadowType)(1));
// Container child GtkScrolledWindow.Gtk.Container+ContainerChild
this.lstOriginal = new global::Gtk.TreeView ();
this.lstOriginal.CanFocus = true;
this.lstOriginal.Name = "lstOriginal";
this.scrollOrg.Add (this.lstOriginal);
this.hbox4.Add (this.scrollOrg);
global::Gtk.Box.BoxChild w4 = ((global::Gtk.Box.BoxChild)(this.hbox4[this.scrollOrg]));
w4.Position = 0;
// Container child hbox4.Gtk.Box+BoxChild
this.scrollTacticlOrg = new global::Valle.GtkUtilidades.ScrollTactil ();
this.scrollTacticlOrg.Events = ((global::Gdk.EventMask)(256));
this.scrollTacticlOrg.Name = "scrooltactil6";
this.hbox4.Add (this.scrollTacticlOrg);
global::Gtk.Box.BoxChild w5 = ((global::Gtk.Box.BoxChild)(this.hbox4[this.scrollTacticlOrg]));
w5.Position = 1;
w5.Expand = false;
w5.Fill = false;
this.vbox5.Add (this.hbox4);
global::Gtk.Box.BoxChild w6 = ((global::Gtk.Box.BoxChild)(this.vbox5[this.hbox4]));
w6.Position = 1;
this.hbox3.Add (this.vbox5);
global::Gtk.Box.BoxChild w7 = ((global::Gtk.Box.BoxChild)(this.hbox3[this.vbox5]));
w7.Position = 0;
// Container child hbox3.Gtk.Box+BoxChild
this.vbox7 = new global::Gtk.VBox ();
this.vbox7.WidthRequest = 350;
this.vbox7.Name = "vbox7";
this.vbox7.Spacing = 6;
// Container child vbox7.Gtk.Box+BoxChild
this.lblInfSelcecionados = new global::Valle.GtkUtilidades.MiLabel ();
this.lblInfSelcecionados.HeightRequest = 25;
this.lblInfSelcecionados.Events = ((global::Gdk.EventMask)(256));
this.lblInfSelcecionados.Name = "lblInfSelcecionados";
this.vbox7.Add (this.lblInfSelcecionados);
global::Gtk.Box.BoxChild w8 = ((global::Gtk.Box.BoxChild)(this.vbox7[this.lblInfSelcecionados]));
w8.Position = 0;
w8.Expand = false;
w8.Fill = false;
// Container child vbox7.Gtk.Box+BoxChild
this.hbox5 = new global::Gtk.HBox ();
this.hbox5.Name = "hbox5";
this.hbox5.Spacing = 6;
// Container child hbox5.Gtk.Box+BoxChild
this.scrollSel = new global::Gtk.ScrolledWindow ();
this.scrollSel.Name = "GtkScrolledWindow1";
this.scrollSel.ShadowType = ((global::Gtk.ShadowType)(1));
// Container child GtkScrolledWindow1.Gtk.Container+ContainerChild
this.listSeleccionados = new global::Gtk.TreeView ();
this.listSeleccionados.CanFocus = true;
this.listSeleccionados.Name = "listSeleccionados";
this.scrollSel.Add (this.listSeleccionados);
this.hbox5.Add (this.scrollSel);
global::Gtk.Box.BoxChild w10 = ((global::Gtk.Box.BoxChild)(this.hbox5[this.scrollSel]));
w10.Position = 0;
// Container child hbox5.Gtk.Box+BoxChild
this.scroltactilSel = new global::Valle.GtkUtilidades.ScrollTactil ();
this.scroltactilSel.Events = ((global::Gdk.EventMask)(256));
this.scroltactilSel.Name = "scrooltactil7";
this.hbox5.Add (this.scroltactilSel);
global::Gtk.Box.BoxChild w11 = ((global::Gtk.Box.BoxChild)(this.hbox5[this.scroltactilSel]));
w11.Position = 1;
w11.Expand = false;
w11.Fill = false;
this.vbox7.Add (this.hbox5);
global::Gtk.Box.BoxChild w12 = ((global::Gtk.Box.BoxChild)(this.vbox7[this.hbox5]));
w12.Position = 1;
// Container child vbox7.Gtk.Box+BoxChild
this.hbuttonbox2 = new global::Gtk.HButtonBox ();
this.hbuttonbox2.Name = "hbuttonbox2";
this.hbuttonbox2.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(4));
// Container child hbuttonbox2.Gtk.ButtonBox+ButtonBoxChild
this.btnAceptar = new global::Gtk.Button ();
this.btnAceptar.WidthRequest = 100;
this.btnAceptar.HeightRequest = 100;
this.btnAceptar.CanFocus = true;
this.btnAceptar.Name = "btnAceptar";
this.btnAceptar.UseUnderline = true;
// Container child btnAceptar.Gtk.Container+ContainerChild
global::Gtk.Alignment w13 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w14 = new global::Gtk.HBox ();
w14.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w15 = new global::Gtk.Image ();
w15.Pixbuf = global::Stetic.IconLoader.LoadIcon (this, "gtk-apply", global::Gtk.IconSize.Dialog);
w14.Add (w15);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w17 = new global::Gtk.Label ();
w14.Add (w17);
w13.Add (w14);
this.btnAceptar.Add (w13);
this.hbuttonbox2.Add (this.btnAceptar);
global::Gtk.ButtonBox.ButtonBoxChild w21 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox2[this.btnAceptar]));
w21.Expand = false;
w21.Fill = false;
// Container child hbuttonbox2.Gtk.ButtonBox+ButtonBoxChild
this.btnCaja = new global::Gtk.Button ();
this.btnCaja.CanFocus = true;
this.btnCaja.Name = "btnCaja";
// Container child btnCaja.Gtk.Container+ContainerChild
this.vbox159 = new global::Gtk.VBox ();
this.vbox159.Name = "vbox159";
this.vbox159.Spacing = 6;
// Container child vbox159.Gtk.Box+BoxChild
this.image23 = new global::Gtk.Image ();
this.image23.Name = "image23";
this.image23.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.TpvFinal.iconos.CASH01B.ICO");
this.vbox159.Add (this.image23);
global::Gtk.Box.BoxChild w22 = ((global::Gtk.Box.BoxChild)(this.vbox159[this.image23]));
w22.Position = 0;
// Container child vbox159.Gtk.Box+BoxChild
this.label1 = new global::Gtk.Label ();
this.label1.Name = "label1";
this.label1.LabelProp = global::Mono.Unix.Catalog.GetString ("<big>Caja</big>");
this.label1.UseMarkup = true;
this.vbox159.Add (this.label1);
global::Gtk.Box.BoxChild w23 = ((global::Gtk.Box.BoxChild)(this.vbox159[this.label1]));
w23.Position = 1;
w23.Expand = false;
w23.Fill = false;
this.btnCaja.Add (this.vbox159);
this.btnCaja.Label = null;
this.hbuttonbox2.Add (this.btnCaja);
global::Gtk.ButtonBox.ButtonBoxChild w25 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox2[this.btnCaja]));
w25.Position = 1;
w25.Expand = false;
w25.Fill = false;
// Container child hbuttonbox2.Gtk.ButtonBox+ButtonBoxChild
this.btnSalir = new global::Gtk.Button ();
this.btnSalir.CanFocus = true;
this.btnSalir.Name = "btnSalir";
this.btnSalir.UseUnderline = true;
// Container child btnSalir.Gtk.Container+ContainerChild
global::Gtk.Alignment w26 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w27 = new global::Gtk.HBox ();
w27.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w28 = new global::Gtk.Image ();
w28.Pixbuf = global::Stetic.IconLoader.LoadIcon (this, "gtk-cancel", global::Gtk.IconSize.Dialog);
w27.Add (w28);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w30 = new global::Gtk.Label ();
w27.Add (w30);
w26.Add (w27);
this.btnSalir.Add (w26);
this.hbuttonbox2.Add (this.btnSalir);
global::Gtk.ButtonBox.ButtonBoxChild w34 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox2[this.btnSalir]));
w34.Position = 2;
w34.Expand = false;
w34.Fill = false;
this.vbox7.Add (this.hbuttonbox2);
global::Gtk.Box.BoxChild w35 = ((global::Gtk.Box.BoxChild)(this.vbox7[this.hbuttonbox2]));
w35.PackType = ((global::Gtk.PackType)(1));
w35.Position = 2;
w35.Expand = false;
w35.Fill = false;
// Container child vbox7.Gtk.Box+BoxChild
this.pneDisplay = new global::Gtk.HBox ();
this.pneDisplay.Name = "pneDisplay";
this.pneDisplay.Spacing = 6;
// Container child pneDisplay.Gtk.Box+BoxChild
this.lblT = new global::Valle.GtkUtilidades.MiLabel ();
this.lblT.WidthRequest = 150;
this.lblT.HeightRequest = 50;
this.lblT.Events = ((global::Gdk.EventMask)(256));
this.lblT.Name = "lblT";
this.pneDisplay.Add (this.lblT);
global::Gtk.Box.BoxChild w36 = ((global::Gtk.Box.BoxChild)(this.pneDisplay[this.lblT]));
w36.Position = 0;
w36.Expand = false;
w36.Fill = false;
// Container child pneDisplay.Gtk.Box+BoxChild
this.lblDisplay = new global::Valle.GtkUtilidades.MiLabel ();
this.lblDisplay.Events = ((global::Gdk.EventMask)(256));
this.lblDisplay.Name = "lblDisplay";
this.pneDisplay.Add (this.lblDisplay);
global::Gtk.Box.BoxChild w37 = ((global::Gtk.Box.BoxChild)(this.pneDisplay[this.lblDisplay]));
w37.Position = 1;
this.vbox7.Add (this.pneDisplay);
global::Gtk.Box.BoxChild w38 = ((global::Gtk.Box.BoxChild)(this.vbox7[this.pneDisplay]));
w38.PackType = ((global::Gtk.PackType)(1));
w38.Position = 3;
w38.Expand = false;
w38.Fill = false;
this.hbox3.Add (this.vbox7);
global::Gtk.Box.BoxChild w39 = ((global::Gtk.Box.BoxChild)(this.hbox3[this.vbox7]));
w39.Position = 1;
this.vbox1.Add (this.hbox3);
global::Gtk.Box.BoxChild w40 = ((global::Gtk.Box.BoxChild)(this.vbox1[this.hbox3]));
w40.Position = 1;
this.Add (this.vbox1);
if ((this.Child != null)) {
this.Child.ShowAll ();
}
this.DefaultWidth = 752;
this.DefaultHeight = 580;
this.ExposeEvent += new global::Gtk.ExposeEventHandler (this.OnExposeEvent);
this.listSeleccionados.CursorChanged += new global::System.EventHandler(this.OnListSeleccionadosRowActivated);
this.lstOriginal.CursorChanged += new global::System.EventHandler(this.listTicketOriginal_SelectedIndexChanged);
this.btnSalir.Clicked += new global::System.EventHandler(this.btnSalir_Click);
this.btnCaja.Clicked += new global::System.EventHandler(this.btnCaja_Click);
this.btnAceptar.Clicked+= new global::System.EventHandler(this.btnAcepar_Click);
}
}
}
| |
namespace ZetaResourceEditor.UI.Helper;
using DevExpress.XtraTreeList.Nodes;
using ExtendedControlsLibrary.Skinning.CustomTreeList;
using System;
using System.Windows.Forms;
using ZetaAsync;
public partial class ZetaResourceEditorTreeListControl :
MyTreeList
{
public ZetaResourceEditorTreeListControl()
{
InitializeComponent();
}
public bool WasDoubleClick { get; set; }
private const int WmLbuttondblclk = 0x203;
protected override void WndProc(ref Message m)
{
// http://groups.google.com/group/microsoft.public.dotnet.framework.windowsforms/msg/d16ac686dc6b42?hl=en&lr=&ie=UTF-8
if (m.Msg == WmLbuttondblclk)
{
WasDoubleClick = true;
}
base.WndProc(ref m);
}
private const string DummyNode = @"8f6daa3-3e1c-4a55-b53c-6ca8e68a282a";
protected override bool RaiseBeforeExpand(
TreeListNode node)
{
CheckExpandDynamicNodes(node);
return base.RaiseBeforeExpand(node);
}
public event EventHandler<ExpandDynamicChildrenEventArgs> ExpandDynamicChildren;
public void CheckExpandDynamicNodes(
TreeListNode node)
{
if (
node.Nodes.Count > 0 &&
node.Nodes[0][0] as string == DummyNode ||
node[0] as string == DummyNode)
{
ExpandDynamicChildren?.Invoke(this, new ExpandDynamicChildrenEventArgs(node));
}
}
public void CheckAddDummyNode(TreeListNode node)
{
if (node.Nodes.Count <= 0)
{
AppendNode(
new object[]
{
DummyNode,
null,
null,
null,
null
},
node);
}
}
public new void ClearSelection()
{
var prevCount = Selection.Count + 1;
while (Selection.Count > 0 && prevCount > Selection.Count)
{
Selection[0].Selected = false;
prevCount = Selection.Count;
}
}
public TreeListNode SelectedNode
{
get => Selection.Count <= 0 ? null : Selection[0];
set
{
ClearSelection();
if (value != null)
{
value.Selected = true;
}
FocusedNode = value;
if (value != null)
{
MakeNodeVisible(value);
}
}
}
/// <summary>
/// Moves the specified node up by one,
/// staying in the same level.
/// Wraps if at the top.
/// </summary>
/// <param name="item">The item.</param>
public void MoveItemUpByOne(
TreeListNode item)
{
BeginUpdate();
try
{
var nodes = item.ParentNode == null ? Nodes : item.ParentNode.Nodes;
var itemIndex = GetNodeIndex(item);
var newItemIndex = itemIndex - 1;
SetNodeIndex(item, newItemIndex < 0 ? nodes.Count : newItemIndex);
}
finally
{
EndUpdate();
}
}
/// <summary>
/// Moves the specified node down by one,
/// staying in the same level.
/// Wraps if at the top.
/// </summary>
/// <param name="item">The item.</param>
public void MoveItemDownByOne(
TreeListNode item)
{
BeginUpdate();
try
{
var nodes = item.ParentNode == null ? Nodes : item.ParentNode.Nodes;
var itemIndex = GetNodeIndex(item);
var newItemIndex = itemIndex + 1;
SetNodeIndex(item, newItemIndex >= nodes.Count ? 0 : newItemIndex);
}
finally
{
EndUpdate();
}
}
public void SortChildrenAlphabetically(
TreeListNode item)
{
BeginUpdate();
try
{
// http://de.wikipedia.org/wiki/Bubblesort.
var n = item.Nodes.Count;
bool changed;
do
{
changed = false;
for (var i = 0; i < n - 1; i++)
{
var iA = item.Nodes[i].GetDisplayText(0);
var iB = item.Nodes[i + 1].GetDisplayText(0);
if (string.Compare(iA, iB, StringComparison.OrdinalIgnoreCase) > 0)
{
var xA = GetNodeIndex(item.Nodes[i]);
var xB = GetNodeIndex(item.Nodes[i + 1]);
SetNodeIndex(item.Nodes[i + 1], xA);
changed = true;
}
}
} while (changed);
//var nodes = item.Nodes.Cast<TreeListNode>().ToList();
//nodes.Sort((x, y) => x.GetDisplayText(0).CompareTo(y.GetDisplayText(0)));
//item.Nodes.Clear();
//nodes.ForEach(item.Nodes.Add);
// --
//var nodes = item.ParentNode == null ? Nodes : item.ParentNode.Nodes;
//var itemIndex = GetNodeIndex(item);
//var newItemIndex = itemIndex + 1;
//SetNodeIndex(item, newItemIndex >= nodes.Count ? 0 : newItemIndex);
}
finally
{
EndUpdate();
}
}
/// <summary>
/// Ensures the items order positions set.
/// </summary>
public void EnsureItemsOrderPositionsSet(
object threadPoolManager,
TreeListNode parentNode,
AsynchronousMode asynchronousMode)
{
var previousOrderPosition = -1;
var nodes = parentNode == null ? Nodes : parentNode.Nodes;
// Take the current item order of the items in the
// list and ensure the order position is
// ascending (not naturally immediate following numbers).
var itemIndex = 0;
while (itemIndex < nodes.Count)
{
var listViewItem = nodes[itemIndex];
var obj = (IOrderPosition)listViewItem.Tag;
var currentOrderPosition = obj.OrderPosition;
// Must adjust.
if (currentOrderPosition <= previousOrderPosition)
{
// Increment.
var newCurrentOrderPosition = previousOrderPosition + 1;
if (obj.OrderPosition != newCurrentOrderPosition)
{
// New order position.
obj.OrderPosition = newCurrentOrderPosition;
// Mark as modified, but do no display update,
// since nothing VISUAL has changed.
obj.StoreOrderPosition(threadPoolManager, null, asynchronousMode, null);
}
// Remember for next turn.
previousOrderPosition = newCurrentOrderPosition;
}
else
{
// Remember for next turn.
previousOrderPosition = currentOrderPosition;
}
itemIndex++;
}
}
public static bool IsNodeChildNodeOf(TreeListNode nodeToTest, TreeListNode potentialParentNode)
{
if (nodeToTest == potentialParentNode)
{
return true;
}
else
{
foreach (TreeListNode node in potentialParentNode.Nodes)
{
if (IsNodeChildNodeOf(nodeToTest, node)) return true;
}
return false;
}
}
}
| |
using System;
using Csla;
using ParentLoad.DataAccess;
using ParentLoad.DataAccess.ERCLevel;
namespace ParentLoad.Business.ERCLevel
{
/// <summary>
/// B09_Region_Child (editable child object).<br/>
/// This is a generated base class of <see cref="B09_Region_Child"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="B08_Region"/> collection.
/// </remarks>
[Serializable]
public partial class B09_Region_Child : BusinessBase<B09_Region_Child>
{
#region State Fields
[NotUndoable]
[NonSerialized]
internal int region_ID1 = 0;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Region_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Region_Child_NameProperty = RegisterProperty<string>(p => p.Region_Child_Name, "Region Child Name");
/// <summary>
/// Gets or sets the Region Child Name.
/// </summary>
/// <value>The Region Child Name.</value>
public string Region_Child_Name
{
get { return GetProperty(Region_Child_NameProperty); }
set { SetProperty(Region_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="B09_Region_Child"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="B09_Region_Child"/> object.</returns>
internal static B09_Region_Child NewB09_Region_Child()
{
return DataPortal.CreateChild<B09_Region_Child>();
}
/// <summary>
/// Factory method. Loads a <see cref="B09_Region_Child"/> object from the given B09_Region_ChildDto.
/// </summary>
/// <param name="data">The <see cref="B09_Region_ChildDto"/>.</param>
/// <returns>A reference to the fetched <see cref="B09_Region_Child"/> object.</returns>
internal static B09_Region_Child GetB09_Region_Child(B09_Region_ChildDto data)
{
B09_Region_Child obj = new B09_Region_Child();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(data);
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="B09_Region_Child"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public B09_Region_Child()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="B09_Region_Child"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="B09_Region_Child"/> object from the given <see cref="B09_Region_ChildDto"/>.
/// </summary>
/// <param name="data">The B09_Region_ChildDto to use.</param>
private void Fetch(B09_Region_ChildDto data)
{
// Value properties
LoadProperty(Region_Child_NameProperty, data.Region_Child_Name);
// parent properties
region_ID1 = data.Parent_Region_ID;
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="B09_Region_Child"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(B08_Region parent)
{
var dto = new B09_Region_ChildDto();
dto.Parent_Region_ID = parent.Region_ID;
dto.Region_Child_Name = Region_Child_Name;
using (var dalManager = DalFactoryParentLoad.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnInsertPre(args);
var dal = dalManager.GetProvider<IB09_Region_ChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Insert(dto);
args = new DataPortalHookArgs(resultDto);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="B09_Region_Child"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(B08_Region parent)
{
if (!IsDirty)
return;
var dto = new B09_Region_ChildDto();
dto.Parent_Region_ID = parent.Region_ID;
dto.Region_Child_Name = Region_Child_Name;
using (var dalManager = DalFactoryParentLoad.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnUpdatePre(args);
var dal = dalManager.GetProvider<IB09_Region_ChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Update(dto);
args = new DataPortalHookArgs(resultDto);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="B09_Region_Child"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(B08_Region parent)
{
using (var dalManager = DalFactoryParentLoad.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IB09_Region_ChildDal>();
using (BypassPropertyChecks)
{
dal.Delete(parent.Region_ID);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
namespace ACorns.WCF.DynamicClientProxy.Internal
{
/// <summary>
/// Helper to emit classes.
/// With Copy&Paste from Hawkeye (http://www.acorns.com.au/Project/Hawkeye/)
/// Very crude implementation :)
/// </summary>
internal abstract class AbstractClassBuilder<TInterface> : ITypeBuilder
where TInterface : class
{
private const string ASSEMBLY_NAME = "ACorns.WCFDCPG.";
private const MethodAttributes defaultMethodAttributes = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.Final | MethodAttributes.NewSlot;
private static bool saveGeneratedAssembly; // set to true to save the generated assembly to the disk
private AssemblyBuilder assemblyBuilder;
private AssemblyName assemblyName;
private ModuleBuilder moduleBuilder;
private readonly Type baseClassType;
private string generatedAssemblyName;
private string generatedClassName;
protected AbstractClassBuilder(Type baseClassType)
{
this.baseClassType = baseClassType;
}
#region Properties
public string GeneratedClassName
{
get { return generatedClassName; }
}
#endregion
private void GenerateAssembly()
{
try
{
if (assemblyBuilder == null)
{
assemblyName = new AssemblyName();
assemblyName.Name = generatedAssemblyName;
assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, saveGeneratedAssembly ? AssemblyBuilderAccess.RunAndSave : AssemblyBuilderAccess.Run);
if (saveGeneratedAssembly)
{
moduleBuilder = assemblyBuilder.DefineDynamicModule(generatedAssemblyName, generatedAssemblyName + ".dll");
}
else
{
moduleBuilder = assemblyBuilder.DefineDynamicModule(generatedAssemblyName);
}
}
if (moduleBuilder == null)
{
throw new ApplicationException("Could not generate module builder");
}
}
catch (Exception ex)
{
throw new ApplicationException("Could not generate assembly " + generatedAssemblyName, ex);
}
}
/// <summary>
/// Generate a type declare like
/// public class MyType : ClientBase < ITheInterface >, ITheInterface
/// that implements the interface for us
/// </summary>
/// <returns></returns>
private Type GenerateTypeImplementation()
{
TypeBuilder builder;
try
{
builder = moduleBuilder.DefineType(generatedAssemblyName + "." + generatedClassName, TypeAttributes.Public, baseClassType);
}
catch (Exception ex)
{
throw new ApplicationException("Could not DefineType " + generatedClassName + " : " + baseClassType, ex);
}
if (builder == null)
{
throw new ApplicationException("Could not DefineType " + generatedClassName + " : " + baseClassType + " interface " + typeof (TInterface).FullName);
}
try
{
builder.AddInterfaceImplementation(typeof (TInterface)); // implement the interface
}
catch (Exception ex)
{
throw new ApplicationException("Could not DefineType " + generatedClassName + " : " + baseClassType + " interface " + typeof (TInterface).FullName, ex);
}
GenerateConstructor(builder);
GenerateMethodImpl(builder);
try
{
Type generatedType = builder.CreateType();
return generatedType;
}
catch (Exception ex)
{
throw new ApplicationException("Could not CreateType " + generatedClassName + " : " + baseClassType + " interface " + typeof (TInterface).FullName, ex);
}
}
public void SaveGeneratedAssembly()
{
if (saveGeneratedAssembly)
{
assemblyBuilder.Save(generatedAssemblyName + ".dll");
assemblyBuilder = null; // reset
}
}
/// <summary>
/// Read the interface declaration and emit a method for each method declaration
/// </summary>
/// <param name="builder"></param>
protected virtual void GenerateMethodImpl(TypeBuilder builder)
{
GenerateMethodImpl(builder, typeof (TInterface));
}
protected virtual void GenerateMethodImpl(TypeBuilder builder, Type currentType)
{
MethodInfo[] methods = currentType.GetMethods();
foreach (MethodInfo method in methods)
{
Type[] parameterTypes = GetParameters(method.GetParameters()); // declare the method with the correct parameters
MethodBuilder methodBuilder = builder.DefineMethod(method.Name, defaultMethodAttributes, method.ReturnType, parameterTypes);
// Start building the method
methodBuilder.CreateMethodBody(null, 0);
ILGenerator iLGenerator = methodBuilder.GetILGenerator();
GenerateMethodImpl(method, parameterTypes, iLGenerator);
// declare that we override the interface method
builder.DefineMethodOverride(methodBuilder, method);
}
Type[] inheritedInterfaces = currentType.GetInterfaces();
foreach (Type inheritedInterface in inheritedInterfaces)
{
GenerateMethodImpl(builder, inheritedInterface);
}
}
protected abstract void GenerateMethodImpl(MethodInfo method, Type[] parameterTypes, ILGenerator iLGenerator);
protected bool IsVoidMethod(MethodInfo methodInfo)
{
if (methodInfo.ReturnType == typeof (void))
return true;
else
return false;
}
protected MethodInfo GetMethodFromBaseClass(string methodName)
{
return baseClassType.GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetProperty);
}
/// <summary>
/// Simply generate a constructor:
/// public MyClass(string configName)
/// : base ( configName )
/// {
/// }
/// </summary>
/// <param name="builder"></param>
private void GenerateConstructor(TypeBuilder builder)
{
// Define the constructor
Type[] constructorParameters = new[] {typeof (string)};
ConstructorBuilder constructorBuilder = builder.DefineConstructor(MethodAttributes.Public | MethodAttributes.RTSpecialName, CallingConventions.Standard, constructorParameters);
ILGenerator iLGenerator = constructorBuilder.GetILGenerator();
iLGenerator.Emit(OpCodes.Ldarg_0); // this
iLGenerator.Emit(OpCodes.Ldarg_1); // load the param
// Call the base constructor
ConstructorInfo originalConstructor = baseClassType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, constructorParameters, null);
iLGenerator.Emit(OpCodes.Call, originalConstructor);
iLGenerator.Emit(OpCodes.Ret);
}
#region Utils
private static Type[] GetParameters(ParameterInfo[] declareParams)
{
List<Type> parameters = new List<Type>();
foreach (ParameterInfo param in declareParams)
{
parameters.Add(param.ParameterType);
}
return parameters.ToArray();
}
#endregion
#region Static Utils
public Type GenerateType(string className)
{
generatedClassName = className;
generatedAssemblyName = ASSEMBLY_NAME + generatedClassName;
GenerateAssembly();
Type type = moduleBuilder.GetType(generatedClassName);
if (type != null)
{
// we already created this type ?
return type;
}
// Generate a new type
type = GenerateTypeImplementation();
return type;
}
#endregion
}
}
| |
#if !HAS_SPAN
using System;
using System.Collections;
using System.IO;
using NBitcoin.BouncyCastle.Utilities;
namespace NBitcoin.BouncyCastle.Asn1
{
internal abstract class Asn1Sequence
: Asn1Object, IEnumerable
{
private readonly IList seq;
/**
* return an Asn1Sequence from the given object.
*
* @param obj the object we want converted.
* @exception ArgumentException if the object cannot be converted.
*/
public static Asn1Sequence GetInstance(
object obj)
{
if (obj == null || obj is Asn1Sequence)
{
return (Asn1Sequence)obj;
}
else if (obj is Asn1SequenceParser)
{
return Asn1Sequence.GetInstance(((Asn1SequenceParser)obj).ToAsn1Object());
}
else if (obj is byte[])
{
try
{
return Asn1Sequence.GetInstance(FromByteArray((byte[])obj));
}
catch (IOException e)
{
throw new ArgumentException("failed to construct sequence from byte[]: " + e.Message);
}
}
else if (obj is Asn1Encodable)
{
Asn1Object primitive = ((Asn1Encodable)obj).ToAsn1Object();
if (primitive is Asn1Sequence)
{
return (Asn1Sequence)primitive;
}
}
throw new ArgumentException("Unknown object in GetInstance: " + Platform.GetTypeName(obj), "obj");
}
protected internal Asn1Sequence(
int capacity)
{
seq = Platform.CreateArrayList(capacity);
}
public virtual IEnumerator GetEnumerator()
{
return seq.GetEnumerator();
}
[Obsolete("Use GetEnumerator() instead")]
public IEnumerator GetObjects()
{
return GetEnumerator();
}
private class Asn1SequenceParserImpl
: Asn1SequenceParser
{
private readonly Asn1Sequence outer;
private readonly int max;
private int index;
public Asn1SequenceParserImpl(
Asn1Sequence outer)
{
this.outer = outer;
this.max = outer.Count;
}
public IAsn1Convertible ReadObject()
{
if (index == max)
return null;
Asn1Encodable obj = outer[index++];
if (obj is Asn1Sequence)
return ((Asn1Sequence)obj).Parser;
// NB: Asn1OctetString implements Asn1OctetStringParser directly
// if (obj is Asn1OctetString)
// return ((Asn1OctetString)obj).Parser;
return obj;
}
public Asn1Object ToAsn1Object()
{
return outer;
}
}
public virtual Asn1SequenceParser Parser
{
get
{
return new Asn1SequenceParserImpl(this);
}
}
/**
* return the object at the sequence position indicated by index.
*
* @param index the sequence number (starting at zero) of the object
* @return the object at the sequence position indicated by index.
*/
public virtual Asn1Encodable this[int index]
{
get
{
return (Asn1Encodable)seq[index];
}
}
[Obsolete("Use 'object[index]' syntax instead")]
public Asn1Encodable GetObjectAt(
int index)
{
return this[index];
}
[Obsolete("Use 'Count' property instead")]
public int Size
{
get
{
return Count;
}
}
public virtual int Count
{
get
{
return seq.Count;
}
}
protected override int Asn1GetHashCode()
{
int hc = Count;
foreach (object o in this)
{
hc *= 17;
if (o == null)
{
hc ^= DerNull.Instance.GetHashCode();
}
else
{
hc ^= o.GetHashCode();
}
}
return hc;
}
protected override bool Asn1Equals(
Asn1Object asn1Object)
{
Asn1Sequence other = asn1Object as Asn1Sequence;
if (other == null)
return false;
if (Count != other.Count)
return false;
IEnumerator s1 = GetEnumerator();
IEnumerator s2 = other.GetEnumerator();
while (s1.MoveNext() && s2.MoveNext())
{
Asn1Object o1 = GetCurrent(s1).ToAsn1Object();
Asn1Object o2 = GetCurrent(s2).ToAsn1Object();
if (!o1.Equals(o2))
return false;
}
return true;
}
private Asn1Encodable GetCurrent(IEnumerator e)
{
Asn1Encodable encObj = (Asn1Encodable)e.Current;
// unfortunately null was allowed as a substitute for DER null
if (encObj == null)
return DerNull.Instance;
return encObj;
}
protected internal void AddObject(
Asn1Encodable obj)
{
seq.Add(obj);
}
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// System.Net.HttpListenerResponse
//
// Author:
// Gonzalo Paniagua Javier (gonzalo@novell.com)
//
// Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace System.Net
{
public sealed partial class HttpListenerResponse : IDisposable
{
private long _contentLength;
private bool _clSet;
private string _contentType;
private bool _keepAlive = true;
private HttpResponseStream _outputStream;
private Version _version = HttpVersion.Version11;
private string _location;
private int _statusCode = 200;
private string _statusDescription = "OK";
private bool _chunked;
private HttpListenerContext _context;
internal object _headersLock = new object();
private bool _forceCloseChunked;
internal HttpListenerResponse(HttpListenerContext context)
{
_context = context;
}
internal bool ForceCloseChunked => _forceCloseChunked;
public long ContentLength64
{
get => _contentLength;
set
{
CheckDisposed();
CheckSentHeaders();
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), SR.net_clsmall);
_clSet = true;
_contentLength = value;
}
}
public string ContentType
{
get => _contentType;
set
{
CheckDisposed();
CheckSentHeaders();
_contentType = value;
}
}
public bool KeepAlive
{
get => _keepAlive;
set
{
CheckDisposed();
CheckSentHeaders();
_keepAlive = value;
}
}
public Stream OutputStream
{
get
{
if (_outputStream == null)
_outputStream = _context.Connection.GetResponseStream();
return _outputStream;
}
}
public Version ProtocolVersion
{
get => _version;
set
{
CheckDisposed();
CheckSentHeaders();
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.Major != 1 || (value.Minor != 0 && value.Minor != 1))
throw new ArgumentException(SR.net_wrongversion, nameof(value));
_version = value;
}
}
public string RedirectLocation
{
get => _location;
set
{
CheckDisposed();
CheckSentHeaders();
_location = value;
}
}
public bool SendChunked
{
get => _chunked;
set
{
CheckDisposed();
CheckSentHeaders();
_chunked = value;
}
}
public int StatusCode
{
get => _statusCode;
set
{
CheckDisposed();
CheckSentHeaders();
if (value < 100 || value > 999)
throw new ProtocolViolationException(SR.net_invalidstatus);
_statusCode = value;
}
}
public string StatusDescription
{
get => _statusDescription;
set => _statusDescription = value;
}
private void Dispose() => Close(true);
public void Close()
{
if (Disposed)
return;
Close(false);
}
public void Abort()
{
if (Disposed)
return;
Close(true);
}
private void Close(bool force)
{
Disposed = true;
_context.Connection.Close(force);
}
public void Close(byte[] responseEntity, bool willBlock)
{
if (Disposed)
return;
if (responseEntity == null)
throw new ArgumentNullException(nameof(responseEntity));
ContentLength64 = responseEntity.Length;
OutputStream.Write(responseEntity, 0, (int)_contentLength);
Close(false);
}
public void CopyFrom(HttpListenerResponse templateResponse)
{
_webHeaders.Clear();
_webHeaders.Add(templateResponse._webHeaders);
_contentLength = templateResponse._contentLength;
_statusCode = templateResponse._statusCode;
_statusDescription = templateResponse._statusDescription;
_keepAlive = templateResponse._keepAlive;
_version = templateResponse._version;
}
public void Redirect(string url)
{
StatusCode = 302; // Found
_location = url;
}
private bool FindCookie(Cookie cookie)
{
string name = cookie.Name;
string domain = cookie.Domain;
string path = cookie.Path;
foreach (Cookie c in _cookies)
{
if (name != c.Name)
continue;
if (domain != c.Domain)
continue;
if (path == c.Path)
return true;
}
return false;
}
internal void SendHeaders(bool closing, MemoryStream ms, bool isWebSocketHandshake = false)
{
if (!isWebSocketHandshake)
{
if (_contentType != null)
{
_webHeaders.Set(HttpKnownHeaderNames.ContentType, _contentType);
}
if (_webHeaders[HttpKnownHeaderNames.Server] == null)
_webHeaders.Set(HttpKnownHeaderNames.Server, HttpHeaderStrings.NetCoreServerName);
CultureInfo inv = CultureInfo.InvariantCulture;
if (_webHeaders[HttpKnownHeaderNames.Date] == null)
_webHeaders.Set(HttpKnownHeaderNames.Date, DateTime.UtcNow.ToString("r", inv));
if (!_chunked)
{
if (!_clSet && closing)
{
_clSet = true;
_contentLength = 0;
}
if (_clSet)
_webHeaders.Set(HttpKnownHeaderNames.ContentLength, _contentLength.ToString(inv));
}
Version v = _context.Request.ProtocolVersion;
if (!_clSet && !_chunked && v >= HttpVersion.Version11)
_chunked = true;
/* Apache forces closing the connection for these status codes:
* HttpStatusCode.BadRequest 400
* HttpStatusCode.RequestTimeout 408
* HttpStatusCode.LengthRequired 411
* HttpStatusCode.RequestEntityTooLarge 413
* HttpStatusCode.RequestUriTooLong 414
* HttpStatusCode.InternalServerError 500
* HttpStatusCode.ServiceUnavailable 503
*/
bool conn_close = (_statusCode == (int)HttpStatusCode.BadRequest || _statusCode == (int)HttpStatusCode.RequestTimeout
|| _statusCode == (int)HttpStatusCode.LengthRequired || _statusCode == (int)HttpStatusCode.RequestEntityTooLarge
|| _statusCode == (int)HttpStatusCode.RequestUriTooLong || _statusCode == (int)HttpStatusCode.InternalServerError
|| _statusCode == (int)HttpStatusCode.ServiceUnavailable);
if (conn_close == false)
conn_close = !_context.Request.KeepAlive;
// They sent both KeepAlive: true and Connection: close
if (!_keepAlive || conn_close)
{
_webHeaders.Set(HttpKnownHeaderNames.Connection, HttpHeaderStrings.Close);
conn_close = true;
}
if (_chunked)
_webHeaders.Set(HttpKnownHeaderNames.TransferEncoding, HttpHeaderStrings.Chunked);
int reuses = _context.Connection.Reuses;
if (reuses >= 100)
{
_forceCloseChunked = true;
if (!conn_close)
{
_webHeaders.Set(HttpKnownHeaderNames.Connection, HttpHeaderStrings.Close);
conn_close = true;
}
}
if (!conn_close)
{
_webHeaders.Set(HttpKnownHeaderNames.KeepAlive, String.Format("timeout=15,max={0}", 100 - reuses));
if (_context.Request.ProtocolVersion <= HttpVersion.Version10)
_webHeaders.Set(HttpKnownHeaderNames.Connection, HttpHeaderStrings.KeepAlive);
}
if (_location != null)
_webHeaders.Set(HttpKnownHeaderNames.Location, _location);
if (_cookies != null)
{
foreach (Cookie cookie in _cookies)
_webHeaders.Set(HttpKnownHeaderNames.SetCookie, CookieToClientString(cookie));
}
}
Encoding encoding = Encoding.Default;
StreamWriter writer = new StreamWriter(ms, encoding, 256);
writer.Write("HTTP/{0} {1} {2}\r\n", _version, _statusCode, _statusDescription);
string headers_str = FormatHeaders(_webHeaders);
writer.Write(headers_str);
writer.Flush();
int preamble = encoding.GetPreamble().Length;
if (_outputStream == null)
_outputStream = _context.Connection.GetResponseStream();
/* Assumes that the ms was at position 0 */
ms.Position = preamble;
SentHeaders = !isWebSocketHandshake;
}
private static string FormatHeaders(WebHeaderCollection headers)
{
var sb = new StringBuilder();
for (int i = 0; i < headers.Count; i++)
{
string key = headers.GetKey(i);
string[] values = headers.GetValues(i);
for (int j = 0; j < values.Length; j++)
{
sb.Append(key).Append(": ").Append(values[j]).Append("\r\n");
}
}
return sb.Append("\r\n").ToString();
}
private static string CookieToClientString(Cookie cookie)
{
if (cookie.Name.Length == 0)
return String.Empty;
StringBuilder result = new StringBuilder(64);
if (cookie.Version > 0)
result.Append("Version=").Append(cookie.Version).Append(";");
result.Append(cookie.Name).Append("=").Append(cookie.Value);
if (cookie.Path != null && cookie.Path.Length != 0)
result.Append(";Path=").Append(QuotedString(cookie, cookie.Path));
if (cookie.Domain != null && cookie.Domain.Length != 0)
result.Append(";Domain=").Append(QuotedString(cookie, cookie.Domain));
if (cookie.Port != null && cookie.Port.Length != 0)
result.Append(";Port=").Append(cookie.Port);
return result.ToString();
}
private static string QuotedString(Cookie cookie, string value)
{
if (cookie.Version == 0 || IsToken(value))
return value;
else
return "\"" + value.Replace("\"", "\\\"") + "\"";
}
private static string s_tspecials = "()<>@,;:\\\"/[]?={} \t"; // from RFC 2965, 2068
private static bool IsToken(string value)
{
int len = value.Length;
for (int i = 0; i < len; i++)
{
char c = value[i];
if (c < 0x20 || c >= 0x7f || s_tspecials.IndexOf(c) != -1)
return false;
}
return true;
}
private bool Disposed { get; set; }
internal bool SentHeaders { get; set; }
}
}
| |
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using System;
using System.Collections;
namespace UIWidgets {
/// <summary>
/// Spinner validation.
/// </summary>
public enum SpinnerValidation {
OnKeyDown = 0,
OnEndInput = 1,
}
/// <summary>
/// Spinner base class.
/// </summary>
abstract public class SpinnerBase<T> : InputField, IPointerDownHandler
where T : struct
{
/// <summary>
/// The min.
/// </summary>
[SerializeField]
protected T _min;
/// <summary>
/// The max.
/// </summary>
[SerializeField]
protected T _max;
/// <summary>
/// The step.
/// </summary>
[SerializeField]
protected T _step;
/// <summary>
/// The value.
/// </summary>
[SerializeField]
protected T _value;
/// <summary>
/// The validation type.
/// </summary>
[SerializeField]
public SpinnerValidation Validation = SpinnerValidation.OnKeyDown;
/// <summary>
/// Delay of hold in seconds for permanent increase/descrease value.
/// </summary>
[SerializeField]
public float HoldStartDelay = 0.5f;
/// <summary>
/// Delay of hold in seconds between increase/descrease value.
/// </summary>
[SerializeField]
public float HoldChangeDelay = 0.1f;
/// <summary>
/// Gets or sets the minimum.
/// </summary>
/// <value>The minimum.</value>
public T Min {
get {
return _min;
}
set {
_min = value;
}
}
/// <summary>
/// Gets or sets the maximum.
/// </summary>
/// <value>The maximum.</value>
public T Max {
get {
return _max;
}
set {
_max = value;
}
}
/// <summary>
/// Gets or sets the step.
/// </summary>
/// <value>The step.</value>
public T Step {
get {
return _step;
}
set {
_step = value;
}
}
/// <summary>
/// Gets or sets the value.
/// </summary>
/// <value>The value.</value>
public T Value {
get {
return _value;
}
set {
SetValue(value);
}
}
/// <summary>
/// The plus button.
/// </summary>
[SerializeField]
protected ButtonAdvanced _plusButton;
/// <summary>
/// The minus button.
/// </summary>
[SerializeField]
protected ButtonAdvanced _minusButton;
/// <summary>
/// Gets or sets the plus button.
/// </summary>
/// <value>The plus button.</value>
public ButtonAdvanced PlusButton {
get {
return _plusButton;
}
set {
if (_plusButton!=null)
{
_plusButton.onClick.RemoveListener(OnPlusClick);
_plusButton.onPointerDown.RemoveListener(OnPlusButtonDown);
_plusButton.onPointerUp.RemoveListener(OnPlusButtonUp);
}
_plusButton = value;
if (_plusButton!=null)
{
_plusButton.onClick.AddListener(OnPlusClick);
_plusButton.onPointerDown.AddListener(OnPlusButtonDown);
_plusButton.onPointerUp.AddListener(OnPlusButtonUp);
}
}
}
/// <summary>
/// Gets or sets the minus button.
/// </summary>
/// <value>The minus button.</value>
public ButtonAdvanced MinusButton {
get {
return _minusButton;
}
set {
if (_minusButton!=null)
{
_minusButton.onClick.RemoveListener(OnMinusClick);
_minusButton.onPointerDown.RemoveListener(OnMinusButtonDown);
_minusButton.onPointerUp.RemoveListener(OnMinusButtonUp);
}
_minusButton = value;
if (_minusButton!=null)
{
_minusButton.onClick.AddListener(OnMinusClick);
_minusButton.onPointerDown.AddListener(OnMinusButtonDown);
_minusButton.onPointerUp.AddListener(OnMinusButtonUp);
}
}
}
/// <summary>
/// onPlusClick event.
/// </summary>
public UnityEvent onPlusClick = new UnityEvent();
/// <summary>
/// onMinusClick event.
/// </summary>
public UnityEvent onMinusClick = new UnityEvent();
/// <summary>
/// Increase value on step.
/// </summary>
abstract public void Plus();
/// <summary>
/// Decrease value on step.
/// </summary>
abstract public void Minus();
/// <summary>
/// Sets the value.
/// </summary>
/// <param name="newValue">New value.</param>
abstract protected void SetValue(T newValue);
/// <summary>
/// Start this instance.
/// </summary>
protected override void Start()
{
base.Start();
onValidateInput = SpinnerValidate;
#if UNITY_4_6 || UNITY_4_7 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2
onValueChange.AddListener(ValueChange);
#else
onValueChanged.AddListener(ValueChange);
#endif
onEndEdit.AddListener(ValueEndEdit);
PlusButton = _plusButton;
MinusButton = _minusButton;
Value = _value;
}
IEnumerator HoldPlus()
{
yield return new WaitForSeconds(HoldStartDelay);
while (true)
{
Plus();
yield return new WaitForSeconds(HoldChangeDelay);
}
}
IEnumerator HoldMinus()
{
yield return new WaitForSeconds(HoldStartDelay);
while (true)
{
Minus();
yield return new WaitForSeconds(HoldChangeDelay);
}
}
/// <summary>
/// Raises the minus click event.
/// </summary>
public void OnMinusClick()
{
Minus();
onMinusClick.Invoke();
}
/// <summary>
/// Raises the plus click event.
/// </summary>
public void OnPlusClick()
{
Plus();
onPlusClick.Invoke();
}
IEnumerator corutine;
/// <summary>
/// Raises the plus button down event.
/// </summary>
/// <param name="eventData">Current event data.</param>
public void OnPlusButtonDown(PointerEventData eventData)
{
if (corutine!=null)
{
StopCoroutine(corutine);
}
corutine = HoldPlus();
StartCoroutine(corutine);
}
/// <summary>
/// Raises the plus button up event.
/// </summary>
/// <param name="eventData">Current event data.</param>
public void OnPlusButtonUp(PointerEventData eventData)
{
StopCoroutine(corutine);
}
/// <summary>
/// Raises the minus button down event.
/// </summary>
/// <param name="eventData">Current event data.</param>
public void OnMinusButtonDown(PointerEventData eventData)
{
if (corutine!=null)
{
StopCoroutine(corutine);
}
corutine = HoldMinus();
StartCoroutine(corutine);
}
/// <summary>
/// Raises the minus button up event.
/// </summary>
/// <param name="eventData">Current event data.</param>
public void OnMinusButtonUp(PointerEventData eventData)
{
StopCoroutine(corutine);
}
/// <summary>
/// Ons the destroy.
/// </summary>
protected virtual void onDestroy()
{
#if UNITY_4_6 || UNITY_4_7 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2
onValueChange.RemoveListener(ValueChange);
#else
onValueChanged.RemoveListener(ValueChange);
#endif
onEndEdit.RemoveListener(ValueEndEdit);
PlusButton = null;
MinusButton = null;
}
/// <summary>
/// Called when value changed.
/// </summary>
/// <param name="value">Value.</param>
abstract protected void ValueChange(string value);
/// <summary>
/// Called when end edit.
/// </summary>
/// <param name="value">Value.</param>
abstract protected void ValueEndEdit(string value);
char SpinnerValidate(string validateText, int charIndex, char addedChar)
{
if (SpinnerValidation.OnEndInput==Validation)
{
return ValidateShort(validateText, charIndex, addedChar);
}
else
{
return ValidateFull(validateText, charIndex, addedChar);
}
}
/// <summary>
/// Validate when key down for Validation=OnEndInput.
/// </summary>
/// <returns>The char.</returns>
/// <param name="validateText">Validate text.</param>
/// <param name="charIndex">Char index.</param>
/// <param name="addedChar">Added char.</param>
abstract protected char ValidateShort(string validateText, int charIndex, char addedChar);
/// <summary>
/// Validates when key down for Validation=OnKeyDown.
/// </summary>
/// <returns>The char.</returns>
/// <param name="validateText">Validate text.</param>
/// <param name="charIndex">Char index.</param>
/// <param name="addedChar">Added char.</param>
abstract protected char ValidateFull(string validateText, int charIndex, char addedChar);
/// <summary>
/// Clamps a value between a minimum and maximum value.
/// </summary>
/// <returns>The bounds.</returns>
/// <param name="value">Value.</param>
abstract protected T InBounds(T value);
}
}
| |
// Copyright 2019 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.
using Android.App;
using Android.OS;
using Android.Runtime;
using Android.Speech.Tts;
using Android.Widget;
using ArcGISRuntime;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Location;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Navigation;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.Tasks.NetworkAnalysis;
using Esri.ArcGISRuntime.UI;
using Esri.ArcGISRuntime.UI.Controls;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Threading.Tasks;
namespace ArcGISRuntimeXamarin.Samples.NavigateRoute
{
[Activity(ConfigurationChanges = Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)]
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Navigate route",
category: "Network analysis",
description: "Use a routing service to navigate between points.",
instructions: "Tap 'Navigate' to simulate traveling and to receive directions from a preset starting point to a preset destination. Tap 'Recenter' to refocus on the location display.",
tags: new[] { "directions", "maneuver", "navigation", "route", "turn-by-turn", "voice", "Featured" })]
[ArcGISRuntime.Samples.Shared.Attributes.OfflineData()]
public class NavigateRoute : Activity, TextToSpeech.IOnInitListener
{
// Hold references to the UI controls.
private MapView _myMapView;
private Button _navigateButton;
private Button _recenterButton;
private TextView _status;
// Variables for tracking the navigation route.
private RouteTracker _tracker;
private RouteResult _routeResult;
private Route _route;
// List of driving directions for the route.
private IReadOnlyList<DirectionManeuver> _directionsList;
// Speech synthesizer to play voice guidance audio.
private TextToSpeech _textToSpeech;
// String to hold route status for the UI.
private string _statusMessage;
// Graphics to show progress along the route.
private Graphic _routeAheadGraphic;
private Graphic _routeTraveledGraphic;
// San Diego Convention Center.
private readonly MapPoint _conventionCenter = new MapPoint(-117.160386727, 32.706608, SpatialReferences.Wgs84);
// USS San Diego Memorial.
private readonly MapPoint _memorial = new MapPoint(-117.173034, 32.712327, SpatialReferences.Wgs84);
// RH Fleet Aerospace Museum.
private readonly MapPoint _aerospaceMuseum = new MapPoint(-117.147230, 32.730467, SpatialReferences.Wgs84);
// Feature service for routing in San Diego.
private readonly Uri _routingUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/Route");
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
Title = "Navigate route";
CreateLayout();
Initialize();
}
private async void Initialize()
{
try
{
// Create the map view.
_myMapView.Map = new Map(BasemapStyle.ArcGISStreets);
// Create the text to speech object.
_textToSpeech = new TextToSpeech(this, this, "com.google.android.tts");
// Create the route task, using the online routing service.
RouteTask routeTask = await RouteTask.CreateAsync(_routingUri);
// Get the default route parameters.
RouteParameters routeParams = await routeTask.CreateDefaultParametersAsync();
// Explicitly set values for parameters.
routeParams.ReturnDirections = true;
routeParams.ReturnStops = true;
routeParams.ReturnRoutes = true;
routeParams.OutputSpatialReference = SpatialReferences.Wgs84;
// Create stops for each location.
Stop stop1 = new Stop(_conventionCenter) { Name = "San Diego Convention Center" };
Stop stop2 = new Stop(_memorial) { Name = "USS San Diego Memorial" };
Stop stop3 = new Stop(_aerospaceMuseum) { Name = "RH Fleet Aerospace Museum" };
// Assign the stops to the route parameters.
List<Stop> stopPoints = new List<Stop> { stop1, stop2, stop3 };
routeParams.SetStops(stopPoints);
// Get the route results.
_routeResult = await routeTask.SolveRouteAsync(routeParams);
_route = _routeResult.Routes[0];
// Add a graphics overlay for the route graphics.
_myMapView.GraphicsOverlays.Add(new GraphicsOverlay());
// Add graphics for the stops.
SimpleMarkerSymbol stopSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Diamond, Color.OrangeRed, 20);
_myMapView.GraphicsOverlays[0].Graphics.Add(new Graphic(_conventionCenter, stopSymbol));
_myMapView.GraphicsOverlays[0].Graphics.Add(new Graphic(_memorial, stopSymbol));
_myMapView.GraphicsOverlays[0].Graphics.Add(new Graphic(_aerospaceMuseum, stopSymbol));
// Create a graphic (with a dashed line symbol) to represent the route.
_routeAheadGraphic = new Graphic(_route.RouteGeometry) { Symbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Dash, Color.BlueViolet, 5) };
// Create a graphic (solid) to represent the route that's been traveled (initially empty).
_routeTraveledGraphic = new Graphic { Symbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.LightBlue, 3) };
// Add the route graphics to the map view.
_myMapView.GraphicsOverlays[0].Graphics.Add(_routeAheadGraphic);
_myMapView.GraphicsOverlays[0].Graphics.Add(_routeTraveledGraphic);
// Set the map viewpoint to show the entire route.
await _myMapView.SetViewpointGeometryAsync(_route.RouteGeometry, 100);
// Enable the navigation button.
_navigateButton.Enabled = true;
}
catch (Exception e)
{
new AlertDialog.Builder(this).SetMessage(e.Message).SetTitle("Error").Show();
}
}
private void StartNavigation(object sender, EventArgs e)
{
// Disable the start navigation button.
_navigateButton.Enabled = false;
// Get the directions for the route.
_directionsList = _route.DirectionManeuvers;
// Create a route tracker.
_tracker = new RouteTracker(_routeResult, 0, true);
_tracker.NewVoiceGuidance += SpeakDirection;
// Handle route tracking status changes.
_tracker.TrackingStatusChanged += TrackingStatusUpdated;
// Turn on navigation mode for the map view.
_myMapView.LocationDisplay.AutoPanMode = LocationDisplayAutoPanMode.Navigation;
_myMapView.LocationDisplay.AutoPanModeChanged += AutoPanModeChanged;
// Add a data source for the location display.
var simulationParameters = new SimulationParameters(DateTimeOffset.Now, 40.0);
var simulatedDataSource = new SimulatedLocationDataSource();
simulatedDataSource.SetLocationsWithPolyline(_route.RouteGeometry, simulationParameters);
_myMapView.LocationDisplay.DataSource = new RouteTrackerDisplayLocationDataSource(simulatedDataSource, _tracker);
// Use this instead if you want real location:
// _myMapView.LocationDisplay.DataSource = new RouteTrackerLocationDataSource(new SystemLocationDataSource(), _tracker);
// Enable the location display (this wil start the location data source).
_myMapView.LocationDisplay.IsEnabled = true;
}
private void TrackingStatusUpdated(object sender, RouteTrackerTrackingStatusChangedEventArgs e)
{
TrackingStatus status = e.TrackingStatus;
// Start building a status message for the UI.
System.Text.StringBuilder statusMessageBuilder = new System.Text.StringBuilder();
// Check the destination status.
if (status.DestinationStatus == DestinationStatus.NotReached || status.DestinationStatus == DestinationStatus.Approaching)
{
statusMessageBuilder.AppendLine("Distance remaining: " +
status.RouteProgress.RemainingDistance.DisplayText + " " +
status.RouteProgress.RemainingDistance.DisplayTextUnits.PluralDisplayName);
statusMessageBuilder.AppendLine("Time remaining: " +
status.RouteProgress.RemainingTime.ToString(@"hh\:mm\:ss"));
if (status.CurrentManeuverIndex + 1 < _directionsList.Count)
{
statusMessageBuilder.AppendLine("Next direction: " + _directionsList[status.CurrentManeuverIndex + 1].DirectionText);
}
// Set geometries for progress and the remaining route.
_routeAheadGraphic.Geometry = status.RouteProgress.RemainingGeometry;
_routeTraveledGraphic.Geometry = status.RouteProgress.TraversedGeometry;
}
else if (status.DestinationStatus == DestinationStatus.Reached)
{
statusMessageBuilder.AppendLine("Destination reached.");
// Set the route geometries to reflect the completed route.
_routeAheadGraphic.Geometry = null;
_routeTraveledGraphic.Geometry = status.RouteResult.Routes[0].RouteGeometry;
// Navigate to the next stop (if there are stops remaining).
if (status.RemainingDestinationCount > 1)
{
_tracker.SwitchToNextDestinationAsync();
}
else
{
RunOnUiThread(() =>
{
// Stop the simulated location data source.
_myMapView.LocationDisplay.DataSource.StopAsync();
});
}
}
_statusMessage = statusMessageBuilder.ToString().TrimEnd('\n').TrimEnd('\r');
// Update the status in the UI.
RunOnUiThread(SetLabelText);
}
private void SetLabelText()
{
_status.Text = _statusMessage;
}
private void SpeakDirection(object sender, RouteTrackerNewVoiceGuidanceEventArgs e)
{
_textToSpeech.Stop();
_textToSpeech.Speak(e.VoiceGuidance.Text, QueueMode.Flush, null, null);
}
private void AutoPanModeChanged(object sender, LocationDisplayAutoPanMode e)
{
// Turn the recenter button on or off when the location display changes to or from navigation mode.
_recenterButton.Enabled = e != LocationDisplayAutoPanMode.Navigation;
}
private void Recenter(object sender, EventArgs e)
{
// Change the mapview to use navigation mode.
_myMapView.LocationDisplay.AutoPanMode = LocationDisplayAutoPanMode.Navigation;
}
private void CreateLayout()
{
// Load the layout from the axml resource.
SetContentView(Resource.Layout.NavigateRoute);
_myMapView = FindViewById<MapView>(Resource.Id.MapView);
_navigateButton = FindViewById<Button>(Resource.Id.navigateButton);
_recenterButton = FindViewById<Button>(Resource.Id.recenterButton);
_status = FindViewById<TextView>(Resource.Id.statusLabel);
// Add listeners for all of the buttons.
_navigateButton.Click += StartNavigation;
_recenterButton.Click += Recenter;
}
public void OnInit([GeneratedEnum] OperationResult status)
{
Console.WriteLine(status.ToString());
}
protected override void OnDestroy()
{
// Stop the location data source.
_myMapView?.LocationDisplay?.DataSource?.StopAsync();
base.OnDestroy();
}
}
/*
* This location data source uses an input data source and a route tracker.
* The location source that it updates is based on the snapped-to-route location from the route tracker.
*/
public class RouteTrackerDisplayLocationDataSource : LocationDataSource
{
private LocationDataSource _inputDataSource;
private RouteTracker _routeTracker;
public RouteTrackerDisplayLocationDataSource(LocationDataSource dataSource, RouteTracker routeTracker)
{
// Set the data source
_inputDataSource = dataSource ?? throw new ArgumentNullException(nameof(dataSource));
// Set the route tracker.
_routeTracker = routeTracker ?? throw new ArgumentNullException(nameof(routeTracker));
// Change the tracker location when the source location changes.
_inputDataSource.LocationChanged += InputLocationChanged;
// Update the location output when the tracker location updates.
_routeTracker.TrackingStatusChanged += TrackingStatusChanged;
}
private void InputLocationChanged(object sender, Location e)
{
// Update the tracker location with the new location from the source (simulation or GPS).
_routeTracker.TrackLocationAsync(e);
}
private void TrackingStatusChanged(object sender, RouteTrackerTrackingStatusChangedEventArgs e)
{
// Check if the tracking status has a location.
if (e.TrackingStatus.DisplayLocation != null)
{
// Call the base method for LocationDataSource to update the location with the tracked (snapped to route) location.
UpdateLocation(e.TrackingStatus.DisplayLocation);
}
}
protected override Task OnStartAsync() => _inputDataSource.StartAsync();
protected override Task OnStopAsync() => _inputDataSource.StartAsync();
}
}
| |
/*
* Copyright 2010 ZXing 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.
*/
using System;
using System.Collections.Generic;
using System.Text;
using ZXing.Common;
namespace ZXing.OneD
{
/// <summary>
/// <p>Decodes Code 93 barcodes.</p>
/// <author>Sean Owen</author>
/// <see cref="Code39Reader" />
/// </summary>
public sealed class Code93Reader : OneDReader
{
// Note that 'abcd' are dummy characters in place of control characters.
internal const String ALPHABET_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%abcd*";
private static readonly char[] ALPHABET = ALPHABET_STRING.ToCharArray();
/// <summary>
/// These represent the encodings of characters, as patterns of wide and narrow bars.
/// The 9 least-significant bits of each int correspond to the pattern of wide and narrow.
/// </summary>
internal static readonly int[] CHARACTER_ENCODINGS = {
0x114, 0x148, 0x144, 0x142, 0x128, 0x124, 0x122, 0x150, 0x112, 0x10A, // 0-9
0x1A8, 0x1A4, 0x1A2, 0x194, 0x192, 0x18A, 0x168, 0x164, 0x162, 0x134, // A-J
0x11A, 0x158, 0x14C, 0x146, 0x12C, 0x116, 0x1B4, 0x1B2, 0x1AC, 0x1A6, // K-T
0x196, 0x19A, 0x16C, 0x166, 0x136, 0x13A, // U-Z
0x12E, 0x1D4, 0x1D2, 0x1CA, 0x16E, 0x176, 0x1AE, // - - %
0x126, 0x1DA, 0x1D6, 0x132, 0x15E, // Control chars? $-*
};
private static readonly int ASTERISK_ENCODING = CHARACTER_ENCODINGS[47];
private readonly StringBuilder decodeRowResult;
private readonly int[] counters;
/// <summary>
/// Initializes a new instance of the <see cref="Code93Reader"/> class.
/// </summary>
public Code93Reader()
{
decodeRowResult = new StringBuilder(20);
counters = new int[6];
}
/// <summary>
/// <p>Attempts to decode a one-dimensional barcode format given a single row of
/// an image.</p>
/// </summary>
/// <param name="rowNumber">row number from top of the row</param>
/// <param name="row">the black/white pixel data of the row</param>
/// <param name="hints">decode hints</param>
/// <returns><see cref="Result"/>containing encoded string and start/end of barcode</returns>
override public Result decodeRow(int rowNumber, BitArray row, IDictionary<DecodeHintType, object> hints)
{
for (var index = 0; index < counters.Length; index++)
counters[index] = 0;
decodeRowResult.Length = 0;
int[] start = findAsteriskPattern(row);
if (start == null)
return null;
// Read off white space
int nextStart = row.getNextSet(start[1]);
int end = row.Size;
char decodedChar;
int lastStart;
do
{
if (!recordPattern(row, nextStart, counters))
return null;
int pattern = toPattern(counters);
if (pattern < 0)
{
return null;
}
if (!patternToChar(pattern, out decodedChar))
return null;
decodeRowResult.Append(decodedChar);
lastStart = nextStart;
foreach (int counter in counters)
{
nextStart += counter;
}
// Read off white space
nextStart = row.getNextSet(nextStart);
} while (decodedChar != '*');
decodeRowResult.Remove(decodeRowResult.Length - 1, 1); // remove asterisk
int lastPatternSize = 0;
foreach (int counter in counters)
{
lastPatternSize += counter;
}
// Should be at least one more black module
if (nextStart == end || !row[nextStart])
{
return null;
}
if (decodeRowResult.Length < 2)
{
// false positive -- need at least 2 checksum digits
return null;
}
if (!checkChecksums(decodeRowResult))
return null;
// Remove checksum digits
decodeRowResult.Length = decodeRowResult.Length - 2;
String resultString = decodeExtended(decodeRowResult);
if (resultString == null)
return null;
float left = (start[1] + start[0])/2.0f;
float right = lastStart + lastPatternSize / 2.0f;
var resultPointCallback = hints == null || !hints.ContainsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK)
? null
: (ResultPointCallback) hints[DecodeHintType.NEED_RESULT_POINT_CALLBACK];
if (resultPointCallback != null)
{
resultPointCallback(new ResultPoint(left, rowNumber));
resultPointCallback(new ResultPoint(right, rowNumber));
}
return new Result(
resultString,
null,
new[]
{
new ResultPoint(left, rowNumber),
new ResultPoint(right, rowNumber)
},
BarcodeFormat.CODE_93);
}
private int[] findAsteriskPattern(BitArray row)
{
int width = row.Size;
int rowOffset = row.getNextSet(0);
for (var index = 0; index < counters.Length; index++)
counters[index] = 0;
int counterPosition = 0;
int patternStart = rowOffset;
bool isWhite = false;
int patternLength = counters.Length;
for (int i = rowOffset; i < width; i++)
{
if (row[i] ^ isWhite)
{
counters[counterPosition]++;
}
else
{
if (counterPosition == patternLength - 1)
{
if (toPattern(counters) == ASTERISK_ENCODING)
{
return new int[] { patternStart, i };
}
patternStart += counters[0] + counters[1];
Array.Copy(counters, 2, counters, 0, patternLength - 2);
counters[patternLength - 2] = 0;
counters[patternLength - 1] = 0;
counterPosition--;
}
else
{
counterPosition++;
}
counters[counterPosition] = 1;
isWhite = !isWhite;
}
}
return null;
}
private static int toPattern(int[] counters)
{
int max = counters.Length;
int sum = 0;
foreach (var counter in counters)
{
sum += counter;
}
int pattern = 0;
for (int i = 0; i < max; i++)
{
int scaledShifted = (counters[i] << INTEGER_MATH_SHIFT) * 9 / sum;
int scaledUnshifted = scaledShifted >> INTEGER_MATH_SHIFT;
if ((scaledShifted & 0xFF) > 0x7F)
{
scaledUnshifted++;
}
if (scaledUnshifted < 1 || scaledUnshifted > 4)
{
return -1;
}
if ((i & 0x01) == 0)
{
for (int j = 0; j < scaledUnshifted; j++)
{
pattern = (pattern << 1) | 0x01;
}
}
else
{
pattern <<= scaledUnshifted;
}
}
return pattern;
}
private static bool patternToChar(int pattern, out char c)
{
for (int i = 0; i < CHARACTER_ENCODINGS.Length; i++)
{
if (CHARACTER_ENCODINGS[i] == pattern)
{
c = ALPHABET[i];
return true;
}
}
c = '*';
return false;
}
private static String decodeExtended(StringBuilder encoded)
{
int length = encoded.Length;
StringBuilder decoded = new StringBuilder(length);
for (int i = 0; i < length; i++)
{
char c = encoded[i];
if (c >= 'a' && c <= 'd')
{
if (i >= length - 1)
{
return null;
}
char next = encoded[i + 1];
char decodedChar = '\0';
switch (c)
{
case 'd':
// +A to +Z map to a to z
if (next >= 'A' && next <= 'Z')
{
decodedChar = (char)(next + 32);
}
else
{
return null;
}
break;
case 'a':
// $A to $Z map to control codes SH to SB
if (next >= 'A' && next <= 'Z')
{
decodedChar = (char)(next - 64);
}
else
{
return null;
}
break;
case 'b':
if (next >= 'A' && next <= 'E')
{
// %A to %E map to control codes ESC to USep
decodedChar = (char)(next - 38);
}
else if (next >= 'F' && next <= 'J') {
// %F to %J map to ; < = > ?
decodedChar = (char) (next - 11);
}
else if (next >= 'K' && next <= 'O') {
// %K to %O map to [ \ ] ^ _
decodedChar = (char) (next + 16);
}
else if (next >= 'P' && next <= 'S') {
// %P to %S map to { | } ~
decodedChar = (char) (next + 43);
}
else if (next >= 'T' && next <= 'Z')
{
// %T to %Z all map to DEL (127)
decodedChar = (char)127;
}
else
{
return null;
}
break;
case 'c':
// /A to /O map to ! to , and /Z maps to :
if (next >= 'A' && next <= 'O')
{
decodedChar = (char)(next - 32);
}
else if (next == 'Z')
{
decodedChar = ':';
}
else
{
return null;
}
break;
}
decoded.Append(decodedChar);
// bump up i again since we read two characters
i++;
}
else
{
decoded.Append(c);
}
}
return decoded.ToString();
}
private static bool checkChecksums(StringBuilder result)
{
int length = result.Length;
if (!checkOneChecksum(result, length - 2, 20))
return false;
if (!checkOneChecksum(result, length - 1, 15))
return false;
return true;
}
private static bool checkOneChecksum(StringBuilder result, int checkPosition, int weightMax)
{
int weight = 1;
int total = 0;
for (int i = checkPosition - 1; i >= 0; i--)
{
total += weight * ALPHABET_STRING.IndexOf(result[i]);
if (++weight > weightMax)
{
weight = 1;
}
}
if (result[checkPosition] != ALPHABET[total % 47])
{
return false;
}
return true;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Compression.Test
{
public class zip_ReadTests
{
[Fact]
public static async Task ReadNormal()
{
await ZipTest.IsZipSameAsDirAsync(
ZipTest.zfile("normal.zip"), ZipTest.zfolder("normal"), ZipArchiveMode.Read);
await ZipTest.IsZipSameAsDirAsync(
ZipTest.zfile("fake64.zip"), ZipTest.zfolder("small"), ZipArchiveMode.Read);
await ZipTest.IsZipSameAsDirAsync(
ZipTest.zfile("empty.zip"), ZipTest.zfolder("empty"), ZipArchiveMode.Read);
await ZipTest.IsZipSameAsDirAsync(
ZipTest.zfile("appended.zip"), ZipTest.zfolder("small"), ZipArchiveMode.Read);
await ZipTest.IsZipSameAsDirAsync(
ZipTest.zfile("prepended.zip"), ZipTest.zfolder("small"), ZipArchiveMode.Read);
await ZipTest.IsZipSameAsDirAsync(
ZipTest.zfile("emptydir.zip"), ZipTest.zfolder("emptydir"), ZipArchiveMode.Read);
await ZipTest.IsZipSameAsDirAsync(
ZipTest.zfile("small.zip"), ZipTest.zfolder("small"), ZipArchiveMode.Read);
if (Interop.IsWindows) // [ActiveIssue(846, PlatformID.AnyUnix)]
{
await ZipTest.IsZipSameAsDirAsync(
ZipTest.zfile("unicode.zip"), ZipTest.zfolder("unicode"), ZipArchiveMode.Read);
}
}
[Fact]
public static async Task ReadStreaming()
{
//don't include large, because that means loading the whole thing in memory
await TestStreamingRead(ZipTest.zfile("normal.zip"), ZipTest.zfolder("normal"));
await TestStreamingRead(ZipTest.zfile("fake64.zip"), ZipTest.zfolder("small"));
if (Interop.IsWindows) // [ActiveIssue(846, PlatformID.AnyUnix)]
{
await TestStreamingRead(ZipTest.zfile("unicode.zip"), ZipTest.zfolder("unicode"));
}
await TestStreamingRead(ZipTest.zfile("empty.zip"), ZipTest.zfolder("empty"));
await TestStreamingRead(ZipTest.zfile("appended.zip"), ZipTest.zfolder("small"));
await TestStreamingRead(ZipTest.zfile("prepended.zip"), ZipTest.zfolder("small"));
await TestStreamingRead(ZipTest.zfile("emptydir.zip"), ZipTest.zfolder("emptydir"));
}
private static async Task TestStreamingRead(String zipFile, String directory)
{
using (var stream = await StreamHelpers.CreateTempCopyStream(zipFile))
{
Stream wrapped = new WrappedStream(stream, true, false, false, null);
ZipTest.IsZipSameAsDir(wrapped, directory, ZipArchiveMode.Read, false, false);
Assert.False(wrapped.CanRead, "Wrapped stream should be closed at this point"); //check that it was closed
}
}
[Fact]
public static async Task ReadStreamOps()
{
using (ZipArchive archive = new ZipArchive(await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("normal.zip")), ZipArchiveMode.Read))
{
foreach (ZipArchiveEntry e in archive.Entries)
{
using (Stream s = e.Open())
{
Assert.True(s.CanRead, "Can read to read archive");
Assert.False(s.CanWrite, "Can't write to read archive");
Assert.False(s.CanSeek, "Can't seek on archive");
Assert.Equal(ZipTest.LengthOfUnseekableStream(s), e.Length); //"Length is not correct on unseekable stream"
}
}
}
}
[Fact]
public static async Task ReadInterleaved()
{
using (ZipArchive archive = new ZipArchive(await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("normal.zip"))))
{
ZipArchiveEntry e1 = archive.GetEntry("first.txt");
ZipArchiveEntry e2 = archive.GetEntry("notempty/second.txt");
//read all of e1 and e2's contents
Byte[] e1readnormal = new Byte[e1.Length];
Byte[] e2readnormal = new Byte[e2.Length];
Byte[] e1interleaved = new Byte[e1.Length];
Byte[] e2interleaved = new Byte[e2.Length];
using (Stream e1s = e1.Open())
{
ZipTest.ReadBytes(e1s, e1readnormal, e1.Length);
}
using (Stream e2s = e2.Open())
{
ZipTest.ReadBytes(e2s, e2readnormal, e2.Length);
}
//now read interleaved, assume we are working with < 4gb files
const Int32 bytesAtATime = 15;
using (Stream e1s = e1.Open(), e2s = e2.Open())
{
Int32 e1pos = 0;
Int32 e2pos = 0;
while (e1pos < e1.Length || e2pos < e2.Length)
{
if (e1pos < e1.Length)
{
Int32 e1bytesRead = e1s.Read(e1interleaved, e1pos,
bytesAtATime + e1pos > e1.Length ? (Int32)e1.Length - e1pos : bytesAtATime);
e1pos += e1bytesRead;
}
if (e2pos < e2.Length)
{
Int32 e2bytesRead = e2s.Read(e2interleaved, e2pos,
bytesAtATime + e2pos > e2.Length ? (Int32)e2.Length - e2pos : bytesAtATime);
e2pos += e2bytesRead;
}
}
}
//now compare to original read
ZipTest.ArraysEqual<Byte>(e1readnormal, e1interleaved, e1readnormal.Length);
ZipTest.ArraysEqual<Byte>(e2readnormal, e2interleaved, e2readnormal.Length);
//now read one entry interleaved
Byte[] e1selfInterleaved1 = new Byte[e1.Length];
Byte[] e1selfInterleaved2 = new Byte[e2.Length];
using (Stream s1 = e1.Open(), s2 = e1.Open())
{
Int32 s1pos = 0;
Int32 s2pos = 0;
while (s1pos < e1.Length || s2pos < e1.Length)
{
if (s1pos < e1.Length)
{
Int32 s1bytesRead = s1.Read(e1interleaved, s1pos,
bytesAtATime + s1pos > e1.Length ? (Int32)e1.Length - s1pos : bytesAtATime);
s1pos += s1bytesRead;
}
if (s2pos < e1.Length)
{
Int32 s2bytesRead = s2.Read(e2interleaved, s2pos,
bytesAtATime + s2pos > e1.Length ? (Int32)e1.Length - s2pos : bytesAtATime);
s2pos += s2bytesRead;
}
}
}
//now compare to original read
ZipTest.ArraysEqual<Byte>(e1readnormal, e1selfInterleaved1, e1readnormal.Length);
ZipTest.ArraysEqual<Byte>(e1readnormal, e1selfInterleaved2, e1readnormal.Length);
}
}
[Fact]
public static async Task ReadModeInvalidOpsTest()
{
ZipArchive archive = new ZipArchive(await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("normal.zip")), ZipArchiveMode.Read);
ZipArchiveEntry e = archive.GetEntry("first.txt");
//should also do it on deflated stream
//on archive
Assert.Throws<NotSupportedException>(() => archive.CreateEntry("hi there")); //"Should not be able to create entry"
//on entry
Assert.Throws<NotSupportedException>(() => e.Delete()); //"Should not be able to delete entry"
//Throws<NotSupportedException>(() => e.MoveTo("dirka"));
Assert.Throws<NotSupportedException>(() => e.LastWriteTime = new DateTimeOffset()); //"Should not be able to update time"
//on stream
Stream s = e.Open();
Assert.Throws<NotSupportedException>(() => s.Flush()); //"Should not be able to flush on read stream"
Assert.Throws<NotSupportedException>(() => s.WriteByte(25)); //"should not be able to write to read stream"
Assert.Throws<NotSupportedException>(() => s.Position = 4); //"should not be able to seek on read stream"
Assert.Throws<NotSupportedException>(() => s.Seek(0, SeekOrigin.Begin)); //"should not be able to seek on read stream"
Assert.Throws<NotSupportedException>(() => s.SetLength(0)); //"should not be able to resize read stream"
archive.Dispose();
//after disposed
Assert.Throws<ObjectDisposedException>(() => { var x = archive.Entries; }); //"Should not be able to get entries on disposed archive"
Assert.Throws<NotSupportedException>(() => archive.CreateEntry("dirka")); //"should not be able to create on disposed archive"
Assert.Throws<ObjectDisposedException>(() => e.Open()); //"should not be able to open on disposed archive"
Assert.Throws<NotSupportedException>(() => e.Delete()); //"should not be able to delete on disposed archive"
Assert.Throws<ObjectDisposedException>(() => { e.LastWriteTime = new DateTimeOffset(); }); //"Should not be able to update on disposed archive"
Assert.Throws<NotSupportedException>(() => s.ReadByte()); //"should not be able to read on disposed archive"
s.Dispose();
}
}
}
| |
using System;
using System.Diagnostics;
using Lucene.Net.Documents;
namespace Lucene.Net.Index
{
using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator;
using FixedBitSet = Lucene.Net.Util.FixedBitSet;
using InPlaceMergeSorter = Lucene.Net.Util.InPlaceMergeSorter;
using NumericDocValuesField = NumericDocValuesField;
using NumericDocValuesUpdate = Lucene.Net.Index.DocValuesUpdate.NumericDocValuesUpdate;
using PackedInts = Lucene.Net.Util.Packed.PackedInts;
using PagedGrowableWriter = Lucene.Net.Util.Packed.PagedGrowableWriter;
using PagedMutable = Lucene.Net.Util.Packed.PagedMutable;
/*
* 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.
*/
/// <summary>
/// A <seealso cref="DocValuesFieldUpdates"/> which holds updates of documents, of a single
/// <seealso cref="NumericDocValuesField"/>.
///
/// @lucene.experimental
/// </summary>
internal class NumericDocValuesFieldUpdates : DocValuesFieldUpdates
{
internal sealed class Iterator : DocValuesFieldUpdates.Iterator
{
internal readonly int Size;
internal readonly PagedGrowableWriter Values;
internal readonly FixedBitSet DocsWithField;
internal readonly PagedMutable Docs;
internal long Idx = 0; // long so we don't overflow if size == Integer.MAX_VALUE
internal int Doc_Renamed = -1;
internal long? Value_Renamed = null;
internal Iterator(int size, PagedGrowableWriter values, FixedBitSet docsWithField, PagedMutable docs)
{
this.Size = size;
this.Values = values;
this.DocsWithField = docsWithField;
this.Docs = docs;
}
public object Value()
{
return Value_Renamed;
}
public int NextDoc()
{
if (Idx >= Size)
{
Value_Renamed = null;
return Doc_Renamed = DocIdSetIterator.NO_MORE_DOCS;
}
Doc_Renamed = (int)Docs.Get(Idx);
++Idx;
while (Idx < Size && Docs.Get(Idx) == Doc_Renamed)
{
++Idx;
}
if (!DocsWithField.Get((int)(Idx - 1)))
{
Value_Renamed = null;
}
else
{
// idx points to the "next" element
Value_Renamed = Convert.ToInt64(Values.Get(Idx - 1));
}
return Doc_Renamed;
}
public int Doc()
{
return Doc_Renamed;
}
public void Reset()
{
Doc_Renamed = -1;
Value_Renamed = null;
Idx = 0;
}
}
private FixedBitSet DocsWithField;
private PagedMutable Docs;
private PagedGrowableWriter Values;
private int Size;
public NumericDocValuesFieldUpdates(string field, int maxDoc)
: base(field, Type_e.NUMERIC)
{
DocsWithField = new FixedBitSet(64);
Docs = new PagedMutable(1, 1024, PackedInts.BitsRequired(maxDoc - 1), PackedInts.COMPACT);
Values = new PagedGrowableWriter(1, 1024, 1, PackedInts.FAST);
Size = 0;
}
public override void Add(int doc, object value)
{
// TODO: if the Sorter interface changes to take long indexes, we can remove that limitation
if (Size == int.MaxValue)
{
throw new InvalidOperationException("cannot support more than Integer.MAX_VALUE doc/value entries");
}
long? val = (long?)value;
if (val == null)
{
val = NumericDocValuesUpdate.MISSING;
}
// grow the structures to have room for more elements
if (Docs.Size() == Size)
{
Docs = Docs.Grow(Size + 1);
Values = Values.Grow(Size + 1);
DocsWithField = FixedBitSet.EnsureCapacity(DocsWithField, (int)Docs.Size());
}
if (val != NumericDocValuesUpdate.MISSING)
{
// only mark the document as having a value in that field if the value wasn't set to null (MISSING)
DocsWithField.Set(Size);
}
Docs.Set(Size, doc);
Values.Set(Size, (long)val);
++Size;
}
internal override DocValuesFieldUpdates.Iterator GetIterator()
{
PagedMutable docs = this.Docs;
PagedGrowableWriter values = this.Values;
FixedBitSet docsWithField = this.DocsWithField;
new InPlaceMergeSorterAnonymousInnerClassHelper(this, docs, values, docsWithField).Sort(0, Size);
return new Iterator(Size, values, docsWithField, docs);
}
private class InPlaceMergeSorterAnonymousInnerClassHelper : InPlaceMergeSorter
{
private readonly NumericDocValuesFieldUpdates OuterInstance;
private PagedMutable Docs;
private PagedGrowableWriter Values;
private FixedBitSet DocsWithField;
public InPlaceMergeSorterAnonymousInnerClassHelper(NumericDocValuesFieldUpdates outerInstance, PagedMutable docs, PagedGrowableWriter values, FixedBitSet docsWithField)
{
this.OuterInstance = outerInstance;
this.Docs = docs;
this.Values = values;
this.DocsWithField = docsWithField;
}
protected override void Swap(int i, int j)
{
long tmpDoc = Docs.Get(j);
Docs.Set(j, Docs.Get(i));
Docs.Set(i, tmpDoc);
long tmpVal = Values.Get(j);
Values.Set(j, Values.Get(i));
Values.Set(i, tmpVal);
bool tmpBool = DocsWithField.Get(j);
if (DocsWithField.Get(i))
{
DocsWithField.Set(j);
}
else
{
DocsWithField.Clear(j);
}
if (tmpBool)
{
DocsWithField.Set(i);
}
else
{
DocsWithField.Clear(i);
}
}
protected override int Compare(int i, int j)
{
int x = (int)Docs.Get(i);
int y = (int)Docs.Get(j);
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
}
public override void Merge(DocValuesFieldUpdates other)
{
Debug.Assert(other is NumericDocValuesFieldUpdates);
NumericDocValuesFieldUpdates otherUpdates = (NumericDocValuesFieldUpdates)other;
if (Size + otherUpdates.Size > int.MaxValue)
{
throw new InvalidOperationException("cannot support more than Integer.MAX_VALUE doc/value entries; size=" + Size + " other.size=" + otherUpdates.Size);
}
Docs = Docs.Grow(Size + otherUpdates.Size);
Values = Values.Grow(Size + otherUpdates.Size);
DocsWithField = FixedBitSet.EnsureCapacity(DocsWithField, (int)Docs.Size());
for (int i = 0; i < otherUpdates.Size; i++)
{
int doc = (int)otherUpdates.Docs.Get(i);
if (otherUpdates.DocsWithField.Get(i))
{
DocsWithField.Set(Size);
}
Docs.Set(Size, doc);
Values.Set(Size, otherUpdates.Values.Get(i));
++Size;
}
}
public override bool Any()
{
return Size > 0;
}
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
public class DelegateProxy
{
public delegate void PopCacheDelegateProxy(UnityEngine.Object o);
public delegate string StringBuilderDelegateProxy(params object[] args);
public delegate void SetObjRenderQDelegateProxy(GameObject oModel, int iLayer, int iRenderQueue);
public delegate void GameDestroyImmediate(UnityEngine.Object obj);
public delegate UnityEngine.Object DelegateInstantiate(UnityEngine.Object o, Vector3 postion, Quaternion rotation);
public delegate UnityEngine.Object DelegateInstantiateNoParam(UnityEngine.Object o);
public delegate void GameDestoryDelegateProxy(UnityEngine.Object obj);
public delegate void GameDestoryPoolDelegateProxy(GameObject obj);
public delegate void ShowViewDelegateProxy(string name, object arg = null);
public delegate void DestroyViewDelegateProxy(string name);
public delegate void LoadAssetDelegateProxy(string strFileName, AssetCallBack back);
public delegate void UnloadAssetDelegateProxy(object[] args);
public delegate void DestroyEffectDelegateProxy(GameObject obj, int layer);
public delegate bool HasViewDelegateProxy(string name);
public delegate void HideViewDelegateProxy(string name);
public delegate void PlayUIAudioDelegateProxy(int index);
public delegate void GetGuiCompentDelegateProxy(Dictionary<int, GameObject> lastgameObject, ref List<Component> newPanels, ref List<Component> tempPanels);
public delegate void OnShareCallbackDelegateProxy(string result);
public delegate void OnSetPayCallbackDelegateProxy(List<IAPProductInfo> productInfos);
public delegate void OnVerifyTransCallbackDelegateProxy(string pid, int amount, string transactionData, string transactionIdentifier, string account, string rolename, string serverid, string accountid);
public delegate bool OnSendMessageCallbackDelegateProxy(int iMSG, params object[] objects);
public static DelegateProxy.PopCacheDelegateProxy PopCacheProxy;
public static DelegateProxy.StringBuilderDelegateProxy StringBuilderPorxy;
public static DelegateProxy.GameDestroyImmediate mGameDestroyImme;
public static DelegateProxy.DelegateInstantiate mDelegateInstantiate;
public static DelegateProxy.DelegateInstantiateNoParam mDelegateInstantiateNoParam;
public static DelegateProxy.GameDestoryDelegateProxy GameDestoryProxy;
public static DelegateProxy.GameDestoryPoolDelegateProxy GameDestoryPoolProxy;
public static DelegateProxy.ShowViewDelegateProxy ShowViewProxy;
public static DelegateProxy.DestroyViewDelegateProxy DestroyViewProxy;
public static DelegateProxy.LoadAssetDelegateProxy LoadAssetProxy;
public static DelegateProxy.UnloadAssetDelegateProxy UnloadAssetProxy;
public static DelegateProxy.DestroyEffectDelegateProxy DestroyEffectProxy;
public static DelegateProxy.HasViewDelegateProxy HasViewProxy;
public static DelegateProxy.HideViewDelegateProxy HideViewProxy;
public static DelegateProxy.PlayUIAudioDelegateProxy PlayUIAudioProxy;
public static DelegateProxy.GetGuiCompentDelegateProxy GetGuiCompentProxy;
public static DelegateProxy.OnShareCallbackDelegateProxy OnShareCallbackProxy;
public static DelegateProxy.OnSetPayCallbackDelegateProxy OnSetPayCallbackProxy;
public static DelegateProxy.OnVerifyTransCallbackDelegateProxy OnVerifyTransCallbackProxy;
public static DelegateProxy.OnSendMessageCallbackDelegateProxy onSendMessageCallbackDelegateProxy;
public static void PopCache(UnityEngine.Object o)
{
if (DelegateProxy.PopCacheProxy != null)
{
DelegateProxy.PopCacheProxy(o);
}
}
public static string StringBuilder(params object[] args)
{
if (DelegateProxy.StringBuilderPorxy != null)
{
return DelegateProxy.StringBuilderPorxy(args);
}
return string.Empty;
}
public static void DestroyObjectImmediate(UnityEngine.Object obj)
{
if (DelegateProxy.mGameDestroyImme != null)
{
DelegateProxy.mGameDestroyImme(obj);
}
else
{
UnityEngine.Object.DestroyImmediate(obj);
}
}
public static UnityEngine.Object Instantiate(UnityEngine.Object o, Vector3 postion, Quaternion rotation)
{
if (DelegateProxy.mDelegateInstantiate != null)
{
return DelegateProxy.mDelegateInstantiate(o, postion, rotation);
}
return UnityEngine.Object.Instantiate(o, postion, rotation);
}
public static UnityEngine.Object Instantiate(UnityEngine.Object o)
{
if (DelegateProxy.mDelegateInstantiateNoParam != null)
{
return DelegateProxy.mDelegateInstantiateNoParam(o);
}
return UnityEngine.Object.Instantiate(o);
}
public static void GameDestory(UnityEngine.Object obj)
{
if (DelegateProxy.GameDestoryProxy != null)
{
DelegateProxy.GameDestoryProxy(obj);
}
}
public static void GamePoolDestory(GameObject obj)
{
if (DelegateProxy.GameDestoryPoolProxy != null)
{
DelegateProxy.GameDestoryPoolProxy(obj);
}
}
public static void ShowView(string name, object arg = null)
{
if (DelegateProxy.ShowViewProxy != null)
{
DelegateProxy.ShowViewProxy(name, arg);
}
}
public static void DestroyView(string name)
{
if (DelegateProxy.DestroyViewProxy != null)
{
DelegateProxy.DestroyViewProxy(name);
}
}
public static void LoadAsset(string strFileName, AssetCallBack callback)
{
if (DelegateProxy.LoadAssetProxy != null)
{
DelegateProxy.LoadAssetProxy(strFileName, callback);
}
}
public static void UnloadAsset(object[] args)
{
if (DelegateProxy.UnloadAssetProxy != null)
{
DelegateProxy.UnloadAssetProxy(args);
}
}
public static void DestroyEffect(GameObject obj, int layer)
{
if (DelegateProxy.DestroyEffectProxy != null)
{
DelegateProxy.DestroyEffectProxy(obj, layer);
}
}
public static bool HasView(string name)
{
return DelegateProxy.HasViewProxy != null && DelegateProxy.HasViewProxy(name);
}
public static void HideView(string name)
{
if (DelegateProxy.HideViewProxy != null)
{
DelegateProxy.HideViewProxy(name);
}
}
public static void PlayUIAudio(int index)
{
if (DelegateProxy.PlayUIAudioProxy != null)
{
DelegateProxy.PlayUIAudioProxy(index);
}
}
public static void GetGuiCompent(Dictionary<int, GameObject> lastgameObject, ref List<Component> newPanels, ref List<Component> tempPanels)
{
if (DelegateProxy.GetGuiCompentProxy != null)
{
DelegateProxy.GetGuiCompentProxy(lastgameObject, ref newPanels, ref tempPanels);
}
}
public static void OnShareCallback(string result)
{
if (DelegateProxy.OnShareCallbackProxy != null)
{
DelegateProxy.OnShareCallbackProxy(result);
}
}
public static void OnSetPayCallback(List<IAPProductInfo> productInfos)
{
if (DelegateProxy.OnSetPayCallbackProxy != null)
{
DelegateProxy.OnSetPayCallbackProxy(productInfos);
}
}
public static void OnVerifyTransCallback(string pid, int amount, string transactionData, string transactionIdentifier, string account, string rolename, string serverid, string accountid)
{
if (DelegateProxy.OnVerifyTransCallbackProxy != null)
{
DelegateProxy.OnVerifyTransCallbackProxy(pid, amount, transactionData, transactionIdentifier, account, rolename, serverid, accountid);
}
}
public static void OnSendMessageCallback(int iMSG, params object[] objects)
{
if (DelegateProxy.onSendMessageCallbackDelegateProxy != null)
{
DelegateProxy.onSendMessageCallbackDelegateProxy(iMSG, objects);
}
}
}
| |
using System;
using System.Collections;
using System.Runtime.InteropServices;
using WbemClient_v1;
using System.ComponentModel;
namespace System.Management
{
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
/// <summary>
/// <para> Represents different collections of management objects
/// retrieved through WMI. The objects in this collection are of <see cref='System.Management.ManagementBaseObject'/>-derived types, including <see cref='System.Management.ManagementObject'/> and <see cref='System.Management.ManagementClass'/>
/// .</para>
/// <para> The collection can be the result of a WMI
/// query executed through a <see cref='System.Management.ManagementObjectSearcher'/> object, or an enumeration of
/// management objects of a specified type retrieved through a <see cref='System.Management.ManagementClass'/> representing that type.
/// In addition, this can be a collection of management objects related in a specified
/// way to a specific management object - in this case the collection would
/// be retrieved through a method such as <see cref='System.Management.ManagementObject.GetRelated()'/>.</para>
/// <para>The collection can be walked using the <see cref='System.Management.ManagementObjectCollection.ManagementObjectEnumerator'/> and objects in it can be inspected or
/// manipulated for various management tasks.</para>
/// </summary>
/// <example>
/// <code lang='C#'>using System;
/// using System.Management;
///
/// // This example demonstrates how to enumerate instances of a ManagementClass object.
/// class Sample_ManagementObjectCollection
/// {
/// public static int Main(string[] args) {
/// ManagementClass diskClass = new ManagementClass("Win32_LogicalDisk");
/// ManagementObjectCollection disks = diskClass.GetInstances();
/// foreach (ManagementObject disk in disks) {
/// Console.WriteLine("Disk = " + disk["deviceid"]);
/// }
/// return 0;
/// }
/// }
/// </code>
/// <code lang='VB'>Imports System
/// Imports System.Management
///
/// ' This example demonstrates how to enumerate instances of a ManagementClass object.
/// Class Sample_ManagementObjectCollection
/// Overloads Public Shared Function Main(args() As String) As Integer
/// Dim diskClass As New ManagementClass("Win32_LogicalDisk")
/// Dim disks As ManagementObjectCollection = diskClass.GetInstances()
/// Dim disk As ManagementObject
/// For Each disk In disks
/// Console.WriteLine("Disk = " & disk("deviceid").ToString())
/// Next disk
/// Return 0
/// End Function
/// End Class
/// </code>
/// </example>
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
public class ManagementObjectCollection : ICollection, IEnumerable, IDisposable
{
private static readonly string name = typeof(ManagementObjectCollection).FullName;
//fields
internal ManagementScope scope;
internal EnumerationOptions options;
private IEnumWbemClassObject enumWbem; //holds WMI enumerator for this collection
private bool isDisposed = false;
//internal IWbemServices GetIWbemServices () {
// return scope.GetIWbemServices ();
//}
//internal ConnectionOptions Connection {
// get { return scope.Connection; }
//}
//Constructor
internal ManagementObjectCollection(
ManagementScope scope,
EnumerationOptions options,
IEnumWbemClassObject enumWbem)
{
if (null != options)
this.options = (EnumerationOptions) options.Clone();
else
this.options = new EnumerationOptions ();
if (null != scope)
this.scope = (ManagementScope)scope.Clone ();
else
this.scope = ManagementScope._Clone(null);
this.enumWbem = enumWbem;
}
/// <summary>
/// <para>Disposes of resources the object is holding. This is the destructor for the object.</para>
/// </summary>
~ManagementObjectCollection ()
{
Dispose ( false );
}
/// <summary>
/// Releases resources associated with this object. After this
/// method has been called, an attempt to use this object will
/// result in an ObjectDisposedException being thrown.
/// </summary>
public void Dispose ()
{
if (!isDisposed)
{
Dispose ( true ) ;
}
}
private void Dispose ( bool disposing )
{
if ( disposing )
{
GC.SuppressFinalize (this);
isDisposed = true;
}
Marshal.ReleaseComObject (enumWbem);
}
//
//ICollection properties & methods
//
/// <summary>
/// <para>Represents the number of objects in the collection.</para>
/// </summary>
/// <value>
/// <para>The number of objects in the collection.</para>
/// </value>
/// <remarks>
/// <para>This property is very expensive - it requires that
/// all members of the collection be enumerated.</para>
/// </remarks>
public int Count
{
get
{
if (isDisposed)
throw new ObjectDisposedException(name);
//
// [Whidbey RAID (marioh) : 27063]
// See bug for more detailed comment. We can not use foreach since it
// _always_ calls Dispose on the collection invalidating the IEnumWbemClassObject
// pointers.
// We fi this by doing a manual walk of the collection.
//
int count = 0;
IEnumerator enumCol = this.GetEnumerator ( ) ;
while ( enumCol.MoveNext() == true )
{
count++ ;
}
return count ;
}
}
/// <summary>
/// <para>Represents whether the object is synchronized.</para>
/// </summary>
/// <value>
/// <para><see langword='true'/>, if the object is synchronized;
/// otherwise, <see langword='false'/>.</para>
/// </value>
public bool IsSynchronized
{
get
{
if (isDisposed)
throw new ObjectDisposedException(name);
return false;
}
}
/// <summary>
/// <para>Represents the object to be used for synchronization.</para>
/// </summary>
/// <value>
/// <para> The object to be used for synchronization.</para>
/// </value>
public Object SyncRoot
{
get
{
if (isDisposed)
throw new ObjectDisposedException(name);
return this;
}
}
/// <overload>
/// Copies the collection to an array.
/// </overload>
/// <summary>
/// <para> Copies the collection to an array.</para>
/// </summary>
/// <param name='array'>An array to copy to. </param>
/// <param name='index'>The index to start from. </param>
public void CopyTo (Array array, Int32 index)
{
if (isDisposed)
throw new ObjectDisposedException(name);
if (null == array)
throw new ArgumentNullException ("array");
if ((index < array.GetLowerBound (0)) || (index > array.GetUpperBound(0)))
throw new ArgumentOutOfRangeException ("index");
// Since we don't know the size until we've enumerated
// we'll have to dump the objects in a list first then
// try to copy them in.
int capacity = array.Length - index;
int numObjects = 0;
ArrayList arrList = new ArrayList ();
ManagementObjectEnumerator en = this.GetEnumerator();
ManagementBaseObject obj;
while (en.MoveNext())
{
obj = en.Current;
arrList.Add(obj);
numObjects++;
if (numObjects > capacity)
throw new ArgumentException (null, "index");
}
// If we get here we are OK. Now copy the list to the array
arrList.CopyTo (array, index);
return;
}
/// <summary>
/// <para>Copies the items in the collection to a <see cref='System.Management.ManagementBaseObject'/>
/// array.</para>
/// </summary>
/// <param name='objectCollection'>The target array.</param>
/// <param name=' index'>The index to start from.</param>
public void CopyTo (ManagementBaseObject[] objectCollection, Int32 index)
{
CopyTo ((Array)objectCollection, index);
}
//
//IEnumerable methods
//
//****************************************
//GetEnumerator
//****************************************
/// <summary>
/// <para>Returns the enumerator for the collection. If the collection was retrieved from an operation that
/// specified the EnumerationOptions.Rewindable = false only one iteration through this enumerator is allowed.
/// Note that this applies to using the Count property of the collection as well since an iteration over the collection
/// is required. Due to this, code using the Count property should never specify EnumerationOptions.Rewindable = false.
/// </para>
/// </summary>
/// <returns>
/// An <see cref='System.Collections.IEnumerator'/>that can be used to iterate through the
/// collection.
/// </returns>
public ManagementObjectEnumerator GetEnumerator()
{
if (isDisposed)
throw new ObjectDisposedException(name);
//
// [Everett SP1 (marioh) : 149274]
// The crux of the problem with this bug is that we we do not clone the enumerator
// if its the first enumerator. If it is the first enumerator we pass the reference
// to the enumerator implementation rather than a clone. If the enumerator is used
// from within a foreach statement in the client code, the foreach statement will
// dec the ref count on the reference which also happens to be the reference to the
// original enumerator causing subsequent uses of the collection to fail.
// The fix is to always clone the enumerator (assuming its a rewindable enumerator)
// to avoid invalidating the collection.
//
// If its a forward only enumerator we simply pass back the original enumerator (i.e.
// not cloned) and if it gets disposed we end up throwing the next time its used. Essentially,
// the enumerator becomes the collection.
//
// Unless this is the first enumerator, we have
// to clone. This may throw if we are non-rewindable.
if ( this.options.Rewindable == true )
{
IEnumWbemClassObject enumWbemClone = null;
int status = (int)ManagementStatus.NoError;
try
{
status = scope.GetSecuredIEnumWbemClassObjectHandler(enumWbem ).Clone_( ref enumWbemClone);
if ((status & 0x80000000) == 0)
{
//since the original enumerator might not be reset, we need
//to reset the new one.
status = scope.GetSecuredIEnumWbemClassObjectHandler(enumWbemClone ).Reset_( );
}
}
catch (COMException e)
{
ManagementException.ThrowWithExtendedInfo (e);
}
if ((status & 0xfffff000) == 0x80041000)
{
//
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
}
else if ((status & 0x80000000) != 0)
{
//
Marshal.ThrowExceptionForHR(status);
}
return new ManagementObjectEnumerator (this, enumWbemClone);
}
else
{
//
// Notice that we use the original enumerator and hence enum position is retained.
// For example, if the client code manually walked half the collection and then
// used a foreach statement, the foreach statement would continue from where the
// manual walk ended.
//
return new ManagementObjectEnumerator(this, enumWbem);
}
}
/// <internalonly/>
/// <summary>
/// <para>Returns an enumerator that can iterate through a collection.</para>
/// </summary>
/// <returns>
/// An <see cref='System.Collections.IEnumerator'/> that can be used to iterate
/// through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator ();
}
//
// ManagementObjectCollection methods
//
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
/// <summary>
/// <para>Represents the enumerator on the collection.</para>
/// </summary>
/// <example>
/// <code lang='C#'>using System;
/// using System.Management;
///
/// // This example demonstrates how to enumerate all logical disks
/// // using the ManagementObjectEnumerator object.
/// class Sample_ManagementObjectEnumerator
/// {
/// public static int Main(string[] args) {
/// ManagementClass diskClass = new ManagementClass("Win32_LogicalDisk");
/// ManagementObjectCollection disks = diskClass.GetInstances();
/// ManagementObjectCollection.ManagementObjectEnumerator disksEnumerator =
/// disks.GetEnumerator();
/// while(disksEnumerator.MoveNext()) {
/// ManagementObject disk = (ManagementObject)disksEnumerator.Current;
/// Console.WriteLine("Disk found: " + disk["deviceid"]);
/// }
/// return 0;
/// }
/// }
/// </code>
/// <code lang='VB'>Imports System
/// Imports System.Management
/// ' This sample demonstrates how to enumerate all logical disks
/// ' using ManagementObjectEnumerator object.
/// Class Sample_ManagementObjectEnumerator
/// Overloads Public Shared Function Main(args() As String) As Integer
/// Dim diskClass As New ManagementClass("Win32_LogicalDisk")
/// Dim disks As ManagementObjectCollection = diskClass.GetInstances()
/// Dim disksEnumerator As _
/// ManagementObjectCollection.ManagementObjectEnumerator = _
/// disks.GetEnumerator()
/// While disksEnumerator.MoveNext()
/// Dim disk As ManagementObject = _
/// CType(disksEnumerator.Current, ManagementObject)
/// Console.WriteLine("Disk found: " & disk("deviceid"))
/// End While
/// Return 0
/// End Function
/// End Class
/// </code>
/// </example>
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
public class ManagementObjectEnumerator : IEnumerator, IDisposable
{
private static readonly string name = typeof(ManagementObjectEnumerator).FullName;
private IEnumWbemClassObject enumWbem;
private ManagementObjectCollection collectionObject;
private uint cachedCount; //says how many objects are in the enumeration cache (when using BlockSize option)
private int cacheIndex; //used to walk the enumeration cache
private IWbemClassObjectFreeThreaded[] cachedObjects; //points to objects currently available in enumeration cache
private bool atEndOfCollection;
private bool isDisposed = false;
//constructor
internal ManagementObjectEnumerator(
ManagementObjectCollection collectionObject,
IEnumWbemClassObject enumWbem)
{
this.enumWbem = enumWbem;
this.collectionObject = collectionObject;
cachedObjects = new IWbemClassObjectFreeThreaded[collectionObject.options.BlockSize];
cachedCount = 0;
cacheIndex = -1; // Reset position
atEndOfCollection = false;
}
/// <summary>
/// <para>Disposes of resources the object is holding. This is the destructor for the object.</para>
/// </summary>
~ManagementObjectEnumerator ()
{
Dispose ();
}
/// <summary>
/// Releases resources associated with this object. After this
/// method has been called, an attempt to use this object will
/// result in an ObjectDisposedException being thrown.
/// </summary>
public void Dispose ()
{
if (!isDisposed)
{
if (null != enumWbem)
{
Marshal.ReleaseComObject (enumWbem);
enumWbem = null;
}
cachedObjects = null;
// DO NOT dispose of collectionObject. It is merely a reference - its lifetime
// exceeds that of this object. If collectionObject.Dispose was to be done here,
// a reference count would be needed.
//
collectionObject = null;
isDisposed = true;
GC.SuppressFinalize (this);
}
}
/// <summary>
/// <para>Gets the current <see cref='System.Management.ManagementBaseObject'/> that this enumerator points
/// to.</para>
/// </summary>
/// <value>
/// <para>The current object in the enumeration.</para>
/// </value>
public ManagementBaseObject Current
{
get
{
if (isDisposed)
throw new ObjectDisposedException(name);
if (cacheIndex < 0)
throw new InvalidOperationException();
return ManagementBaseObject.GetBaseObject (cachedObjects[cacheIndex],
collectionObject.scope);
}
}
/// <internalonly/>
/// <summary>
/// <para>Returns the current object in the enumeration.</para>
/// </summary>
/// <value>
/// <para>The current object in the enumeration.</para>
/// </value>
object IEnumerator.Current
{
get
{
return Current;
}
}
//****************************************
//MoveNext
//****************************************
/// <summary>
/// Indicates whether the enumerator has moved to
/// the next object in the enumeration.
/// </summary>
/// <returns>
/// <para><see langword='true'/>, if the enumerator was
/// successfully advanced to the next element; <see langword='false'/> if the enumerator has
/// passed the end of the collection.</para>
/// </returns>
public bool MoveNext ()
{
if (isDisposed)
throw new ObjectDisposedException(name);
//If there are no more objects in the collection return false
if (atEndOfCollection)
return false;
//Look for the next object
cacheIndex++;
if ((cachedCount - cacheIndex) == 0) //cache is empty - need to get more objects
{
//If the timeout is set to infinite, need to use the WMI infinite constant
int timeout = (collectionObject.options.Timeout.Ticks == Int64.MaxValue) ?
(int)tag_WBEM_TIMEOUT_TYPE.WBEM_INFINITE : (int)collectionObject.options.Timeout.TotalMilliseconds;
//Get the next [BLockSize] objects within the specified timeout
//
SecurityHandler securityHandler = collectionObject.scope.GetSecurityHandler();
//Because Interop doesn't support custom marshalling for arrays, we have to use
//the "DoNotMarshal" objects in the interop and then convert to the "FreeThreaded"
//counterparts afterwards.
IWbemClassObject_DoNotMarshal[] tempArray = new IWbemClassObject_DoNotMarshal[collectionObject.options.BlockSize];
int status = collectionObject.scope.GetSecuredIEnumWbemClassObjectHandler(enumWbem ).Next_(timeout, (uint)collectionObject.options.BlockSize,tempArray, ref cachedCount);
securityHandler.Reset();
if (status >= 0)
{
//Convert results and put them in cache.
for (int i = 0; i < cachedCount; i++)
{
cachedObjects[i] = new IWbemClassObjectFreeThreaded
(
Marshal.GetIUnknownForObject(tempArray[i])
);
}
}
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status);
}
else
{
//If there was a timeout and no object can be returned we throw a timeout exception...
// -
if ((status == (int)tag_WBEMSTATUS.WBEM_S_TIMEDOUT) && (cachedCount == 0))
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
//If not timeout and no objects were returned - we're at the end of the collection
if ((status == (int)tag_WBEMSTATUS.WBEM_S_FALSE) && (cachedCount == 0))
{
atEndOfCollection = true;
cacheIndex--; //back to last object
/* This call to Dispose is being removed as per discussion with URT people and the newly supported
* Dispose() call in the foreach implementation itself.
*
* //Release the COM object (so that the user doesn't have to)
Dispose();
*/
return false;
}
}
cacheIndex = 0;
}
return true;
}
//****************************************
//Reset
//****************************************
/// <summary>
/// <para>Resets the enumerator to the beginning of the collection.</para>
/// </summary>
public void Reset ()
{
if (isDisposed)
throw new ObjectDisposedException(name);
//If the collection is not rewindable you can't do this
if (!collectionObject.options.Rewindable)
throw new InvalidOperationException();
else
{
//Reset the WMI enumerator
SecurityHandler securityHandler = collectionObject.scope.GetSecurityHandler();
int status = (int)ManagementStatus.NoError;
try
{
status = collectionObject.scope.GetSecuredIEnumWbemClassObjectHandler(enumWbem).Reset_();
}
catch (COMException e)
{
//
ManagementException.ThrowWithExtendedInfo (e);
}
finally
{
securityHandler.Reset ();
}
if ((status & 0xfffff000) == 0x80041000)
{
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
}
else if ((status & 0x80000000) != 0)
{
Marshal.ThrowExceptionForHR(status);
}
//Flush the current enumeration cache
for (int i=(cacheIndex >= 0 ? cacheIndex : 0); i<cachedCount; i++)
Marshal.ReleaseComObject((IWbemClassObject_DoNotMarshal)(Marshal.GetObjectForIUnknown(cachedObjects[i])));
cachedCount = 0;
cacheIndex = -1;
atEndOfCollection = false;
}
}
} //ManagementObjectEnumerator class
} //ManagementObjectCollection class
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Cloud.OsConfig.V1
{
/// <summary>Resource name for the <c>Instance</c> resource.</summary>
public sealed partial class InstanceName : gax::IResourceName, sys::IEquatable<InstanceName>
{
/// <summary>The possible contents of <see cref="InstanceName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/zones/{zone}/instances/{instance}</c>.
/// </summary>
ProjectZoneInstance = 1,
/// <summary>
/// A resource name with pattern <c>projects/{project}/locations/{location}/instances/{instance}</c>.
/// </summary>
ProjectLocationInstance = 2,
}
private static gax::PathTemplate s_projectZoneInstance = new gax::PathTemplate("projects/{project}/zones/{zone}/instances/{instance}");
private static gax::PathTemplate s_projectLocationInstance = new gax::PathTemplate("projects/{project}/locations/{location}/instances/{instance}");
/// <summary>Creates a <see cref="InstanceName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="InstanceName"/> containing the provided <paramref name="unparsedResourceName"/>
/// .
/// </returns>
public static InstanceName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new InstanceName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="InstanceName"/> with the pattern
/// <c>projects/{project}/zones/{zone}/instances/{instance}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="zoneId">The <c>Zone</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="InstanceName"/> constructed from the provided ids.</returns>
public static InstanceName FromProjectZoneInstance(string projectId, string zoneId, string instanceId) =>
new InstanceName(ResourceNameType.ProjectZoneInstance, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), zoneId: gax::GaxPreconditions.CheckNotNullOrEmpty(zoneId, nameof(zoneId)), instanceId: gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId)));
/// <summary>
/// Creates a <see cref="InstanceName"/> with the pattern
/// <c>projects/{project}/locations/{location}/instances/{instance}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="InstanceName"/> constructed from the provided ids.</returns>
public static InstanceName FromProjectLocationInstance(string projectId, string locationId, string instanceId) =>
new InstanceName(ResourceNameType.ProjectLocationInstance, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), instanceId: gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="InstanceName"/> with pattern
/// <c>projects/{project}/zones/{zone}/instances/{instance}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="zoneId">The <c>Zone</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="InstanceName"/> with pattern
/// <c>projects/{project}/zones/{zone}/instances/{instance}</c>.
/// </returns>
public static string Format(string projectId, string zoneId, string instanceId) =>
FormatProjectZoneInstance(projectId, zoneId, instanceId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="InstanceName"/> with pattern
/// <c>projects/{project}/zones/{zone}/instances/{instance}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="zoneId">The <c>Zone</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="InstanceName"/> with pattern
/// <c>projects/{project}/zones/{zone}/instances/{instance}</c>.
/// </returns>
public static string FormatProjectZoneInstance(string projectId, string zoneId, string instanceId) =>
s_projectZoneInstance.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(zoneId, nameof(zoneId)), gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="InstanceName"/> with pattern
/// <c>projects/{project}/locations/{location}/instances/{instance}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="InstanceName"/> with pattern
/// <c>projects/{project}/locations/{location}/instances/{instance}</c>.
/// </returns>
public static string FormatProjectLocationInstance(string projectId, string locationId, string instanceId) =>
s_projectLocationInstance.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId)));
/// <summary>Parses the given resource name string into a new <see cref="InstanceName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/zones/{zone}/instances/{instance}</c></description></item>
/// <item><description><c>projects/{project}/locations/{location}/instances/{instance}</c></description></item>
/// </list>
/// </remarks>
/// <param name="instanceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="InstanceName"/> if successful.</returns>
public static InstanceName Parse(string instanceName) => Parse(instanceName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="InstanceName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/zones/{zone}/instances/{instance}</c></description></item>
/// <item><description><c>projects/{project}/locations/{location}/instances/{instance}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="instanceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="InstanceName"/> if successful.</returns>
public static InstanceName Parse(string instanceName, bool allowUnparsed) =>
TryParse(instanceName, allowUnparsed, out InstanceName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="InstanceName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/zones/{zone}/instances/{instance}</c></description></item>
/// <item><description><c>projects/{project}/locations/{location}/instances/{instance}</c></description></item>
/// </list>
/// </remarks>
/// <param name="instanceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="InstanceName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string instanceName, out InstanceName result) => TryParse(instanceName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="InstanceName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/zones/{zone}/instances/{instance}</c></description></item>
/// <item><description><c>projects/{project}/locations/{location}/instances/{instance}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="instanceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="InstanceName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string instanceName, bool allowUnparsed, out InstanceName result)
{
gax::GaxPreconditions.CheckNotNull(instanceName, nameof(instanceName));
gax::TemplatedResourceName resourceName;
if (s_projectZoneInstance.TryParseName(instanceName, out resourceName))
{
result = FromProjectZoneInstance(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (s_projectLocationInstance.TryParseName(instanceName, out resourceName))
{
result = FromProjectLocationInstance(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(instanceName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private InstanceName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string instanceId = null, string locationId = null, string projectId = null, string zoneId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
InstanceId = instanceId;
LocationId = locationId;
ProjectId = projectId;
ZoneId = zoneId;
}
/// <summary>
/// Constructs a new instance of a <see cref="InstanceName"/> class from the component parts of pattern
/// <c>projects/{project}/zones/{zone}/instances/{instance}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="zoneId">The <c>Zone</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param>
public InstanceName(string projectId, string zoneId, string instanceId) : this(ResourceNameType.ProjectZoneInstance, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), zoneId: gax::GaxPreconditions.CheckNotNullOrEmpty(zoneId, nameof(zoneId)), instanceId: gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Instance</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string InstanceId { get; }
/// <summary>
/// The <c>Location</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Zone</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string ZoneId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectZoneInstance: return s_projectZoneInstance.Expand(ProjectId, ZoneId, InstanceId);
case ResourceNameType.ProjectLocationInstance: return s_projectLocationInstance.Expand(ProjectId, LocationId, InstanceId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as InstanceName);
/// <inheritdoc/>
public bool Equals(InstanceName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(InstanceName a, InstanceName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(InstanceName a, InstanceName b) => !(a == b);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: Allows developers to view the base data types as
** an arbitrary array of bits.
**
**
===========================================================*/
namespace System {
using System;
using System.Runtime.CompilerServices;
using System.Diagnostics.Contracts;
using System.Security;
// The BitConverter class contains methods for
// converting an array of bytes to one of the base data
// types, as well as for converting a base data type to an
// array of bytes.
//
// Only statics, does not need to be marked with the serializable attribute
public static class BitConverter {
// This field indicates the "endianess" of the architecture.
// The value is set to true if the architecture is
// little endian; false if it is big endian.
#if BIGENDIAN
public static readonly bool IsLittleEndian /* = false */;
#else
public static readonly bool IsLittleEndian = true;
#endif
// Converts a byte into an array of bytes with length one.
public static byte[] GetBytes(bool value) {
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 1);
byte[] r = new byte[1];
r[0] = (value ? (byte)Boolean.True : (byte)Boolean.False );
return r;
}
// Converts a char into an array of bytes with length two.
public static byte[] GetBytes(char value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 2);
return GetBytes((short)value);
}
// Converts a short into an array of bytes with length
// two.
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe static byte[] GetBytes(short value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 2);
byte[] bytes = new byte[2];
fixed(byte* b = bytes)
*((short*)b) = value;
return bytes;
}
// Converts an int into an array of bytes with length
// four.
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe static byte[] GetBytes(int value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 4);
byte[] bytes = new byte[4];
fixed(byte* b = bytes)
*((int*)b) = value;
return bytes;
}
// Converts a long into an array of bytes with length
// eight.
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe static byte[] GetBytes(long value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 8);
byte[] bytes = new byte[8];
fixed(byte* b = bytes)
*((long*)b) = value;
return bytes;
}
// Converts an ushort into an array of bytes with
// length two.
[CLSCompliant(false)]
public static byte[] GetBytes(ushort value) {
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 2);
return GetBytes((short)value);
}
// Converts an uint into an array of bytes with
// length four.
[CLSCompliant(false)]
public static byte[] GetBytes(uint value) {
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 4);
return GetBytes((int)value);
}
// Converts an unsigned long into an array of bytes with
// length eight.
[CLSCompliant(false)]
public static byte[] GetBytes(ulong value) {
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 8);
return GetBytes((long)value);
}
// Converts a float into an array of bytes with length
// four.
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe static byte[] GetBytes(float value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 4);
return GetBytes(*(int*)&value);
}
// Converts a double into an array of bytes with length
// eight.
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe static byte[] GetBytes(double value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 8);
return GetBytes(*(long*)&value);
}
// Converts an array of bytes into a char.
public static char ToChar(byte[] value, int startIndex)
{
if (value == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
}
if ((uint)startIndex >= value.Length) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
}
if (startIndex > value.Length - 2) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
Contract.EndContractBlock();
return (char)ToInt16(value, startIndex);
}
// Converts an array of bytes into a short.
[System.Security.SecuritySafeCritical] // auto-generated
public static unsafe short ToInt16(byte[] value, int startIndex) {
if( value == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
}
if ((uint) startIndex >= value.Length) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
}
if (startIndex > value.Length -2) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
Contract.EndContractBlock();
fixed( byte * pbyte = &value[startIndex]) {
if( startIndex % 2 == 0) { // data is aligned
return *((short *) pbyte);
}
else {
if( IsLittleEndian) {
return (short)((*pbyte) | (*(pbyte + 1) << 8)) ;
}
else {
return (short)((*pbyte << 8) | (*(pbyte + 1)));
}
}
}
}
// Converts an array of bytes into an int.
[System.Security.SecuritySafeCritical] // auto-generated
public static unsafe int ToInt32 (byte[] value, int startIndex) {
if( value == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
}
if ((uint) startIndex >= value.Length) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
}
if (startIndex > value.Length -4) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
Contract.EndContractBlock();
fixed( byte * pbyte = &value[startIndex]) {
if( startIndex % 4 == 0) { // data is aligned
return *((int *) pbyte);
}
else {
if( IsLittleEndian) {
return (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24);
}
else {
return (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3));
}
}
}
}
// Converts an array of bytes into a long.
[System.Security.SecuritySafeCritical] // auto-generated
public static unsafe long ToInt64 (byte[] value, int startIndex) {
if (value == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
}
if ((uint) startIndex >= value.Length) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
}
if (startIndex > value.Length -8) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
Contract.EndContractBlock();
fixed( byte * pbyte = &value[startIndex]) {
if( startIndex % 8 == 0) { // data is aligned
return *((long *) pbyte);
}
else {
if( IsLittleEndian) {
int i1 = (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24);
int i2 = (*(pbyte+4)) | (*(pbyte + 5) << 8) | (*(pbyte + 6) << 16) | (*(pbyte + 7) << 24);
return (uint)i1 | ((long)i2 << 32);
}
else {
int i1 = (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3));
int i2 = (*(pbyte+4) << 24) | (*(pbyte + 5) << 16) | (*(pbyte + 6) << 8) | (*(pbyte + 7));
return (uint)i2 | ((long)i1 << 32);
}
}
}
}
// Converts an array of bytes into an ushort.
//
[CLSCompliant(false)]
public static ushort ToUInt16(byte[] value, int startIndex)
{
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
if ((uint)startIndex >= value.Length)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
if (startIndex > value.Length - 2)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
Contract.EndContractBlock();
return (ushort)ToInt16(value, startIndex);
}
// Converts an array of bytes into an uint.
//
[CLSCompliant(false)]
public static uint ToUInt32(byte[] value, int startIndex)
{
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
if ((uint)startIndex >= value.Length)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
if (startIndex > value.Length - 4)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
Contract.EndContractBlock();
return (uint)ToInt32(value, startIndex);
}
// Converts an array of bytes into an unsigned long.
//
[CLSCompliant(false)]
public static ulong ToUInt64(byte[] value, int startIndex)
{
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
if ((uint)startIndex >= value.Length)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
if (startIndex > value.Length - 8)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
Contract.EndContractBlock();
return (ulong)ToInt64(value, startIndex);
}
// Converts an array of bytes into a float.
[System.Security.SecuritySafeCritical] // auto-generated
unsafe public static float ToSingle (byte[] value, int startIndex)
{
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
if ((uint)startIndex >= value.Length)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
if (startIndex > value.Length - 4)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
Contract.EndContractBlock();
int val = ToInt32(value, startIndex);
return *(float*)&val;
}
// Converts an array of bytes into a double.
[System.Security.SecuritySafeCritical] // auto-generated
unsafe public static double ToDouble (byte[] value, int startIndex)
{
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
if ((uint)startIndex >= value.Length)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
if (startIndex > value.Length - 8)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
Contract.EndContractBlock();
long val = ToInt64(value, startIndex);
return *(double*)&val;
}
private static char GetHexValue(int i) {
Contract.Assert( i >=0 && i <16, "i is out of range.");
if (i<10) {
return (char)(i + '0');
}
return (char)(i - 10 + 'A');
}
// Converts an array of bytes into a String.
public static String ToString (byte[] value, int startIndex, int length) {
if (value == null) {
throw new ArgumentNullException("value");
}
if (startIndex < 0 || startIndex >= value.Length && startIndex > 0) { // Don't throw for a 0 length array.
throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
}
if (length < 0) {
throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
}
if (startIndex > value.Length - length) {
throw new ArgumentException(Environment.GetResourceString("Arg_ArrayPlusOffTooSmall"));
}
Contract.EndContractBlock();
if (length == 0) {
return string.Empty;
}
if (length > (Int32.MaxValue / 3)) {
// (Int32.MaxValue / 3) == 715,827,882 Bytes == 699 MB
throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_LengthTooLarge", (Int32.MaxValue / 3)));
}
int chArrayLength = length * 3;
char[] chArray = new char[chArrayLength];
int i = 0;
int index = startIndex;
for (i = 0; i < chArrayLength; i += 3) {
byte b = value[index++];
chArray[i]= GetHexValue(b/16);
chArray[i+1] = GetHexValue(b%16);
chArray[i+2] = '-';
}
// We don't need the last '-' character
return new String(chArray, 0, chArray.Length - 1);
}
// Converts an array of bytes into a String.
public static String ToString(byte [] value) {
if (value == null)
throw new ArgumentNullException("value");
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
return ToString(value, 0, value.Length);
}
// Converts an array of bytes into a String.
public static String ToString (byte [] value, int startIndex) {
if (value == null)
throw new ArgumentNullException("value");
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
return ToString(value, startIndex, value.Length - startIndex);
}
/*==================================ToBoolean===================================
**Action: Convert an array of bytes to a boolean value. We treat this array
** as if the first 4 bytes were an Int4 an operate on this value.
**Returns: True if the Int4 value of the first 4 bytes is non-zero.
**Arguments: value -- The byte array
** startIndex -- The position within the array.
**Exceptions: See ToInt4.
==============================================================================*/
// Converts an array of bytes into a boolean.
public static bool ToBoolean(byte[] value, int startIndex) {
if (value==null)
throw new ArgumentNullException("value");
if (startIndex < 0)
throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (startIndex > value.Length - 1)
throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
return (value[startIndex]==0)?false:true;
}
[SecuritySafeCritical]
public static unsafe long DoubleToInt64Bits(double value) {
return *((long *)&value);
}
[SecuritySafeCritical]
public static unsafe double Int64BitsToDouble(long value) {
return *((double*)&value);
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Layouts
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Text;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.LayoutRenderers;
/// <summary>
/// Represents a string with embedded placeholders that can render contextual information.
/// </summary>
/// <remarks>
/// <para>
/// This layout is not meant to be used explicitly. Instead you can just use a string containing layout
/// renderers everywhere the layout is required.
/// </para>
/// <a href="https://github.com/NLog/NLog/wiki/SimpleLayout">See NLog Wiki</a>
/// </remarks>
/// <seealso href="https://github.com/NLog/NLog/wiki/SimpleLayout">Documentation on NLog Wiki</seealso>
[Layout("SimpleLayout")]
[ThreadAgnostic]
[AppDomainFixedOutput]
public class SimpleLayout : Layout, IUsesStackTrace
{
private string _fixedText;
private string _layoutText;
private IRawValue _rawValueRenderer;
private IStringValueRenderer _stringValueRenderer;
private readonly ConfigurationItemFactory _configurationItemFactory;
/// <summary>
/// Initializes a new instance of the <see cref="SimpleLayout" /> class.
/// </summary>
public SimpleLayout()
: this(string.Empty)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SimpleLayout" /> class.
/// </summary>
/// <param name="txt">The layout string to parse.</param>
public SimpleLayout([Localizable(false)] string txt)
: this(txt, ConfigurationItemFactory.Default)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SimpleLayout"/> class.
/// </summary>
/// <param name="txt">The layout string to parse.</param>
/// <param name="configurationItemFactory">The NLog factories to use when creating references to layout renderers.</param>
public SimpleLayout([Localizable(false)] string txt, ConfigurationItemFactory configurationItemFactory)
:this(txt, configurationItemFactory, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SimpleLayout"/> class.
/// </summary>
/// <param name="txt">The layout string to parse.</param>
/// <param name="configurationItemFactory">The NLog factories to use when creating references to layout renderers.</param>
/// <param name="throwConfigExceptions">Whether <see cref="NLogConfigurationException"/> should be thrown on parse errors.</param>
internal SimpleLayout([Localizable(false)] string txt, ConfigurationItemFactory configurationItemFactory, bool? throwConfigExceptions)
{
_configurationItemFactory = configurationItemFactory;
SetLayoutText(txt, throwConfigExceptions);
}
internal SimpleLayout(LayoutRenderer[] renderers, [Localizable(false)] string text, ConfigurationItemFactory configurationItemFactory)
{
_configurationItemFactory = configurationItemFactory;
OriginalText = text;
SetLayoutRenderers(renderers, text);
}
/// <summary>
/// Original text before compile to Layout renderes
/// </summary>
public string OriginalText { get; private set; }
/// <summary>
/// Gets or sets the layout text.
/// </summary>
/// <docgen category='Layout Options' order='10' />
public string Text
{
get => _layoutText;
set => SetLayoutText(value);
}
private void SetLayoutText(string value, bool? throwConfigExceptions = null)
{
OriginalText = value;
var renderers = LayoutParser.CompileLayout(value, _configurationItemFactory, throwConfigExceptions, out var txt);
SetLayoutRenderers(renderers, txt);
}
/// <summary>
/// Is the message fixed? (no Layout renderers used)
/// </summary>
public bool IsFixedText => _fixedText != null;
/// <summary>
/// Get the fixed text. Only set when <see cref="IsFixedText"/> is <c>true</c>
/// </summary>
public string FixedText => _fixedText;
/// <summary>
/// Is the message a simple formatted string? (Can skip StringBuilder)
/// </summary>
internal bool IsSimpleStringText => _stringValueRenderer != null;
/// <summary>
/// Gets a collection of <see cref="LayoutRenderer"/> objects that make up this layout.
/// </summary>
[NLogConfigurationIgnoreProperty]
public ReadOnlyCollection<LayoutRenderer> Renderers => _renderers ?? (_renderers = new ReadOnlyCollection<LayoutRenderer>(_layoutRenderers));
private ReadOnlyCollection<LayoutRenderer> _renderers;
private LayoutRenderer[] _layoutRenderers;
/// <summary>
/// Gets a collection of <see cref="LayoutRenderer"/> objects that make up this layout.
/// </summary>
public IEnumerable<LayoutRenderer> LayoutRenderers => _layoutRenderers;
/// <summary>
/// Gets the level of stack trace information required for rendering.
/// </summary>
public new StackTraceUsage StackTraceUsage => base.StackTraceUsage;
/// <summary>
/// Converts a text to a simple layout.
/// </summary>
/// <param name="text">Text to be converted.</param>
/// <returns>A <see cref="SimpleLayout"/> object.</returns>
public static implicit operator SimpleLayout([Localizable(false)] string text)
{
if (text is null) return null;
return new SimpleLayout(text);
}
/// <summary>
/// Escapes the passed text so that it can
/// be used literally in all places where
/// layout is normally expected without being
/// treated as layout.
/// </summary>
/// <param name="text">The text to be escaped.</param>
/// <returns>The escaped text.</returns>
/// <remarks>
/// Escaping is done by replacing all occurrences of
/// '${' with '${literal:text=${}'
/// </remarks>
public static string Escape([Localizable(false)] string text)
{
return text.Replace("${", @"${literal:text=\$\{}");
}
/// <summary>
/// Evaluates the specified text by expanding all layout renderers.
/// </summary>
/// <param name="text">The text to be evaluated.</param>
/// <param name="logEvent">Log event to be used for evaluation.</param>
/// <returns>The input text with all occurrences of ${} replaced with
/// values provided by the appropriate layout renderers.</returns>
public static string Evaluate([Localizable(false)] string text, LogEventInfo logEvent)
{
var layout = new SimpleLayout(text);
return layout.Render(logEvent);
}
/// <summary>
/// Evaluates the specified text by expanding all layout renderers
/// in new <see cref="LogEventInfo" /> context.
/// </summary>
/// <param name="text">The text to be evaluated.</param>
/// <returns>The input text with all occurrences of ${} replaced with
/// values provided by the appropriate layout renderers.</returns>
public static string Evaluate([Localizable(false)] string text)
{
return Evaluate(text, LogEventInfo.CreateNullEvent());
}
/// <inheritdoc/>
public override string ToString()
{
if (string.IsNullOrEmpty(Text) && _layoutRenderers.Length > 0)
{
return ToStringWithNestedItems(_layoutRenderers, r => r.ToString());
}
return Text;
}
internal void SetLayoutRenderers(LayoutRenderer[] layoutRenderers, string text)
{
_layoutRenderers = layoutRenderers ?? ArrayHelper.Empty<LayoutRenderer>();
_renderers = null;
_fixedText = null;
_rawValueRenderer = null;
_stringValueRenderer = null;
if (_layoutRenderers.Length == 0)
{
_fixedText = string.Empty;
}
else if (_layoutRenderers.Length == 1)
{
if (_layoutRenderers[0] is LiteralLayoutRenderer renderer)
{
_fixedText = renderer.Text;
}
else if (_layoutRenderers[0] is IStringValueRenderer stringValueRenderer)
{
_stringValueRenderer = stringValueRenderer;
}
if (_layoutRenderers[0] is IRawValue rawValueRenderer)
{
_rawValueRenderer = rawValueRenderer;
}
}
_layoutText = text;
if (LoggingConfiguration != null)
{
PerformObjectScanning();
}
}
/// <inheritdoc/>
protected override void InitializeLayout()
{
for (int i = 0; i < _layoutRenderers.Length; i++)
{
LayoutRenderer renderer = _layoutRenderers[i];
try
{
renderer.Initialize(LoggingConfiguration);
}
catch (Exception exception)
{
//also check IsErrorEnabled, otherwise 'MustBeRethrown' writes it to Error
//check for performance
if (InternalLogger.IsWarnEnabled || InternalLogger.IsErrorEnabled)
{
InternalLogger.Warn(exception, "Exception in '{0}.InitializeLayout()'", renderer.GetType().FullName);
}
if (exception.MustBeRethrown())
{
throw;
}
}
}
base.InitializeLayout();
}
/// <inheritdoc/>
public override void Precalculate(LogEventInfo logEvent)
{
if (!IsLogEventMutableSafe(logEvent))
{
Render(logEvent);
}
}
internal override void PrecalculateBuilder(LogEventInfo logEvent, StringBuilder target)
{
if (!IsLogEventMutableSafe(logEvent))
{
PrecalculateBuilderInternal(logEvent, target);
}
}
private bool IsLogEventMutableSafe(LogEventInfo logEvent)
{
if (_rawValueRenderer != null)
{
try
{
if (!IsInitialized)
{
Initialize(LoggingConfiguration);
}
if (ThreadAgnostic)
{
if (MutableUnsafe)
{
// If raw value doesn't have the ability to mutate, then we can skip precalculate
var success = _rawValueRenderer.TryGetRawValue(logEvent, out var value);
if (success && IsObjectValueMutableSafe(value))
return true;
}
else
{
return true;
}
}
return false;
}
catch (Exception exception)
{
//also check IsErrorEnabled, otherwise 'MustBeRethrown' writes it to Error
//check for performance
if (InternalLogger.IsWarnEnabled || InternalLogger.IsErrorEnabled)
{
InternalLogger.Warn(exception, "Exception in precalculate using '{0}.TryGetRawValue()'", _rawValueRenderer?.GetType());
}
if (exception.MustBeRethrown())
{
throw;
}
}
}
return ThreadAgnostic && !MutableUnsafe;
}
private static bool IsObjectValueMutableSafe(object value)
{
return value != null && (Convert.GetTypeCode(value) != TypeCode.Object || value.GetType().IsValueType());
}
/// <inheritdoc/>
internal override bool TryGetRawValue(LogEventInfo logEvent, out object rawValue)
{
if (_rawValueRenderer != null)
{
try
{
if (!IsInitialized)
{
Initialize(LoggingConfiguration);
}
if ((!ThreadAgnostic || MutableUnsafe) && logEvent.TryGetCachedLayoutValue(this, out _))
{
rawValue = null;
return false; // Raw-Value has been precalculated, so not available
}
var success = _rawValueRenderer.TryGetRawValue(logEvent, out rawValue);
return success;
}
catch (Exception exception)
{
//also check IsErrorEnabled, otherwise 'MustBeRethrown' writes it to Error
//check for performance
if (InternalLogger.IsWarnEnabled || InternalLogger.IsErrorEnabled)
{
InternalLogger.Warn(exception, "Exception in TryGetRawValue using '{0}.TryGetRawValue()'", _rawValueRenderer?.GetType());
}
if (exception.MustBeRethrown())
{
throw;
}
}
}
rawValue = null;
return false;
}
/// <inheritdoc/>
protected override string GetFormattedMessage(LogEventInfo logEvent)
{
if (IsFixedText)
{
return _fixedText;
}
if (_stringValueRenderer != null)
{
try
{
string stringValue = _stringValueRenderer.GetFormattedString(logEvent);
if (stringValue != null)
return stringValue;
_stringValueRenderer = null; // Optimization is not possible
}
catch (Exception exception)
{
//also check IsErrorEnabled, otherwise 'MustBeRethrown' writes it to Error
//check for performance
if (InternalLogger.IsWarnEnabled || InternalLogger.IsErrorEnabled)
{
InternalLogger.Warn(exception, "Exception in '{0}.GetFormattedString()'", _stringValueRenderer?.GetType().FullName);
}
if (exception.MustBeRethrown())
{
throw;
}
}
}
return RenderAllocateBuilder(logEvent);
}
private void RenderAllRenderers(LogEventInfo logEvent, StringBuilder target)
{
//Memory profiling pointed out that using a foreach-loop was allocating
//an Enumerator. Switching to a for-loop avoids the memory allocation.
for (int i = 0; i < _layoutRenderers.Length; i++)
{
LayoutRenderer renderer = _layoutRenderers[i];
try
{
renderer.RenderAppendBuilder(logEvent, target);
}
catch (Exception exception)
{
//also check IsErrorEnabled, otherwise 'MustBeRethrown' writes it to Error
//check for performance
if (InternalLogger.IsWarnEnabled || InternalLogger.IsErrorEnabled)
{
InternalLogger.Warn(exception, "Exception in '{0}.Append()'", renderer.GetType().FullName);
}
if (exception.MustBeRethrown())
{
throw;
}
}
}
}
/// <inheritdoc/>
protected override void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target)
{
if (IsFixedText)
{
target.Append(_fixedText);
return;
}
RenderAllRenderers(logEvent, target);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace CarMarketPlace.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using SharpDX.Mathematics.Interop;
namespace SharpDX.Direct2D1
{
public partial class DeviceContext
{
/// <summary>
/// Initializes a new instance of the <see cref="DeviceContext"/> class.
/// </summary>
/// <param name="surface">The surface.</param>
/// <unmanaged>HRESULT D2D1CreateDeviceContext([In] IDXGISurface* dxgiSurface,[In, Optional] const D2D1_CREATION_PROPERTIES* creationProperties,[Out] ID2D1DeviceContext** d2dDeviceContext)</unmanaged>
public DeviceContext(SharpDX.DXGI.Surface surface)
: base(IntPtr.Zero)
{
D2D1.CreateDeviceContext(surface, null, this);
}
/// <summary>
/// Initializes a new instance of the <see cref="Device"/> class.
/// </summary>
/// <param name="surface">The surface.</param>
/// <param name="creationProperties">The creation properties.</param>
/// <unmanaged>HRESULT D2D1CreateDeviceContext([In] IDXGISurface* dxgiSurface,[In, Optional] const D2D1_CREATION_PROPERTIES* creationProperties,[Out] ID2D1DeviceContext** d2dDeviceContext)</unmanaged>
public DeviceContext(SharpDX.DXGI.Surface surface, CreationProperties creationProperties)
: base(IntPtr.Zero)
{
D2D1.CreateDeviceContext(surface, creationProperties, this);
}
/// <summary>
/// Initializes a new instance of the <see cref="DeviceContext"/> class using an existing <see cref="Device"/>.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="options">The options to be applied to the created device context.</param>
/// <remarks>
/// The new device context will not have a selected target bitmap. The caller must create and select a bitmap as the target surface of the context.
/// </remarks>
/// <unmanaged>HRESULT ID2D1Device::CreateDeviceContext([In] D2D1_DEVICE_CONTEXT_OPTIONS options,[Out] ID2D1DeviceContext** deviceContext)</unmanaged>
public DeviceContext(Device device, DeviceContextOptions options)
: base(IntPtr.Zero)
{
device.CreateDeviceContext(options, this);
}
/// <summary>
/// No documentation.
/// </summary>
/// <param name="effect">No documentation.</param>
/// <param name="targetOffset">No documentation.</param>
/// <param name="interpolationMode">No documentation.</param>
/// <param name="compositeMode">No documentation.</param>
/// <unmanaged>void ID2D1DeviceContext::DrawImage([In] ID2D1Image* image,[In, Optional] const D2D_POINT_2F* targetOffset,[In, Optional] const D2D_RECT_F* imageRectangle,[In] D2D1_INTERPOLATION_MODE interpolationMode,[In] D2D1_COMPOSITE_MODE compositeMode)</unmanaged>
public void DrawImage(SharpDX.Direct2D1.Effect effect, RawVector2 targetOffset, SharpDX.Direct2D1.InterpolationMode interpolationMode = InterpolationMode.Linear, SharpDX.Direct2D1.CompositeMode compositeMode = CompositeMode.SourceOver)
{
using (var output = effect.Output)
DrawImage(output, targetOffset, null, interpolationMode, compositeMode);
}
/// <summary>
/// No documentation.
/// </summary>
/// <param name="effect">No documentation.</param>
/// <param name="interpolationMode">No documentation.</param>
/// <param name="compositeMode">No documentation.</param>
/// <unmanaged>void ID2D1DeviceContext::DrawImage([In] ID2D1Image* image,[In, Optional] const D2D_POINT_2F* targetOffset,[In, Optional] const D2D_RECT_F* imageRectangle,[In] D2D1_INTERPOLATION_MODE interpolationMode,[In] D2D1_COMPOSITE_MODE compositeMode)</unmanaged>
public void DrawImage(SharpDX.Direct2D1.Effect effect, SharpDX.Direct2D1.InterpolationMode interpolationMode = InterpolationMode.Linear, SharpDX.Direct2D1.CompositeMode compositeMode = CompositeMode.SourceOver)
{
using (var output = effect.Output)
DrawImage(output, null, null, interpolationMode, compositeMode);
}
/// <summary>
/// No documentation.
/// </summary>
/// <param name="image">No documentation.</param>
/// <param name="targetOffset">No documentation.</param>
/// <param name="interpolationMode">No documentation.</param>
/// <param name="compositeMode">No documentation.</param>
/// <unmanaged>void ID2D1DeviceContext::DrawImage([In] ID2D1Image* image,[In, Optional] const D2D_POINT_2F* targetOffset,[In, Optional] const D2D_RECT_F* imageRectangle,[In] D2D1_INTERPOLATION_MODE interpolationMode,[In] D2D1_COMPOSITE_MODE compositeMode)</unmanaged>
public void DrawImage(SharpDX.Direct2D1.Image image, RawVector2 targetOffset, SharpDX.Direct2D1.InterpolationMode interpolationMode = InterpolationMode.Linear, SharpDX.Direct2D1.CompositeMode compositeMode = CompositeMode.SourceOver)
{
DrawImage(image, targetOffset, null, interpolationMode, compositeMode);
}
/// <summary>
/// No documentation.
/// </summary>
/// <param name="image">No documentation.</param>
/// <param name="interpolationMode">No documentation.</param>
/// <param name="compositeMode">No documentation.</param>
/// <unmanaged>void ID2D1DeviceContext::DrawImage([In] ID2D1Image* image,[In, Optional] const D2D_POINT_2F* targetOffset,[In, Optional] const D2D_RECT_F* imageRectangle,[In] D2D1_INTERPOLATION_MODE interpolationMode,[In] D2D1_COMPOSITE_MODE compositeMode)</unmanaged>
public void DrawImage(SharpDX.Direct2D1.Image image, SharpDX.Direct2D1.InterpolationMode interpolationMode = InterpolationMode.Linear, SharpDX.Direct2D1.CompositeMode compositeMode = CompositeMode.SourceOver)
{
DrawImage(image, null, null, interpolationMode, compositeMode);
}
/// <summary>
/// Draws the bitmap.
/// </summary>
/// <param name="bitmap">The bitmap.</param>
/// <param name="opacity">The opacity.</param>
/// <param name="interpolationMode">The interpolation mode.</param>
/// <unmanaged>void ID2D1DeviceContext::DrawBitmap([In] ID2D1Bitmap* bitmap,[In, Optional] const D2D_RECT_F* destinationRectangle,[In] float opacity,[In] D2D1_INTERPOLATION_MODE interpolationMode,[In, Optional] const D2D_RECT_F* sourceRectangle,[In, Optional] const D2D_MATRIX_4X4_F* perspectiveTransform)</unmanaged>
public void DrawBitmap(SharpDX.Direct2D1.Bitmap bitmap, float opacity, SharpDX.Direct2D1.InterpolationMode interpolationMode)
{
DrawBitmap(bitmap, null, opacity, interpolationMode, null, null);
}
/// <summary>
/// Draws the bitmap.
/// </summary>
/// <param name="bitmap">The bitmap.</param>
/// <param name="opacity">The opacity.</param>
/// <param name="interpolationMode">The interpolation mode.</param>
/// <param name="perspectiveTransformRef">The perspective transform ref.</param>
/// <unmanaged>void ID2D1DeviceContext::DrawBitmap([In] ID2D1Bitmap* bitmap,[In, Optional] const D2D_RECT_F* destinationRectangle,[In] float opacity,[In] D2D1_INTERPOLATION_MODE interpolationMode,[In, Optional] const D2D_RECT_F* sourceRectangle,[In, Optional] const D2D_MATRIX_4X4_F* perspectiveTransform)</unmanaged>
public void DrawBitmap(SharpDX.Direct2D1.Bitmap bitmap, float opacity, SharpDX.Direct2D1.InterpolationMode interpolationMode, RawMatrix perspectiveTransformRef)
{
DrawBitmap(bitmap, null, opacity, interpolationMode, null, perspectiveTransformRef);
}
/// <summary>
/// Draws the bitmap.
/// </summary>
/// <param name="bitmap">The bitmap.</param>
/// <param name="opacity">The opacity.</param>
/// <param name="interpolationMode">The interpolation mode.</param>
/// <param name="sourceRectangle">The source rectangle.</param>
/// <param name="perspectiveTransformRef">The perspective transform ref.</param>
/// <unmanaged>void ID2D1DeviceContext::DrawBitmap([In] ID2D1Bitmap* bitmap,[In, Optional] const D2D_RECT_F* destinationRectangle,[In] float opacity,[In] D2D1_INTERPOLATION_MODE interpolationMode,[In, Optional] const D2D_RECT_F* sourceRectangle,[In, Optional] const D2D_MATRIX_4X4_F* perspectiveTransform)</unmanaged>
public void DrawBitmap(SharpDX.Direct2D1.Bitmap bitmap, float opacity, SharpDX.Direct2D1.InterpolationMode interpolationMode, RawRectangleF sourceRectangle, RawMatrix perspectiveTransformRef)
{
DrawBitmap(bitmap, null, opacity, interpolationMode, sourceRectangle, perspectiveTransformRef);
}
/// <summary>
/// No documentation.
/// </summary>
/// <param name="layerParameters">No documentation.</param>
/// <param name="layer">No documentation.</param>
/// <unmanaged>void ID2D1DeviceContext::PushLayer([In] const D2D1_LAYER_PARAMETERS1* layerParameters,[In, Optional] ID2D1Layer* layer)</unmanaged>
public void PushLayer(SharpDX.Direct2D1.LayerParameters1 layerParameters, SharpDX.Direct2D1.Layer layer)
{
PushLayer(ref layerParameters, layer);
}
/// <summary>
/// Gets the effect invalid rectangles.
/// </summary>
/// <param name="effect">The effect.</param>
/// <returns></returns>
/// <unmanaged>HRESULT ID2D1DeviceContext::GetEffectInvalidRectangles([In] ID2D1Effect* effect,[Out, Buffer] D2D_RECT_F* rectangles,[In] unsigned int rectanglesCount)</unmanaged>
public RawRectangleF[] GetEffectInvalidRectangles(SharpDX.Direct2D1.Effect effect)
{
var invalidRects = new RawRectangleF[GetEffectInvalidRectangleCount(effect)];
if (invalidRects.Length == 0)
return invalidRects;
GetEffectInvalidRectangles(effect, invalidRects, invalidRects.Length);
return invalidRects;
}
/// <summary>
/// Gets the effect required input rectangles.
/// </summary>
/// <param name="renderEffect">The render effect.</param>
/// <param name="inputDescriptions">The input descriptions.</param>
/// <returns></returns>
/// <unmanaged>HRESULT ID2D1DeviceContext::GetEffectRequiredInputRectangles([In] ID2D1Effect* renderEffect,[In, Optional] const D2D_RECT_F* renderImageRectangle,[In, Buffer] const D2D1_EFFECT_INPUT_DESCRIPTION* inputDescriptions,[Out, Buffer] D2D_RECT_F* requiredInputRects,[In] unsigned int inputCount)</unmanaged>
public RawRectangleF[] GetEffectRequiredInputRectangles(SharpDX.Direct2D1.Effect renderEffect, SharpDX.Direct2D1.EffectInputDescription[] inputDescriptions)
{
var result = new RawRectangleF[inputDescriptions.Length];
GetEffectRequiredInputRectangles(renderEffect, null, inputDescriptions, result, inputDescriptions.Length);
return result;
}
/// <summary>
/// Gets the effect required input rectangles.
/// </summary>
/// <param name="renderEffect">The render effect.</param>
/// <param name="renderImageRectangle">The render image rectangle.</param>
/// <param name="inputDescriptions">The input descriptions.</param>
/// <returns></returns>
/// <unmanaged>HRESULT ID2D1DeviceContext::GetEffectRequiredInputRectangles([In] ID2D1Effect* renderEffect,[In, Optional] const D2D_RECT_F* renderImageRectangle,[In, Buffer] const D2D1_EFFECT_INPUT_DESCRIPTION* inputDescriptions,[Out, Buffer] D2D_RECT_F* requiredInputRects,[In] unsigned int inputCount)</unmanaged>
public RawRectangleF[] GetEffectRequiredInputRectangles(SharpDX.Direct2D1.Effect renderEffect, RawRectangleF renderImageRectangle, SharpDX.Direct2D1.EffectInputDescription[] inputDescriptions)
{
var result = new RawRectangleF[inputDescriptions.Length];
GetEffectRequiredInputRectangles(renderEffect, renderImageRectangle, inputDescriptions, result, inputDescriptions.Length);
return result;
}
/// <summary>
/// No documentation.
/// </summary>
/// <param name="opacityMask">No documentation.</param>
/// <param name="brush">No documentation.</param>
/// <unmanaged>void ID2D1DeviceContext::FillOpacityMask([In] ID2D1Bitmap* opacityMask,[In] ID2D1Brush* brush,[In, Optional] const D2D_RECT_F* destinationRectangle,[In, Optional] const D2D_RECT_F* sourceRectangle)</unmanaged>
public void FillOpacityMask(SharpDX.Direct2D1.Bitmap opacityMask, SharpDX.Direct2D1.Brush brush)
{
FillOpacityMask(opacityMask, brush, null, null);
}
}
}
| |
// ==++==
//
// Copyright(c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
namespace System.Reflection
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Runtime.ConstrainedExecution;
#if FEATURE_REMOTING
using System.Runtime.Remoting.Metadata;
#endif //FEATURE_REMOTING
using System.Runtime.Serialization;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using MemberListType = System.RuntimeType.MemberListType;
#if !MONO
using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
#endif
using System.Runtime.CompilerServices;
[Serializable]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_MethodInfo))]
#pragma warning disable 618
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
#pragma warning restore 618
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class MethodInfo : MethodBase
#if !MOBILE
, _MethodInfo
#endif
{
#region Constructor
protected MethodInfo() { }
#endregion
#if !FEATURE_CORECLR
public static bool operator ==(MethodInfo left, MethodInfo right)
{
if (ReferenceEquals(left, right))
return true;
if ((object)left == null || (object)right == null ||
left is RuntimeMethodInfo || right is RuntimeMethodInfo)
{
return false;
}
return left.Equals(right);
}
public static bool operator !=(MethodInfo left, MethodInfo right)
{
return !(left == right);
}
#endif // !FEATURE_CORECLR
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Method; } }
#endregion
#region Public Abstract\Virtual Members
public virtual Type ReturnType { get { throw new NotImplementedException(); } }
public virtual ParameterInfo ReturnParameter { get { throw new NotImplementedException(); } }
public abstract ICustomAttributeProvider ReturnTypeCustomAttributes { get; }
public abstract MethodInfo GetBaseDefinition();
[System.Runtime.InteropServices.ComVisible(true)]
public override Type[] GetGenericArguments() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }
[System.Runtime.InteropServices.ComVisible(true)]
public virtual MethodInfo GetGenericMethodDefinition() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }
public virtual MethodInfo MakeGenericMethod(params Type[] typeArguments) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }
public virtual Delegate CreateDelegate(Type delegateType) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }
public virtual Delegate CreateDelegate(Type delegateType, Object target) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }
#endregion
#if !FEATURE_CORECLR && !MOBILE
Type _MethodInfo.GetType()
{
return base.GetType();
}
void _MethodInfo.GetTypeInfoCount(out uint pcTInfo)
{
throw new NotImplementedException();
}
void _MethodInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
{
throw new NotImplementedException();
}
void _MethodInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
{
throw new NotImplementedException();
}
// If you implement this method, make sure to include _MethodInfo.Invoke in VM\DangerousAPIs.h and
// include _MethodInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp.
void _MethodInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
{
throw new NotImplementedException();
}
#endif
#if MONO
// TODO: Remove, needed only for MonoCustomAttribute
internal virtual MethodInfo GetBaseMethod ()
{
return this;
}
#endif
}
#if !MONO
[Serializable]
internal sealed class RuntimeMethodInfo : MethodInfo, ISerializable, IRuntimeMethodInfo
{
#region Private Data Members
private IntPtr m_handle;
private RuntimeTypeCache m_reflectedTypeCache;
private string m_name;
private string m_toString;
private ParameterInfo[] m_parameters;
private ParameterInfo m_returnParameter;
private BindingFlags m_bindingFlags;
private MethodAttributes m_methodAttributes;
private Signature m_signature;
private RuntimeType m_declaringType;
private object m_keepalive;
private INVOCATION_FLAGS m_invocationFlags;
#if FEATURE_APPX
private bool IsNonW8PFrameworkAPI()
{
if (m_declaringType.IsArray && IsPublic && !IsStatic)
return false;
RuntimeAssembly rtAssembly = GetRuntimeAssembly();
if (rtAssembly.IsFrameworkAssembly())
{
int ctorToken = rtAssembly.InvocableAttributeCtorToken;
if (System.Reflection.MetadataToken.IsNullToken(ctorToken) ||
!CustomAttribute.IsAttributeDefined(GetRuntimeModule(), MetadataToken, ctorToken))
return true;
}
if (GetRuntimeType().IsNonW8PFrameworkAPI())
return true;
if (IsGenericMethod && !IsGenericMethodDefinition)
{
foreach (Type t in GetGenericArguments())
{
if (((RuntimeType)t).IsNonW8PFrameworkAPI())
return true;
}
}
return false;
}
internal override bool IsDynamicallyInvokable
{
get
{
return !AppDomain.ProfileAPICheck || !IsNonW8PFrameworkAPI();
}
}
#endif
internal INVOCATION_FLAGS InvocationFlags
{
[System.Security.SecuritySafeCritical]
get
{
if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0)
{
INVOCATION_FLAGS invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_UNKNOWN;
Type declaringType = DeclaringType;
//
// first take care of all the NO_INVOKE cases.
if (ContainsGenericParameters ||
ReturnType.IsByRef ||
(declaringType != null && declaringType.ContainsGenericParameters) ||
((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) ||
((Attributes & MethodAttributes.RequireSecObject) == MethodAttributes.RequireSecObject))
{
// We don't need other flags if this method cannot be invoked
invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE;
}
else
{
// this should be an invocable method, determine the other flags that participate in invocation
invocationFlags = RuntimeMethodHandle.GetSecurityFlags(this);
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) == 0)
{
if ( (Attributes & MethodAttributes.MemberAccessMask) != MethodAttributes.Public ||
(declaringType != null && declaringType.NeedsReflectionSecurityCheck) )
{
// If method is non-public, or declaring type is not visible
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY;
}
else if (IsGenericMethod)
{
Type[] genericArguments = GetGenericArguments();
for (int i = 0; i < genericArguments.Length; i++)
{
if (genericArguments[i].NeedsReflectionSecurityCheck)
{
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY;
break;
}
}
}
}
}
#if FEATURE_APPX
if (AppDomain.ProfileAPICheck && IsNonW8PFrameworkAPI())
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API;
#endif // FEATURE_APPX
m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED;
}
return m_invocationFlags;
}
}
#endregion
#region Constructor
[System.Security.SecurityCritical] // auto-generated
internal RuntimeMethodInfo(
RuntimeMethodHandleInternal handle, RuntimeType declaringType,
RuntimeTypeCache reflectedTypeCache, MethodAttributes methodAttributes, BindingFlags bindingFlags, object keepalive)
{
Contract.Ensures(!m_handle.IsNull());
Contract.Assert(!handle.IsNullHandle());
Contract.Assert(methodAttributes == RuntimeMethodHandle.GetAttributes(handle));
m_bindingFlags = bindingFlags;
m_declaringType = declaringType;
m_keepalive = keepalive;
m_handle = handle.Value;
m_reflectedTypeCache = reflectedTypeCache;
m_methodAttributes = methodAttributes;
}
#endregion
#if FEATURE_REMOTING
#region Legacy Remoting Cache
// The size of CachedData is accounted for by BaseObjectWithCachedData in object.h.
// This member is currently being used by Remoting for caching remoting data. If you
// need to cache data here, talk to the Remoting team to work out a mechanism, so that
// both caching systems can happily work together.
private RemotingMethodCachedData m_cachedData;
internal RemotingMethodCachedData RemotingCache
{
get
{
// This grabs an internal copy of m_cachedData and uses
// that instead of looking at m_cachedData directly because
// the cache may get cleared asynchronously. This prevents
// us from having to take a lock.
RemotingMethodCachedData cache = m_cachedData;
if (cache == null)
{
cache = new RemotingMethodCachedData(this);
RemotingMethodCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null);
if (ret != null)
cache = ret;
}
return cache;
}
}
#endregion
#endif //FEATURE_REMOTING
#region Private Methods
RuntimeMethodHandleInternal IRuntimeMethodInfo.Value
{
[System.Security.SecuritySafeCritical]
get
{
return new RuntimeMethodHandleInternal(m_handle);
}
}
private RuntimeType ReflectedTypeInternal
{
get
{
return m_reflectedTypeCache.GetRuntimeType();
}
}
[System.Security.SecurityCritical] // auto-generated
private ParameterInfo[] FetchNonReturnParameters()
{
if (m_parameters == null)
m_parameters = RuntimeParameterInfo.GetParameters(this, this, Signature);
return m_parameters;
}
[System.Security.SecurityCritical] // auto-generated
private ParameterInfo FetchReturnParameter()
{
if (m_returnParameter == null)
m_returnParameter = RuntimeParameterInfo.GetReturnParameter(this, this, Signature);
return m_returnParameter;
}
#endregion
#region Internal Members
internal override string FormatNameAndSig(bool serialization)
{
// Serialization uses ToString to resolve MethodInfo overloads.
StringBuilder sbName = new StringBuilder(Name);
// serialization == true: use unambiguous (except for assembly name) type names to distinguish between overloads.
// serialization == false: use basic format to maintain backward compatibility of MethodInfo.ToString().
TypeNameFormatFlags format = serialization ? TypeNameFormatFlags.FormatSerialization : TypeNameFormatFlags.FormatBasic;
if (IsGenericMethod)
sbName.Append(RuntimeMethodHandle.ConstructInstantiation(this, format));
sbName.Append("(");
sbName.Append(ConstructParameters(GetParameterTypes(), CallingConvention, serialization));
sbName.Append(")");
return sbName.ToString();
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal override bool CacheEquals(object o)
{
RuntimeMethodInfo m = o as RuntimeMethodInfo;
if ((object)m == null)
return false;
return m.m_handle == m_handle;
}
internal Signature Signature
{
get
{
if (m_signature == null)
m_signature = new Signature(this, m_declaringType);
return m_signature;
}
}
internal BindingFlags BindingFlags { get { return m_bindingFlags; } }
// Differs from MethodHandle in that it will return a valid handle even for reflection only loaded types
internal RuntimeMethodHandle GetMethodHandle()
{
return new RuntimeMethodHandle(this);
}
[System.Security.SecuritySafeCritical] // auto-generated
internal RuntimeMethodInfo GetParentDefinition()
{
if (!IsVirtual || m_declaringType.IsInterface)
return null;
RuntimeType parent = (RuntimeType)m_declaringType.BaseType;
if (parent == null)
return null;
int slot = RuntimeMethodHandle.GetSlot(this);
if (RuntimeTypeHandle.GetNumVirtuals(parent) <= slot)
return null;
return (RuntimeMethodInfo)RuntimeType.GetMethodBase(parent, RuntimeTypeHandle.GetMethodAt(parent, slot));
}
// Unlike DeclaringType, this will return a valid type even for global methods
internal RuntimeType GetDeclaringTypeInternal()
{
return m_declaringType;
}
#endregion
#region Object Overrides
public override String ToString()
{
if (m_toString == null)
m_toString = ReturnType.FormatTypeName() + " " + FormatNameAndSig();
return m_toString;
}
public override int GetHashCode()
{
// See RuntimeMethodInfo.Equals() below.
if (IsGenericMethod)
return ValueType.GetHashCodeOfPtr(m_handle);
else
return base.GetHashCode();
}
[System.Security.SecuritySafeCritical] // auto-generated
public override bool Equals(object obj)
{
if (!IsGenericMethod)
return obj == (object)this;
// We cannot do simple object identity comparisons for generic methods.
// Equals will be called in CerHashTable when RuntimeType+RuntimeTypeCache.GetGenericMethodInfo()
// retrive items from and insert items into s_methodInstantiations which is a CerHashtable.
//
RuntimeMethodInfo mi = obj as RuntimeMethodInfo;
if (mi == null || !mi.IsGenericMethod)
return false;
// now we know that both operands are generic methods
IRuntimeMethodInfo handle1 = RuntimeMethodHandle.StripMethodInstantiation(this);
IRuntimeMethodInfo handle2 = RuntimeMethodHandle.StripMethodInstantiation(mi);
if (handle1.Value.Value != handle2.Value.Value)
return false;
Type[] lhs = GetGenericArguments();
Type[] rhs = mi.GetGenericArguments();
if (lhs.Length != rhs.Length)
return false;
for (int i = 0; i < lhs.Length; i++)
{
if (lhs[i] != rhs[i])
return false;
}
if (DeclaringType != mi.DeclaringType)
return false;
if (ReflectedType != mi.ReflectedType)
return false;
return true;
}
#endregion
#region ICustomAttributeProvider
[System.Security.SecuritySafeCritical] // auto-generated
public override Object[] GetCustomAttributes(bool inherit)
{
return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType as RuntimeType, inherit);
}
[System.Security.SecuritySafeCritical] // auto-generated
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException("attributeType");
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType");
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType, inherit);
}
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException("attributeType");
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType");
return CustomAttribute.IsDefined(this, attributeRuntimeType, inherit);
}
public override IList<CustomAttributeData> GetCustomAttributesData()
{
return CustomAttributeData.GetCustomAttributesInternal(this);
}
#endregion
#region MemberInfo Overrides
public override String Name
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
if (m_name == null)
m_name = RuntimeMethodHandle.GetName(this);
return m_name;
}
}
public override Type DeclaringType
{
get
{
if (m_reflectedTypeCache.IsGlobal)
return null;
return m_declaringType;
}
}
public override Type ReflectedType
{
get
{
if (m_reflectedTypeCache.IsGlobal)
return null;
return m_reflectedTypeCache.GetRuntimeType();
}
}
public override MemberTypes MemberType { get { return MemberTypes.Method; } }
public override int MetadataToken
{
[System.Security.SecuritySafeCritical] // auto-generated
get { return RuntimeMethodHandle.GetMethodDef(this); }
}
public override Module Module { get { return GetRuntimeModule(); } }
internal RuntimeType GetRuntimeType() { return m_declaringType; }
internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); }
internal RuntimeAssembly GetRuntimeAssembly() { return GetRuntimeModule().GetRuntimeAssembly(); }
public override bool IsSecurityCritical
{
get { return RuntimeMethodHandle.IsSecurityCritical(this); }
}
public override bool IsSecuritySafeCritical
{
get { return RuntimeMethodHandle.IsSecuritySafeCritical(this); }
}
public override bool IsSecurityTransparent
{
get { return RuntimeMethodHandle.IsSecurityTransparent(this); }
}
#endregion
#region MethodBase Overrides
[System.Security.SecuritySafeCritical] // auto-generated
internal override ParameterInfo[] GetParametersNoCopy()
{
FetchNonReturnParameters();
return m_parameters;
}
[System.Security.SecuritySafeCritical] // auto-generated
[System.Diagnostics.Contracts.Pure]
public override ParameterInfo[] GetParameters()
{
FetchNonReturnParameters();
if (m_parameters.Length == 0)
return m_parameters;
ParameterInfo[] ret = new ParameterInfo[m_parameters.Length];
Array.Copy(m_parameters, ret, m_parameters.Length);
return ret;
}
public override MethodImplAttributes GetMethodImplementationFlags()
{
return RuntimeMethodHandle.GetImplAttributes(this);
}
internal bool IsOverloaded
{
get
{
return m_reflectedTypeCache.GetMethodList(MemberListType.CaseSensitive, Name).Length > 1;
}
}
public override RuntimeMethodHandle MethodHandle
{
get
{
Type declaringType = DeclaringType;
if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInReflectionOnly"));
return new RuntimeMethodHandle(this);
}
}
public override MethodAttributes Attributes { get { return m_methodAttributes; } }
public override CallingConventions CallingConvention
{
get
{
return Signature.CallingConvention;
}
}
[System.Security.SecuritySafeCritical] // overrides SafeCritical member
#if !FEATURE_CORECLR
#pragma warning disable 618
[ReflectionPermissionAttribute(SecurityAction.Demand, Flags = ReflectionPermissionFlag.MemberAccess)]
#pragma warning restore 618
#endif
public override MethodBody GetMethodBody()
{
MethodBody mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal);
if (mb != null)
mb.m_methodBase = this;
return mb;
}
#endregion
#region Invocation Logic(On MemberBase)
private void CheckConsistency(Object target)
{
// only test instance methods
if ((m_methodAttributes & MethodAttributes.Static) != MethodAttributes.Static)
{
if (!m_declaringType.IsInstanceOfType(target))
{
if (target == null)
throw new TargetException(Environment.GetResourceString("RFLCT.Targ_StatMethReqTarg"));
else
throw new TargetException(Environment.GetResourceString("RFLCT.Targ_ITargMismatch"));
}
}
}
[System.Security.SecuritySafeCritical]
private void ThrowNoInvokeException()
{
// method is ReflectionOnly
Type declaringType = DeclaringType;
if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
{
throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyInvoke"));
}
// method is on a class that contains stack pointers
else if ((InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS) != 0)
{
throw new NotSupportedException();
}
// method is vararg
else if ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs)
{
throw new NotSupportedException();
}
// method is generic or on a generic class
else if (DeclaringType.ContainsGenericParameters || ContainsGenericParameters)
{
throw new InvalidOperationException(Environment.GetResourceString("Arg_UnboundGenParam"));
}
// method is abstract class
else if (IsAbstract)
{
throw new MemberAccessException();
}
// ByRef return are not allowed in reflection
else if (ReturnType.IsByRef)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_ByRefReturn"));
}
throw new TargetException();
}
[System.Security.SecuritySafeCritical]
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
object[] arguments = InvokeArgumentsCheck(obj, invokeAttr, binder, parameters, culture);
#region Security Check
INVOCATION_FLAGS invocationFlags = InvocationFlags;
#if FEATURE_APPX
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
if (caller != null && !caller.IsSafeForReflection())
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName));
}
#endif
if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY)) != 0)
{
#if !FEATURE_CORECLR
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD) != 0)
CodeAccessPermission.Demand(PermissionType.ReflectionMemberAccess);
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) != 0)
#endif // !FEATURE_CORECLR
RuntimeMethodHandle.PerformSecurityCheck(obj, this, m_declaringType, (uint)m_invocationFlags);
}
#endregion
return UnsafeInvokeInternal(obj, parameters, arguments);
}
[System.Security.SecurityCritical]
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
internal object UnsafeInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
object[] arguments = InvokeArgumentsCheck(obj, invokeAttr, binder, parameters, culture);
return UnsafeInvokeInternal(obj, parameters, arguments);
}
[System.Security.SecurityCritical]
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
private object UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
{
if (arguments == null || arguments.Length == 0)
return RuntimeMethodHandle.InvokeMethod(obj, null, Signature, false);
else
{
Object retValue = RuntimeMethodHandle.InvokeMethod(obj, arguments, Signature, false);
// copy out. This should be made only if ByRef are present.
for (int index = 0; index < arguments.Length; index++)
parameters[index] = arguments[index];
return retValue;
}
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
private object[] InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
Signature sig = Signature;
// get the signature
int formalCount = sig.Arguments.Length;
int actualCount = (parameters != null) ? parameters.Length : 0;
INVOCATION_FLAGS invocationFlags = InvocationFlags;
// INVOCATION_FLAGS_CONTAINS_STACK_POINTERS means that the struct (either the declaring type or the return type)
// contains pointers that point to the stack. This is either a ByRef or a TypedReference. These structs cannot
// be boxed and thus cannot be invoked through reflection which only deals with boxed value type objects.
if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE | INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS)) != 0)
ThrowNoInvokeException();
// check basic method consistency. This call will throw if there are problems in the target/method relationship
CheckConsistency(obj);
if (formalCount != actualCount)
throw new TargetParameterCountException(Environment.GetResourceString("Arg_ParmCnt"));
if (actualCount != 0)
return CheckArguments(parameters, binder, invokeAttr, culture, sig);
else
return null;
}
#endregion
#region MethodInfo Overrides
public override Type ReturnType
{
get { return Signature.ReturnType; }
}
public override ICustomAttributeProvider ReturnTypeCustomAttributes
{
get { return ReturnParameter; }
}
public override ParameterInfo ReturnParameter
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
Contract.Ensures(m_returnParameter != null);
FetchReturnParameter();
return m_returnParameter as ParameterInfo;
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public override MethodInfo GetBaseDefinition()
{
if (!IsVirtual || IsStatic || m_declaringType == null || m_declaringType.IsInterface)
return this;
int slot = RuntimeMethodHandle.GetSlot(this);
RuntimeType declaringType = (RuntimeType)DeclaringType;
RuntimeType baseDeclaringType = declaringType;
RuntimeMethodHandleInternal baseMethodHandle = new RuntimeMethodHandleInternal();
do {
int cVtblSlots = RuntimeTypeHandle.GetNumVirtuals(declaringType);
if (cVtblSlots <= slot)
break;
baseMethodHandle = RuntimeTypeHandle.GetMethodAt(declaringType, slot);
baseDeclaringType = declaringType;
declaringType = (RuntimeType)declaringType.BaseType;
} while (declaringType != null);
return(MethodInfo)RuntimeType.GetMethodBase(baseDeclaringType, baseMethodHandle);
}
[System.Security.SecuritySafeCritical]
public override Delegate CreateDelegate(Type delegateType)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
// This API existed in v1/v1.1 and only expected to create closed
// instance delegates. Constrain the call to BindToMethodInfo to
// open delegates only for backwards compatibility. But we'll allow
// relaxed signature checking and open static delegates because
// there's no ambiguity there (the caller would have to explicitly
// pass us a static method or a method with a non-exact signature
// and the only change in behavior from v1.1 there is that we won't
// fail the call).
return CreateDelegateInternal(
delegateType,
null,
DelegateBindingFlags.OpenDelegateOnly | DelegateBindingFlags.RelaxedSignature,
ref stackMark);
}
[System.Security.SecuritySafeCritical]
public override Delegate CreateDelegate(Type delegateType, Object target)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
// This API is new in Whidbey and allows the full range of delegate
// flexability (open or closed delegates binding to static or
// instance methods with relaxed signature checking). The delegate
// can also be closed over null. There's no ambiguity with all these
// options since the caller is providing us a specific MethodInfo.
return CreateDelegateInternal(
delegateType,
target,
DelegateBindingFlags.RelaxedSignature,
ref stackMark);
}
[System.Security.SecurityCritical]
private Delegate CreateDelegateInternal(Type delegateType, Object firstArgument, DelegateBindingFlags bindingFlags, ref StackCrawlMark stackMark)
{
// Validate the parameters.
if (delegateType == null)
throw new ArgumentNullException("delegateType");
Contract.EndContractBlock();
RuntimeType rtType = delegateType as RuntimeType;
if (rtType == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "delegateType");
if (!rtType.IsDelegate())
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), "delegateType");
Delegate d = Delegate.CreateDelegateInternal(rtType, this, firstArgument, bindingFlags, ref stackMark);
if (d == null)
{
throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth"));
}
return d;
}
#endregion
#region Generics
[System.Security.SecuritySafeCritical] // auto-generated
public override MethodInfo MakeGenericMethod(params Type[] methodInstantiation)
{
if (methodInstantiation == null)
throw new ArgumentNullException("methodInstantiation");
Contract.EndContractBlock();
RuntimeType[] methodInstantionRuntimeType = new RuntimeType[methodInstantiation.Length];
if (!IsGenericMethodDefinition)
throw new InvalidOperationException(
Environment.GetResourceString("Arg_NotGenericMethodDefinition", this));
for (int i = 0; i < methodInstantiation.Length; i++)
{
Type methodInstantiationElem = methodInstantiation[i];
if (methodInstantiationElem == null)
throw new ArgumentNullException();
RuntimeType rtMethodInstantiationElem = methodInstantiationElem as RuntimeType;
if (rtMethodInstantiationElem == null)
{
Type[] methodInstantiationCopy = new Type[methodInstantiation.Length];
for (int iCopy = 0; iCopy < methodInstantiation.Length; iCopy++)
methodInstantiationCopy[iCopy] = methodInstantiation[iCopy];
methodInstantiation = methodInstantiationCopy;
return System.Reflection.Emit.MethodBuilderInstantiation.MakeGenericMethod(this, methodInstantiation);
}
methodInstantionRuntimeType[i] = rtMethodInstantiationElem;
}
RuntimeType[] genericParameters = GetGenericArgumentsInternal();
RuntimeType.SanityCheckGenericArguments(methodInstantionRuntimeType, genericParameters);
MethodInfo ret = null;
try
{
ret = RuntimeType.GetMethodBase(ReflectedTypeInternal,
RuntimeMethodHandle.GetStubIfNeeded(new RuntimeMethodHandleInternal(this.m_handle), m_declaringType, methodInstantionRuntimeType)) as MethodInfo;
}
catch (VerificationException e)
{
RuntimeType.ValidateGenericArguments(this, methodInstantionRuntimeType, e);
throw;
}
return ret;
}
internal RuntimeType[] GetGenericArgumentsInternal()
{
return RuntimeMethodHandle.GetMethodInstantiationInternal(this);
}
public override Type[] GetGenericArguments()
{
Type[] types = RuntimeMethodHandle.GetMethodInstantiationPublic(this);
if (types == null)
{
types = EmptyArray<Type>.Value;
}
return types;
}
public override MethodInfo GetGenericMethodDefinition()
{
if (!IsGenericMethod)
throw new InvalidOperationException();
Contract.EndContractBlock();
return RuntimeType.GetMethodBase(m_declaringType, RuntimeMethodHandle.StripMethodInstantiation(this)) as MethodInfo;
}
public override bool IsGenericMethod
{
get { return RuntimeMethodHandle.HasMethodInstantiation(this); }
}
public override bool IsGenericMethodDefinition
{
get { return RuntimeMethodHandle.IsGenericMethodDefinition(this); }
}
public override bool ContainsGenericParameters
{
get
{
if (DeclaringType != null && DeclaringType.ContainsGenericParameters)
return true;
if (!IsGenericMethod)
return false;
Type[] pis = GetGenericArguments();
for (int i = 0; i < pis.Length; i++)
{
if (pis[i].ContainsGenericParameters)
return true;
}
return false;
}
}
#endregion
#region ISerializable Implementation
[System.Security.SecurityCritical] // auto-generated
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
Contract.EndContractBlock();
if (m_reflectedTypeCache.IsGlobal)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_GlobalMethodSerialization"));
MemberInfoSerializationHolder.GetSerializationInfo(
info,
Name,
ReflectedTypeInternal,
ToString(),
SerializationToString(),
MemberTypes.Method,
IsGenericMethod & !IsGenericMethodDefinition ? GetGenericArguments() : null);
}
internal string SerializationToString()
{
return ReturnType.FormatTypeName(true) + " " + FormatNameAndSig(true);
}
#endregion
#region Legacy Internal
internal static MethodBase InternalGetCurrentMethod(ref StackCrawlMark stackMark)
{
IRuntimeMethodInfo method = RuntimeMethodHandle.GetCurrentMethod(ref stackMark);
if (method == null)
return null;
return RuntimeType.GetMethodBase(method);
}
#endregion
}
#endif
}
| |
//-----------------------------------------------------------------------------
// 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 ( isObject( moveMap ) )
moveMap.delete();
new ActionMap(moveMap);
//------------------------------------------------------------------------------
// Non-remapable binds
//------------------------------------------------------------------------------
function escapeFromGame()
{
if ( $Server::ServerType $= "SinglePlayer" )
MessageBoxYesNo( "Exit", "Exit from this Mission?", "disconnect();", "");
else
MessageBoxYesNo( "Disconnect", "Disconnect from the server?", "disconnect();", "");
}
moveMap.bindCmd(keyboard, "escape", "", "handleEscape();");
function showPlayerList(%val)
{
if (%val)
PlayerListGui.toggle();
}
moveMap.bind( keyboard, F2, showPlayerList );
function hideHUDs(%val)
{
if (%val)
HudlessPlayGui.toggle();
}
moveMap.bind(keyboard, "ctrl h", hideHUDs);
function doScreenShotHudless(%val)
{
if(%val)
{
canvas.setContent(HudlessPlayGui);
//doScreenshot(%val);
schedule(10, 0, "doScreenShot", %val);
}
else
canvas.setContent(PlayGui);
}
moveMap.bind(keyboard, "alt p", doScreenShotHudless);
//------------------------------------------------------------------------------
// Movement Keys
//------------------------------------------------------------------------------
$movementSpeed = 1; // m/s
function setSpeed(%speed)
{
if(%speed)
$movementSpeed = %speed;
}
function moveleft(%val)
{
$mvLeftAction = %val * $movementSpeed;
}
function moveright(%val)
{
$mvRightAction = %val * $movementSpeed;
}
function moveforward(%val)
{
$mvForwardAction = %val * $movementSpeed;
}
function movebackward(%val)
{
$mvBackwardAction = %val * $movementSpeed;
}
function moveup(%val)
{
%object = ServerConnection.getControlObject();
if(%object.isInNamespaceHierarchy("Camera"))
$mvUpAction = %val * $movementSpeed;
}
function movedown(%val)
{
%object = ServerConnection.getControlObject();
if(%object.isInNamespaceHierarchy("Camera"))
$mvDownAction = %val * $movementSpeed;
}
function turnLeft( %val )
{
$mvYawRightSpeed = %val ? $Pref::Input::KeyboardTurnSpeed : 0;
}
function turnRight( %val )
{
$mvYawLeftSpeed = %val ? $Pref::Input::KeyboardTurnSpeed : 0;
}
function panUp( %val )
{
$mvPitchDownSpeed = %val ? $Pref::Input::KeyboardTurnSpeed : 0;
}
function panDown( %val )
{
$mvPitchUpSpeed = %val ? $Pref::Input::KeyboardTurnSpeed : 0;
}
function getMouseAdjustAmount(%val)
{
// based on a default camera FOV of 90'
return(%val * ($cameraFov / 90) * 0.01) * $pref::Input::LinkMouseSensitivity;
}
function getGamepadAdjustAmount(%val)
{
// based on a default camera FOV of 90'
return(%val * ($cameraFov / 90) * 0.01) * 10.0;
}
function yaw(%val)
{
%yawAdj = getMouseAdjustAmount(%val);
if(ServerConnection.isControlObjectRotDampedCamera())
{
// Clamp and scale
%yawAdj = mClamp(%yawAdj, -m2Pi()+0.01, m2Pi()-0.01);
%yawAdj *= 0.5;
}
$mvYaw += %yawAdj;
}
function pitch(%val)
{
%pitchAdj = getMouseAdjustAmount(%val);
if(ServerConnection.isControlObjectRotDampedCamera())
{
// Clamp and scale
%pitchAdj = mClamp(%pitchAdj, -m2Pi()+0.01, m2Pi()-0.01);
%pitchAdj *= 0.5;
}
$mvPitch += %pitchAdj;
}
function jump(%val)
{
$mvTriggerCount2++;
}
function gamePadMoveX( %val )
{
if(%val > 0)
{
$mvRightAction = %val * $movementSpeed;
$mvLeftAction = 0;
}
else
{
$mvRightAction = 0;
$mvLeftAction = -%val * $movementSpeed;
}
}
function gamePadMoveY( %val )
{
if(%val > 0)
{
$mvForwardAction = %val * $movementSpeed;
$mvBackwardAction = 0;
}
else
{
$mvForwardAction = 0;
$mvBackwardAction = -%val * $movementSpeed;
}
}
function gamepadYaw(%val)
{
%yawAdj = getGamepadAdjustAmount(%val);
if(ServerConnection.isControlObjectRotDampedCamera())
{
// Clamp and scale
%yawAdj = mClamp(%yawAdj, -m2Pi()+0.01, m2Pi()-0.01);
%yawAdj *= 0.5;
}
if(%yawAdj > 0)
{
$mvYawLeftSpeed = %yawAdj;
$mvYawRightSpeed = 0;
}
else
{
$mvYawLeftSpeed = 0;
$mvYawRightSpeed = -%yawAdj;
}
}
function gamepadPitch(%val)
{
%pitchAdj = getGamepadAdjustAmount(%val);
if(ServerConnection.isControlObjectRotDampedCamera())
{
// Clamp and scale
%pitchAdj = mClamp(%pitchAdj, -m2Pi()+0.01, m2Pi()-0.01);
%pitchAdj *= 0.5;
}
if(%pitchAdj > 0)
{
$mvPitchDownSpeed = %pitchAdj;
$mvPitchUpSpeed = 0;
}
else
{
$mvPitchDownSpeed = 0;
$mvPitchUpSpeed = -%pitchAdj;
}
}
moveMap.bind( keyboard, a, moveleft );
moveMap.bind( keyboard, d, moveright );
moveMap.bind( keyboard, left, moveleft );
moveMap.bind( keyboard, right, moveright );
moveMap.bind( keyboard, w, moveforward );
moveMap.bind( keyboard, s, movebackward );
moveMap.bind( keyboard, up, moveforward );
moveMap.bind( keyboard, down, movebackward );
moveMap.bind( keyboard, e, moveup );
moveMap.bind( keyboard, c, movedown );
moveMap.bind( keyboard, space, jump );
moveMap.bind( mouse, xaxis, yaw );
moveMap.bind( mouse, yaxis, pitch );
moveMap.bind( gamepad, thumbrx, "D", "-0.23 0.23", gamepadYaw );
moveMap.bind( gamepad, thumbry, "D", "-0.23 0.23", gamepadPitch );
moveMap.bind( gamepad, thumblx, "D", "-0.23 0.23", gamePadMoveX );
moveMap.bind( gamepad, thumbly, "D", "-0.23 0.23", gamePadMoveY );
moveMap.bind( gamepad, btn_a, jump );
moveMap.bindCmd( gamepad, btn_back, "disconnect();", "" );
moveMap.bindCmd(gamepad, dpadl, "toggleLightColorViz();", "");
moveMap.bindCmd(gamepad, dpadu, "toggleDepthViz();", "");
moveMap.bindCmd(gamepad, dpadd, "toggleNormalsViz();", "");
moveMap.bindCmd(gamepad, dpadr, "toggleLightSpecularViz();", "");
// ----------------------------------------------------------------------------
// Stance/pose
// ----------------------------------------------------------------------------
function doCrouch(%val)
{
$mvTriggerCount3++;
}
moveMap.bind(keyboard, lcontrol, doCrouch);
moveMap.bind(gamepad, btn_b, doCrouch);
function doSprint(%val)
{
$mvTriggerCount5++;
}
moveMap.bind(keyboard, lshift, doSprint);
//------------------------------------------------------------------------------
// Mouse Trigger
//------------------------------------------------------------------------------
function mouseFire(%val)
{
$mvTriggerCount0++;
}
//function altTrigger(%val)
//{
//$mvTriggerCount1++;
//}
moveMap.bind( mouse, button0, mouseFire );
//moveMap.bind( mouse, button1, altTrigger );
//------------------------------------------------------------------------------
// Gamepad Trigger
//------------------------------------------------------------------------------
function gamepadFire(%val)
{
if(%val > 0.1 && !$gamepadFireTriggered)
{
$gamepadFireTriggered = true;
$mvTriggerCount0++;
}
else if(%val <= 0.1 && $gamepadFireTriggered)
{
$gamepadFireTriggered = false;
$mvTriggerCount0++;
}
}
function gamepadAltTrigger(%val)
{
if(%val > 0.1 && !$gamepadAltTriggerTriggered)
{
$gamepadAltTriggerTriggered = true;
$mvTriggerCount1++;
}
else if(%val <= 0.1 && $gamepadAltTriggerTriggered)
{
$gamepadAltTriggerTriggered = false;
$mvTriggerCount1++;
}
}
moveMap.bind(gamepad, triggerr, gamepadFire);
moveMap.bind(gamepad, triggerl, gamepadAltTrigger);
//------------------------------------------------------------------------------
// Zoom and FOV functions
//------------------------------------------------------------------------------
if($Player::CurrentFOV $= "")
$Player::CurrentFOV = $pref::Player::DefaultFOV / 2;
// toggleZoomFOV() works by dividing the CurrentFOV by 2. Each time that this
// toggle is hit it simply divides the CurrentFOV by 2 once again. If the
// FOV is reduced below a certain threshold then it resets to equal half of the
// DefaultFOV value. This gives us 4 zoom levels to cycle through.
function toggleZoomFOV()
{
$Player::CurrentFOV = $Player::CurrentFOV / 2;
if($Player::CurrentFOV < 5)
resetCurrentFOV();
if(ServerConnection.zoomed)
setFOV($Player::CurrentFOV);
else
{
setFov(ServerConnection.getControlCameraDefaultFov());
}
}
function resetCurrentFOV()
{
$Player::CurrentFOV = ServerConnection.getControlCameraDefaultFov() / 2;
}
function turnOffZoom()
{
ServerConnection.zoomed = false;
setFov(ServerConnection.getControlCameraDefaultFov());
Reticle.setVisible(true);
zoomReticle.setVisible(false);
// Rather than just disable the DOF effect, we want to set it to the level's
// preset values.
//DOFPostEffect.disable();
ppOptionsUpdateDOFSettings();
}
function setZoomFOV(%val)
{
if(%val)
toggleZoomFOV();
}
function toggleZoom(%val)
{
if (%val)
{
ServerConnection.zoomed = true;
setFov($Player::CurrentFOV);
Reticle.setVisible(false);
zoomReticle.setVisible(true);
DOFPostEffect.setAutoFocus( true );
DOFPostEffect.setFocusParams( 0.5, 0.5, 50, 500, -5, 5 );
DOFPostEffect.enable();
}
else
{
turnOffZoom();
}
}
function mouseButtonZoom(%val)
{
toggleZoom(%val);
}
moveMap.bind(keyboard, f, setZoomFOV); // f for field of view
moveMap.bind(keyboard, z, toggleZoom); // z for zoom
moveMap.bind( mouse, button1, mouseButtonZoom );
//------------------------------------------------------------------------------
// Camera & View functions
//------------------------------------------------------------------------------
function toggleFreeLook( %val )
{
if ( %val )
$mvFreeLook = true;
else
$mvFreeLook = false;
}
function toggleFirstPerson(%val)
{
if (%val)
{
ServerConnection.setFirstPerson(!ServerConnection.isFirstPerson());
}
}
function toggleCamera(%val)
{
if (%val)
commandToServer('ToggleCamera');
}
moveMap.bind( keyboard, v, toggleFreeLook ); // v for vanity
moveMap.bind(keyboard, tab, toggleFirstPerson );
moveMap.bind(keyboard, "alt c", toggleCamera);
moveMap.bind( gamepad, btn_start, toggleCamera );
moveMap.bind( gamepad, btn_x, toggleFirstPerson );
// ----------------------------------------------------------------------------
// Misc. Player stuff
// ----------------------------------------------------------------------------
// Gideon does not have these animations, so the player does not need access to
// them. Commenting instead of removing so as to retain an example for those
// who will want to use a player model that has these animations and wishes to
// use them.
//moveMap.bindCmd(keyboard, "ctrl w", "commandToServer('playCel',\"wave\");", "");
//moveMap.bindCmd(keyboard, "ctrl s", "commandToServer('playCel',\"salute\");", "");
moveMap.bindCmd(keyboard, "ctrl k", "commandToServer('suicide');", "");
//------------------------------------------------------------------------------
// Item manipulation
//------------------------------------------------------------------------------
moveMap.bindCmd(keyboard, "1", "commandToServer('use',\"Ryder\");", "");
moveMap.bindCmd(keyboard, "2", "commandToServer('use',\"Lurker\");", "");
moveMap.bindCmd(keyboard, "3", "commandToServer('use',\"LurkerGrenadeLauncher\");", "");
moveMap.bindCmd(keyboard, "4", "commandToServer('use',\"ProxMine\");", "");
moveMap.bindCmd(keyboard, "5", "commandToServer('use',\"DeployableTurret\");", "");
moveMap.bindCmd(keyboard, "r", "commandToServer('reloadWeapon');", "");
function unmountWeapon(%val)
{
if (%val)
commandToServer('unmountWeapon');
}
moveMap.bind(keyboard, 0, unmountWeapon);
function throwWeapon(%val)
{
if (%val)
commandToServer('Throw', "Weapon");
}
function tossAmmo(%val)
{
if (%val)
commandToServer('Throw', "Ammo");
}
moveMap.bind(keyboard, "alt w", throwWeapon);
moveMap.bind(keyboard, "alt a", tossAmmo);
function nextWeapon(%val)
{
if (%val)
commandToServer('cycleWeapon', "next");
}
function prevWeapon(%val)
{
if (%val)
commandToServer('cycleWeapon', "prev");
}
function mouseWheelWeaponCycle(%val)
{
if (%val < 0)
commandToServer('cycleWeapon', "next");
else if (%val > 0)
commandToServer('cycleWeapon', "prev");
}
moveMap.bind(keyboard, q, nextWeapon);
moveMap.bind(keyboard, "ctrl q", prevWeapon);
moveMap.bind(mouse, "zaxis", mouseWheelWeaponCycle);
//------------------------------------------------------------------------------
// Message HUD functions
//------------------------------------------------------------------------------
function pageMessageHudUp( %val )
{
if ( %val )
pageUpMessageHud();
}
function pageMessageHudDown( %val )
{
if ( %val )
pageDownMessageHud();
}
function resizeMessageHud( %val )
{
if ( %val )
cycleMessageHudSize();
}
moveMap.bind(keyboard, u, toggleMessageHud );
//moveMap.bind(keyboard, y, teamMessageHud );
moveMap.bind(keyboard, "pageUp", pageMessageHudUp );
moveMap.bind(keyboard, "pageDown", pageMessageHudDown );
moveMap.bind(keyboard, "p", resizeMessageHud );
//------------------------------------------------------------------------------
// Demo recording functions
//------------------------------------------------------------------------------
function startRecordingDemo( %val )
{
if ( %val )
startDemoRecord();
}
function stopRecordingDemo( %val )
{
if ( %val )
stopDemoRecord();
}
moveMap.bind( keyboard, F3, startRecordingDemo );
moveMap.bind( keyboard, F4, stopRecordingDemo );
//------------------------------------------------------------------------------
// Theora Video Capture (Records a movie file)
//------------------------------------------------------------------------------
function toggleMovieRecording(%val)
{
if (!%val)
return;
%movieEncodingType = "THEORA"; // Valid encoder values are "PNG" and "THEORA" (default).
%movieFPS = 30; // video capture frame rate.
if (!$RecordingMovie)
{
// locate a non-existent filename to use
for(%i = 0; %i < 1000; %i++)
{
%num = %i;
if(%num < 10)
%num = "0" @ %num;
if(%num < 100)
%num = "0" @ %num;
%filePath = "movies/movie" @ %num;
if(!isfile(%filePath))
break;
}
if(%i == 1000)
return;
// Start the movie recording
recordMovie(%filePath, %movieFPS, %movieEncodingType);
}
else
{
// Stop the current recording
stopMovie();
}
}
// Key binding works at any time and not just while in a game.
GlobalActionMap.bind(keyboard, "alt m", toggleMovieRecording);
//------------------------------------------------------------------------------
// Helper Functions
//------------------------------------------------------------------------------
function dropCameraAtPlayer(%val)
{
if (%val)
commandToServer('dropCameraAtPlayer');
}
function dropPlayerAtCamera(%val)
{
if (%val)
commandToServer('DropPlayerAtCamera');
}
moveMap.bind(keyboard, "F8", dropCameraAtPlayer);
moveMap.bind(keyboard, "F7", dropPlayerAtCamera);
function bringUpOptions(%val)
{
if (%val)
Canvas.pushDialog(OptionsDlg);
}
GlobalActionMap.bind(keyboard, "ctrl o", bringUpOptions);
//------------------------------------------------------------------------------
// Debugging Functions
//------------------------------------------------------------------------------
function showMetrics(%val)
{
if(%val)
{
if(!Canvas.isMember(FrameOverlayGui))
metrics("fps gfx shadow sfx terrain groundcover forest net");
else
metrics("");
}
}
GlobalActionMap.bind(keyboard, "ctrl F2", showMetrics);
//------------------------------------------------------------------------------
//
// Start profiler by pressing ctrl f3
// ctrl f3 - starts profile that will dump to console and file
//
function doProfile(%val)
{
if (%val)
{
// key down -- start profile
echo("Starting profile session...");
profilerReset();
profilerEnable(true);
}
else
{
// key up -- finish off profile
echo("Ending profile session...");
profilerDumpToFile("profilerDumpToFile" @ getSimTime() @ ".txt");
profilerEnable(false);
}
}
GlobalActionMap.bind(keyboard, "ctrl F3", doProfile);
//------------------------------------------------------------------------------
// Misc.
//------------------------------------------------------------------------------
GlobalActionMap.bind(keyboard, "tilde", toggleConsole);
GlobalActionMap.bindCmd(keyboard, "alt k", "cls();","");
GlobalActionMap.bindCmd(keyboard, "alt enter", "", "Canvas.attemptFullscreenToggle();");
GlobalActionMap.bindCmd(keyboard, "F1", "", "contextHelp();");
moveMap.bindCmd(keyboard, "n", "toggleNetGraph();", "");
// ----------------------------------------------------------------------------
// Useful vehicle stuff
// ----------------------------------------------------------------------------
// Trace a line along the direction the crosshair is pointing
// If you find a car with a player in it...eject them
function carjack()
{
%player = LocalClientConnection.getControlObject();
if (%player.getClassName() $= "Player")
{
%eyeVec = %player.getEyeVector();
%startPos = %player.getEyePoint();
%endPos = VectorAdd(%startPos, VectorScale(%eyeVec, 1000));
%target = ContainerRayCast(%startPos, %endPos, $TypeMasks::VehicleObjectType);
if (%target)
{
// See if anyone is mounted in the car's driver seat
%mount = %target.getMountNodeObject(0);
// Can only carjack bots
// remove '&& %mount.getClassName() $= "AIPlayer"' to allow you
// to carjack anyone/anything
if (%mount && %mount.getClassName() $= "AIPlayer")
{
commandToServer('carUnmountObj', %mount);
}
}
}
}
// Bind the keys to the carjack command
moveMap.bindCmd(keyboard, "ctrl z", "carjack();", "");
// Starting vehicle action map code
if ( isObject( vehicleMap ) )
vehicleMap.delete();
new ActionMap(vehicleMap);
// The key command for flipping the car
vehicleMap.bindCmd(keyboard, "ctrl x", "commandToServer(\'flipCar\');", "");
function getOut()
{
vehicleMap.pop();
moveMap.push();
commandToServer('dismountVehicle');
}
function brakeLights()
{
// Turn on/off the Cheetah's head lights.
commandToServer('toggleBrakeLights');
}
function brake(%val)
{
commandToServer('toggleBrakeLights');
$mvTriggerCount2++;
}
vehicleMap.bind( keyboard, w, moveforward );
vehicleMap.bind( keyboard, s, movebackward );
vehicleMap.bind( keyboard, up, moveforward );
vehicleMap.bind( keyboard, down, movebackward );
vehicleMap.bind( mouse, xaxis, yaw );
vehicleMap.bind( mouse, yaxis, pitch );
vehicleMap.bind( mouse, button0, mouseFire );
vehicleMap.bind( mouse, button1, altTrigger );
vehicleMap.bindCmd(keyboard, "ctrl f","getout();","");
vehicleMap.bind(keyboard, space, brake);
vehicleMap.bindCmd(keyboard, "l", "brakeLights();", "");
vehicleMap.bindCmd(keyboard, "escape", "", "handleEscape();");
vehicleMap.bind( keyboard, v, toggleFreeLook ); // v for vanity
//vehicleMap.bind(keyboard, tab, toggleFirstPerson );
vehicleMap.bind(keyboard, "alt c", toggleCamera);
// bind the left thumbstick for steering
vehicleMap.bind( gamepad, thumblx, "D", "-0.23 0.23", gamepadYaw );
// bind the gas, break, and reverse buttons
vehicleMap.bind( gamepad, btn_a, moveforward );
vehicleMap.bind( gamepad, btn_b, brake );
vehicleMap.bind( gamepad, btn_x, movebackward );
// bind exiting the vehicle to a button
vehicleMap.bindCmd(gamepad, btn_y,"getout();","");
// ----------------------------------------------------------------------------
// Oculus Rift
// ----------------------------------------------------------------------------
function OVRSensorRotEuler(%pitch, %roll, %yaw)
{
//echo("Sensor euler: " @ %pitch SPC %roll SPC %yaw);
$mvRotZ0 = %yaw;
$mvRotX0 = %pitch;
$mvRotY0 = %roll;
}
$mvRotIsEuler0 = true;
$OculusVR::GenerateAngleAxisRotationEvents = false;
$OculusVR::GenerateEulerRotationEvents = true;
moveMap.bind( oculusvr, ovr_sensorrotang0, OVRSensorRotEuler );
| |
/*
* Bitmap.cs - Implementation of the "System.Drawing.Bitmap" class.
*
* Copyright (C) 2003 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.Drawing
{
using System.IO;
using System.Security;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Drawing.Imaging;
using System.Drawing.Design;
using System.ComponentModel;
using DotGNU.Images;
using System.Drawing.Toolkit;
#if !ECMA_COMPAT
[Serializable]
[ComVisible(true)]
#endif
#if CONFIG_COMPONENT_MODEL_DESIGN
[Editor("System.Drawing.Design.BitmapEditor, System.Drawing.Design",
typeof(UITypeEditor))]
#endif
public sealed class Bitmap : System.Drawing.Image
{
// Constructors.
public Bitmap(Image original)
: this(original, original.Width, original.Height) {}
public Bitmap(Image original, Size newSize)
: this (original, newSize.Width, newSize.Height) {}
public Bitmap(Stream stream) : this(stream, false) {}
public Bitmap(Stream stream, bool useIcm)
{
DotGNU.Images.Image dgImage = new DotGNU.Images.Image();
dgImage.Load(stream);
SetDGImage(dgImage);
}
public Bitmap(String filename) : this(filename, false) {}
public Bitmap(String filename, bool useIcm)
{
DotGNU.Images.Image dgImage = new DotGNU.Images.Image();
dgImage.Load(filename);
SetDGImage(dgImage);
}
public Bitmap(int width, int height)
: this(width, height, Imaging.PixelFormat.Format24bppRgb) {}
public Bitmap(int width, int height,
System.Drawing.Imaging.PixelFormat format)
{
SetDGImage(new DotGNU.Images.Image
(width, height, (DotGNU.Images.PixelFormat)format));
dgImage.AddFrame();
}
public Bitmap(int width, int height, Graphics g)
{
if(g == null)
{
throw new ArgumentNullException("g");
}
SetDGImage(new DotGNU.Images.Image
(width, height, DotGNU.Images.PixelFormat.Format24bppRgb));
dgImage.AddFrame();
}
public Bitmap(Type type, String resource)
{
Stream stream = GetManifestResourceStream(type, resource);
if(stream == null)
{
throw new ArgumentException(S._("Arg_UnknownResource"));
}
try
{
DotGNU.Images.Image dgImage = new DotGNU.Images.Image();
dgImage.Load(stream);
SetDGImage(dgImage);
}
finally
{
stream.Close();
}
}
public Bitmap(Image original, int width, int height)
{
if(original.dgImage != null)
{
SetDGImage(original.dgImage.Stretch(width, height));
}
}
public Bitmap(int width, int height, int stride,
System.Drawing.Imaging.PixelFormat format, IntPtr scan0)
{
// We don't support loading bitmaps from unmanaged buffers.
throw new SecurityException();
}
internal Bitmap(DotGNU.Images.Image image) : base(image) {}
#if CONFIG_SERIALIZATION
internal Bitmap(SerializationInfo info, StreamingContext context)
: base(info, context) {}
#endif
// Get a manifest resource stream. Profile-safe version.
internal static Stream GetManifestResourceStream(Type type, String name)
{
#if !ECMA_COMPAT
return type.Module.Assembly.GetManifestResourceStream
(type, name);
#else
if(type.Namespace != null && type.Namespace != String.Empty)
{
return type.Module.Assembly.GetManifestResourceStream
(type.Namespace + "." + name);
}
return type.Module.Assembly.GetManifestResourceStream(name);
#endif
}
// Clone this bitmap and transform it into a new pixel format
[TODO]
public Bitmap Clone
(Rectangle rect, System.Drawing.Imaging.PixelFormat format)
{
// TODO : There has to be a better way !!
Bitmap b = new Bitmap(rect.Width, rect.Height, format);
for(int x = 0 ; x < rect.Width ; x++)
{
for(int y = 0 ; y < rect.Height ; y++)
{
b.SetPixel(x,y, GetPixel(rect.Left+x,rect.Top+y));
}
}
return b;
}
[TODO]
public Bitmap Clone
(RectangleF rect, System.Drawing.Imaging.PixelFormat format)
{
// TODO : There has to be a better way !!
Bitmap b = new Bitmap((int)rect.Width, (int)rect.Height, format);
for(int x = 0 ; x < rect.Width ; x++)
{
for(int y = 0 ; y < rect.Height ; y++)
{
b.SetPixel(x,y,
GetPixel((int)rect.Left+x, (int)rect.Top+y));
}
}
return b;
}
// Create a bitmap from a native icon handle.
public static Bitmap FromHicon(IntPtr hicon)
{
throw new SecurityException();
}
// Create a bitmap from a Windows resource name.
public static Bitmap FromResource(IntPtr hinstance, String bitmapName)
{
throw new SecurityException();
}
// Convert this bitmap into a native bitmap handle.
#if CONFIG_COMPONENT_MODEL
[EditorBrowsable(EditorBrowsableState.Advanced)]
#endif
public IntPtr GetHbitmap()
{
return GetHbitmap(Color.LightGray);
}
[TODO]
#if CONFIG_COMPONENT_MODEL
[EditorBrowsable(EditorBrowsableState.Advanced)]
#endif
public IntPtr GetHbitmap(Color background)
{
throw new SecurityException();
}
// Convert this bitmap into a native icon handle.
[TODO]
#if CONFIG_COMPONENT_MODEL
[EditorBrowsable(EditorBrowsableState.Advanced)]
#endif
public IntPtr GetHicon()
{
throw new SecurityException();
}
// Get the color of a specific pixel.
public Color GetPixel(int x, int y)
{
if(dgImage != null)
{
int pix = dgImage.GetFrame(0).GetPixel(x, y);
return Color.FromArgb((pix >> 16) & 0xFF,
(pix >> 8) & 0xFF,
pix & 0xFF);
}
return Color.Empty;
}
// Lock a region of this bitmap. Use of this method is discouraged.
// It assumes that managed arrays are fixed in place in memory,
// which is true for ilrun, but maybe not other CLR implementations.
// We also assume that "format" is the same as the bitmap's real format.
public unsafe BitmapData LockBits
(Rectangle rect, ImageLockMode flags,
System.Drawing.Imaging.PixelFormat format)
{
BitmapData bitmapData = new BitmapData();
bitmapData.Width = rect.Width;
bitmapData.Height = rect.Height;
bitmapData.PixelFormat = format;
if(dgImage != null)
{
Frame frame = dgImage.GetFrame(0);
if(frame != null)
{
if (format != this.PixelFormat)
{
frame = frame.Reformat((DotGNU.Images.PixelFormat) format);
}
bitmapData.Stride = frame.Stride;
byte[] data = frame.Data;
bitmapData.dataHandle = GCHandle.Alloc(data);
int offset = rect.X * GetPixelFormatSize(format) / 8;
// TODO: will GCHandle.AddrOfPinnedObject work more
// portably across GCs ?
fixed (byte *pixel = &(data[rect.Y * frame.Stride]))
{
bitmapData.Scan0 = (IntPtr)(void *)(pixel + offset);
}
}
}
return bitmapData;
}
// Make a particular color transparent within this bitmap.
public void MakeTransparent()
{
Color transparentColor = Color.LightGray;
if(Width > 1 && Height > 1)
{
transparentColor = GetPixel(0, Height - 1);
if(transparentColor.A == 0xFF)
{
// Use light grey
transparentColor = Color.LightGray;
}
}
MakeTransparent(transparentColor);
}
public void MakeTransparent(Color transparentColor)
{
// Make all the frames transparent.
for (int f = 0; f < dgImage.NumFrames; f++)
{
Frame frame = dgImage.GetFrame(f);
int color = transparentColor.ToArgb();
if(!Image.IsAlphaPixelFormat(PixelFormat))
{
// Remove the alpha component.
color = color & 0x00FFFFFF;
}
frame.MakeTransparent(color);
}
}
// Set a pixel within this bitmap.
public void SetPixel(int x, int y, Color color)
{
if(dgImage != null)
{
dgImage.GetFrame(0).SetPixel
(x, y, (color.R << 16) | (color.G << 8) | color.B);
}
}
// Set the resolution for this bitmap.
public void SetResolution(float dpiX, float dpiY)
{
horizontalResolution = dpiX;
verticalResolution = dpiY;
}
// Unlock the bits within this bitmap.
public void UnlockBits(BitmapData bitmapData)
{
// Nothing to do in this implementation.
bitmapData.dataHandle.Free();
}
}; // class Bitmap
}; // namespace System.Drawing
| |
/*
* Swaggy Jenkins
*
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.1.2-pre.0
* Contact: blah@cliffano.com
* Generated by: https://openapi-generator.tech
*/
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Org.OpenAPITools.Converters;
namespace Org.OpenAPITools.Models
{
/// <summary>
///
/// </summary>
[DataContract]
public partial class PipelineRunImpl : IEquatable<PipelineRunImpl>
{
/// <summary>
/// Gets or Sets Class
/// </summary>
[DataMember(Name="_class", EmitDefaultValue=false)]
public string Class { get; set; }
/// <summary>
/// Gets or Sets Links
/// </summary>
[DataMember(Name="_links", EmitDefaultValue=false)]
public PipelineRunImpllinks Links { get; set; }
/// <summary>
/// Gets or Sets DurationInMillis
/// </summary>
[DataMember(Name="durationInMillis", EmitDefaultValue=false)]
public int DurationInMillis { get; set; }
/// <summary>
/// Gets or Sets EnQueueTime
/// </summary>
[DataMember(Name="enQueueTime", EmitDefaultValue=false)]
public string EnQueueTime { get; set; }
/// <summary>
/// Gets or Sets EndTime
/// </summary>
[DataMember(Name="endTime", EmitDefaultValue=false)]
public string EndTime { get; set; }
/// <summary>
/// Gets or Sets EstimatedDurationInMillis
/// </summary>
[DataMember(Name="estimatedDurationInMillis", EmitDefaultValue=false)]
public int EstimatedDurationInMillis { get; set; }
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public string Id { get; set; }
/// <summary>
/// Gets or Sets Organization
/// </summary>
[DataMember(Name="organization", EmitDefaultValue=false)]
public string Organization { get; set; }
/// <summary>
/// Gets or Sets Pipeline
/// </summary>
[DataMember(Name="pipeline", EmitDefaultValue=false)]
public string Pipeline { get; set; }
/// <summary>
/// Gets or Sets Result
/// </summary>
[DataMember(Name="result", EmitDefaultValue=false)]
public string Result { get; set; }
/// <summary>
/// Gets or Sets RunSummary
/// </summary>
[DataMember(Name="runSummary", EmitDefaultValue=false)]
public string RunSummary { get; set; }
/// <summary>
/// Gets or Sets StartTime
/// </summary>
[DataMember(Name="startTime", EmitDefaultValue=false)]
public string StartTime { get; set; }
/// <summary>
/// Gets or Sets State
/// </summary>
[DataMember(Name="state", EmitDefaultValue=false)]
public string State { get; set; }
/// <summary>
/// Gets or Sets Type
/// </summary>
[DataMember(Name="type", EmitDefaultValue=false)]
public string Type { get; set; }
/// <summary>
/// Gets or Sets CommitId
/// </summary>
[DataMember(Name="commitId", EmitDefaultValue=false)]
public string CommitId { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class PipelineRunImpl {\n");
sb.Append(" Class: ").Append(Class).Append("\n");
sb.Append(" Links: ").Append(Links).Append("\n");
sb.Append(" DurationInMillis: ").Append(DurationInMillis).Append("\n");
sb.Append(" EnQueueTime: ").Append(EnQueueTime).Append("\n");
sb.Append(" EndTime: ").Append(EndTime).Append("\n");
sb.Append(" EstimatedDurationInMillis: ").Append(EstimatedDurationInMillis).Append("\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Organization: ").Append(Organization).Append("\n");
sb.Append(" Pipeline: ").Append(Pipeline).Append("\n");
sb.Append(" Result: ").Append(Result).Append("\n");
sb.Append(" RunSummary: ").Append(RunSummary).Append("\n");
sb.Append(" StartTime: ").Append(StartTime).Append("\n");
sb.Append(" State: ").Append(State).Append("\n");
sb.Append(" Type: ").Append(Type).Append("\n");
sb.Append(" CommitId: ").Append(CommitId).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
if (obj is null) return false;
if (ReferenceEquals(this, obj)) return true;
return obj.GetType() == GetType() && Equals((PipelineRunImpl)obj);
}
/// <summary>
/// Returns true if PipelineRunImpl instances are equal
/// </summary>
/// <param name="other">Instance of PipelineRunImpl to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(PipelineRunImpl other)
{
if (other is null) return false;
if (ReferenceEquals(this, other)) return true;
return
(
Class == other.Class ||
Class != null &&
Class.Equals(other.Class)
) &&
(
Links == other.Links ||
Links != null &&
Links.Equals(other.Links)
) &&
(
DurationInMillis == other.DurationInMillis ||
DurationInMillis.Equals(other.DurationInMillis)
) &&
(
EnQueueTime == other.EnQueueTime ||
EnQueueTime != null &&
EnQueueTime.Equals(other.EnQueueTime)
) &&
(
EndTime == other.EndTime ||
EndTime != null &&
EndTime.Equals(other.EndTime)
) &&
(
EstimatedDurationInMillis == other.EstimatedDurationInMillis ||
EstimatedDurationInMillis.Equals(other.EstimatedDurationInMillis)
) &&
(
Id == other.Id ||
Id != null &&
Id.Equals(other.Id)
) &&
(
Organization == other.Organization ||
Organization != null &&
Organization.Equals(other.Organization)
) &&
(
Pipeline == other.Pipeline ||
Pipeline != null &&
Pipeline.Equals(other.Pipeline)
) &&
(
Result == other.Result ||
Result != null &&
Result.Equals(other.Result)
) &&
(
RunSummary == other.RunSummary ||
RunSummary != null &&
RunSummary.Equals(other.RunSummary)
) &&
(
StartTime == other.StartTime ||
StartTime != null &&
StartTime.Equals(other.StartTime)
) &&
(
State == other.State ||
State != null &&
State.Equals(other.State)
) &&
(
Type == other.Type ||
Type != null &&
Type.Equals(other.Type)
) &&
(
CommitId == other.CommitId ||
CommitId != null &&
CommitId.Equals(other.CommitId)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
var hashCode = 41;
// Suitable nullity checks etc, of course :)
if (Class != null)
hashCode = hashCode * 59 + Class.GetHashCode();
if (Links != null)
hashCode = hashCode * 59 + Links.GetHashCode();
hashCode = hashCode * 59 + DurationInMillis.GetHashCode();
if (EnQueueTime != null)
hashCode = hashCode * 59 + EnQueueTime.GetHashCode();
if (EndTime != null)
hashCode = hashCode * 59 + EndTime.GetHashCode();
hashCode = hashCode * 59 + EstimatedDurationInMillis.GetHashCode();
if (Id != null)
hashCode = hashCode * 59 + Id.GetHashCode();
if (Organization != null)
hashCode = hashCode * 59 + Organization.GetHashCode();
if (Pipeline != null)
hashCode = hashCode * 59 + Pipeline.GetHashCode();
if (Result != null)
hashCode = hashCode * 59 + Result.GetHashCode();
if (RunSummary != null)
hashCode = hashCode * 59 + RunSummary.GetHashCode();
if (StartTime != null)
hashCode = hashCode * 59 + StartTime.GetHashCode();
if (State != null)
hashCode = hashCode * 59 + State.GetHashCode();
if (Type != null)
hashCode = hashCode * 59 + Type.GetHashCode();
if (CommitId != null)
hashCode = hashCode * 59 + CommitId.GetHashCode();
return hashCode;
}
}
#region Operators
#pragma warning disable 1591
public static bool operator ==(PipelineRunImpl left, PipelineRunImpl right)
{
return Equals(left, right);
}
public static bool operator !=(PipelineRunImpl left, PipelineRunImpl right)
{
return !Equals(left, right);
}
#pragma warning restore 1591
#endregion Operators
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Compute
{
using System;
using System.Collections.Generic;
using System.Threading;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Tests.Process;
using NUnit.Framework;
/// <summary>
/// Base class for all task-related tests.
/// </summary>
public abstract class AbstractTaskTest
{
/** */
protected const string Grid1Name = "grid1";
/** */
protected const string Grid2Name = "grid2";
/** */
protected const string Grid3Name = "grid3";
/** */
protected const string Cache1Name = "cache1";
/** Whether this is a test with forked JVMs. */
private readonly bool _fork;
/** First node. */
[NonSerialized]
protected IIgnite Grid1;
/** Second node. */
[NonSerialized]
private IIgnite _grid2;
/** Third node. */
[NonSerialized]
private IIgnite _grid3;
/** Second process. */
[NonSerialized]
private IgniteProcess _proc2;
/** Third process. */
[NonSerialized]
private IgniteProcess _proc3;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="fork">Fork flag.</param>
protected AbstractTaskTest(bool fork)
{
_fork = fork;
}
/// <summary>
/// Initialization routine.
/// </summary>
[TestFixtureSetUp]
public void InitClient()
{
TestUtils.KillProcesses();
if (_fork)
{
Grid1 = Ignition.Start(Configuration("config\\compute\\compute-standalone.xml"));
_proc2 = Fork("config\\compute\\compute-standalone.xml");
while (true)
{
if (!_proc2.Alive)
throw new Exception("Process 2 died unexpectedly: " + _proc2.Join());
if (Grid1.GetCluster().GetNodes().Count < 2)
Thread.Sleep(100);
else
break;
}
_proc3 = Fork("config\\compute\\compute-standalone.xml");
while (true)
{
if (!_proc3.Alive)
throw new Exception("Process 3 died unexpectedly: " + _proc3.Join());
if (Grid1.GetCluster().GetNodes().Count < 3)
Thread.Sleep(100);
else
break;
}
}
else
{
Grid1 = Ignition.Start(Configuration("config\\compute\\compute-grid1.xml"));
_grid2 = Ignition.Start(Configuration("config\\compute\\compute-grid2.xml"));
_grid3 = Ignition.Start(Configuration("config\\compute\\compute-grid3.xml"));
}
}
[SetUp]
public void BeforeTest()
{
Console.WriteLine("Test started: " + TestContext.CurrentContext.Test.Name);
}
[TestFixtureTearDown]
public void StopClient()
{
if (Grid1 != null)
Ignition.Stop(Grid1.Name, true);
if (_fork)
{
if (_proc2 != null) {
_proc2.Kill();
_proc2.Join();
}
if (_proc3 != null)
{
_proc3.Kill();
_proc3.Join();
}
}
else
{
if (_grid2 != null)
Ignition.Stop(_grid2.Name, true);
if (_grid3 != null)
Ignition.Stop(_grid3.Name, true);
}
}
/// <summary>
/// Configuration for node.
/// </summary>
/// <param name="path">Path to Java XML configuration.</param>
/// <returns>Node configuration.</returns>
protected IgniteConfiguration Configuration(string path)
{
IgniteConfiguration cfg = new IgniteConfiguration();
if (!_fork)
{
BinaryConfiguration portCfg = new BinaryConfiguration();
ICollection<BinaryTypeConfiguration> portTypeCfgs = new List<BinaryTypeConfiguration>();
GetBinaryTypeConfigurations(portTypeCfgs);
portCfg.TypeConfigurations = portTypeCfgs;
cfg.BinaryConfiguration = portCfg;
}
cfg.JvmClasspath = TestUtils.CreateTestClasspath();
cfg.JvmOptions = TestUtils.TestJavaOptions();
cfg.SpringConfigUrl = path;
return cfg;
}
/// <summary>
/// Create forked process with the following Spring config.
/// </summary>
/// <param name="path">Path to Java XML configuration.</param>
/// <returns>Forked process.</returns>
private static IgniteProcess Fork(string path)
{
return new IgniteProcess(
"-springConfigUrl=" + path,
"-J-ea",
"-J-Xcheck:jni",
"-J-Xms512m",
"-J-Xmx512m",
"-J-DIGNITE_QUIET=false"
//"-J-Xnoagent", "-J-Djava.compiler=NONE", "-J-Xdebug", "-J-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5006"
);
}
/// <summary>
/// Define binary types.
/// </summary>
/// <param name="portTypeCfgs">Binary type configurations.</param>
protected virtual void GetBinaryTypeConfigurations(ICollection<BinaryTypeConfiguration> portTypeCfgs)
{
// No-op.
}
}
}
| |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
using System.Reflection;
#endif
[System.AttributeUsage(System.AttributeTargets.Field)]
public class FilePathAttribute : PropertyAttribute
{
public enum PathType
{
File,
FileInProject,
FileInStreamingAssets,
Folder
};
public enum DialogType
{
Open,
Save,
};
#if UNITY_EDITOR
PathType pathType;
DialogType dialogType = DialogType.Save;
string fileType = "";
#endif
public FilePathAttribute(PathType _pathType)
{
#if UNITY_EDITOR
this.pathType = _pathType;
#endif
}
public FilePathAttribute(string _fileType, PathType _pathType = PathType.File, DialogType dialogType = DialogType.Save)
{
#if UNITY_EDITOR
this.fileType = _fileType;
this.dialogType = dialogType;
this.pathType = _pathType;
#endif
}
#if UNITY_EDITOR
public bool PathExists(string CurrentFilename)
{
try
{
var Path = System.IO.Path.GetFullPath(CurrentFilename);
switch ( this.pathType )
{
case PathType.File:
case PathType.FileInProject:
case PathType.FileInStreamingAssets:
return System.IO.File.Exists(Path);
case PathType.Folder:
return System.IO.Directory.Exists(Path);
}
}
catch
{
}
return false;
}
#endif
#if UNITY_EDITOR
public string BrowseForPath(string PanelTitle,string CurrentFilename)
{
var Dir = "";
try
{
Dir = System.IO.Path.GetFullPath (CurrentFilename);
}
catch{
}
var Filename = CurrentFilename;
try
{
Filename = System.IO.Path.GetFileName (CurrentFilename);
}
catch{
}
System.Func<string, string, string> OpenFilePanelInProject = (Title, FileType) =>
{
if (string.IsNullOrEmpty(Dir))
Dir = PopX.IO.Application_ProjectPath;
var Path = EditorUtility.OpenFilePanel(Title, Dir, FileType);
return PopX.IO.GetProjectRelativePath(Path);
};
System.Func<string, string, string> OpenFilePanelInStreamingAssets = (Title, FileType) =>
{
if (string.IsNullOrEmpty(Dir))
Dir = Application.streamingAssetsPath;
var Path = EditorUtility.OpenFilePanel(Title, Dir, FileType);
return PopX.IO.GetStreamingAssetsRelativePath(Path);
};
if (string.IsNullOrEmpty (Filename))
Filename = "Filename";
if (pathType == PathType.File && dialogType == DialogType.Save)
return EditorUtility.SaveFilePanel(PanelTitle, Dir, Filename, fileType);
if (pathType == PathType.File && dialogType == DialogType.Open)
return EditorUtility.OpenFilePanel(PanelTitle, Dir, fileType);
if (pathType == PathType.FileInProject && dialogType == DialogType.Save)
return EditorUtility.SaveFilePanelInProject(PanelTitle, Filename, fileType, "");
if (pathType == PathType.FileInProject && dialogType == DialogType.Open)
return OpenFilePanelInProject(PanelTitle, fileType);
if (pathType == PathType.FileInStreamingAssets && dialogType == DialogType.Open)
return OpenFilePanelInStreamingAssets(PanelTitle, fileType);
if (pathType == PathType.Folder && dialogType == DialogType.Save)
return EditorUtility.SaveFolderPanel(PanelTitle, Dir, Filename);
if (pathType == PathType.Folder && dialogType == DialogType.Open)
return EditorUtility.OpenFolderPanel(PanelTitle, Dir, Filename);
throw new System.Exception ("Unhandled path/dialog type " + pathType + "/" + dialogType);
}
#endif
}
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(FilePathAttribute))]
public class FilePathAttributePropertyDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
var Attrib = (FilePathAttribute)attribute;
var TargetObject = property.serializedObject.targetObject;
bool ShowShowButton = Attrib.PathExists (property.stringValue);
// calc sizes
float BrowseWidthPercent = 0.12f;
float ShowWidthPercent = ShowShowButton ? 0.10f : 0;
var BrowseWidth = position.width * BrowseWidthPercent;
var ShowWidth = position.width * ShowWidthPercent;
var FieldWidth = position.width * (1 - BrowseWidthPercent - ShowWidthPercent);
Rect FieldRect = new Rect (new Vector2(position.xMin,position.yMin), new Vector2 (FieldWidth, position.height));
Rect ShowRect = new Rect ( new Vector2(FieldRect.xMax,position.yMin), new Vector2 (ShowWidth, position.height));
Rect BrowseRect = new Rect ( new Vector2(ShowRect.xMax,position.yMin), new Vector2 (BrowseWidth, position.height));
// draw browse button
if (GUI.Button (BrowseRect, "Browse..."))
{
var CurrentPath = property.stringValue;
var NewPath = Attrib.BrowseForPath ( TargetObject.name, CurrentPath );
// empty = cancelled
if ( !string.IsNullOrEmpty(NewPath)) {
property.stringValue = NewPath;
}
}
if (ShowShowButton) {
if (GUI.Button (ShowRect, "Show")) {
try {
var CurrentPath = property.stringValue;
CurrentPath = System.IO.Path.GetFullPath (CurrentPath);
EditorUtility.RevealInFinder (CurrentPath);
} catch {
}
}
}
// draw normal field
EditorGUI.PropertyField (FieldRect, property, label, true);
}
/*
public override float GetPropertyHeight (SerializedProperty property, GUIContent label)
{
var Attrib = (ShowIfAttribute)attribute;
var TargetObject = property.serializedObject.targetObject;
if ( IsVisible(TargetObject,Attrib)) {
//base.OnGUI (position, prop, label);
return base.GetPropertyHeight ( property, label);
}
return 0;
}
*/
}
#endif
| |
using System.Linq;
using FluentNHibernate.Mapping;
using FluentNHibernate.Mapping.Providers;
using FluentNHibernate.MappingModel;
using FluentNHibernate.MappingModel.ClassBased;
using FluentNHibernate.Visitors;
using NUnit.Framework;
namespace FluentNHibernate.Testing.PersistenceModelTests
{
[TestFixture]
public class SeparateSubclassVisitorFixture
{
private IIndeterminateSubclassMappingProviderCollection providers;
private ClassMapping fooMapping;
[SetUp]
public void SetUp()
{
providers = new IndeterminateSubclassMappingProviderCollection();
}
[Test]
public void Should_add_subclass_that_implements_the_parent_interface()
{
/* The Parent is the IFoo interface the desired results
* of this test is the inclusion of the Foo<T> through the
* GenericFooMap<T> subclass mapping.
*/
fooMapping = ((IMappingProvider)new FooMap()).GetClassMapping();
providers.Add(new StringFooMap());
var sut = CreateSut();
sut.ProcessClass(fooMapping);
Assert.AreEqual(1, fooMapping.Subclasses.Count());
Assert.AreEqual(1, fooMapping.Subclasses.Where(sub => sub.Type.Equals(typeof(Foo<string>))).Count());
}
[Test]
public void Should_add_subclass_that_implements_the_parent_base()
{
/* The Parent is the FooBase class the desired results
* of this test is the inclusion of the Foo<T> through the
* GenericFooMap<T> subclass mapping.
*/
fooMapping = ((IMappingProvider)new BaseMap()).GetClassMapping();
providers.Add(new StringFooMap());
var sut = CreateSut();
sut.ProcessClass(fooMapping);
Assert.AreEqual(1, fooMapping.Subclasses.Count());
Assert.AreEqual(1, fooMapping.Subclasses.Where(sub => sub.Type.Equals(typeof(Foo<string>))).Count());
}
[Test]
public void Should_not_add_subclassmap_that_does_not_implement_parent_interface()
{
/* The Parent is the IFoo interface the desired results
* of this test is the exclusion of the StandAlone class
* since it does not implement the interface.
*/
fooMapping = ((IMappingProvider)new FooMap()).GetClassMapping();
providers.Add(new StandAloneMap());
var sut = CreateSut();
sut.ProcessClass(fooMapping);
Assert.AreEqual(0, fooMapping.Subclasses.Count());
}
[Test]
public void Should_not_add_subclassmap_that_does_not_implement_parent_base()
{
/* The Parent is the FooBase class the desired results
* of this test is the exclusion of the StandAlone class
* since it does not implement the interface.
*/
fooMapping = ((IMappingProvider)new BaseMap()).GetClassMapping();
providers.Add(new StandAloneMap());
var sut = CreateSut();
sut.ProcessClass(fooMapping);
Assert.AreEqual(0, fooMapping.Subclasses.Count());
}
[Test]
public void Should_not_add_subclassmap_that_implements_a_subclass_of_the_parent_interface()
{
/* The Parent is the IFoo interface the desired results
* of this test is the inclusion of the BaseImpl class and
* the exclusion of the Foo<T> class since it implements
* the BaseImpl class which already implements FooBase.
*/
fooMapping = ((IMappingProvider)new FooMap()).GetClassMapping();
providers.Add(new BaseImplMap());
providers.Add(new StringFooMap());
var sut = CreateSut();
sut.ProcessClass(fooMapping);
Assert.AreEqual(1, fooMapping.Subclasses.Count());
Assert.AreEqual(1, fooMapping.Subclasses.Where(sub => sub.Type.Equals(typeof(BaseImpl))).Count());
}
[Test]
public void Should_not_add_subclassmap_that_implements_a_subclass_of_the_parent_base()
{
/* The Parent is the FooBase class the desired results
* of this test is the inclusion of the BaseImpl class and
* the exclusion of the Foo<T> class since it implements
* the BaseImpl class which already implements FooBase.
*/
fooMapping = ((IMappingProvider)new BaseMap()).GetClassMapping();
providers.Add(new BaseImplMap());
providers.Add(new StringFooMap());
var sut = CreateSut();
sut.ProcessClass(fooMapping);
Assert.AreEqual(1, fooMapping.Subclasses.Count());
Assert.AreEqual(1, fooMapping.Subclasses.Where(sub => sub.Type.Equals(typeof(BaseImpl))).Count());
}
[Test]
public void Should_add_explicit_extend_subclasses_to_their_parent()
{
fooMapping = ((IMappingProvider)new ExtendsParentMap()).GetClassMapping();
providers.Add(new ExtendsChildMap());
var sut = CreateSut();
sut.ProcessClass(fooMapping);
Assert.AreEqual(1, fooMapping.Subclasses.Count());
Assert.AreEqual(1, fooMapping.Subclasses.Where(sub => sub.Type.Equals(typeof(ExtendsChild))).Count());
}
[Test]
public void Should_choose_UnionSubclass_when_the_class_mapping_IsUnionSubclass_is_true()
{
fooMapping = ((IMappingProvider)new BaseMap()).GetClassMapping();
fooMapping.Set(x => x.IsUnionSubclass, Layer.Defaults, true);
providers.Add(new StringFooMap());
var sut = CreateSut();
sut.ProcessClass(fooMapping);
fooMapping.Subclasses.First().SubclassType.ShouldEqual(SubclassType.UnionSubclass);
}
private SeparateSubclassVisitor CreateSut()
{
return new SeparateSubclassVisitor(providers);
}
private interface IFoo
{ }
private class Base : IFoo
{ }
private abstract class BaseImpl : Base
{ }
private class Foo<T> : BaseImpl, IFoo
{ }
private class FooMap : ClassMap<IFoo>
{ }
private class BaseMap : ClassMap<Base>
{ }
private class BaseImplMap : SubclassMap<BaseImpl>
{ }
private abstract class GenericFooMap<T> : SubclassMap<Foo<T>>
{ }
private class StringFooMap : GenericFooMap<string>
{ }
private interface IStand
{ }
private class StandAlone : IStand
{ }
private class StandAloneMap : SubclassMap<StandAlone>
{ }
class ExtendsParent
{}
class ExtendsChild
{}
class ExtendsParentMap : ClassMap<ExtendsParent>
{}
class ExtendsChildMap : SubclassMap<ExtendsChild>
{
public ExtendsChildMap()
{
Extends<ExtendsParent>();
}
}
}
}
| |
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Implementation.TodoComments;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.TodoComment
{
public class TodoCommentTests
{
[WpfFact]
public async Task SingleLineTodoComment_Colon()
{
var code = @"// [|TODO:test|]";
await TestAsync(code);
}
[WpfFact]
public async Task SingleLineTodoComment_Space()
{
var code = @"// [|TODO test|]";
await TestAsync(code);
}
[WpfFact]
public async Task SingleLineTodoComment_Underscore()
{
var code = @"// TODO_test";
await TestAsync(code);
}
[WpfFact]
public async Task SingleLineTodoComment_Number()
{
var code = @"// TODO1 test";
await TestAsync(code);
}
[WpfFact]
public async Task SingleLineTodoComment_Quote()
{
var code = @"// ""TODO test""";
await TestAsync(code);
}
[WpfFact]
public async Task SingleLineTodoComment_Middle()
{
var code = @"// Hello TODO test";
await TestAsync(code);
}
[WpfFact]
public async Task SingleLineTodoComment_Document()
{
var code = @"/// [|TODO test|]";
await TestAsync(code);
}
[WpfFact]
public async Task SingleLineTodoComment_Preprocessor1()
{
var code = @"#if DEBUG // [|TODO test|]";
await TestAsync(code);
}
[WpfFact]
public async Task SingleLineTodoComment_Preprocessor2()
{
var code = @"#if DEBUG /// [|TODO test|]";
await TestAsync(code);
}
[WpfFact]
public async Task SingleLineTodoComment_Region()
{
var code = @"#region // TODO test";
await TestAsync(code);
}
[WpfFact]
public async Task SingleLineTodoComment_EndRegion()
{
var code = @"#endregion // [|TODO test|]";
await TestAsync(code);
}
[WpfFact]
public async Task SingleLineTodoComment_TrailingSpan()
{
var code = @"// [|TODO test |]";
await TestAsync(code);
}
[WpfFact]
public async Task MultilineTodoComment_Singleline()
{
var code = @"/* [|TODO: hello |]*/";
await TestAsync(code);
}
[WpfFact]
public async Task MultilineTodoComment_Singleline_Document()
{
var code = @"/** [|TODO: hello |]*/";
await TestAsync(code);
}
[WpfFact]
public async Task MultilineTodoComment_Multiline()
{
var code = @"
/* [|TODO: hello |]
[|TODO: hello |]
[|TODO: hello |]
* [|TODO: hello |]
[|TODO: hello |]*/";
await TestAsync(code);
}
[WpfFact]
public async Task MultilineTodoComment_Multiline_DocComment()
{
var code = @"
/** [|TODO: hello |]
[|TODO: hello |]
[|TODO: hello |]
* [|TODO: hello |]
[|TODO: hello |]*/";
await TestAsync(code);
}
[WpfFact]
public async Task SinglelineDocumentComment_Multiline()
{
var code = @"
/// <summary>
/// [|TODO : test |]
/// </summary>
/// [|UNDONE: test2 |]";
await TestAsync(code);
}
private static async Task TestAsync(string codeWithMarker)
{
using (var workspace = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(codeWithMarker))
{
var commentTokens = new TodoCommentTokens();
var provider = new TodoCommentIncrementalAnalyzerProvider(commentTokens);
var worker = (TodoCommentIncrementalAnalyzer)provider.CreateIncrementalAnalyzer(workspace);
var document = workspace.Documents.First();
var documentId = document.Id;
var reasons = new InvocationReasons(PredefinedInvocationReasons.DocumentAdded);
worker.AnalyzeSyntaxAsync(workspace.CurrentSolution.GetDocument(documentId), CancellationToken.None).Wait();
var todoLists = worker.GetItems_TestingOnly(documentId);
var expectedLists = document.SelectedSpans;
Assert.Equal(todoLists.Length, expectedLists.Count);
for (int i = 0; i < todoLists.Length; i++)
{
var todo = todoLists[i];
var span = expectedLists[i];
var line = document.InitialTextSnapshot.GetLineFromPosition(span.Start);
var text = document.InitialTextSnapshot.GetText(span.ToSpan());
Assert.Equal(todo.MappedLine, line.LineNumber);
Assert.Equal(todo.MappedColumn, span.Start - line.Start);
Assert.Equal(todo.Message, text);
}
}
}
}
}
| |
#region Copyright notice and license
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using Grpc.Core.Utils;
namespace Grpc.Core
{
/// <summary>
/// A collection of metadata entries that can be exchanged during a call.
/// gRPC supports these types of metadata:
/// <list type="bullet">
/// <item><term>Request headers</term><description>are sent by the client at the beginning of a remote call before any request messages are sent.</description></item>
/// <item><term>Response headers</term><description>are sent by the server at the beginning of a remote call handler before any response messages are sent.</description></item>
/// <item><term>Response trailers</term><description>are sent by the server at the end of a remote call along with resulting call status.</description></item>
/// </list>
/// </summary>
public sealed class Metadata : IList<Metadata.Entry>
{
/// <summary>
/// All binary headers should have this suffix.
/// </summary>
public const string BinaryHeaderSuffix = "-bin";
/// <summary>
/// An read-only instance of metadata containing no entries.
/// </summary>
public static readonly Metadata Empty = new Metadata().Freeze();
/// <summary>
/// To be used in initial metadata to request specific compression algorithm
/// for given call. Direct selection of compression algorithms is an internal
/// feature and is not part of public API.
/// </summary>
internal const string CompressionRequestAlgorithmMetadataKey = "grpc-internal-encoding-request";
static readonly Encoding EncodingASCII = System.Text.Encoding.ASCII;
readonly List<Entry> entries;
bool readOnly;
/// <summary>
/// Initializes a new instance of <c>Metadata</c>.
/// </summary>
public Metadata()
{
this.entries = new List<Entry>();
}
/// <summary>
/// Makes this object read-only.
/// </summary>
/// <returns>this object</returns>
internal Metadata Freeze()
{
this.readOnly = true;
return this;
}
// TODO: add support for access by key
#region IList members
/// <summary>
/// <see cref="T:IList`1"/>
/// </summary>
public int IndexOf(Metadata.Entry item)
{
return entries.IndexOf(item);
}
/// <summary>
/// <see cref="T:IList`1"/>
/// </summary>
public void Insert(int index, Metadata.Entry item)
{
GrpcPreconditions.CheckNotNull(item);
CheckWriteable();
entries.Insert(index, item);
}
/// <summary>
/// <see cref="T:IList`1"/>
/// </summary>
public void RemoveAt(int index)
{
CheckWriteable();
entries.RemoveAt(index);
}
/// <summary>
/// <see cref="T:IList`1"/>
/// </summary>
public Metadata.Entry this[int index]
{
get
{
return entries[index];
}
set
{
GrpcPreconditions.CheckNotNull(value);
CheckWriteable();
entries[index] = value;
}
}
/// <summary>
/// <see cref="T:IList`1"/>
/// </summary>
public void Add(Metadata.Entry item)
{
GrpcPreconditions.CheckNotNull(item);
CheckWriteable();
entries.Add(item);
}
/// <summary>
/// Adds a new ASCII-valued metadata entry. See <c>Metadata.Entry</c> constructor for params.
/// </summary>
public void Add(string key, string value)
{
Add(new Entry(key, value));
}
/// <summary>
/// Adds a new binary-valued metadata entry. See <c>Metadata.Entry</c> constructor for params.
/// </summary>
public void Add(string key, byte[] valueBytes)
{
Add(new Entry(key, valueBytes));
}
/// <summary>
/// <see cref="T:IList`1"/>
/// </summary>
public void Clear()
{
CheckWriteable();
entries.Clear();
}
/// <summary>
/// <see cref="T:IList`1"/>
/// </summary>
public bool Contains(Metadata.Entry item)
{
return entries.Contains(item);
}
/// <summary>
/// <see cref="T:IList`1"/>
/// </summary>
public void CopyTo(Metadata.Entry[] array, int arrayIndex)
{
entries.CopyTo(array, arrayIndex);
}
/// <summary>
/// <see cref="T:IList`1"/>
/// </summary>
public int Count
{
get { return entries.Count; }
}
/// <summary>
/// <see cref="T:IList`1"/>
/// </summary>
public bool IsReadOnly
{
get { return readOnly; }
}
/// <summary>
/// <see cref="T:IList`1"/>
/// </summary>
public bool Remove(Metadata.Entry item)
{
CheckWriteable();
return entries.Remove(item);
}
/// <summary>
/// <see cref="T:IList`1"/>
/// </summary>
public IEnumerator<Metadata.Entry> GetEnumerator()
{
return entries.GetEnumerator();
}
IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return entries.GetEnumerator();
}
private void CheckWriteable()
{
GrpcPreconditions.CheckState(!readOnly, "Object is read only");
}
#endregion
/// <summary>
/// Metadata entry
/// </summary>
public class Entry
{
readonly string key;
readonly string value;
readonly byte[] valueBytes;
private Entry(string key, string value, byte[] valueBytes)
{
this.key = key;
this.value = value;
this.valueBytes = valueBytes;
}
/// <summary>
/// Initializes a new instance of the <see cref="Grpc.Core.Metadata.Entry"/> struct with a binary value.
/// </summary>
/// <param name="key">Metadata key. Gets converted to lowercase. Needs to have suffix indicating a binary valued metadata entry. Can only contain lowercase alphanumeric characters, underscores, hyphens and dots.</param>
/// <param name="valueBytes">Value bytes.</param>
public Entry(string key, byte[] valueBytes)
{
this.key = NormalizeKey(key);
GrpcPreconditions.CheckArgument(HasBinaryHeaderSuffix(this.key),
"Key for binary valued metadata entry needs to have suffix indicating binary value.");
this.value = null;
GrpcPreconditions.CheckNotNull(valueBytes, "valueBytes");
this.valueBytes = new byte[valueBytes.Length];
Buffer.BlockCopy(valueBytes, 0, this.valueBytes, 0, valueBytes.Length); // defensive copy to guarantee immutability
}
/// <summary>
/// Initializes a new instance of the <see cref="Grpc.Core.Metadata.Entry"/> struct with an ASCII value.
/// </summary>
/// <param name="key">Metadata key. Gets converted to lowercase. Must not use suffix indicating a binary valued metadata entry. Can only contain lowercase alphanumeric characters, underscores, hyphens and dots.</param>
/// <param name="value">Value string. Only ASCII characters are allowed.</param>
public Entry(string key, string value)
{
this.key = NormalizeKey(key);
GrpcPreconditions.CheckArgument(!HasBinaryHeaderSuffix(this.key),
"Key for ASCII valued metadata entry cannot have suffix indicating binary value.");
this.value = GrpcPreconditions.CheckNotNull(value, "value");
this.valueBytes = null;
}
/// <summary>
/// Gets the metadata entry key.
/// </summary>
public string Key
{
get
{
return this.key;
}
}
/// <summary>
/// Gets the binary value of this metadata entry.
/// </summary>
public byte[] ValueBytes
{
get
{
if (valueBytes == null)
{
return EncodingASCII.GetBytes(value);
}
// defensive copy to guarantee immutability
var bytes = new byte[valueBytes.Length];
Buffer.BlockCopy(valueBytes, 0, bytes, 0, valueBytes.Length);
return bytes;
}
}
/// <summary>
/// Gets the string value of this metadata entry.
/// </summary>
public string Value
{
get
{
GrpcPreconditions.CheckState(!IsBinary, "Cannot access string value of a binary metadata entry");
return value ?? EncodingASCII.GetString(valueBytes);
}
}
/// <summary>
/// Returns <c>true</c> if this entry is a binary-value entry.
/// </summary>
public bool IsBinary
{
get
{
return value == null;
}
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents the current <see cref="Grpc.Core.Metadata.Entry"/>.
/// </summary>
public override string ToString()
{
if (IsBinary)
{
return string.Format("[Entry: key={0}, valueBytes={1}]", key, valueBytes);
}
return string.Format("[Entry: key={0}, value={1}]", key, value);
}
/// <summary>
/// Gets the serialized value for this entry. For binary metadata entries, this leaks
/// the internal <c>valueBytes</c> byte array and caller must not change contents of it.
/// </summary>
internal byte[] GetSerializedValueUnsafe()
{
return valueBytes ?? EncodingASCII.GetBytes(value);
}
/// <summary>
/// Creates a binary value or ascii value metadata entry from data received from the native layer.
/// We trust C core to give us well-formed data, so we don't perform any checks or defensive copying.
/// </summary>
internal static Entry CreateUnsafe(string key, byte[] valueBytes)
{
if (HasBinaryHeaderSuffix(key))
{
return new Entry(key, null, valueBytes);
}
return new Entry(key, EncodingASCII.GetString(valueBytes), null);
}
private static string NormalizeKey(string key)
{
GrpcPreconditions.CheckNotNull(key, "key");
GrpcPreconditions.CheckArgument(IsValidKey(key, out bool isLowercase),
"Metadata entry key not valid. Keys can only contain lowercase alphanumeric characters, underscores, hyphens and dots.");
if (isLowercase)
{
// save allocation of a new string if already lowercase
return key;
}
return key.ToLowerInvariant();
}
private static bool IsValidKey(string input, out bool isLowercase)
{
isLowercase = true;
for (int i = 0; i < input.Length; i++)
{
char c = input[i];
if ('a' <= c && c <= 'z' ||
'0' <= c && c <= '9' ||
c == '.' ||
c == '_' ||
c == '-' )
continue;
if ('A' <= c && c <= 'Z')
{
isLowercase = false;
continue;
}
return false;
}
return true;
}
/// <summary>
/// Returns <c>true</c> if the key has "-bin" binary header suffix.
/// </summary>
private static bool HasBinaryHeaderSuffix(string key)
{
// We don't use just string.EndsWith because its implementation is extremely slow
// on CoreCLR and we've seen significant differences in gRPC benchmarks caused by it.
// See https://github.com/dotnet/coreclr/issues/5612
int len = key.Length;
if (len >= 4 &&
key[len - 4] == '-' &&
key[len - 3] == 'b' &&
key[len - 2] == 'i' &&
key[len - 1] == 'n')
{
return true;
}
return false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: Platform independent integer
**
**
===========================================================*/
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
namespace System
{
// CONTRACT with Runtime
// The UIntPtr type is one of the primitives understood by the compilers and runtime
// Data Contract: Single field of type void *
[CLSCompliant(false)]
public struct UIntPtr : IEquatable<UIntPtr>
{
unsafe private void* _value;
[Intrinsic]
public static readonly UIntPtr Zero;
[Intrinsic]
[NonVersionable]
public unsafe UIntPtr(uint value)
{
_value = (void*)value;
}
[Intrinsic]
[NonVersionable]
public unsafe UIntPtr(ulong value)
{
#if BIT64
_value = (void*)value;
#else
_value = (void*)checked((uint)value);
#endif
}
[Intrinsic]
[NonVersionable]
public unsafe UIntPtr(void* value)
{
_value = value;
}
[Intrinsic]
[NonVersionable]
public unsafe void* ToPointer()
{
return _value;
}
[Intrinsic]
[NonVersionable]
public unsafe uint ToUInt32()
{
#if BIT64
return checked((uint)_value);
#else
return (uint)_value;
#endif
}
[Intrinsic]
[NonVersionable]
public unsafe ulong ToUInt64()
{
return (ulong)_value;
}
[Intrinsic]
[NonVersionable]
public static explicit operator UIntPtr(uint value)
{
return new UIntPtr(value);
}
[Intrinsic]
[NonVersionable]
public static explicit operator UIntPtr(ulong value)
{
return new UIntPtr(value);
}
[Intrinsic]
[NonVersionable]
public static unsafe explicit operator UIntPtr(void* value)
{
return new UIntPtr(value);
}
[Intrinsic]
[NonVersionable]
public static unsafe explicit operator void* (UIntPtr value)
{
return value._value;
}
[Intrinsic]
[NonVersionable]
public unsafe static explicit operator uint (UIntPtr value)
{
#if BIT64
return checked((uint)value._value);
#else
return (uint)value._value;
#endif
}
[Intrinsic]
[NonVersionable]
public unsafe static explicit operator ulong (UIntPtr value)
{
return (ulong)value._value;
}
unsafe bool IEquatable<UIntPtr>.Equals(UIntPtr value)
{
return _value == value._value;
}
[Intrinsic]
[NonVersionable]
public unsafe static bool operator ==(UIntPtr value1, UIntPtr value2)
{
return value1._value == value2._value;
}
[Intrinsic]
[NonVersionable]
public unsafe static bool operator !=(UIntPtr value1, UIntPtr value2)
{
return value1._value != value2._value;
}
public static unsafe int Size
{
[Intrinsic]
[NonVersionable]
get
{
#if BIT64
return 8;
#else
return 4;
#endif
}
}
public unsafe override String ToString()
{
#if BIT64
return ((ulong)_value).ToString(FormatProvider.InvariantCulture);
#else
return ((uint)_value).ToString(FormatProvider.InvariantCulture);
#endif
}
public unsafe override bool Equals(Object obj)
{
if (obj is UIntPtr)
{
return (_value == ((UIntPtr)obj)._value);
}
return false;
}
public unsafe override int GetHashCode()
{
#if BIT64
ulong l = (ulong)_value;
return (unchecked((int)l) ^ (int)(l >> 32));
#else
return unchecked((int)_value);
#endif
}
[NonVersionable]
public static UIntPtr Add(UIntPtr pointer, int offset)
{
return pointer + offset;
}
[Intrinsic]
[NonVersionable]
public static UIntPtr operator +(UIntPtr pointer, int offset)
{
#if BIT64
return new UIntPtr(pointer.ToUInt64() + (ulong)offset);
#else
return new UIntPtr(pointer.ToUInt32() + (uint)offset);
#endif
}
[NonVersionable]
public static UIntPtr Subtract(UIntPtr pointer, int offset)
{
return pointer - offset;
}
[Intrinsic]
[NonVersionable]
public static UIntPtr operator -(UIntPtr pointer, int offset)
{
#if BIT64
return new UIntPtr(pointer.ToUInt64() - (ulong)offset);
#else
return new UIntPtr(pointer.ToUInt32() - (uint)offset);
#endif
}
}
}
| |
/*
Copyright (c) 2004-2009 Krzysztof Ostrowski. All rights reserved.
Redistribution and use in source and binary forms,
with or without modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
THIS SOFTWARE IS PROVIDED "AS IS" BY THE ABOVE COPYRIGHT HOLDER(S)
AND ALL OTHER CONTRIBUTORS AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDER(S) OR ANY OTHER
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace QS.Fx.Attributes
{
public sealed class Attributes : IAttributes
{
#region Constructor
public Attributes(params IAttribute[] _attributes)
{
foreach (IAttribute _attribute in _attributes)
this._attributes.Add(_attribute.Class, _attribute);
}
public Attributes(object _object)
{
Type type = _object.GetType();
foreach (System.Reflection.FieldInfo info in type.GetFields(System.Reflection.BindingFlags.Public |
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance))
{
if (info.FieldType.Equals(typeof(string)))
{
foreach (AttributeAttribute _attribute in info.GetCustomAttributes(typeof(AttributeAttribute), true))
{
QS.Fx.Base.ID id = new QS.Fx.Base.ID(_attribute.Class);
IAttributeClass c;
if (AttributeClasses.GetAttributeClass(id, out c))
{
IAttribute a = new _AttributeFromField(c, _object, info);
_attributes.Add(c, a);
}
}
}
}
foreach (System.Reflection.PropertyInfo info in type.GetProperties(System.Reflection.BindingFlags.Public |
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance))
{
if (info.PropertyType.Equals(typeof(string)))
{
foreach (AttributeAttribute _attribute in info.GetCustomAttributes(typeof(AttributeAttribute), true))
{
QS.Fx.Base.ID id = new QS.Fx.Base.ID(_attribute.Class);
IAttributeClass c;
if (AttributeClasses.GetAttributeClass(id, out c))
{
IAttribute a = new _AttributeFromProperty(c, _object, info);
_attributes.Add(c, a);
}
}
}
}
}
#endregion
#region Fields
private IDictionary<IAttributeClass, IAttribute> _attributes = new Dictionary<IAttributeClass, IAttribute>();
#endregion
#region IAttributes Members
bool IAttributes.Get(IAttributeClass _class, out IAttribute _attribute)
{
lock (this)
{
return _attributes.TryGetValue(_class, out _attribute);
}
}
IAttribute IAttributes.Get(IAttributeClass _class)
{
lock (this)
{
IAttribute _attribute;
if (!_attributes.TryGetValue(_class, out _attribute))
throw new Exception("Cannot attribute of class \"" + _class.ID.ToString() + "\".");
return _attribute;
}
}
#endregion
#region IEnumerable<IAttribute> Members
IEnumerator<IAttribute> IEnumerable<IAttribute>.GetEnumerator()
{
lock (this)
{
List<IAttribute> __attributes = new List<IAttribute>(_attributes.Values);
return __attributes.GetEnumerator();
}
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
lock (this)
{
List<object> __attributes = new List<object>();
foreach (Attribute _attribute in _attributes.Values)
__attributes.Add(_attribute);
return __attributes.GetEnumerator();
}
}
#endregion
#region Class _AttributeFromField
private class _AttributeFromField : IAttribute
{
#region Constructor
public _AttributeFromField(IAttributeClass _class, object _object, System.Reflection.FieldInfo _fieldinfo)
{
this._class = _class;
this._object = _object;
this._fieldinfo = _fieldinfo;
}
#endregion
#region Fields
private IAttributeClass _class;
private object _object;
private System.Reflection.FieldInfo _fieldinfo;
#endregion
#region IAttribute Members
IAttributeClass IAttribute.Class
{
get { return _class; }
}
string IAttribute.Value
{
get { return (string) _fieldinfo.GetValue(_object); }
}
#endregion
}
#endregion
#region Class _AttributeFromProperty
private class _AttributeFromProperty : IAttribute
{
#region Constructor
public _AttributeFromProperty(IAttributeClass _class, object _object, System.Reflection.PropertyInfo _propertyinfo)
{
this._class = _class;
this._object = _object;
this._propertyinfo = _propertyinfo;
}
#endregion
#region Fields
private IAttributeClass _class;
private object _object;
private System.Reflection.PropertyInfo _propertyinfo;
#endregion
#region IAttribute Members
IAttributeClass IAttribute.Class
{
get { return _class; }
}
string IAttribute.Value
{
get { return (string) _propertyinfo.GetValue(_object, null); }
}
#endregion
}
#endregion
#region Serialize
public static QS.Fx.Reflection.Xml.Attribute[] Serialize(QS.Fx.Attributes.IAttributes _attributes)
{
List<QS.Fx.Reflection.Xml.Attribute> _a = new List<QS.Fx.Reflection.Xml.Attribute>();
if (_attributes != null)
{
foreach (QS.Fx.Attributes.IAttribute _attribute in _attributes)
_a.Add(new QS.Fx.Reflection.Xml.Attribute(_attribute.Class.ID.ToString(), _attribute.Value));
}
return _a.ToArray();
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.RecoveryServices.SiteRecovery
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.RecoveryServices;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ReplicationPoliciesOperations operations.
/// </summary>
public partial interface IReplicationPoliciesOperations
{
/// <summary>
/// Gets the requested policy.
/// </summary>
/// <remarks>
/// Gets the details of a replication policy.
/// </remarks>
/// <param name='policyName'>
/// Replication policy name.
/// </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<Policy>> GetWithHttpMessagesAsync(string policyName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates the policy.
/// </summary>
/// <remarks>
/// The operation to create a replication policy
/// </remarks>
/// <param name='policyName'>
/// Replication policy name
/// </param>
/// <param name='input'>
/// Create policy input
/// </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<Policy>> CreateWithHttpMessagesAsync(string policyName, CreatePolicyInput input, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete the policy.
/// </summary>
/// <remarks>
/// The operation to delete a replication policy.
/// </remarks>
/// <param name='policyName'>
/// Replication policy name.
/// </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 policyName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates the protection profile.
/// </summary>
/// <remarks>
/// The operation to update a replication policy.
/// </remarks>
/// <param name='policyName'>
/// Protection profile Id.
/// </param>
/// <param name='input'>
/// Update Protection Profile Input
/// </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<Policy>> UpdateWithHttpMessagesAsync(string policyName, UpdatePolicyInput input, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the list of replication policies
/// </summary>
/// <remarks>
/// Lists the replication policies for a vault.
/// </remarks>
/// <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<IPage<Policy>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates the policy.
/// </summary>
/// <remarks>
/// The operation to create a replication policy
/// </remarks>
/// <param name='policyName'>
/// Replication policy name
/// </param>
/// <param name='input'>
/// Create policy input
/// </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<Policy>> BeginCreateWithHttpMessagesAsync(string policyName, CreatePolicyInput input, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete the policy.
/// </summary>
/// <remarks>
/// The operation to delete a replication policy.
/// </remarks>
/// <param name='policyName'>
/// Replication policy name.
/// </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> BeginDeleteWithHttpMessagesAsync(string policyName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates the protection profile.
/// </summary>
/// <remarks>
/// The operation to update a replication policy.
/// </remarks>
/// <param name='policyName'>
/// Protection profile Id.
/// </param>
/// <param name='input'>
/// Update Protection Profile Input
/// </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<Policy>> BeginUpdateWithHttpMessagesAsync(string policyName, UpdatePolicyInput input, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the list of replication policies
/// </summary>
/// <remarks>
/// Lists the replication policies for a vault.
/// </remarks>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="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<IPage<Policy>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// Copyright 2004-2009 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Castle.DynamicProxy.Builder.CodeBuilder
{
using System;
using System.Reflection;
using System.Reflection.Emit;
using Castle.DynamicProxy.Builder.CodeBuilder.Utils;
using Castle.DynamicProxy.Builder.CodeBuilder.SimpleAST;
/// <summary>
/// Summary description for AbstractEasyType.
/// </summary>
[CLSCompliant(false)]
public abstract class AbstractEasyType
{
private int _counter;
protected TypeBuilder _typebuilder;
protected ConstructorCollection _constructors;
protected MethodCollection _methods;
protected NestedTypeCollection _nested;
protected PropertiesCollection _properties;
protected EventsCollection _events;
public AbstractEasyType()
{
_nested = new NestedTypeCollection();
_methods = new MethodCollection();
_constructors = new ConstructorCollection();
_properties = new PropertiesCollection();
_events = new EventsCollection();
}
public void CreateDefaultConstructor( )
{
_constructors.Add( new EasyDefaultConstructor( this ) );
}
public EasyConstructor CreateConstructor( params ArgumentReference[] arguments )
{
EasyConstructor member = new EasyConstructor( this, arguments );
_constructors.Add( member );
return member;
}
public EasyConstructor CreateRuntimeConstructor( params ArgumentReference[] arguments )
{
EasyRuntimeConstructor member = new EasyRuntimeConstructor( this, arguments );
_constructors.Add( member );
return member;
}
public EasyMethod CreateMethod( String name, ReturnReferenceExpression returnType, params ArgumentReference[] arguments )
{
EasyMethod member = new EasyMethod( this, name, returnType, arguments );
_methods.Add(member);
return member;
}
public EasyMethod CreateMethod( String name, ReturnReferenceExpression returnType, MethodAttributes attributes, params ArgumentReference[] arguments )
{
EasyMethod member = new EasyMethod( this, name, attributes, returnType, arguments );
_methods.Add(member);
return member;
}
public EasyMethod CreateMethod( String name, MethodAttributes attrs, ReturnReferenceExpression returnType, params Type[] args)
{
EasyMethod member = new EasyMethod( this, name, attrs, returnType, ArgumentsUtil.ConvertToArgumentReference(args) );
_methods.Add(member);
return member;
}
public EasyRuntimeMethod CreateRuntimeMethod( String name, ReturnReferenceExpression returnType, params ArgumentReference[] arguments )
{
EasyRuntimeMethod member = new EasyRuntimeMethod( this, name, returnType, arguments );
_methods.Add(member);
return member;
}
public FieldReference CreateField( string name, Type fieldType )
{
return CreateField(name, fieldType, true);
}
public FieldReference CreateField( string name, Type fieldType, bool serializable )
{
FieldAttributes atts = FieldAttributes.Public;
if (!serializable)
{
atts |= FieldAttributes.NotSerialized;
}
FieldBuilder fieldBuilder = _typebuilder.DefineField( name, fieldType, atts );
return new FieldReference( fieldBuilder );
}
public EasyProperty CreateProperty( String name, Type returnType )
{
EasyProperty prop = new EasyProperty( this, name, returnType );
_properties.Add(prop);
return prop;
}
public EasyProperty CreateProperty( PropertyInfo property )
{
EasyProperty prop = new EasyProperty( this, property.Name, property.PropertyType );
prop.IndexParameters = property.GetIndexParameters();
_properties.Add(prop);
return prop;
}
public EasyEvent CreateEvent( String name, Type eventHandlerType )
{
EasyEvent easyEvent = new EasyEvent( this, name, eventHandlerType );
_events.Add(easyEvent);
return easyEvent;
}
public ConstructorCollection Constructors
{
get { return _constructors; }
}
public MethodCollection Methods
{
get { return _methods; }
}
public PropertiesCollection Properties
{
get { return _properties; }
}
public TypeBuilder TypeBuilder
{
get { return _typebuilder; }
}
internal Type BaseType
{
get { return TypeBuilder.BaseType; }
}
internal int IncrementAndGetCounterValue
{
get { return ++_counter; }
}
public virtual Type BuildType()
{
EnsureBuildersAreInAValidState();
Type type = _typebuilder.CreateType();
foreach(EasyNested builder in _nested)
{
builder.BuildType();
}
return type;
}
protected virtual void EnsureBuildersAreInAValidState()
{
if (_constructors.Count == 0)
{
CreateDefaultConstructor();
}
foreach(IEasyMember builder in _properties)
{
builder.EnsureValidCodeBlock();
builder.Generate();
}
foreach(IEasyMember builder in _events)
{
builder.EnsureValidCodeBlock();
builder.Generate();
}
foreach(IEasyMember builder in _constructors)
{
builder.EnsureValidCodeBlock();
builder.Generate();
}
foreach(IEasyMember builder in _methods)
{
builder.EnsureValidCodeBlock();
builder.Generate();
}
}
}
}
| |
namespace AjTalk.Tests
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using AjTalk;
using AjTalk.Compiler;
using AjTalk.Hosting;
using AjTalk.Language;
using AjTalk.Tests.Language;
using AjTalk.Tests.NativeObjects;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class LoaderVmTests
{
[TestMethod]
public void GetEmptyLine()
{
Loader loader = new Loader(new StringReader("\n"), new VmCompiler());
Assert.IsNull(loader.GetBlockText());
}
[TestMethod]
public void GetSpaceLine()
{
Loader loader = new Loader(new StringReader(" \n"), new VmCompiler());
Assert.AreEqual(" \r\n", loader.GetBlockText());
Assert.IsNull(loader.GetBlockText());
}
[TestMethod]
public void GetTwoLinesBlock()
{
Loader loader = new Loader(new StringReader("line 1\r\nline 2\r\n!"), new VmCompiler());
Assert.IsNotNull(loader);
Assert.AreEqual("line 1\r\nline 2\r\n", loader.GetBlockText());
Assert.IsNull(loader.GetBlockText());
}
[TestMethod]
public void ProcessDoubleBang()
{
Loader loader = new Loader(new StringReader("!!new! !!new"), new VmCompiler());
Assert.AreEqual("!new", loader.GetBlockText());
Assert.AreEqual(" !new", loader.GetBlockText());
Assert.IsNull(loader.GetBlockText());
}
[TestMethod]
public void GetTwoBlocks()
{
Loader loader = new Loader(new StringReader("line 1\r\nline 2\r\n!\r\nline 3\r\nline 4\r\n!\r\n"), new VmCompiler());
Assert.IsNotNull(loader);
Assert.AreEqual("line 1\r\nline 2\r\n", loader.GetBlockText());
Assert.AreEqual("line 3\r\nline 4\r\n", loader.GetBlockText());
Assert.IsNull(loader.GetBlockText());
}
[TestMethod]
public void GetBlockAndInmediate()
{
Loader loader = new Loader(new StringReader("line 1\nline 2\n!inmediate!\n"), new VmCompiler());
Assert.IsNotNull(loader);
Assert.AreEqual("line 1\r\nline 2\r\n", loader.GetBlockText());
Assert.AreEqual("inmediate", loader.GetBlockText());
Assert.IsNull(loader.GetBlockText());
}
[TestMethod]
public void ExecuteBlock()
{
Loader loader = new Loader(new StringReader("One := 1\n!\n"), new VmCompiler());
Machine machine = new Machine();
loader.LoadAndExecute(machine);
Assert.AreEqual(1, machine.GetGlobalObject("One"));
}
[TestMethod]
public void ExecuteBlockWithTwoCommands()
{
Loader loader = new Loader(new StringReader("One := 1.\nTwo := 2\n!\n"), new VmCompiler());
Machine machine = new Machine();
loader.LoadAndExecute(machine);
Assert.AreEqual(1, machine.GetGlobalObject("One"));
Assert.AreEqual(2, machine.GetGlobalObject("Two"));
}
[TestMethod]
public void ExecuteTwoBlocks()
{
Loader loader = new Loader(new StringReader("One := 1.\n!\nTwo := 2\n!\n"), new VmCompiler());
Machine machine = new Machine();
loader.LoadAndExecute(machine);
Assert.AreEqual(1, machine.GetGlobalObject("One"));
Assert.AreEqual(2, machine.GetGlobalObject("Two"));
}
[TestMethod]
[DeploymentItem(@"CodeFiles\SetObject.st")]
public void ExecuteSetObjectFile()
{
Loader loader = new Loader(@"SetObject.st", new VmCompiler());
Machine machine = new Machine();
loader.LoadAndExecute(machine);
Assert.AreEqual(1, machine.GetGlobalObject("One"));
}
[TestMethod]
[DeploymentItem(@"CodeFiles\SetDotNetObject.st")]
public void ExecuteSetDotNetObjectFile()
{
Loader loader = new Loader(@"SetDotNetObject.st", new VmCompiler());
Machine machine = new Machine();
loader.LoadAndExecute(machine);
object obj = machine.GetGlobalObject("FileInfo");
Assert.IsNotNull(obj);
Assert.IsInstanceOfType(obj, typeof(System.IO.FileInfo));
}
[TestMethod]
[DeploymentItem(@"CodeFiles\SetObjects.st")]
public void ExecuteSetObjectsFile()
{
Loader loader = new Loader(@"SetObjects.st", new VmCompiler());
Machine machine = new Machine();
loader.LoadAndExecute(machine);
Assert.AreEqual(1, machine.GetGlobalObject("One"));
Assert.AreEqual(2, machine.GetGlobalObject("Two"));
}
[TestMethod]
[DeploymentItem(@"CodeFiles\DefineSubclass.st")]
public void ExecuteDefineSubclassFile()
{
Loader loader = new Loader(@"DefineSubclass.st", new VmCompiler());
Machine machine = CreateMachine();
Assert.IsNull(machine.GetGlobalObject("Object"));
loader.LoadAndExecute(machine);
Assert.IsNotNull(machine.GetGlobalObject("Object"));
}
[TestMethod]
[DeploymentItem(@"CodeFiles\DefineSubclassWithVariables.st")]
public void ExecuteDefineSubclassWithVariablesFile()
{
Loader loader = new Loader(@"DefineSubclassWithVariables.st", new VmCompiler());
Machine machine = CreateMachine();
Assert.IsNull(machine.GetGlobalObject("Rectangle"));
loader.LoadAndExecute(machine);
object obj = machine.GetGlobalObject("Rectangle");
Assert.IsNotNull(obj);
Assert.IsInstanceOfType(obj, typeof(IClass));
IClass cls = (IClass)obj;
Assert.AreEqual(0, cls.GetInstanceVariableOffset("x"));
Assert.AreEqual(1, cls.GetInstanceVariableOffset("y"));
}
[TestMethod]
[DeploymentItem(@"CodeFiles\DefineRectangle.st")]
public void ExecuteDefineRectangleFile()
{
Loader loader = new Loader(@"DefineRectangle.st", new VmCompiler());
Machine machine = CreateMachine();
Assert.IsNull(machine.GetGlobalObject("Rectangle"));
loader.LoadAndExecute(machine);
object obj = machine.GetGlobalObject("Rectangle");
Assert.IsNotNull(obj);
Assert.IsInstanceOfType(obj, typeof(IClass));
IClass cls = (IClass)obj;
Assert.AreEqual(0, cls.GetInstanceVariableOffset("x"));
Assert.AreEqual(1, cls.GetInstanceVariableOffset("y"));
Assert.AreEqual(2, cls.GetInstanceVariableOffset("width"));
Assert.AreEqual(3, cls.GetInstanceVariableOffset("height"));
Assert.IsNotNull(cls.GetInstanceMethod("x"));
Assert.IsNotNull(cls.GetInstanceMethod("x:"));
Assert.IsNotNull(cls.GetInstanceMethod("y"));
Assert.IsNotNull(cls.GetInstanceMethod("y:"));
}
[TestMethod]
[DeploymentItem(@"CodeFiles\DefineRectangleWithNewAndInitialize.st")]
public void ExecuteDefineRectangleWithNewAndInitializeFile()
{
Loader loader = new Loader(@"DefineRectangleWithNewAndInitialize.st", new VmCompiler());
Machine machine = CreateMachine();
Assert.IsNull(machine.GetGlobalObject("Rectangle"));
loader.LoadAndExecute(machine);
object obj = machine.GetGlobalObject("result");
Assert.IsNotNull(obj);
Assert.IsInstanceOfType(obj, typeof(IObject));
IObject iobj = (IObject)obj;
Assert.AreEqual(10, iobj[0]);
Assert.AreEqual(20, iobj[1]);
}
[TestMethod]
[DeploymentItem(@"CodeFiles\DefineClassSubclass.st")]
public void ExecuteDefineClassSubclassFile()
{
Loader loader = new Loader(@"DefineClassSubclass.st", new VmCompiler());
Machine machine = CreateMachine();
Assert.IsNull(machine.GetGlobalObject("Rectangle"));
loader.LoadAndExecute(machine);
object obj = machine.GetGlobalObject("Rectangle");
Assert.IsNotNull(obj);
Assert.IsInstanceOfType(obj, typeof(IClass));
IClass cls = (IClass)obj;
Assert.AreEqual(0, cls.GetInstanceVariableOffset("x"));
Assert.AreEqual(1, cls.GetInstanceVariableOffset("y"));
Assert.AreEqual(2, cls.GetInstanceVariableOffset("width"));
Assert.AreEqual(3, cls.GetInstanceVariableOffset("height"));
Assert.IsNotNull(cls.GetInstanceMethod("x"));
Assert.IsNotNull(cls.GetInstanceMethod("x:"));
Assert.IsNotNull(cls.GetInstanceMethod("y"));
Assert.IsNotNull(cls.GetInstanceMethod("y:"));
Assert.IsNotNull(cls.GetInstanceMethod("width"));
Assert.IsNotNull(cls.GetInstanceMethod("height"));
}
[TestMethod]
[DeploymentItem(@"CodeFiles\Library1.st")]
public void LoadLibrary()
{
Loader loader = new Loader(@"Library1.st", new VmCompiler());
Machine machine = CreateMachine();
Assert.IsNull(machine.GetGlobalObject("Object"));
Assert.IsNull(machine.GetGlobalObject("Behavior"));
Assert.IsNull(machine.GetGlobalObject("ClassDescription"));
Assert.IsNull(machine.GetGlobalObject("Class"));
Assert.IsNull(machine.GetGlobalObject("Metaclass"));
loader.LoadAndExecute(machine);
Assert.IsNotNull(machine.GetGlobalObject("Object"));
Assert.IsNotNull(machine.GetGlobalObject("Behavior"));
Assert.IsNotNull(machine.GetGlobalObject("ClassDescription"));
Assert.IsNotNull(machine.GetGlobalObject("Class"));
Assert.IsNotNull(machine.GetGlobalObject("Metaclass"));
}
[TestMethod]
[DeploymentItem(@"CodeFiles\Library1.st")]
public void LoadLibraryWithBootstrap()
{
Loader loader = new Loader(@"Library1.st", new VmCompiler());
Machine machine = CreateMachine();
loader.LoadAndExecute(machine);
IClass objclass = (IClass)machine.GetGlobalObject("Object");
IClass behaviorclass = (IClass)machine.GetGlobalObject("Behavior");
IClass classdescriptionclass = (IClass)machine.GetGlobalObject("ClassDescription");
IClass classclass = (IClass)machine.GetGlobalObject("Class");
IClass metaclassclass = (IClass)machine.GetGlobalObject("Metaclass");
Assert.AreEqual(objclass, behaviorclass.SuperClass);
Assert.AreEqual(behaviorclass, classdescriptionclass.SuperClass);
Assert.AreEqual(classdescriptionclass, classclass.SuperClass);
Assert.AreEqual(classdescriptionclass, metaclassclass.SuperClass);
Assert.IsNotNull(objclass.MetaClass);
Assert.IsNotNull(behaviorclass.MetaClass);
Assert.IsNotNull(classdescriptionclass.MetaClass);
Assert.IsNotNull(classclass.MetaClass);
Assert.IsNotNull(metaclassclass.MetaClass);
Assert.AreEqual(objclass.MetaClass, behaviorclass.MetaClass.SuperClass);
Assert.AreEqual(behaviorclass.MetaClass, classdescriptionclass.MetaClass.SuperClass);
Assert.AreEqual(classdescriptionclass.MetaClass, classclass.MetaClass.SuperClass);
Assert.AreEqual(classdescriptionclass.MetaClass, metaclassclass.MetaClass.SuperClass);
Assert.AreEqual(metaclassclass, objclass.MetaClass.Behavior);
Assert.AreEqual(metaclassclass, behaviorclass.MetaClass.Behavior);
Assert.AreEqual(metaclassclass, classdescriptionclass.MetaClass.Behavior);
Assert.AreEqual(metaclassclass, classclass.MetaClass.Behavior);
Assert.AreEqual(metaclassclass, metaclassclass.MetaClass.Behavior);
// TODO objclass super should be nil == null, now is object nil
// Assert.IsNull(objclass.SuperClass);
Assert.IsNotNull(objclass.MetaClass.SuperClass);
Assert.AreEqual(classclass, objclass.MetaClass.SuperClass);
}
[TestMethod]
[DeploymentItem(@"Library\Object.st")]
[DeploymentItem(@"CodeFiles\ObjectTest.st")]
public void LoadObject()
{
Machine machine = CreateMachine();
Loader loader = new Loader(@"Object.st", new VmCompiler());
loader.LoadAndExecute(machine);
loader = new Loader(@"ObjectTest.st", new VmCompiler());
loader.LoadAndExecute(machine);
object obj = machine.GetGlobalObject("Object");
Assert.IsNotNull(obj);
Assert.IsInstanceOfType(obj, typeof(IClass));
IClass cls = (IClass)obj;
Assert.IsNotNull(cls.GetClassMethod("new"));
Assert.IsNotNull(cls.GetClassMethod("basicNew"));
object result = machine.GetGlobalObject("result");
Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(IObject));
Assert.AreEqual(cls, ((IObject)result).Behavior);
object rcls = machine.GetGlobalObject("resultclass");
Assert.AreEqual(cls, rcls);
Assert.AreEqual(true, machine.GetGlobalObject("aresame"));
Assert.AreEqual(false, machine.GetGlobalObject("arenotsame"));
Assert.AreEqual(true, machine.GetGlobalObject("areequal"));
Assert.AreEqual(false, machine.GetGlobalObject("arenotequal"));
Assert.AreEqual(false, machine.GetGlobalObject("notaresame"));
Assert.AreEqual(true, machine.GetGlobalObject("notarenotsame"));
Assert.AreEqual(false, machine.GetGlobalObject("notareequal"));
Assert.AreEqual(true, machine.GetGlobalObject("notarenotequal"));
}
[TestMethod]
[DeploymentItem(@"Library\Object.st")]
[DeploymentItem(@"Library\Behavior.st")]
[DeploymentItem(@"CodeFiles\BehaviorTest.st")]
public void LoadBehavior()
{
Machine machine = CreateMachine();
Loader loader = new Loader(@"Object.st", new VmCompiler());
loader.LoadAndExecute(machine);
loader = new Loader(@"Behavior.st", new VmCompiler());
loader.LoadAndExecute(machine);
loader = new Loader(@"BehaviorTest.st", new VmCompiler());
loader.LoadAndExecute(machine);
object obj = machine.GetGlobalObject("NewBehavior");
Assert.IsNotNull(obj);
Assert.IsInstanceOfType(obj, typeof(IClass));
IClass cls = (IClass)obj;
Assert.AreEqual("Behavior", ((IClass)cls.SuperClass).Name);
Assert.IsNotNull(cls.Behavior.GetInstanceMethod("compile:"));
}
[TestMethod]
[DeploymentItem(@"Library\Object.st")]
[DeploymentItem(@"Library\Behavior.st")]
[DeploymentItem(@"Library\Class.st")]
[DeploymentItem(@"CodeFiles\ClassTest.st")]
public void LoadClass()
{
Machine machine = CreateMachine();
Loader loader = new Loader(@"Object.st", new VmCompiler());
loader.LoadAndExecute(machine);
loader = new Loader(@"Behavior.st", new VmCompiler());
loader.LoadAndExecute(machine);
loader = new Loader(@"Class.st", new VmCompiler());
loader.LoadAndExecute(machine);
loader = new Loader(@"ClassTest.st", new VmCompiler());
loader.LoadAndExecute(machine);
object obj = machine.GetGlobalObject("MyClass");
Assert.IsNotNull(obj);
Assert.IsInstanceOfType(obj, typeof(IClass));
IClass cls = (IClass)obj;
Assert.AreEqual("MyClass", cls.Name);
Assert.AreEqual("Object", ((IClass)cls.SuperClass).Name);
object obj2 = machine.GetGlobalObject("Rectangle");
Assert.IsNotNull(obj2);
Assert.IsInstanceOfType(obj2, typeof(IClass));
IClass cls2 = (IClass)obj2;
Assert.AreEqual("Rectangle", cls2.Name);
Assert.AreEqual("Object", ((IClass)cls2.SuperClass).Name);
Assert.AreEqual(2, cls2.NoInstanceVariables);
Assert.AreEqual(0, cls2.Behavior.NoInstanceVariables);
Assert.AreEqual(1, cls2.NoClassVariables);
Assert.AreEqual("width height", cls2.GetInstanceVariableNamesAsString());
Assert.AreEqual("Number", cls2.GetClassVariableNamesAsString());
object obj3 = machine.GetGlobalObject("rect");
Assert.IsNotNull(obj3);
Assert.IsInstanceOfType(obj3, typeof(IObject));
IObject rect = (IObject)obj3;
Assert.AreEqual(cls2, rect.Behavior);
Assert.AreEqual(100, rect[0]);
Assert.AreEqual(50, rect[1]);
}
[TestMethod]
[DeploymentItem(@"CodeFiles\Library1.st")]
public void ReviewClassGraph()
{
Loader loader = new Loader(@"Library1.st", new VmCompiler());
Machine machine = CreateMachine();
loader.LoadAndExecute(machine);
IBehavior objclass = (IBehavior)machine.GetGlobalObject("Object");
Assert.IsNotNull(objclass);
Assert.IsNotNull(objclass.Behavior);
Assert.IsNotNull(objclass.MetaClass);
Assert.IsNull(objclass.SuperClass);
IBehavior behclass = (IBehavior)machine.GetGlobalObject("Behavior");
Assert.IsNotNull(behclass);
Assert.IsNotNull(behclass.Behavior);
Assert.IsNotNull(behclass.MetaClass);
Assert.IsNotNull(behclass.SuperClass);
Assert.AreEqual(objclass, behclass.SuperClass);
Assert.AreEqual(objclass.MetaClass, behclass.MetaClass.SuperClass);
IClassDescription classdes = (IClassDescription)machine.GetGlobalObject("ClassDescription");
Assert.IsNotNull(classdes);
Assert.IsNotNull(classdes.Behavior);
Assert.IsNotNull(classdes.MetaClass);
Assert.IsNotNull(classdes.SuperClass);
Assert.AreEqual(behclass, classdes.SuperClass);
Assert.AreEqual(behclass.MetaClass, classdes.MetaClass.SuperClass);
IClass clazz = (IClass)machine.GetGlobalObject("Class");
Assert.IsNotNull(clazz);
Assert.IsNotNull(clazz.Behavior);
Assert.IsNotNull(clazz.MetaClass);
Assert.IsNotNull(clazz.SuperClass);
Assert.AreEqual(classdes, clazz.SuperClass);
Assert.AreEqual(classdes.MetaClass, clazz.MetaClass.SuperClass);
}
[TestMethod]
[DeploymentItem(@"CodeFiles\NativeBehavior.st")]
public void LoadNativeBehavior()
{
Loader loader = new Loader(@"NativeBehavior.st", new VmCompiler());
Machine machine = CreateMachine();
loader.LoadAndExecute(machine);
object result = machine.GetGlobalObject("myList");
Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(ArrayList));
ArrayList list = (ArrayList)result;
Assert.AreEqual(2, list.Count);
Assert.AreEqual(1, list[0]);
Assert.AreEqual("foo", list[1]);
}
[TestMethod]
[DeploymentItem(@"CodeFiles\NativeRectangle.st")]
public void LoadNativeRectangle()
{
Loader loader = new Loader(@"NativeRectangle.st", new VmCompiler());
Machine machine = CreateMachine();
loader.LoadAndExecute(machine);
object result1 = machine.GetGlobalObject("Rectangle");
Assert.IsNotNull(result1);
Assert.IsInstanceOfType(result1, typeof(NativeBehavior));
object result2 = machine.GetGlobalObject("rect");
Assert.IsNotNull(result2);
Assert.IsInstanceOfType(result2, typeof(Rectangle));
object result = machine.GetGlobalObject("result");
Assert.AreEqual(200, result);
}
[TestMethod]
[DeploymentItem(@"CodeFiles\NativeFileInfo.st")]
public void LoadNativeFileInfo()
{
Loader loader = new Loader(@"NativeFileInfo.st", new VmCompiler());
Machine machine = CreateMachine();
loader.LoadAndExecute(machine);
object result = machine.GetGlobalObject("myFileInfo");
Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(FileInfo));
Assert.IsFalse((bool)machine.GetGlobalObject("result"));
}
[TestMethod]
public void ExecuteTwoCommands()
{
Loader loader = new Loader(new StringReader("a := 1. b := 2"), new VmCompiler());
Machine machine = CreateMachine();
loader.LoadAndExecute(machine);
Assert.AreEqual(1, machine.GetGlobalObject("a"));
Assert.AreEqual(2, machine.GetGlobalObject("b"));
}
[TestMethod]
[DeploymentItem(@"CodeFiles\FileOut01.st")]
public void LoadFileOut01()
{
Loader loader = new Loader(@"FileOut01.st", new VmCompiler());
Machine machine = CreateMachine();
loader.LoadAndExecute(machine);
object result = machine.GetGlobalObject("Object");
Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(BaseClass));
}
[TestMethod]
[DeploymentItem(@"CodeFiles\FileOut02.st")]
public void LoadFileOut02()
{
Loader loader = new Loader(@"FileOut02.st", new VmCompiler());
Machine machine = CreateMachine();
loader.LoadAndExecute(machine);
object result = machine.GetGlobalObject("Object");
Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(BaseClass));
}
[TestMethod]
[DeploymentItem(@"CodeFiles\Library2.st")]
[DeploymentItem(@"CodeFiles\PharoCorePoint.st")]
public void LoadPharoCorePoint()
{
Loader loaderlib = new Loader(@"Library2.st", new VmCompiler());
Loader loader = new Loader(@"PharoCorePoint.st", new VmCompiler());
Machine machine = CreateMachine();
loaderlib.LoadAndExecute(machine);
loader.LoadAndExecute(machine);
object result = machine.GetGlobalObject("Point");
Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(BaseClass));
}
[TestMethod]
[DeploymentItem(@"CodeFiles\Library2.st")]
[DeploymentItem(@"CodeFiles\PharoCoreRectangle.st")]
public void LoadPharoCoreRectangle()
{
Loader loaderlib = new Loader(@"Library2.st", new VmCompiler());
Loader loader = new Loader(@"PharoCoreRectangle.st", new VmCompiler());
Machine machine = CreateMachine();
loaderlib.LoadAndExecute(machine);
loader.LoadAndExecute(machine);
object result = machine.GetGlobalObject("Rectangle");
Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(BaseClass));
}
[TestMethod]
[DeploymentItem(@"CodeFiles\Library2.st")]
[DeploymentItem(@"CodeFiles\PharoCoreKernelObjects.st")]
public void LoadPharoCoreKernelObjects()
{
Loader loaderlib = new Loader(@"Library2.st", new VmCompiler());
Loader loader = new Loader(@"PharoCoreKernelObjects.st", new VmCompiler());
Machine machine = CreateMachine();
loaderlib.LoadAndExecute(machine);
loader.LoadAndExecute(machine);
object result = machine.GetGlobalObject("Object");
Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(BaseClass));
result = machine.GetGlobalObject("ProtoObject");
Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(BaseClass));
result = machine.GetGlobalObject("Boolean");
Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(BaseClass));
result = machine.GetGlobalObject("UndefinedObject");
Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(BaseClass));
}
[TestMethod]
[DeploymentItem(@"CodeFiles\Library2.st")]
[DeploymentItem(@"CodeFiles\PharoCoreKernelObjects.st")]
[DeploymentItem(@"CodeFiles\PharoKernelNumbers.st")]
public void LoadPharoNumbers()
{
Loader loaderlib = new Loader(@"Library2.st", new VmCompiler());
Loader loaderobj = new Loader(@"PharoCoreKernelObjects.st", new VmCompiler());
Loader loader = new Loader(@"PharoKernelNumbers.st", new VmCompiler());
Machine machine = CreateMachine();
loaderlib.LoadAndExecute(machine);
loaderobj.LoadAndExecute(machine);
loader.LoadAndExecute(machine);
object result = machine.GetGlobalObject("Object");
Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(BaseClass));
result = machine.GetGlobalObject("ProtoObject");
Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(BaseClass));
result = machine.GetGlobalObject("Boolean");
Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(BaseClass));
result = machine.GetGlobalObject("UndefinedObject");
Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(BaseClass));
}
internal static Machine CreateMachine()
{
Machine machine = new Machine();
object nil = machine.UndefinedObjectClass;
Assert.IsNotNull(nil);
Assert.IsInstanceOfType(nil, typeof(IClass));
return machine;
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using Ink.Parsed;
namespace Ink
{
internal partial class InkParser
{
protected Conditional InnerConditionalContent()
{
var initialQueryExpression = Parse(ConditionExpression);
var conditional = Parse(() => InnerConditionalContent (initialQueryExpression));
if (conditional == null)
return null;
return conditional;
}
protected Conditional InnerConditionalContent(Expression initialQueryExpression)
{
List<ConditionalSingleBranch> alternatives;
bool canBeInline = initialQueryExpression != null;
bool isInline = Parse(Newline) == null;
if (isInline && !canBeInline) {
return null;
}
// Inline innards
if (isInline) {
alternatives = InlineConditionalBranches ();
}
// Multiline innards
else {
alternatives = MultilineConditionalBranches ();
if (alternatives == null) {
// Allow single piece of content within multi-line expression, e.g.:
// { true:
// Some content that isn't preceded by '-'
// }
if (initialQueryExpression) {
List<Parsed.Object> soleContent = StatementsAtLevel (StatementLevel.InnerBlock);
if (soleContent != null) {
var soleBranch = new ConditionalSingleBranch (soleContent);
alternatives = new List<ConditionalSingleBranch> ();
alternatives.Add (soleBranch);
// Also allow a final "- else:" clause
var elseBranch = Parse (SingleMultilineCondition);
if (elseBranch) {
if (!elseBranch.isElse) {
ErrorWithParsedObject ("Expected an '- else:' clause here rather than an extra condition", elseBranch);
elseBranch.isElse = true;
}
alternatives.Add (elseBranch);
}
}
}
// Still null?
if (alternatives == null) {
return null;
}
}
// Empty true branch - didn't get parsed, but should insert one for semantic correctness,
// and to make sure that any evaluation stack values get tidied up correctly.
else if (alternatives.Count == 1 && alternatives [0].isElse && initialQueryExpression) {
var emptyTrueBranch = new ConditionalSingleBranch (null);
emptyTrueBranch.isTrueBranch = true;
alternatives.Insert (0, emptyTrueBranch);
}
// Like a switch statement
// { initialQueryExpression:
// ... match the expression
// }
if (initialQueryExpression) {
bool earlierBranchesHaveOwnExpression = false;
for (int i = 0; i < alternatives.Count; ++i) {
var branch = alternatives [i];
bool isLast = (i == alternatives.Count - 1);
// Matching equality with initial query expression
// We set this flag even for the "else" clause so that
// it knows to tidy up the evaluation stack at the end
// Match query
if (branch.ownExpression) {
branch.matchingEquality = true;
earlierBranchesHaveOwnExpression = true;
}
// Else (final branch)
else if (earlierBranchesHaveOwnExpression && isLast) {
branch.matchingEquality = true;
branch.isElse = true;
}
// Binary condition:
// { trueOrFalse:
// - when true
// - when false
// }
else {
if (!isLast && alternatives.Count > 2) {
ErrorWithParsedObject ("Only final branch can be an 'else'. Did you miss a ':'?", branch);
} else {
if (i == 0)
branch.isTrueBranch = true;
else
branch.isElse = true;
}
}
}
}
// No initial query, so just a multi-line conditional. e.g.:
// {
// - x > 3: greater than three
// - x == 3: equal to three
// - x < 3: less than three
// }
else {
for (int i = 0; i < alternatives.Count; ++i) {
var alt = alternatives [i];
bool isLast = (i == alternatives.Count - 1);
if (alt.ownExpression == null) {
if (isLast) {
alt.isElse = true;
} else {
if (alt.isElse) {
// Do we ALSO have a valid "else" at the end? Let's report the error there.
var finalClause = alternatives [alternatives.Count - 1];
if (finalClause.isElse) {
ErrorWithParsedObject ("Multiple 'else' cases. Can have a maximum of one, at the end.", finalClause);
} else {
ErrorWithParsedObject ("'else' case in conditional should always be the final one", alt);
}
} else {
ErrorWithParsedObject ("Branch doesn't have condition. Are you missing a ':'? ", alt);
}
}
}
}
if (alternatives.Count == 1 && alternatives [0].ownExpression == null) {
ErrorWithParsedObject ("Condition block with no conditions", alternatives [0]);
}
}
}
// TODO: Come up with water-tight error conditions... it's quite a flexible system!
// e.g.
// - inline conditionals must have exactly 1 or 2 alternatives
// - multiline expression shouldn't have mixed existence of branch-conditions?
if (alternatives == null)
return null;
foreach (var branch in alternatives) {
branch.isInline = isInline;
}
var cond = new Conditional (initialQueryExpression, alternatives);
return cond;
}
protected List<ConditionalSingleBranch> InlineConditionalBranches()
{
var listOfLists = Interleave<List<Parsed.Object>> (MixedTextAndLogic, Exclude (String ("|")), flatten: false);
if (listOfLists == null || listOfLists.Count == 0) {
return null;
}
var result = new List<ConditionalSingleBranch> ();
if (listOfLists.Count > 2) {
Error ("Expected one or two alternatives separated by '|' in inline conditional");
} else {
var trueBranch = new ConditionalSingleBranch (listOfLists[0]);
trueBranch.isTrueBranch = true;
result.Add (trueBranch);
if (listOfLists.Count > 1) {
var elseBranch = new ConditionalSingleBranch (listOfLists[1]);
elseBranch.isElse = true;
result.Add (elseBranch);
}
}
return result;
}
protected List<ConditionalSingleBranch> MultilineConditionalBranches()
{
MultilineWhitespace ();
List<object> multipleConditions = OneOrMore (SingleMultilineCondition);
if (multipleConditions == null)
return null;
MultilineWhitespace ();
return multipleConditions.Cast<ConditionalSingleBranch>().ToList();
}
protected ConditionalSingleBranch SingleMultilineCondition()
{
Whitespace ();
// Make sure we're not accidentally parsing a divert
if (ParseString ("->") != null)
return null;
if (ParseString ("-") == null)
return null;
Whitespace ();
Expression expr = null;
bool isElse = Parse(ElseExpression) != null;
if( !isElse )
expr = Parse(ConditionExpression);
List<Parsed.Object> content = StatementsAtLevel (StatementLevel.InnerBlock);
if (expr == null && content == null) {
Error ("expected content for the conditional branch following '-'");
// Recover
content = new List<Ink.Parsed.Object> ();
content.Add (new Text (""));
}
// Allow additional multiline whitespace, if the statements were empty (valid)
// then their surrounding multiline whitespacce needs to be handled manually.
// e.g.
// { x:
// - 1: // intentionally left blank, but newline needs to be parsed
// - 2: etc
// }
MultilineWhitespace ();
var branch = new ConditionalSingleBranch (content);
branch.ownExpression = expr;
branch.isElse = isElse;
return branch;
}
protected Expression ConditionExpression()
{
var expr = Parse(Expression);
if (expr == null)
return null;
DisallowIncrement (expr);
Whitespace ();
if (ParseString (":") == null)
return null;
return expr;
}
protected object ElseExpression()
{
if (ParseString ("else") == null)
return null;
Whitespace ();
if (ParseString (":") == null)
return null;
return ParseSuccess;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
#define USE_INSTRUMENTATION
using System;
using System.IO;
using System.Diagnostics;
using System.Text;
using System.Threading;
using System.Collections.Generic;
/// <summary>
/// Classed used for all logging infrastructure
/// </summary>
class RFLogging
#if !PROJECTK_BUILD
: MarshalByRefObject
#endif
{
Queue<string> messageQueue;
Queue<string> instrumentationMessageQueue;
Thread loggingThread;
volatile bool closeLogFile;
ASCIIEncoding encoding = new ASCIIEncoding();
bool noStatusWarningDisplayed = false;
FileStream logFile = null;
bool reportResults = true;
#if USE_INSTRUMENTATION
FileStream instrumentationLogFile = null;
#endif
const string logDirectory = "Logs";
public RFLogging()
{
CreateInstrumentationLog();
messageQueue = new Queue<string>(25000);
instrumentationMessageQueue = new Queue<string>(25000);
closeLogFile = false;
loggingThread = new Thread(new ThreadStart(LogWorker));
loggingThread.IsBackground = true;
#if !PROJECTK_BUILD
loggingThread.Priority = ThreadPriority.Highest;
#endif
loggingThread.Start();
}
private void LogWorker()
{
while (true)
{
bool cachedCloseLogFile = closeLogFile; // The CloseLog method will set closeLogFile to true indicating we should close the log file
// This value is cached here so we can write all of the remaining messages to log before closing it
int messageQueueCount = messageQueue.Count;
int instrumentationQueueCount = instrumentationMessageQueue.Count;
if (logFile != null && messageQueueCount > 0)
{
try
{
string text;
for (int i = messageQueueCount; i > 0; i--)
{
try
{
lock (messageQueue)
{
text = messageQueue.Dequeue();
}
}
catch (InvalidOperationException) { text = null; }
if (!String.IsNullOrEmpty(text))
{
logFile.Write(encoding.GetBytes(text), 0, text.Length);
text = null;
}
}
logFile.Flush();
}
catch (IOException e)
{
ReliabilityFramework.MyDebugBreak(String.Format("LogWorker IOException:{0}", e.ToString()));
//Disk may be full so simply stop logging
}
}
if(cachedCloseLogFile) {
if(null != logFile) {
#if !PROJECTK_BUILD
logFile.Close();
#endif
logFile = null;
}
closeLogFile = false;
}
if (instrumentationLogFile != null && instrumentationQueueCount > 0)
{
try
{
string text;
for (int i = instrumentationQueueCount; i > 0; i--)
{
try
{
lock (instrumentationMessageQueue)
{
text = instrumentationMessageQueue.Dequeue();
}
}
catch (InvalidOperationException) { text = null; }
if (!String.IsNullOrEmpty(text))
{
instrumentationLogFile.Write(encoding.GetBytes(text), 0, text.Length);
text = null;
}
}
instrumentationLogFile.Flush();
}
catch (IOException e)
{
ReliabilityFramework.MyDebugBreak(String.Format("LogWorker IOException:{0}", e.ToString()));
}
}
}
}
private void CreateInstrumentationLog()
{
if (instrumentationLogFile == null)
{
try
{
string logFilename = logDirectory + "\\instrmentation.log";
while (File.Exists(logFilename))
{
logFilename = logDirectory + "\\instrmentation.log-" + DateTime.Now.ToString().Replace('/', '-').Replace(':', '.');
}
instrumentationLogFile = File.Open(logFilename, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite);
}
catch
{
instrumentationLogFile = null;
return;
}
}
}
/// <summary>
/// This method will open our log file for writing. If for any reason we can't open the log file the error is printed on the screen
/// and we'll simply refuse to log the data. The log file's name is the current test's friendly name. If a log file is already opened
/// that log file will be closed & replaced with this one.
/// </summary>
public void OpenLog(string name)
{
if (logFile != null)
{
#if !PROJECTK_BUILD
logFile.Close();
#endif
logFile = null;
}
// open the log file if the user hasn't disabled it.
string filename = null;
try
{
bool fRetry;
if (!Directory.Exists(logDirectory))
Directory.CreateDirectory(logDirectory);
do
{
fRetry = false;
string safeName = logDirectory + "\\" + name.Replace('\\', ' ').Replace('*', ' ').Replace('?', ' ').Replace('>', ' ').Replace('<', ' ').Replace('|', ' ').Replace(':', ' ').Replace('/', ' ').Replace('"', ' ');
filename = safeName + ".log";
if (File.Exists(filename))
{
filename = String.Format("{0} - {1}.log", safeName, DateTime.Now.ToString().Replace('/', '-').Replace(':', '.'));
}
try
{
logFile = File.Open(filename, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite);
}
catch (IOException e)
{
Console.WriteLine("Failed to open file: {0} {1}", filename, e);
fRetry = true;
}
}
while (fRetry);
WriteToLog("<TestRun>\r\n");
}
catch (ArgumentException)
{
Console.WriteLine("RFLogging - Blank or Empty FriendlyName, logging is disabled: {0}", name);
logFile = null;
}
catch (PathTooLongException)
{
Console.WriteLine("RFLogging - FriendlyName is too long, logging is disabled: {0}", name);
logFile = null;
}
catch (DirectoryNotFoundException ex)
{
Console.WriteLine(ex.ToString());
Console.WriteLine("RFLogging - Friendly name contains drive or directory specifiers, logging is disabled: {0} {1}", name, filename);
logFile = null;
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("RFLogging - Unauthorized access to log file, please change the test name or fix the current directory: {0}.log", name);
logFile = null;
}
catch (NotSupportedException)
{
Console.WriteLine("RFLogging - The friendly test name contains a : in the string, try again: {0}", name);
logFile = null;
}
}
/// <summary>
/// Closes the main stress log file
/// </summary>
public void CloseLog()
{
if (null != logFile)
{
WriteToLog("</TestRun>\r\n");
closeLogFile = true;
for(int i=0; i<60 && closeLogFile; ++i)
{
Thread.Sleep(100);
}
if(closeLogFile)
{
throw new InvalidOperationException("Log was not closed after waiting 1 minute.");
}
}
}
/// <summary>
/// Writes the StartupInfo element of the stress log.
/// </summary>
/// <param name="value"></param>
public void WriteStartupInfo(int randSeed)
{
WriteToLog(" <StartupInfo>\r\n <RandomSeed>" + randSeed.ToString() + "</RandomSeed>\r\n </StartupInfo>\r\n");
}
/// <summary>
/// Writes the performance stats into the stress log
/// </summary>
public void WritePerfStats(float pagesVal, float pageFaultsVal, float ourPageFaultsVal, float cpuVal, float memVal, bool testStartPrevented)
{
WriteToLog(
String.Format(" <PerfStats CPU=\"{0}\" Pages=\"{1}\" PageFaults=\"{2}\" OurPageFaults=\"{3}\" TestStartPrevented=\"{4}\" />\r\n",
cpuVal,
pagesVal,
pageFaultsVal,
ourPageFaultsVal,
testStartPrevented
));
}
/// <summary>
/// Writes the start of a test into the log
/// </summary>
public void WriteTestStart(ReliabilityTest test)
{
WriteToLog(String.Format(" <TestStart DateTime=\"{0}\" TestId=\"{1}\" /> \r\n", DateTime.Now, test.RefOrID));
}
/// <summary>
/// Writes the detection of a race into the log
/// </summary>
public void WriteTestRace(ReliabilityTest test)
{
WriteToLog(String.Format("<TestRace DateTime=\"{0}\" TestId=\"\"/>\r\n", DateTime.Now, test.RefOrID));
}
/// <summary>
/// Writes a pre-command failure into the log
/// </summary>
public void WritePreCommandFailure(ReliabilityTest test, string command, string commandType)
{
WriteToLog(String.Format(" <PreCommandFailure Command=\"\" CommandType=\"{1}\" TestId=\"{2}\"",
command,
commandType,
test.RefOrID));
}
/// <summary>
/// Writes a test failure into the log
/// </summary>
public void WriteTestFail(ReliabilityTest test, string message)
{
string testName = (test == null) ? "Harness" : test.RefOrID;
WriteToLog(String.Format(" <TestFail DateTime=\"{0}\" TestId=\"{1}\" Description=\"{2}\" />\r\n",
DateTime.Now,
testName,
message));
}
/// <summary>
/// Writes a test pass into the log.
/// </summary>
public void WriteTestPass(ReliabilityTest test, string message)
{
string testName = (test == null) ? "Harness" : test.RefOrID;
WriteToLog(String.Format(" <TestPass DateTime=\"{0}\" TestId=\"{1}\" Description=\"{2}\" />\r\n",
DateTime.Now,
testName,
message));
}
// Updates the stress information with the latest time stamp
public void RecordTimeStamp()
{
if (File.Exists(Environment.ExpandEnvironmentVariables("%SCRIPTSDIR%\\record.js")))
{
ProcessStartInfo psi = new ProcessStartInfo("cscript.exe", Environment.ExpandEnvironmentVariables("//b //nologo %SCRIPTSDIR%\\record.js -i %STRESSID% -a UPDATE_RECORD -s RUNNING"));
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
Process p = Process.Start(psi);
p.StandardOutput.ReadToEnd();
p.WaitForExit();
p.Dispose();
}
}
/// <summary>
/// This writes a line of text to the log file. If the log file is not opened no action is taken.
/// </summary>
/// <param name="text">the text to write to the logfile</param>
void WriteToLog(string text)
{
WriteToReport();
if (logFile != null)
{
try
{
lock (messageQueue)
{
messageQueue.Enqueue(text);
}
}
catch (IOException) { /*Eat exceptions for IO */ }
catch (InvalidOperationException) { /*Eat exceptions if we can't queue */}
}
}
private void WriteToReport()
{
if (ReportResults)
{
try
{
if (File.Exists(Environment.ExpandEnvironmentVariables("%SCRIPTSDIR%\\record.js")))
{
ProcessStartInfo psi = new ProcessStartInfo("cscript.exe", Environment.ExpandEnvironmentVariables("//b //nologo %SCRIPTSDIR%\\record.js -i %STRESSID% -a UPDATE_RECORD -s RUNNING"));
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
Process p = Process.Start(psi);
p.StandardOutput.ReadToEnd();
p.WaitForExit();
if (p.ExitCode != 0)
{
string msg = String.Format("cscript.exe " + Environment.ExpandEnvironmentVariables("//b //nologo %SCRIPTSDIR%\\record.js -i %STRESSID% -a UPDATE_RECORD -s RUNNING\r\nWARNING: Status update did not return success!"), p.ExitCode);
WriteToInstrumentationLog(null, LoggingLevels.UrtFrameworks, msg);
}
p.Dispose();
}
else if (!noStatusWarningDisplayed)
{
noStatusWarningDisplayed = true;
Console.WriteLine("WARNING: record.js does not exist, not updating status...");
}
}
catch (Exception e)
{
string msg = String.Format("WARNING: Status update did not return success (exception thrown {0})!", e);
WriteToInstrumentationLog(null, LoggingLevels.UrtFrameworks, msg);
Console.WriteLine(msg);
}
}
}
public bool ReportResults
{
get
{
return (reportResults);
}
set
{
reportResults = value;
}
}
public void LogNoResultReporter(bool fReportResults)
{
if (!noStatusWarningDisplayed)
{
noStatusWarningDisplayed = true;
if (fReportResults)
{
Console.WriteLine("WARNING: record.js does not exist, not updating status...");
}
}
}
/// <summary>
/// Writes a trace line to the instrumentation log. The instrmentation log is primarily
/// used for deeper understanding what has happened during the stress run.
/// </summary>
/// <param name="level"></param>
/// <param name="str"></param>
public void WriteToInstrumentationLog(ReliabilityTestSet curTestSet, LoggingLevels level, string str)
{
if (curTestSet == null || (curTestSet.LoggingLevel & level) != 0)
{
str = String.Format("[{0} {2}] {1}\r\n", DateTime.Now.ToString(), str, Thread.CurrentThread.ManagedThreadId);
try
{
lock (instrumentationMessageQueue)
{
instrumentationMessageQueue.Enqueue(str);
}
}
catch (IOException) { /*Eat exceptions for IO */ }
catch (InvalidOperationException) { /*Eat exceptions if we can't queue */}
}
}
}
| |
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
#nullable enable
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using NUnit.Compatibility;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.Framework.Internal.Builders;
namespace NUnit.Framework
{
/// <summary>
/// Marks the class as a TestFixture.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple=true, Inherited=true)]
public class TestFixtureAttribute : NUnitAttribute, IFixtureBuilder2, ITestFixtureData
{
private readonly NUnitTestFixtureBuilder _builder = new NUnitTestFixtureBuilder();
#region Constructors
/// <summary>
/// Default constructor
/// </summary>
public TestFixtureAttribute() : this(Internal.TestParameters.NoArguments) { }
/// <summary>
/// Construct with a object[] representing a set of arguments.
/// The arguments may later be separated into type arguments and constructor arguments.
/// </summary>
/// <param name="arguments"></param>
public TestFixtureAttribute(params object?[]? arguments)
{
RunState = RunState.Runnable;
Arguments = arguments ?? new object?[] { null };
TypeArgs = new Type[0];
Properties = new PropertyBag();
}
#endregion
#region ITestData Members
/// <summary>
/// Gets or sets the name of the test.
/// </summary>
/// <value>The name of the test.</value>
public string? TestName { get; set; }
/// <summary>
/// Gets or sets the RunState of this test fixture.
/// </summary>
public RunState RunState { get; private set; }
/// <summary>
/// The arguments originally provided to the attribute
/// </summary>
public object?[] Arguments { get; }
/// <summary>
/// Properties pertaining to this fixture
/// </summary>
public IPropertyBag Properties { get; }
#endregion
#region ITestFixtureData Members
/// <summary>
/// Get or set the type arguments. If not set
/// explicitly, any leading arguments that are
/// Types are taken as type arguments.
/// </summary>
public Type[] TypeArgs { get; set; }
#endregion
#region Other Properties
/// <summary>
/// Descriptive text for this fixture
/// </summary>
[DisallowNull]
public string? Description
{
get { return Properties.Get(PropertyNames.Description) as string; }
set
{
Guard.ArgumentNotNull(value, nameof(value));
Properties.Set(PropertyNames.Description, value);
}
}
/// <summary>
/// The author of this fixture
/// </summary>
[DisallowNull]
public string? Author
{
get { return Properties.Get(PropertyNames.Author) as string; }
set
{
Guard.ArgumentNotNull(value, nameof(value));
Properties.Set(PropertyNames.Author, value);
}
}
/// <summary>
/// The type that this fixture is testing
/// </summary>
[DisallowNull]
public Type? TestOf
{
get { return _testOf; }
set
{
Guard.ArgumentNotNull(value, nameof(value));
_testOf = value;
Properties.Set(PropertyNames.TestOf, value.FullName);
}
}
private Type? _testOf;
/// <summary>
/// Gets or sets the ignore reason. May set RunState as a side effect.
/// </summary>
/// <value>The ignore reason.</value>
[DisallowNull]
public string? Ignore
{
get { return IgnoreReason; }
set
{
Guard.ArgumentNotNull(value, nameof(value));
IgnoreReason = value;
}
}
/// <summary>
/// Gets or sets the reason for not running the fixture.
/// </summary>
/// <value>The reason.</value>
[DisallowNull]
public string? Reason
{
get { return this.Properties.Get(PropertyNames.SkipReason) as string; }
set
{
Guard.ArgumentNotNull(value, nameof(value));
this.Properties.Set(PropertyNames.SkipReason, value);
}
}
/// <summary>
/// Gets or sets the ignore reason. When set to a non-null
/// non-empty value, the test is marked as ignored.
/// </summary>
/// <value>The ignore reason.</value>
[DisallowNull]
public string? IgnoreReason
{
get { return Reason; }
set
{
Guard.ArgumentNotNull(value, nameof(value));
RunState = RunState.Ignored;
Reason = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="NUnit.Framework.TestFixtureAttribute"/> is explicit.
/// </summary>
/// <value>
/// <see langword="true"/> if explicit; otherwise, <see langword="false"/>.
/// </value>
public bool Explicit
{
get { return RunState == RunState.Explicit; }
set { RunState = value ? RunState.Explicit : RunState.Runnable; }
}
/// <summary>
/// Gets and sets the category for this fixture.
/// May be a comma-separated list of categories.
/// </summary>
[DisallowNull]
public string? Category
{
get
{
//return Properties.Get(PropertyNames.Category) as string;
var catList = Properties[PropertyNames.Category];
if (catList == null)
return null;
switch (catList.Count)
{
case 0:
return null;
case 1:
return catList[0] as string;
default:
var cats = new string[catList.Count];
int index = 0;
foreach (string cat in catList)
cats[index++] = cat;
return string.Join(",", cats);
}
}
set
{
Guard.ArgumentNotNull(value, nameof(value));
foreach (string cat in value.Split(new char[] { ',' }))
Properties.Add(PropertyNames.Category, cat);
}
}
#endregion
#region IFixtureBuilder Members
/// <summary>
/// Builds a single test fixture from the specified type.
/// </summary>
public IEnumerable<TestSuite> BuildFrom(ITypeInfo typeInfo)
{
return this.BuildFrom(typeInfo, PreFilter.Empty);
}
#endregion
#region IFixtureBuilder2 Members
/// <summary>
/// Builds a single test fixture from the specified type.
/// </summary>
/// <param name="typeInfo">The type info of the fixture to be used.</param>
/// <param name="filter">Filter used to select methods as tests.</param>
public IEnumerable<TestSuite> BuildFrom(ITypeInfo typeInfo, IPreFilter filter)
{
var fixture = _builder.BuildFrom(typeInfo, filter, this);
fixture.ApplyAttributesToTest(new AttributeProviderWrapper<FixtureLifeCycleAttribute>(typeInfo.Type.GetTypeInfo().Assembly));
fixture.ApplyAttributesToTest(typeInfo.Type);
yield return fixture;
}
#endregion
}
}
| |
namespace DeOps.Simulator
{
partial class LegendForm
{
/// <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.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.PicComm = new System.Windows.Forms.PictureBox();
this.PicNet = new System.Windows.Forms.PictureBox();
this.label5 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.label8 = new System.Windows.Forms.Label();
this.PicPing = new System.Windows.Forms.PictureBox();
this.PicPong = new System.Windows.Forms.PictureBox();
this.label9 = new System.Windows.Forms.Label();
this.label10 = new System.Windows.Forms.Label();
this.PicPxyReq = new System.Windows.Forms.PictureBox();
this.PicPxyAck = new System.Windows.Forms.PictureBox();
this.label12 = new System.Windows.Forms.Label();
this.PicStore = new System.Windows.Forms.PictureBox();
this.label13 = new System.Windows.Forms.Label();
this.label14 = new System.Windows.Forms.Label();
this.PicSrchReq = new System.Windows.Forms.PictureBox();
this.PicSrchAck = new System.Windows.Forms.PictureBox();
this.label11 = new System.Windows.Forms.Label();
this.PicMail = new System.Windows.Forms.PictureBox();
this.label15 = new System.Windows.Forms.Label();
this.label16 = new System.Windows.Forms.Label();
this.PicProfile = new System.Windows.Forms.PictureBox();
this.PicBoard = new System.Windows.Forms.PictureBox();
this.label17 = new System.Windows.Forms.Label();
this.label18 = new System.Windows.Forms.Label();
this.PicLoc = new System.Windows.Forms.PictureBox();
this.PicTransfer = new System.Windows.Forms.PictureBox();
this.label19 = new System.Windows.Forms.Label();
this.label20 = new System.Windows.Forms.Label();
this.PicNode = new System.Windows.Forms.PictureBox();
this.PicLink = new System.Windows.Forms.PictureBox();
this.label21 = new System.Windows.Forms.Label();
this.PicUnk = new System.Windows.Forms.PictureBox();
((System.ComponentModel.ISupportInitialize)(this.PicComm)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.PicNet)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.PicPing)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.PicPong)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.PicPxyReq)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.PicPxyAck)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.PicStore)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.PicSrchReq)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.PicSrchAck)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.PicMail)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.PicProfile)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.PicBoard)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.PicLoc)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.PicTransfer)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.PicNode)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.PicLink)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.PicUnk)).BeginInit();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(12, 9);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(220, 16);
this.label1.TabIndex = 0;
this.label1.Text = "Format - Root / Packet / Component";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(120, 46);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(40, 13);
this.label2.TabIndex = 1;
this.label2.Text = "Roots";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.Location = new System.Drawing.Point(12, 46);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(53, 13);
this.label3.TabIndex = 2;
this.label3.Text = "Packets";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label4.Location = new System.Drawing.Point(241, 46);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(76, 13);
this.label4.TabIndex = 3;
this.label4.Text = "Components";
//
// PicComm
//
this.PicComm.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(192)))), ((int)(((byte)(0)))));
this.PicComm.Location = new System.Drawing.Point(58, 91);
this.PicComm.Name = "PicComm";
this.PicComm.Size = new System.Drawing.Size(17, 17);
this.PicComm.TabIndex = 13;
this.PicComm.TabStop = false;
//
// PicNet
//
this.PicNet.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(0)))), ((int)(((byte)(0)))));
this.PicNet.Location = new System.Drawing.Point(58, 68);
this.PicNet.Name = "PicNet";
this.PicNet.Size = new System.Drawing.Size(17, 17);
this.PicNet.TabIndex = 14;
this.PicNet.TabStop = false;
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(12, 72);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(24, 13);
this.label5.TabIndex = 15;
this.label5.Text = "Net";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(12, 95);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(36, 13);
this.label6.TabIndex = 16;
this.label6.Text = "Comm";
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(120, 164);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(32, 13);
this.label7.TabIndex = 20;
this.label7.Text = "Pong";
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(120, 141);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(28, 13);
this.label8.TabIndex = 19;
this.label8.Text = "Ping";
//
// PicPing
//
this.PicPing.BackColor = System.Drawing.Color.Lime;
this.PicPing.Location = new System.Drawing.Point(178, 137);
this.PicPing.Name = "PicPing";
this.PicPing.Size = new System.Drawing.Size(17, 17);
this.PicPing.TabIndex = 18;
this.PicPing.TabStop = false;
//
// PicPong
//
this.PicPong.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(255)))), ((int)(((byte)(128)))));
this.PicPong.Location = new System.Drawing.Point(178, 160);
this.PicPong.Name = "PicPong";
this.PicPong.Size = new System.Drawing.Size(17, 17);
this.PicPong.TabIndex = 17;
this.PicPong.TabStop = false;
//
// label9
//
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(120, 210);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(46, 13);
this.label9.TabIndex = 24;
this.label9.Text = "Pxy Ack";
//
// label10
//
this.label10.AutoSize = true;
this.label10.Location = new System.Drawing.Point(120, 187);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(47, 13);
this.label10.TabIndex = 23;
this.label10.Text = "Pxy Req";
//
// PicPxyReq
//
this.PicPxyReq.BackColor = System.Drawing.Color.Purple;
this.PicPxyReq.Location = new System.Drawing.Point(178, 183);
this.PicPxyReq.Name = "PicPxyReq";
this.PicPxyReq.Size = new System.Drawing.Size(17, 17);
this.PicPxyReq.TabIndex = 22;
this.PicPxyReq.TabStop = false;
//
// PicPxyAck
//
this.PicPxyAck.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(0)))), ((int)(((byte)(192)))));
this.PicPxyAck.Location = new System.Drawing.Point(178, 206);
this.PicPxyAck.Name = "PicPxyAck";
this.PicPxyAck.Size = new System.Drawing.Size(17, 17);
this.PicPxyAck.TabIndex = 21;
this.PicPxyAck.TabStop = false;
//
// label12
//
this.label12.AutoSize = true;
this.label12.Location = new System.Drawing.Point(120, 118);
this.label12.Name = "label12";
this.label12.Size = new System.Drawing.Size(32, 13);
this.label12.TabIndex = 31;
this.label12.Text = "Store";
//
// PicStore
//
this.PicStore.BackColor = System.Drawing.Color.DodgerBlue;
this.PicStore.Location = new System.Drawing.Point(178, 114);
this.PicStore.Name = "PicStore";
this.PicStore.Size = new System.Drawing.Size(17, 17);
this.PicStore.TabIndex = 30;
this.PicStore.TabStop = false;
//
// label13
//
this.label13.AutoSize = true;
this.label13.Location = new System.Drawing.Point(120, 95);
this.label13.Name = "label13";
this.label13.Size = new System.Drawing.Size(51, 13);
this.label13.TabIndex = 28;
this.label13.Text = "Srch Ack";
//
// label14
//
this.label14.AutoSize = true;
this.label14.Location = new System.Drawing.Point(120, 72);
this.label14.Name = "label14";
this.label14.Size = new System.Drawing.Size(52, 13);
this.label14.TabIndex = 27;
this.label14.Text = "Srch Req";
//
// PicSrchReq
//
this.PicSrchReq.BackColor = System.Drawing.Color.Red;
this.PicSrchReq.Location = new System.Drawing.Point(178, 68);
this.PicSrchReq.Name = "PicSrchReq";
this.PicSrchReq.Size = new System.Drawing.Size(17, 17);
this.PicSrchReq.TabIndex = 26;
this.PicSrchReq.TabStop = false;
//
// PicSrchAck
//
this.PicSrchAck.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(0)))));
this.PicSrchAck.Location = new System.Drawing.Point(178, 91);
this.PicSrchAck.Name = "PicSrchAck";
this.PicSrchAck.Size = new System.Drawing.Size(17, 17);
this.PicSrchAck.TabIndex = 25;
this.PicSrchAck.TabStop = false;
//
// label11
//
this.label11.AutoSize = true;
this.label11.Location = new System.Drawing.Point(241, 210);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(26, 13);
this.label11.TabIndex = 45;
this.label11.Text = "Mail";
//
// PicMail
//
this.PicMail.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(255)))));
this.PicMail.Location = new System.Drawing.Point(299, 206);
this.PicMail.Name = "PicMail";
this.PicMail.Size = new System.Drawing.Size(17, 17);
this.PicMail.TabIndex = 44;
this.PicMail.TabStop = false;
//
// label15
//
this.label15.AutoSize = true;
this.label15.Location = new System.Drawing.Point(241, 187);
this.label15.Name = "label15";
this.label15.Size = new System.Drawing.Size(35, 13);
this.label15.TabIndex = 43;
this.label15.Text = "Board";
//
// label16
//
this.label16.AutoSize = true;
this.label16.Location = new System.Drawing.Point(241, 164);
this.label16.Name = "label16";
this.label16.Size = new System.Drawing.Size(36, 13);
this.label16.TabIndex = 42;
this.label16.Text = "Profile";
//
// PicProfile
//
this.PicProfile.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(255)))));
this.PicProfile.Location = new System.Drawing.Point(299, 160);
this.PicProfile.Name = "PicProfile";
this.PicProfile.Size = new System.Drawing.Size(17, 17);
this.PicProfile.TabIndex = 41;
this.PicProfile.TabStop = false;
//
// PicBoard
//
this.PicBoard.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(255)))));
this.PicBoard.Location = new System.Drawing.Point(299, 183);
this.PicBoard.Name = "PicBoard";
this.PicBoard.Size = new System.Drawing.Size(17, 17);
this.PicBoard.TabIndex = 40;
this.PicBoard.TabStop = false;
//
// label17
//
this.label17.AutoSize = true;
this.label17.Location = new System.Drawing.Point(241, 141);
this.label17.Name = "label17";
this.label17.Size = new System.Drawing.Size(46, 13);
this.label17.TabIndex = 39;
this.label17.Text = "Transfer";
//
// label18
//
this.label18.AutoSize = true;
this.label18.Location = new System.Drawing.Point(241, 118);
this.label18.Name = "label18";
this.label18.Size = new System.Drawing.Size(48, 13);
this.label18.TabIndex = 38;
this.label18.Text = "Location";
//
// PicLoc
//
this.PicLoc.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
this.PicLoc.Location = new System.Drawing.Point(299, 114);
this.PicLoc.Name = "PicLoc";
this.PicLoc.Size = new System.Drawing.Size(17, 17);
this.PicLoc.TabIndex = 37;
this.PicLoc.TabStop = false;
//
// PicTransfer
//
this.PicTransfer.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
this.PicTransfer.Location = new System.Drawing.Point(299, 137);
this.PicTransfer.Name = "PicTransfer";
this.PicTransfer.Size = new System.Drawing.Size(17, 17);
this.PicTransfer.TabIndex = 36;
this.PicTransfer.TabStop = false;
//
// label19
//
this.label19.AutoSize = true;
this.label19.Location = new System.Drawing.Point(241, 95);
this.label19.Name = "label19";
this.label19.Size = new System.Drawing.Size(27, 13);
this.label19.TabIndex = 35;
this.label19.Text = "Link";
//
// label20
//
this.label20.AutoSize = true;
this.label20.Location = new System.Drawing.Point(241, 72);
this.label20.Name = "label20";
this.label20.Size = new System.Drawing.Size(33, 13);
this.label20.TabIndex = 34;
this.label20.Text = "Node";
//
// PicNode
//
this.PicNode.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(128)))));
this.PicNode.Location = new System.Drawing.Point(299, 68);
this.PicNode.Name = "PicNode";
this.PicNode.Size = new System.Drawing.Size(17, 17);
this.PicNode.TabIndex = 33;
this.PicNode.TabStop = false;
//
// PicLink
//
this.PicLink.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(128)))));
this.PicLink.Location = new System.Drawing.Point(299, 91);
this.PicLink.Name = "PicLink";
this.PicLink.Size = new System.Drawing.Size(17, 17);
this.PicLink.TabIndex = 32;
this.PicLink.TabStop = false;
//
// label21
//
this.label21.AutoSize = true;
this.label21.Location = new System.Drawing.Point(12, 118);
this.label21.Name = "label21";
this.label21.Size = new System.Drawing.Size(41, 13);
this.label21.TabIndex = 47;
this.label21.Text = "Unkwn";
//
// PicUnk
//
this.PicUnk.BackColor = System.Drawing.Color.Black;
this.PicUnk.Location = new System.Drawing.Point(58, 114);
this.PicUnk.Name = "PicUnk";
this.PicUnk.Size = new System.Drawing.Size(17, 17);
this.PicUnk.TabIndex = 46;
this.PicUnk.TabStop = false;
//
// LegendForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(342, 247);
this.Controls.Add(this.label21);
this.Controls.Add(this.PicUnk);
this.Controls.Add(this.label11);
this.Controls.Add(this.PicMail);
this.Controls.Add(this.label15);
this.Controls.Add(this.label16);
this.Controls.Add(this.PicProfile);
this.Controls.Add(this.PicBoard);
this.Controls.Add(this.label17);
this.Controls.Add(this.label18);
this.Controls.Add(this.PicLoc);
this.Controls.Add(this.PicTransfer);
this.Controls.Add(this.label19);
this.Controls.Add(this.label20);
this.Controls.Add(this.PicNode);
this.Controls.Add(this.PicLink);
this.Controls.Add(this.label12);
this.Controls.Add(this.PicStore);
this.Controls.Add(this.label13);
this.Controls.Add(this.label14);
this.Controls.Add(this.PicSrchReq);
this.Controls.Add(this.PicSrchAck);
this.Controls.Add(this.label9);
this.Controls.Add(this.label10);
this.Controls.Add(this.PicPxyReq);
this.Controls.Add(this.PicPxyAck);
this.Controls.Add(this.label7);
this.Controls.Add(this.label8);
this.Controls.Add(this.PicPing);
this.Controls.Add(this.PicPong);
this.Controls.Add(this.label6);
this.Controls.Add(this.label5);
this.Controls.Add(this.PicNet);
this.Controls.Add(this.PicComm);
this.Controls.Add(this.label4);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "LegendForm";
this.ShowInTaskbar = false;
this.Text = "Legend";
((System.ComponentModel.ISupportInitialize)(this.PicComm)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.PicNet)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.PicPing)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.PicPong)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.PicPxyReq)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.PicPxyAck)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.PicStore)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.PicSrchReq)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.PicSrchAck)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.PicMail)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.PicProfile)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.PicBoard)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.PicLoc)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.PicTransfer)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.PicNode)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.PicLink)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.PicUnk)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.Label label12;
private System.Windows.Forms.Label label13;
private System.Windows.Forms.Label label14;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.Label label15;
private System.Windows.Forms.Label label16;
private System.Windows.Forms.Label label17;
private System.Windows.Forms.Label label18;
private System.Windows.Forms.Label label19;
private System.Windows.Forms.Label label20;
private System.Windows.Forms.Label label21;
public System.Windows.Forms.PictureBox PicComm;
public System.Windows.Forms.PictureBox PicNet;
public System.Windows.Forms.PictureBox PicPing;
public System.Windows.Forms.PictureBox PicPong;
public System.Windows.Forms.PictureBox PicPxyReq;
public System.Windows.Forms.PictureBox PicPxyAck;
public System.Windows.Forms.PictureBox PicStore;
public System.Windows.Forms.PictureBox PicSrchReq;
public System.Windows.Forms.PictureBox PicSrchAck;
public System.Windows.Forms.PictureBox PicMail;
public System.Windows.Forms.PictureBox PicProfile;
public System.Windows.Forms.PictureBox PicBoard;
public System.Windows.Forms.PictureBox PicLoc;
public System.Windows.Forms.PictureBox PicTransfer;
public System.Windows.Forms.PictureBox PicNode;
public System.Windows.Forms.PictureBox PicLink;
public System.Windows.Forms.PictureBox PicUnk;
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using UOPDefine;
namespace UoKRUnpacker
{
public partial class Form1 : Form, StupidInterface
{
public Form1()
{
InitializeComponent();
DoingSomeJob.TheForm = this;
this.FormClosing += delegate(object sender, FormClosingEventArgs e)
{
if (DoingSomeJob.Working)
{
DialogResult drData = MessageBox.Show("Are you sure to close? Still working in background!", "UO:KR Uop Dumper",
MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (drData == DialogResult.No)
{
e.Cancel = true;
}
}
};
this.toolBtnDontFix.Click += delegate(object sender, EventArgs e)
{
this.toolBtnDontFix.Checked = !this.toolBtnDontFix.Checked;
//this.toolBtnDontFix.BackColor = (this.toolBtnDontFix.Checked) ? System.Drawing.Color.Gainsboro : System.Drawing.SystemColors.Control;
};
this.btn_pnlUopFile_RecountFiles.LinkClicked += delegate(object sender, LinkLabelLinkClickedEventArgs e)
{
UOPFile upCurrent = (UOPFile)this.gbSelectedData.Tag;
this.num_pnlUopFile_Files.Value = upCurrent.FilesDynamicCount;
this.btn_pnlUopFile_RecountFiles.LinkVisited = false;
};
this.btn_pnUopDatafile_RecountFiles.LinkClicked += delegate(object sender, LinkLabelLinkClickedEventArgs e)
{
UOPIndexBlockHeader upCurrent = (UOPIndexBlockHeader)this.gbSelectedData.Tag;
this.nud_pnUopDatafile_Files.Value = upCurrent.FilesDynamicCount;
this.btn_pnUopDatafile_RecountFiles.LinkVisited = false;
};
this.btn_pnUopHeaderAndData_PatchData.LinkClicked += delegate(object sender, LinkLabelLinkClickedEventArgs e)
{
UOPPairData upDataPair = (UOPPairData)this.gbSelectedData.Tag;
this.txt_pnUopHeaderAndData_Data.Tag = AddData(upDataPair, false);
this.btn_pnUopHeaderAndData_PatchData.LinkVisited = false;
};
this.btn_pnUopHeaderAndData_PatchDataUnc.LinkClicked += delegate(object sender, LinkLabelLinkClickedEventArgs e)
{
UOPPairData upDataPair = (UOPPairData)this.gbSelectedData.Tag;
this.txt_pnUopHeaderAndData_Data.Tag = AddData(upDataPair, true);
this.btn_pnUopHeaderAndData_PatchData.LinkVisited = false;
};
this.btn_pnUopHeaderAndData_PatchData.Tag = null;
this.btn_pnUopHeaderAndData_PatchDataUnc.Tag = null;
this.num_pnlUopFile_Files.Minimum = 0;
this.num_pnlUopFile_Files.Maximum = Int32.MaxValue;
}
private void SetDisableIcon(bool bEnabled)
{
this.toolBtnRefresh.Enabled = !bEnabled;
this.toolBtnSave.Enabled = !bEnabled;
this.toolBtnSaveAs.Enabled = !bEnabled;
this.toolBtnDontFix.Enabled = !bEnabled;
this.toolBtnDump.Enabled = !bEnabled;
this.toolBtnUnpack.Enabled = !bEnabled;
}
private void SetModifyButtons(bool bEnable)
{
this.btnDetailsModify.Enabled = bEnable;
this.btnDetailsApply.Enabled = !bEnable;
this.btnDetailsDelete.Enabled = !bEnable;
this.btnDetailsUndo.Enabled = !bEnable;
}
private System.Collections.Hashtable AddData(UOPPairData pData, bool unCompressed)
{
this.txt_pnUopHeaderAndData_Data.Tag = null;
if (this.oPatchDlgUopopen.ShowDialog(this) == DialogResult.OK)
{
System.Collections.Hashtable htTosend = new System.Collections.Hashtable();
htTosend.Add("file", this.oPatchDlgUopopen.FileName);
htTosend.Add("uncompressed", unCompressed);
return htTosend;
}
return null;
}
private void LoadUOP()
{
DialogResult drFile = oFileDlgUopopen.ShowDialog(this);
if (drFile != DialogResult.OK)
{
MessageBox.Show("File not selected!", "UO:KR Uop Dumper - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
LoadUOP(oFileDlgUopopen.FileName);
}
private void LoadUOP(string theNewFile)
{
ThreadArgs.MyThreadDelegate mtdParse = delegate(object args)
{
ThreadArgs theArgs = (ThreadArgs)args;
StupidInterface theForm = (StupidInterface)theArgs.Args[0];
string theFile = (string)theArgs.Args[1];
UopManager upIstance = UopManager.getIstance(true);
upIstance.UopPath = theFile;
bool bResult = upIstance.Load();
if (bResult)
theForm.SetTextArea("Done parsing.");
else
theForm.SetTextArea("ERROR while parsing file \"" + theFile + "\" !!!");
if (bResult)
{
theForm.SetNodes();
theForm.DisableOtherIcon(false);
}
theForm.SetLoadIcon(true);
DoingSomeJob.Working = false;
};
DoingSomeJob.Working = true;
this.SetTextArea("Parsing file \"" + theNewFile + "\" ...");
this.SetDisableIcon(true);
this.SetLoadIcon(false);
System.Threading.Thread tRun = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(mtdParse));
tRun.Start(new ThreadArgs(new object[] { this, theNewFile }));
}
private void Parse()
{
UOPFile uopToParse = UopManager.getIstance().UopFile;
this.tvFileData.SuspendLayout();
this.tvFileData.Nodes.Clear();
TreeNodeCollection tncCurrent = this.tvFileData.Nodes;
TreeNode tnRoot = new TreeNode(Utility.GetFileName(UopManager.getIstance().UopPath));
tnRoot.Tag = -1; tncCurrent.Add(tnRoot);
for (int iNode = 0; iNode < uopToParse.m_Content.Count; iNode++)
{
TreeNode tnCurrent = new TreeNode(String.Format("Header Block {0}", iNode));
tnCurrent.ContextMenuStrip = this.ctxMenuNode;
tnCurrent.Tag = iNode;
tnRoot.Nodes.Add(tnCurrent);
}
tnRoot.Expand();
this.tvFileData.ResumeLayout(true);
}
private void RefreshData()
{
SetDisableIcon(true);
// sistema la groupbox
this.pnUopfile.Visible = this.pnUopfile.Enabled = false;
this.pnUopDatafile.Visible = this.pnUopDatafile.Enabled = false;
tvFileData_AfterSelect(null, new TreeViewEventArgs(null));
Parse();
SetDisableIcon(false);
}
private void CommonSave(string sFile, bool bFix)
{
if (DoingSomeJob.Working)
{
MessageBox.Show("Please wait... Still working in background!", "UO:KR Uop Dumper", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
ThreadArgs.MyThreadDelegate mtdParse = delegate(object args)
{
ThreadArgs theArgs = (ThreadArgs)args;
StupidInterface theForm = (StupidInterface)theArgs.Args[0];
string theFile = (string)theArgs.Args[1];
bool theFix = (bool)theArgs.Args[2];
UopManager upIstance = UopManager.getIstance();
if (theFix)
upIstance.FixOffsets(0, 0);
bool bResult = upIstance.Write(theFile);
if (bResult)
{
theForm.SetTextArea("Done saving UOP file.");
if (!upIstance.UopPath.Equals(theFile, StringComparison.OrdinalIgnoreCase))
upIstance.UopPath = theFile;
}
else
theForm.SetTextArea("ERROR while saving file \"" + theFile + "\" !!!");
theForm.DisableOtherIcon(false);
theForm.SetLoadIcon(true);
DoingSomeJob.Working = false;
};
DoingSomeJob.Working = true;
SetTextArea("Saving UOP file to \"" + sFile + "\" ...");
this.SetDisableIcon(true);
this.SetLoadIcon(false);
System.Threading.Thread tRun = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(mtdParse));
tRun.Start(new ThreadArgs(new object[] { this, sFile, bFix }));
}
}
private void CommonDump(ShowPanels spType, object oCast)
{
if (DoingSomeJob.Working)
{
MessageBox.Show("Please wait... Still working in background!", "UO:KR Uop Dumper", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
ThreadArgs.MyThreadDelegate mtdParse = delegate(object args)
{
ThreadArgs theArgs = (ThreadArgs)args;
StupidInterface theForm = (StupidInterface)theArgs.Args[0];
string thePath = (string)theArgs.Args[1];
ShowPanels theType = (ShowPanels)theArgs.Args[2];
object theObject = theArgs.Args[3];
UopManager upIstance = UopManager.getIstance();
string baseName = Path.GetFileNameWithoutExtension(upIstance.UopPath);
string resultName = "";
try
{
if (!Directory.Exists(thePath))
Directory.CreateDirectory(thePath);
int i = 0, j = 0;
switch (spType)
{
case ShowPanels.RootNode:
{
UOPFile toDump = (UOPFile)theObject;
foreach (UOPIndexBlockHeader dumpTemp1 in toDump.m_Content)
{
foreach (UOPPairData dumpTemp2 in dumpTemp1.m_ListData)
{
using (FileStream fsWrite = File.Create(thePath + @"\" + String.Format(StaticData.UNPACK_NAMEPATTERN, baseName, i, j, dumpTemp2.First.IsCompressed ? StaticData.UNPACK_EXT_COMP : StaticData.UNPACK_EXT_UCOMP)))
{
using (BinaryWriter bwWrite = new BinaryWriter(fsWrite))
{
bwWrite.Write(dumpTemp2.Second.Extract(dumpTemp2.First.IsCompressed, dumpTemp2.First.m_LenghtUncompressed));
}
}
j++;
}
i++;
j = 0;
}
resultName = "the UOP file.";
} break;
case ShowPanels.DataNode:
{
UOPIndexBlockHeader toDump = (UOPIndexBlockHeader)theObject;
foreach (UOPIndexBlockHeader dumpTemp1 in upIstance.UopFile.m_Content)
{
if (dumpTemp1.Equals(toDump))
break;
i++;
}
foreach (UOPPairData dumpTemp2 in toDump.m_ListData)
{
using (FileStream fsWrite = File.Create(thePath + @"\" + String.Format(StaticData.UNPACK_NAMEPATTERN, baseName, i, j, dumpTemp2.First.IsCompressed ? StaticData.UNPACK_EXT_COMP : StaticData.UNPACK_EXT_UCOMP)))
{
using (BinaryWriter bwWrite = new BinaryWriter(fsWrite))
{
bwWrite.Write(dumpTemp2.Second.Extract(dumpTemp2.First.IsCompressed, dumpTemp2.First.m_LenghtUncompressed));
}
}
j++;
}
resultName = "the Header Block " + i.ToString() + ".";
} break;
case ShowPanels.SingleHeader:
{
UOPPairData toDump = (UOPPairData)theObject; bool bBreakLoop = false;
foreach (UOPIndexBlockHeader dumpTemp1 in upIstance.UopFile.m_Content)
{
foreach (UOPPairData dumpTemp2 in dumpTemp1.m_ListData)
{
bBreakLoop = dumpTemp2.Equals(toDump);
if (bBreakLoop)
break;
j++;
}
if (bBreakLoop)
break;
i++;
j = 0;
}
using (FileStream fsWrite = File.Create(thePath + @"\" + String.Format(StaticData.UNPACK_NAMEPATTERN, baseName, i, j, toDump.First.IsCompressed ? StaticData.UNPACK_EXT_COMP : StaticData.UNPACK_EXT_UCOMP)))
{
using (BinaryWriter bwWrite = new BinaryWriter(fsWrite))
{
bwWrite.Write(toDump.Second.Extract(toDump.First.IsCompressed, toDump.First.m_LenghtUncompressed));
}
}
resultName = "the Index " + j.ToString() + ".";
} break;
}
GC.Collect();
theForm.SetTextArea("Completed unpacking for " + resultName);
}
catch
{
theForm.SetTextArea("ERROR while unpacking selected data.");
}
finally
{
theForm.DisableOtherIcon(false);
theForm.SetLoadIcon(true);
DoingSomeJob.Working = false;
}
};
DoingSomeJob.Working = true;
SetTextArea("Unpacking seleceted data to \"" + Application.StartupPath + StaticData.UNPACK_DIR + "\" ...");
this.SetDisableIcon(true);
this.SetLoadIcon(false);
System.Threading.Thread tRun = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(mtdParse));
tRun.Start(new ThreadArgs(new object[] { this, Application.StartupPath + StaticData.UNPACK_DIR, spType, oCast }));
}
}
#region Button Details
private void btnDetailsUnpack_Click(object sender, EventArgs e)
{
if (DoingSomeJob.Working)
{
MessageBox.Show("Please wait... Still working in background!", "UO:KR Uop Dumper", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else if (this.pnUopfile.Visible)
{
toolBtnUnpack_Click(sender, e);
}
else if (this.pnUopDatafile.Visible)
{
CommonDump(ShowPanels.DataNode, this.gbSelectedData.Tag);
}
else if (this.pnUopHeaderAndData.Visible)
{
CommonDump(ShowPanels.SingleHeader, this.gbSelectedData.Tag);
}
else
{
SetPanel(ShowPanels.Nothing, null);
}
}
private void btnDetailsModify_Click(object sender, EventArgs e)
{
if (DoingSomeJob.Working)
{
MessageBox.Show("Please wait... Still working in background!", "UO:KR Uop Dumper", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
// for each panel
this.pnUopfile.Enabled = this.pnUopfile.Visible;
this.pnUopDatafile.Enabled = this.pnUopDatafile.Visible;
this.pnUopHeaderAndData.Enabled = this.pnUopHeaderAndData.Visible;
// ---------------------
if (this.pnUopfile.Enabled || this.pnUopDatafile.Enabled || this.pnUopHeaderAndData.Enabled)
SetModifyButtons(false);
}
private void btnDetailsUndo_Click(object sender, EventArgs e)
{
if (DoingSomeJob.Working)
{
MessageBox.Show("Please wait... Still working in background!", "UO:KR Uop Dumper", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
DoingSomeJob.Working = true;
if (this.pnUopfile.Enabled)
{
SetPanel(ShowPanels.RootNode, this.gbSelectedData.Tag);
}
else if (this.pnUopDatafile.Enabled)
{
SetPanel(ShowPanels.DataNode, this.gbSelectedData.Tag);
}
else if (this.pnUopHeaderAndData.Enabled)
{
SetPanel(ShowPanels.SingleHeader, this.gbSelectedData.Tag);
}
else
{
SetPanel(ShowPanels.Nothing, null);
}
DoingSomeJob.Working = false;
}
private void btnDetailsApply_Click(object sender, EventArgs e)
{
if (DoingSomeJob.Working)
{
MessageBox.Show("Please wait... Still working in background!", "UO:KR Uop Dumper", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
DoingSomeJob.Working = true;
if (this.pnUopfile.Enabled)
{
try
{
UOPFile uppeCurrent = (UOPFile)this.gbSelectedData.Tag;
byte[] bHeader1 = Utility.StringToByteArray(this.txt_pnlUopFile_Header1.Text, Utility.HashStringStyle.HexWithSeparator, 24);
byte[] bHeader2 = Utility.StringToByteArray(this.txt_pnlUopFile_Header2.Text, Utility.HashStringStyle.HexWithSeparator, 12);
uint uCount = Decimal.ToUInt32(this.num_pnlUopFile_Files.Value);
if ((bHeader1 == null) || (bHeader1 == null))
{
throw new Exception();
}
else
{
uppeCurrent.m_Header.m_variousData = bHeader1;
uppeCurrent.m_Header.m_totalIndex = uCount;
uppeCurrent.m_Header.m_Unknown = bHeader2;
}
}
catch
{
MessageBox.Show("Error while parsing the data!", "UO:KR Uop Dumper - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
SetPanel(ShowPanels.RootNode, this.gbSelectedData.Tag);
}
else if (this.pnUopDatafile.Enabled)
{
try
{
UOPIndexBlockHeader uppeCurrent = (UOPIndexBlockHeader)this.gbSelectedData.Tag;
ulong ulOffset = UInt64.Parse(this.txt_pnUopDatafile_Offset.Text, System.Globalization.NumberStyles.AllowHexSpecifier);
uint uCount = Decimal.ToUInt32(this.nud_pnUopDatafile_Files.Value);
uppeCurrent.m_Files = uCount;
uppeCurrent.m_OffsetNextIndex = ulOffset;
}
catch
{
MessageBox.Show("Error while parsing the data!", "UO:KR Uop Dumper - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
SetPanel(ShowPanels.DataNode, this.gbSelectedData.Tag);
}
else if (this.pnUopHeaderAndData.Enabled)
{
try
{
UOPPairData uppeCurrent = (UOPPairData)this.gbSelectedData.Tag;
// Header block
ulong ulOffset = UInt64.Parse(this.txt_pnUopHeaderAndData_Offset.Text, System.Globalization.NumberStyles.AllowHexSpecifier);
uint uiUnk1 = UInt32.Parse(this.txt_pnUopHeaderAndData_Unk1.Text, System.Globalization.NumberStyles.AllowHexSpecifier);
uint uiUnk2 = UInt32.Parse(this.txt_pnUopHeaderAndData_Unk2.Text, System.Globalization.NumberStyles.AllowHexSpecifier);
uint uiUnk3 = UInt32.Parse(this.txt_pnUopHeaderAndData_Unk3.Text, System.Globalization.NumberStyles.AllowHexSpecifier);
string sNewFile = null; bool bUncompressed = false;
if (this.txt_pnUopHeaderAndData_Data.Tag != null)
{
sNewFile = (string)(((System.Collections.Hashtable)this.txt_pnUopHeaderAndData_Data.Tag)["file"]);
bUncompressed = (bool)(((System.Collections.Hashtable)this.txt_pnUopHeaderAndData_Data.Tag)["uncompressed"]);
}
ulong ulUnkData = UInt64.Parse(this.txt_pnUopHeaderAndData_DataUnk1.Text, System.Globalization.NumberStyles.AllowHexSpecifier);
if (sNewFile != null)
{
if (UopManager.getIstance().Replace(sNewFile, uppeCurrent, bUncompressed) != UopManager.UopPatchError.Okay)
{
throw new Exception();
}
}
uppeCurrent.First.m_OffsetOfDataBlock = ulOffset;
uppeCurrent.First.m_Unknown1 = uiUnk1;
uppeCurrent.First.m_Unknown2 = uiUnk2;
uppeCurrent.First.m_Unknown3 = uiUnk2;
}
catch
{
MessageBox.Show("Error while parsing the data!", "UO:KR Uop Dumper - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
SetPanel(ShowPanels.SingleHeader, this.gbSelectedData.Tag);
}
else
{
SetPanel(ShowPanels.Nothing, null);
}
DoingSomeJob.Working = false;
}
private void btnDetailsDelete_Click(object sender, EventArgs e)
{
if (DoingSomeJob.Working)
{
MessageBox.Show("Please wait... Still working in background!", "UO:KR Uop Dumper", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
DoingSomeJob.Working = true;
if (this.pnUopfile.Enabled)
{
SetPanel(ShowPanels.RootNode, this.gbSelectedData.Tag);
MessageBox.Show("You cannot delete the UOP file that way!", "UO:KR Uop Dumper - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (this.pnUopDatafile.Enabled)
{
SetTextArea("Deleting selected header block ...");
SetPanel(ShowPanels.DataNode, this.gbSelectedData.Tag);
UopManager.getIstance().Delete((UOPIndexBlockHeader)(this.gbSelectedData.Tag));
RefreshData();
SetTextArea("Deleted selected header block.");
}
else if (this.pnUopHeaderAndData.Enabled)
{
SetTextArea("Deleting selected index ...");
SetPanel(ShowPanels.SingleHeader, this.gbSelectedData.Tag);
UopManager.getIstance().Delete((UOPPairData)(this.gbSelectedData.Tag));
RefreshData();
SetTextArea("Deleted selected index.");
}
else
{
SetPanel(ShowPanels.Nothing, null);
}
SetTextArea("");
DoingSomeJob.Working = false;
}
#endregion
#region Toolbar Buttons
private void toolBtnOpen_Click(object sender, EventArgs e)
{
if (DoingSomeJob.Working)
{
MessageBox.Show("Please wait... Still working in background!", "UO:KR Uop Dumper", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
LoadUOP();
}
}
private void toolBtnSave_Click(object sender, EventArgs e)
{
CommonSave(UopManager.getIstance().UopPath, !this.toolBtnDontFix.Checked);
}
private void toolBtnSaveAs_Click(object sender, EventArgs e)
{
this.oFileDlgUopsave.FileName = UopManager.getIstance().UopPath;
if (this.oFileDlgUopsave.ShowDialog(this) == DialogResult.OK)
CommonSave(this.oFileDlgUopsave.FileName, !this.toolBtnDontFix.Checked);
}
private void toolBtnDump_Click(object sender, EventArgs e)
{
if (DoingSomeJob.Working)
{
MessageBox.Show("Please wait... Still working in background!", "UO:KR Uop Dumper", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
ThreadArgs.MyThreadDelegate mtdParse = delegate(object args)
{
ThreadArgs theArgs = (ThreadArgs)args;
StupidInterface theForm = (StupidInterface)theArgs.Args[0];
string thePath = (string)theArgs.Args[1];
string theFile = (string)theArgs.Args[2];
UopManager upIstance = UopManager.getIstance();
try
{
string pathandfile = thePath + @"\" + theFile;
if (!Directory.Exists(thePath))
Directory.CreateDirectory(thePath);
using (StreamWriter swFile = new StreamWriter(pathandfile, false))
{
swFile.Write(UopManager.getIstance().UopFile.ToString());
}
theForm.SetTextArea("Completed information dump.");
}
catch
{
theForm.SetTextArea("ERROR while writing information dump.");
}
finally
{
theForm.DisableOtherIcon(false);
theForm.SetLoadIcon(true);
DoingSomeJob.Working = false;
}
};
DoingSomeJob.Working = true;
string sPath = Application.StartupPath + StaticData.DUMPINFO_DIR;
string sFile = Utility.GetFileName(UopManager.getIstance().UopPath) + ".txt";
SetTextArea("Dumping UOP file to \"" + sPath + "\\" + sFile + "\" ...");
this.SetDisableIcon(true);
this.SetLoadIcon(false);
System.Threading.Thread tRun = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(mtdParse));
tRun.Start(new ThreadArgs(new object[] { this, sPath, sFile }));
}
}
private void toolBtnUnpack_Click(object sender, EventArgs e)
{
CommonDump(ShowPanels.RootNode, UopManager.getIstance().UopFile);
}
private void toolBtnClose_Click(object sender, EventArgs e)
{
Close();
}
private void toolBtnRefresh_Click(object sender, EventArgs e)
{
DoingSomeJob.Working = true;
RefreshData();
DoingSomeJob.Working = false;
}
private void toolBtnInfo_Click(object sender, EventArgs e)
{
Form2 frmAbout = new Form2();
DialogResult drResult = frmAbout.ShowDialog(this);
if (drResult == DialogResult.OK)
{
frmAbout.Close();
}
else
{
Close();
}
}
private void toolBtnHelp_Click(object sender, EventArgs e)
{
MessageBox.Show(StaticData.HELP_STRING, "UO:KR Uop Dumper", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
#endregion
#region Selected Data
private enum ShowPanels : int
{
RootNode = 0,
DataNode,
SingleHeader,
MultiHeader,
// --------
Nothing
}
private void tvFileData_AfterSelect(object sender, TreeViewEventArgs e)
{
this.lbIndexList.SuspendLayout();
this.lbIndexList.SelectedIndexChanged -= lbIndexList_SelectedIndexChanged;
this.lbIndexList.Items.Clear();
if ((e.Node != null) && (e.Node.Parent != null))
{
UOPFile uopToParse = UopManager.getIstance().UopFile;
for (int iLabel = 0; iLabel < uopToParse.m_Content[(int)e.Node.Tag].m_ListData.Count; iLabel++)
{
this.lbIndexList.Items.Add(String.Format("Index {0}", iLabel));
}
SetPanel(ShowPanels.DataNode, UopManager.getIstance().UopFile.m_Content[(int)e.Node.Tag]);
}
else if ((e.Node != null) && (e.Node.Parent == null))
{
SetPanel(ShowPanels.RootNode, UopManager.getIstance().UopFile);
}
this.lbIndexList.SelectedItem = null;
this.lbIndexList.SelectedIndexChanged += new EventHandler(lbIndexList_SelectedIndexChanged);
this.lbIndexList.ResumeLayout(true);
}
private void lbIndexList_SelectedIndexChanged(object sender, EventArgs e)
{
if ((this.tvFileData.SelectedNode == null) || (this.tvFileData.SelectedNode.Parent == null))
return;
ListBox lbSender = (ListBox)sender;
switch (lbSender.SelectedIndices.Count)
{
case 1:
{
SetPanel(ShowPanels.SingleHeader,
UopManager.getIstance().UopFile.m_Content[(int)(this.tvFileData.SelectedNode.Tag)].m_ListData[lbSender.SelectedIndex]
);
} break;
case 0:
default:
{
SetPanel(ShowPanels.Nothing, null);
} break;
}
}
private void SetPanel(ShowPanels panelType, object dataObject)
{
this.gbSelectedData.SuspendLayout();
this.SetModifyButtons(true);
this.btnDetailsUnpack.Enabled = true;
// -----------------
this.pnUopfile.Visible = this.pnUopfile.Enabled = false;
this.pnUopDatafile.Visible = this.pnUopDatafile.Enabled = false;
this.pnUopHeaderAndData.Visible = this.pnUopHeaderAndData.Enabled = false;
// -----------------
this.gbSelectedData.Tag = dataObject;
switch (panelType)
{
case ShowPanels.RootNode:
{
UOPFile uppeCurrent = (UOPFile) this.gbSelectedData.Tag;
this.txt_pnlUopFile_Header1.Text = Utility.ByteArrayToString(uppeCurrent.m_Header.m_variousData, Utility.HashStringStyle.HexWithSeparator);
this.num_pnlUopFile_Files.Value = uppeCurrent.m_Header.m_totalIndex;
this.txt_pnlUopFile_Header2.Text = Utility.ByteArrayToString(uppeCurrent.m_Header.m_Unknown, Utility.HashStringStyle.HexWithSeparator);
this.pnUopfile.Visible = true;
} break;
case ShowPanels.DataNode:
{
UOPIndexBlockHeader upCurrent = (UOPIndexBlockHeader)this.gbSelectedData.Tag;
this.txt_pnUopDatafile_Offset.Text = String.Format("{0:X}", upCurrent.m_OffsetNextIndex);
this.nud_pnUopDatafile_Files.Value = upCurrent.FilesDynamicCount;
this.pnUopDatafile.Visible = true;
} break;
case ShowPanels.SingleHeader:
{
UOPPairData upCurrent = (UOPPairData)this.gbSelectedData.Tag;
// Header block
this.txt_pnUopHeaderAndData_Offset.Text = String.Format("{0:X}", upCurrent.First.m_OffsetOfDataBlock);
this.txt_pnUopHeaderAndData_SizeHeader.Text = upCurrent.First.m_SizeofDataHeaders.ToString();
this.txt_pnUopHeaderAndData_Unk1.Text = String.Format("{0:X}", upCurrent.First.m_Unknown1);
this.txt_pnUopHeaderAndData_Unk2.Text = String.Format("{0:X}", upCurrent.First.m_Unknown2);
this.txt_pnUopHeaderAndData_Unk3.Text = String.Format("{0:X}", upCurrent.First.m_Unknown3);
this.chk_pnUopHeaderAndData_Compressed.Checked = upCurrent.First.IsCompressed;
// Data block
byte[] bData = new byte[10]; Array.Copy(upCurrent.Second.m_CompressedData, bData, Math.Min(10, upCurrent.Second.m_CompressedData.Length));
this.txt_pnUopHeaderAndData_Data.Text = Utility.ByteArrayToString(bData, Utility.HashStringStyle.HexWithSeparator) + " ...";
this.txt_pnUopHeaderAndData_DataFlags.Text = String.Format("{0:X}", upCurrent.Second.m_DataFlag);
this.txt_pnUopHeaderAndData_DataLocalOffset.Text = String.Format("{0:X}", upCurrent.Second.m_LocalOffsetToData);
this.txt_pnUopHeaderAndData_DataUnk1.Text = String.Format("{0:X}", upCurrent.Second.m_Unknown);
this.lbl_pnUopHeaderAndData_SizeC.Text = String.Format("Compressed: {0}", Utility.StringFileSize(upCurrent.First.m_LenghtCompressed));
this.lbl_pnUopHeaderAndData_SizeU.Text = String.Format("Uncompressed: {0}", Utility.StringFileSize(upCurrent.First.m_LenghtUncompressed));
this.pnUopHeaderAndData.Visible = true;
} break;
case ShowPanels.Nothing:
{
} break;
}
this.gbSelectedData.ResumeLayout(true);
}
#endregion
#region ToolStripMenu TreeView
private enum ToolStripMenuButtons : int
{
Delete = 0,
MoveUp,
MoveDown
}
private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
{
if ( sender != null )
{
TreeNode tnTemp = this.tvFileData.GetNodeAt(this.tvFileData.PointToClient(((ToolStripMenuItem)sender).Owner.Location));
if (tnTemp != null)
{
genericToolStripMenuItem(ToolStripMenuButtons.Delete, (int)tnTemp.Tag);
}
}
}
private void moveUpToolStripMenuItem_Click(object sender, EventArgs e)
{
if (sender != null)
{
TreeNode tnTemp = this.tvFileData.GetNodeAt(this.tvFileData.PointToClient(((ToolStripMenuItem)sender).Owner.Location));
if (tnTemp != null)
{
genericToolStripMenuItem(ToolStripMenuButtons.MoveUp, (int)tnTemp.Tag);
}
}
}
private void moveDownToolStripMenuItem_Click(object sender, EventArgs e)
{
if (sender != null)
{
TreeNode tnTemp = this.tvFileData.GetNodeAt(this.tvFileData.PointToClient(((ToolStripMenuItem)sender).Owner.Location));
if (tnTemp != null)
{
genericToolStripMenuItem(ToolStripMenuButtons.MoveDown, (int)tnTemp.Tag);
}
}
}
private void genericToolStripMenuItem(ToolStripMenuButtons tsmbClick, int iNode)
{
if (iNode == -1)
return;
UOPFile uopToParse = UopManager.getIstance().UopFile;
switch (tsmbClick)
{
case ToolStripMenuButtons.Delete:
{
uopToParse.m_Content.RemoveAt(iNode);
RefreshData();
SetTextArea("Deleted selected header block.");
} break;
case ToolStripMenuButtons.MoveUp:
{
if (iNode != 0)
{
UOPIndexBlockHeader uBack = uopToParse.m_Content[iNode - 1];
uopToParse.m_Content[iNode - 1] = uopToParse.m_Content[iNode];
uopToParse.m_Content[iNode] = uBack;
RefreshData();
SetTextArea("Moved Up selected header block.");
}
} break;
case ToolStripMenuButtons.MoveDown:
{
if (iNode != (uopToParse.m_Content.Count - 1))
{
UOPIndexBlockHeader uFront = uopToParse.m_Content[iNode + 1];
uopToParse.m_Content[iNode + 1] = uopToParse.m_Content[iNode];
uopToParse.m_Content[iNode] = uFront;
RefreshData();
SetTextArea("Moved Down selected header block.");
}
} break;
}
}
#endregion
#region StupidInterface Membri di
delegate void SetTextCallback(string text);
public void SetTextArea(string sText)
{
if (this.InvokeRequired)
{
SetTextCallback stDelegeate = new SetTextCallback(SetTextArea);
this.BeginInvoke(stDelegeate, new object[] { sText });
}
else
{
this.tslblStatus.Text = sText;
}
}
delegate void SetLoadIconCallback(bool bStatus);
public void SetLoadIcon(bool bStatus)
{
if (this.InvokeRequired)
{
SetLoadIconCallback stDelegeate = new SetLoadIconCallback(SetLoadIcon);
this.BeginInvoke(stDelegeate, new object[] { bStatus });
}
else
{
this.toolBtnOpen.Enabled = bStatus;
}
}
public void DisableOtherIcon(bool bEnable)
{
if (this.InvokeRequired)
{
SetLoadIconCallback stDelegeate = new SetLoadIconCallback(DisableOtherIcon);
this.BeginInvoke(stDelegeate, new object[] { bEnable });
}
else
{
this.SetDisableIcon(bEnable);
}
}
public void SetWaitStatus(bool bEnable)
{
if (this.InvokeRequired)
{
SetLoadIconCallback stDelegeate = new SetLoadIconCallback(SetWaitStatus);
this.BeginInvoke(stDelegeate, new object[] { bEnable });
}
else
{
if (bEnable)
{
this.SetCursor(Cursors.WaitCursor);
this.tslblWorking.Visible = true;
}
else
{
this.SetCursor(Cursors.Default);
this.tslblWorking.Visible = false;
}
}
}
delegate void SetNodesDelegate();
public void SetNodes()
{
if (this.InvokeRequired)
{
SetNodesDelegate stDelegeate = new SetNodesDelegate(SetNodes);
this.BeginInvoke(stDelegeate, null);
}
else
{
this.Parse();
}
}
delegate void SetCursorDelegate(Cursor cCursore);
public void SetCursor(Cursor cCursore)
{
if (this.InvokeRequired)
{
SetCursorDelegate stDelegeate = new SetCursorDelegate(SetCursor);
this.BeginInvoke(stDelegeate, new object[] { cCursore });
}
else
{
this.Cursor = cCursore;
}
}
#endregion
}
}
| |
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 Northwind{
/// <summary>
/// Strongly-typed collection for the SummaryOfSalesByQuarter class.
/// </summary>
[Serializable]
public partial class SummaryOfSalesByQuarterCollection : ReadOnlyList<SummaryOfSalesByQuarter, SummaryOfSalesByQuarterCollection>
{
public SummaryOfSalesByQuarterCollection() {}
}
/// <summary>
/// This is Read-only wrapper class for the Summary of Sales by Quarter view.
/// </summary>
[Serializable]
public partial class SummaryOfSalesByQuarter : ReadOnlyRecord<SummaryOfSalesByQuarter>, IReadOnlyRecord
{
#region Default Settings
protected static void SetSQLProps()
{
GetTableSchema();
}
#endregion
#region Schema Accessor
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("Summary of Sales by Quarter", TableType.View, DataService.GetInstance("Northwind"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarShippedDate = new TableSchema.TableColumn(schema);
colvarShippedDate.ColumnName = "ShippedDate";
colvarShippedDate.DataType = DbType.DateTime;
colvarShippedDate.MaxLength = 0;
colvarShippedDate.AutoIncrement = false;
colvarShippedDate.IsNullable = true;
colvarShippedDate.IsPrimaryKey = false;
colvarShippedDate.IsForeignKey = false;
colvarShippedDate.IsReadOnly = false;
schema.Columns.Add(colvarShippedDate);
TableSchema.TableColumn colvarOrderID = new TableSchema.TableColumn(schema);
colvarOrderID.ColumnName = "OrderID";
colvarOrderID.DataType = DbType.Int32;
colvarOrderID.MaxLength = 0;
colvarOrderID.AutoIncrement = false;
colvarOrderID.IsNullable = false;
colvarOrderID.IsPrimaryKey = false;
colvarOrderID.IsForeignKey = false;
colvarOrderID.IsReadOnly = false;
schema.Columns.Add(colvarOrderID);
TableSchema.TableColumn colvarSubtotal = new TableSchema.TableColumn(schema);
colvarSubtotal.ColumnName = "Subtotal";
colvarSubtotal.DataType = DbType.Currency;
colvarSubtotal.MaxLength = 0;
colvarSubtotal.AutoIncrement = false;
colvarSubtotal.IsNullable = true;
colvarSubtotal.IsPrimaryKey = false;
colvarSubtotal.IsForeignKey = false;
colvarSubtotal.IsReadOnly = false;
schema.Columns.Add(colvarSubtotal);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["Northwind"].AddSchema("Summary of Sales by Quarter",schema);
}
}
#endregion
#region Query Accessor
public static Query CreateQuery()
{
return new Query(Schema);
}
#endregion
#region .ctors
public SummaryOfSalesByQuarter()
{
SetSQLProps();
SetDefaults();
MarkNew();
}
public SummaryOfSalesByQuarter(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
{
ForceDefaults();
}
MarkNew();
}
public SummaryOfSalesByQuarter(object keyID)
{
SetSQLProps();
LoadByKey(keyID);
}
public SummaryOfSalesByQuarter(string columnName, object columnValue)
{
SetSQLProps();
LoadByParam(columnName,columnValue);
}
#endregion
#region Props
[XmlAttribute("ShippedDate")]
[Bindable(true)]
public DateTime? ShippedDate
{
get
{
return GetColumnValue<DateTime?>("ShippedDate");
}
set
{
SetColumnValue("ShippedDate", value);
}
}
[XmlAttribute("OrderID")]
[Bindable(true)]
public int OrderID
{
get
{
return GetColumnValue<int>("OrderID");
}
set
{
SetColumnValue("OrderID", value);
}
}
[XmlAttribute("Subtotal")]
[Bindable(true)]
public decimal? Subtotal
{
get
{
return GetColumnValue<decimal?>("Subtotal");
}
set
{
SetColumnValue("Subtotal", value);
}
}
#endregion
#region Columns Struct
public struct Columns
{
public static string ShippedDate = @"ShippedDate";
public static string OrderID = @"OrderID";
public static string Subtotal = @"Subtotal";
}
#endregion
#region IAbstractRecord Members
public new CT GetColumnValue<CT>(string columnName) {
return base.GetColumnValue<CT>(columnName);
}
public object GetColumnValue(string columnName) {
return base.GetColumnValue<object>(columnName);
}
#endregion
}
}
| |
namespace DataDictionaryCreator
{
partial class Main
{
/// <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(Main));
DataDictionaryCreator.Properties.Settings settings1 = new DataDictionaryCreator.Properties.Settings();
DataDictionaryCreator.Properties.Settings settings2 = new DataDictionaryCreator.Properties.Settings();
DataDictionaryCreator.Properties.Settings settings3 = new DataDictionaryCreator.Properties.Settings();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle();
this.saveFileDialogExport = new System.Windows.Forms.SaveFileDialog();
this.toolTip = new System.Windows.Forms.ToolTip(this.components);
this.btnExport = new System.Windows.Forms.Button();
this.txtForeignKeyDescription = new System.Windows.Forms.TextBox();
this.txtPrimaryKeyDescription = new System.Windows.Forms.TextBox();
this.chkOverwriteDescriptions = new System.Windows.Forms.CheckBox();
this.txtAdditionalProperties = new System.Windows.Forms.TextBox();
this.txtConnectionString = new System.Windows.Forms.TextBox();
this.statusStrip = new System.Windows.Forms.StatusStrip();
this.toolStripStatusLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripProgressBar = new System.Windows.Forms.ToolStripProgressBar();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.connectToDatabaseToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.setAdditionalPropertiesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.additionalPropertiesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.autoFillKeysToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.documentDatabaseToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.tablesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.viewsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.exportDocumentationToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.importDocumentationToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.updateAvailableToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.btnNext = new System.Windows.Forms.Button();
this.btnBack = new System.Windows.Forms.Button();
this.lnkException = new System.Windows.Forms.LinkLabel();
this.btnExit = new System.Windows.Forms.Button();
this.tabPageDocumentDatabase = new System.Windows.Forms.TabPage();
this.label17 = new System.Windows.Forms.Label();
this.tabContainerObjects = new System.Windows.Forms.TabControl();
this.tabPageTables = new System.Windows.Forms.TabPage();
this.chkExcludedTable = new System.Windows.Forms.CheckBox();
this.panel1 = new System.Windows.Forms.Panel();
this.dgvColumns = new System.Windows.Forms.DataGridView();
this.label5 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.txtTableDescription = new System.Windows.Forms.TextBox();
this.ddlTables = new System.Windows.Forms.ComboBox();
this.tabPageViews = new System.Windows.Forms.TabPage();
this.label18 = new System.Windows.Forms.Label();
this.label19 = new System.Windows.Forms.Label();
this.txtViewDescription = new System.Windows.Forms.TextBox();
this.ddlViews = new System.Windows.Forms.ComboBox();
this.tabPageImportDocumentation = new System.Windows.Forms.TabPage();
this.label13 = new System.Windows.Forms.Label();
this.label12 = new System.Windows.Forms.Label();
this.lblImport = new System.Windows.Forms.Label();
this.btnImport = new System.Windows.Forms.Button();
this.tabPageExportDocumentation = new System.Windows.Forms.TabPage();
this.label16 = new System.Windows.Forms.Label();
this.label15 = new System.Windows.Forms.Label();
this.label14 = new System.Windows.Forms.Label();
this.chkOpenFile = new System.Windows.Forms.CheckBox();
this.lblExportInfo = new System.Windows.Forms.Label();
this.tabPageAdvancedSettings = new System.Windows.Forms.TabPage();
this.label10 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.label9 = new System.Windows.Forms.Label();
this.label8 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.btnSetKeyDescriptions = new System.Windows.Forms.Button();
this.lblAutoFill = new System.Windows.Forms.Label();
this.tabPageConnect = new System.Windows.Forms.TabPage();
this.lblConnectionSuccess = new System.Windows.Forms.Label();
this.btnDocumentDatabase = new System.Windows.Forms.Button();
this.btnAdvancedSettings = new System.Windows.Forms.Button();
this.btnConnect = new System.Windows.Forms.Button();
this.label11 = new System.Windows.Forms.Label();
this.btnSetConnectionString = new System.Windows.Forms.Button();
this.lblConnectDatabaseInstructions = new System.Windows.Forms.Label();
this.tabContainerMain = new System.Windows.Forms.TabControl();
this.openFileDialogImport = new System.Windows.Forms.OpenFileDialog();
this.openFileDialogImportSample = new System.Windows.Forms.OpenFileDialog();
this.bgwUpdater = new System.ComponentModel.BackgroundWorker();
this.statusStrip.SuspendLayout();
this.menuStrip1.SuspendLayout();
this.tabPageDocumentDatabase.SuspendLayout();
this.tabContainerObjects.SuspendLayout();
this.tabPageTables.SuspendLayout();
this.panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dgvColumns)).BeginInit();
this.tabPageViews.SuspendLayout();
this.tabPageImportDocumentation.SuspendLayout();
this.tabPageExportDocumentation.SuspendLayout();
this.tabPageAdvancedSettings.SuspendLayout();
this.tabPageConnect.SuspendLayout();
this.tabContainerMain.SuspendLayout();
this.SuspendLayout();
//
// saveFileDialogExport
//
resources.ApplyResources(this.saveFileDialogExport, "saveFileDialogExport");
//
// btnExport
//
resources.ApplyResources(this.btnExport, "btnExport");
this.btnExport.Name = "btnExport";
this.toolTip.SetToolTip(this.btnExport, resources.GetString("btnExport.ToolTip"));
this.btnExport.UseVisualStyleBackColor = true;
this.btnExport.Click += new System.EventHandler(this.btnExport_Click);
//
// txtForeignKeyDescription
//
settings1.ADDITIONAL_PROPERTIES = "";
settings1.ALLOW_OVERWRITE = true;
settings1.ExcludedObjects = null;
settings1.FOREIGN_KEY_DESCRIPTION = "Link to {0} table";
settings1.PRIMARY_KEY_DESCRIPTION = "Primary key";
settings1.SettingsKey = "";
settings1.SQL_CONNECTION_STRING = "Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=Northwind;Dat" +
"a Source=(local)";
this.txtForeignKeyDescription.DataBindings.Add(new System.Windows.Forms.Binding("Text", settings1, "FOREIGN_KEY_DESCRIPTION", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
resources.ApplyResources(this.txtForeignKeyDescription, "txtForeignKeyDescription");
this.txtForeignKeyDescription.Name = "txtForeignKeyDescription";
this.txtForeignKeyDescription.Text = settings1.FOREIGN_KEY_DESCRIPTION;
this.toolTip.SetToolTip(this.txtForeignKeyDescription, resources.GetString("txtForeignKeyDescription.ToolTip"));
this.txtForeignKeyDescription.Leave += new System.EventHandler(this.txtForeignKeyDescription_Leave);
//
// txtPrimaryKeyDescription
//
settings2.ADDITIONAL_PROPERTIES = "";
settings2.ALLOW_OVERWRITE = true;
settings2.ExcludedObjects = null;
settings2.FOREIGN_KEY_DESCRIPTION = "Link to {0} table";
settings2.PRIMARY_KEY_DESCRIPTION = "Primary key";
settings2.SettingsKey = "";
settings2.SQL_CONNECTION_STRING = "Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=Northwind;Dat" +
"a Source=(local)";
this.txtPrimaryKeyDescription.DataBindings.Add(new System.Windows.Forms.Binding("Text", settings2, "PRIMARY_KEY_DESCRIPTION", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
resources.ApplyResources(this.txtPrimaryKeyDescription, "txtPrimaryKeyDescription");
this.txtPrimaryKeyDescription.Name = "txtPrimaryKeyDescription";
this.txtPrimaryKeyDescription.Text = settings2.PRIMARY_KEY_DESCRIPTION;
this.toolTip.SetToolTip(this.txtPrimaryKeyDescription, resources.GetString("txtPrimaryKeyDescription.ToolTip"));
this.txtPrimaryKeyDescription.Leave += new System.EventHandler(this.txtPrimaryKeyDescription_Leave);
//
// chkOverwriteDescriptions
//
resources.ApplyResources(this.chkOverwriteDescriptions, "chkOverwriteDescriptions");
this.chkOverwriteDescriptions.BackColor = System.Drawing.Color.Transparent;
settings3.ADDITIONAL_PROPERTIES = "";
settings3.ALLOW_OVERWRITE = true;
settings3.ExcludedObjects = null;
settings3.FOREIGN_KEY_DESCRIPTION = "Link to {0} table";
settings3.PRIMARY_KEY_DESCRIPTION = "Primary key";
settings3.SettingsKey = "";
settings3.SQL_CONNECTION_STRING = "Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=Northwind;Dat" +
"a Source=(local)";
this.chkOverwriteDescriptions.Checked = settings3.ALLOW_OVERWRITE;
this.chkOverwriteDescriptions.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkOverwriteDescriptions.DataBindings.Add(new System.Windows.Forms.Binding("Checked", settings3, "ALLOW_OVERWRITE", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
this.chkOverwriteDescriptions.Name = "chkOverwriteDescriptions";
this.toolTip.SetToolTip(this.chkOverwriteDescriptions, resources.GetString("chkOverwriteDescriptions.ToolTip"));
this.chkOverwriteDescriptions.UseVisualStyleBackColor = false;
this.chkOverwriteDescriptions.CheckStateChanged += new System.EventHandler(this.chkOverwriteDescriptions_CheckStateChanged);
//
// txtAdditionalProperties
//
resources.ApplyResources(this.txtAdditionalProperties, "txtAdditionalProperties");
this.txtAdditionalProperties.Name = "txtAdditionalProperties";
this.toolTip.SetToolTip(this.txtAdditionalProperties, resources.GetString("txtAdditionalProperties.ToolTip"));
this.txtAdditionalProperties.Leave += new System.EventHandler(this.txtAdditionalProperties_Leave);
//
// txtConnectionString
//
this.txtConnectionString.BackColor = System.Drawing.Color.White;
this.txtConnectionString.DataBindings.Add(new System.Windows.Forms.Binding("Text", global::DataDictionaryCreator.Properties.Settings.Default, "SQL_CONNECTION_STRING", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
resources.ApplyResources(this.txtConnectionString, "txtConnectionString");
this.txtConnectionString.Name = "txtConnectionString";
this.txtConnectionString.Text = global::DataDictionaryCreator.Properties.Settings.Default.SQL_CONNECTION_STRING;
this.toolTip.SetToolTip(this.txtConnectionString, resources.GetString("txtConnectionString.ToolTip"));
this.txtConnectionString.TextChanged += new System.EventHandler(this.txtConnectionString_TextChanged);
this.txtConnectionString.DoubleClick += new System.EventHandler(this.txtConnectionString_DoubleClick);
this.txtConnectionString.Leave += new System.EventHandler(this.txtConnectionString_Leave);
//
// statusStrip
//
this.statusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripStatusLabel,
this.toolStripProgressBar});
resources.ApplyResources(this.statusStrip, "statusStrip");
this.statusStrip.Name = "statusStrip";
this.statusStrip.RenderMode = System.Windows.Forms.ToolStripRenderMode.Professional;
//
// toolStripStatusLabel
//
this.toolStripStatusLabel.Name = "toolStripStatusLabel";
resources.ApplyResources(this.toolStripStatusLabel, "toolStripStatusLabel");
this.toolStripStatusLabel.Spring = true;
//
// toolStripProgressBar
//
this.toolStripProgressBar.Name = "toolStripProgressBar";
resources.ApplyResources(this.toolStripProgressBar, "toolStripProgressBar");
this.toolStripProgressBar.Style = System.Windows.Forms.ProgressBarStyle.Continuous;
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.helpToolStripMenuItem,
this.updateAvailableToolStripMenuItem});
resources.ApplyResources(this.menuStrip1, "menuStrip1");
this.menuStrip1.Name = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.connectToDatabaseToolStripMenuItem,
this.setAdditionalPropertiesToolStripMenuItem,
this.documentDatabaseToolStripMenuItem,
this.exportDocumentationToolStripMenuItem,
this.importDocumentationToolStripMenuItem,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
resources.ApplyResources(this.fileToolStripMenuItem, "fileToolStripMenuItem");
//
// connectToDatabaseToolStripMenuItem
//
this.connectToDatabaseToolStripMenuItem.Name = "connectToDatabaseToolStripMenuItem";
resources.ApplyResources(this.connectToDatabaseToolStripMenuItem, "connectToDatabaseToolStripMenuItem");
this.connectToDatabaseToolStripMenuItem.Click += new System.EventHandler(this.connectToDatabaseToolStripMenuItem_Click);
//
// setAdditionalPropertiesToolStripMenuItem
//
this.setAdditionalPropertiesToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.additionalPropertiesToolStripMenuItem,
this.autoFillKeysToolStripMenuItem});
this.setAdditionalPropertiesToolStripMenuItem.Name = "setAdditionalPropertiesToolStripMenuItem";
resources.ApplyResources(this.setAdditionalPropertiesToolStripMenuItem, "setAdditionalPropertiesToolStripMenuItem");
this.setAdditionalPropertiesToolStripMenuItem.Click += new System.EventHandler(this.setAdditionalPropertiesToolStripMenuItem_Click);
//
// additionalPropertiesToolStripMenuItem
//
this.additionalPropertiesToolStripMenuItem.Name = "additionalPropertiesToolStripMenuItem";
resources.ApplyResources(this.additionalPropertiesToolStripMenuItem, "additionalPropertiesToolStripMenuItem");
this.additionalPropertiesToolStripMenuItem.Click += new System.EventHandler(this.additionalPropertiesToolStripMenuItem_Click);
//
// autoFillKeysToolStripMenuItem
//
this.autoFillKeysToolStripMenuItem.Name = "autoFillKeysToolStripMenuItem";
resources.ApplyResources(this.autoFillKeysToolStripMenuItem, "autoFillKeysToolStripMenuItem");
this.autoFillKeysToolStripMenuItem.Click += new System.EventHandler(this.autoFillKeysToolStripMenuItem_Click);
//
// documentDatabaseToolStripMenuItem
//
this.documentDatabaseToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tablesToolStripMenuItem,
this.viewsToolStripMenuItem});
this.documentDatabaseToolStripMenuItem.Name = "documentDatabaseToolStripMenuItem";
resources.ApplyResources(this.documentDatabaseToolStripMenuItem, "documentDatabaseToolStripMenuItem");
this.documentDatabaseToolStripMenuItem.Click += new System.EventHandler(this.documentDatabaseToolStripMenuItem_Click);
//
// tablesToolStripMenuItem
//
this.tablesToolStripMenuItem.Name = "tablesToolStripMenuItem";
resources.ApplyResources(this.tablesToolStripMenuItem, "tablesToolStripMenuItem");
this.tablesToolStripMenuItem.Click += new System.EventHandler(this.tablesToolStripMenuItem_Click);
//
// viewsToolStripMenuItem
//
this.viewsToolStripMenuItem.Name = "viewsToolStripMenuItem";
resources.ApplyResources(this.viewsToolStripMenuItem, "viewsToolStripMenuItem");
this.viewsToolStripMenuItem.Click += new System.EventHandler(this.viewsToolStripMenuItem_Click);
//
// exportDocumentationToolStripMenuItem
//
this.exportDocumentationToolStripMenuItem.Name = "exportDocumentationToolStripMenuItem";
resources.ApplyResources(this.exportDocumentationToolStripMenuItem, "exportDocumentationToolStripMenuItem");
this.exportDocumentationToolStripMenuItem.Click += new System.EventHandler(this.exportDocumentationToolStripMenuItem_Click);
//
// importDocumentationToolStripMenuItem
//
this.importDocumentationToolStripMenuItem.Name = "importDocumentationToolStripMenuItem";
resources.ApplyResources(this.importDocumentationToolStripMenuItem, "importDocumentationToolStripMenuItem");
this.importDocumentationToolStripMenuItem.Click += new System.EventHandler(this.importDocumentationToolStripMenuItem_Click);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
resources.ApplyResources(this.exitToolStripMenuItem, "exitToolStripMenuItem");
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.aboutToolStripMenuItem});
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
resources.ApplyResources(this.helpToolStripMenuItem, "helpToolStripMenuItem");
//
// aboutToolStripMenuItem
//
this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
resources.ApplyResources(this.aboutToolStripMenuItem, "aboutToolStripMenuItem");
this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click);
//
// updateAvailableToolStripMenuItem
//
this.updateAvailableToolStripMenuItem.Name = "updateAvailableToolStripMenuItem";
resources.ApplyResources(this.updateAvailableToolStripMenuItem, "updateAvailableToolStripMenuItem");
this.updateAvailableToolStripMenuItem.Click += new System.EventHandler(this.updateAvailableToolStripMenuItem_Click);
//
// btnNext
//
resources.ApplyResources(this.btnNext, "btnNext");
this.btnNext.Name = "btnNext";
this.btnNext.UseVisualStyleBackColor = true;
this.btnNext.Click += new System.EventHandler(this.btnNext_Click);
//
// btnBack
//
resources.ApplyResources(this.btnBack, "btnBack");
this.btnBack.Name = "btnBack";
this.btnBack.UseVisualStyleBackColor = true;
this.btnBack.Click += new System.EventHandler(this.btnBack_Click);
//
// lnkException
//
resources.ApplyResources(this.lnkException, "lnkException");
this.lnkException.Name = "lnkException";
this.lnkException.TabStop = true;
this.lnkException.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkException_LinkClicked);
//
// btnExit
//
resources.ApplyResources(this.btnExit, "btnExit");
this.btnExit.Name = "btnExit";
this.btnExit.UseVisualStyleBackColor = true;
this.btnExit.Click += new System.EventHandler(this.btnExit_Click);
//
// tabPageDocumentDatabase
//
this.tabPageDocumentDatabase.Controls.Add(this.label17);
this.tabPageDocumentDatabase.Controls.Add(this.tabContainerObjects);
resources.ApplyResources(this.tabPageDocumentDatabase, "tabPageDocumentDatabase");
this.tabPageDocumentDatabase.Name = "tabPageDocumentDatabase";
this.tabPageDocumentDatabase.UseVisualStyleBackColor = true;
//
// label17
//
resources.ApplyResources(this.label17, "label17");
this.label17.BackColor = System.Drawing.Color.Transparent;
this.label17.ForeColor = System.Drawing.SystemColors.ActiveCaption;
this.label17.Name = "label17";
//
// tabContainerObjects
//
resources.ApplyResources(this.tabContainerObjects, "tabContainerObjects");
this.tabContainerObjects.Controls.Add(this.tabPageTables);
this.tabContainerObjects.Controls.Add(this.tabPageViews);
this.tabContainerObjects.Name = "tabContainerObjects";
this.tabContainerObjects.SelectedIndex = 0;
//
// tabPageTables
//
this.tabPageTables.Controls.Add(this.chkExcludedTable);
this.tabPageTables.Controls.Add(this.panel1);
this.tabPageTables.Controls.Add(this.label5);
this.tabPageTables.Controls.Add(this.label4);
this.tabPageTables.Controls.Add(this.txtTableDescription);
this.tabPageTables.Controls.Add(this.ddlTables);
resources.ApplyResources(this.tabPageTables, "tabPageTables");
this.tabPageTables.Name = "tabPageTables";
this.tabPageTables.UseVisualStyleBackColor = true;
//
// chkExcludedTable
//
resources.ApplyResources(this.chkExcludedTable, "chkExcludedTable");
this.chkExcludedTable.Name = "chkExcludedTable";
this.chkExcludedTable.UseVisualStyleBackColor = true;
this.chkExcludedTable.Click += new System.EventHandler(this.chkExcludedTable_Click);
//
// panel1
//
resources.ApplyResources(this.panel1, "panel1");
this.panel1.Controls.Add(this.dgvColumns);
this.panel1.Name = "panel1";
//
// dgvColumns
//
this.dgvColumns.AllowUserToAddRows = false;
this.dgvColumns.AllowUserToDeleteRows = false;
this.dgvColumns.AllowUserToOrderColumns = true;
this.dgvColumns.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
this.dgvColumns.BackgroundColor = System.Drawing.Color.GhostWhite;
this.dgvColumns.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.Sunken;
this.dgvColumns.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.Single;
dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle1.BackColor = System.Drawing.Color.White;
dataGridViewCellStyle1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText;
dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Highlight;
dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.dgvColumns.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1;
this.dgvColumns.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle2.BackColor = System.Drawing.Color.White;
dataGridViewCellStyle2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
dataGridViewCellStyle2.ForeColor = System.Drawing.SystemColors.ControlText;
dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight;
dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
this.dgvColumns.DefaultCellStyle = dataGridViewCellStyle2;
resources.ApplyResources(this.dgvColumns, "dgvColumns");
this.dgvColumns.EditMode = System.Windows.Forms.DataGridViewEditMode.EditOnEnter;
this.dgvColumns.GridColor = System.Drawing.Color.GhostWhite;
this.dgvColumns.Name = "dgvColumns";
dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle3.BackColor = System.Drawing.Color.White;
dataGridViewCellStyle3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
dataGridViewCellStyle3.ForeColor = System.Drawing.SystemColors.WindowText;
dataGridViewCellStyle3.SelectionBackColor = System.Drawing.SystemColors.Highlight;
dataGridViewCellStyle3.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.dgvColumns.RowHeadersDefaultCellStyle = dataGridViewCellStyle3;
this.dgvColumns.RowTemplate.DefaultCellStyle.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.dgvColumns.RowTemplate.Height = 44;
this.dgvColumns.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.dgvColumns_CellValueChanged);
//
// label5
//
resources.ApplyResources(this.label5, "label5");
this.label5.Name = "label5";
//
// label4
//
resources.ApplyResources(this.label4, "label4");
this.label4.Name = "label4";
//
// txtTableDescription
//
resources.ApplyResources(this.txtTableDescription, "txtTableDescription");
this.txtTableDescription.Name = "txtTableDescription";
this.txtTableDescription.Leave += new System.EventHandler(this.txtTableDescription_Leave);
//
// ddlTables
//
this.ddlTables.FormattingEnabled = true;
resources.ApplyResources(this.ddlTables, "ddlTables");
this.ddlTables.Name = "ddlTables";
this.ddlTables.SelectedIndexChanged += new System.EventHandler(this.ddlTables_SelectedIndexChanged);
//
// tabPageViews
//
this.tabPageViews.Controls.Add(this.label18);
this.tabPageViews.Controls.Add(this.label19);
this.tabPageViews.Controls.Add(this.txtViewDescription);
this.tabPageViews.Controls.Add(this.ddlViews);
resources.ApplyResources(this.tabPageViews, "tabPageViews");
this.tabPageViews.Name = "tabPageViews";
this.tabPageViews.UseVisualStyleBackColor = true;
//
// label18
//
resources.ApplyResources(this.label18, "label18");
this.label18.Name = "label18";
//
// label19
//
resources.ApplyResources(this.label19, "label19");
this.label19.Name = "label19";
//
// txtViewDescription
//
resources.ApplyResources(this.txtViewDescription, "txtViewDescription");
this.txtViewDescription.Name = "txtViewDescription";
//
// ddlViews
//
this.ddlViews.FormattingEnabled = true;
resources.ApplyResources(this.ddlViews, "ddlViews");
this.ddlViews.Name = "ddlViews";
//
// tabPageImportDocumentation
//
this.tabPageImportDocumentation.BackColor = System.Drawing.Color.WhiteSmoke;
this.tabPageImportDocumentation.Controls.Add(this.label13);
this.tabPageImportDocumentation.Controls.Add(this.label12);
this.tabPageImportDocumentation.Controls.Add(this.lblImport);
this.tabPageImportDocumentation.Controls.Add(this.btnImport);
resources.ApplyResources(this.tabPageImportDocumentation, "tabPageImportDocumentation");
this.tabPageImportDocumentation.Name = "tabPageImportDocumentation";
this.tabPageImportDocumentation.UseVisualStyleBackColor = true;
//
// label13
//
resources.ApplyResources(this.label13, "label13");
this.label13.BackColor = System.Drawing.Color.Transparent;
this.label13.Name = "label13";
//
// label12
//
resources.ApplyResources(this.label12, "label12");
this.label12.BackColor = System.Drawing.Color.Transparent;
this.label12.ForeColor = System.Drawing.SystemColors.ActiveCaption;
this.label12.Name = "label12";
//
// lblImport
//
resources.ApplyResources(this.lblImport, "lblImport");
this.lblImport.BackColor = System.Drawing.Color.Transparent;
this.lblImport.Name = "lblImport";
//
// btnImport
//
resources.ApplyResources(this.btnImport, "btnImport");
this.btnImport.Name = "btnImport";
this.btnImport.UseVisualStyleBackColor = true;
this.btnImport.Click += new System.EventHandler(this.btnImport_Click);
//
// tabPageExportDocumentation
//
this.tabPageExportDocumentation.BackColor = System.Drawing.Color.WhiteSmoke;
this.tabPageExportDocumentation.Controls.Add(this.label16);
this.tabPageExportDocumentation.Controls.Add(this.label15);
this.tabPageExportDocumentation.Controls.Add(this.label14);
this.tabPageExportDocumentation.Controls.Add(this.chkOpenFile);
this.tabPageExportDocumentation.Controls.Add(this.lblExportInfo);
this.tabPageExportDocumentation.Controls.Add(this.btnExport);
resources.ApplyResources(this.tabPageExportDocumentation, "tabPageExportDocumentation");
this.tabPageExportDocumentation.Name = "tabPageExportDocumentation";
this.tabPageExportDocumentation.UseVisualStyleBackColor = true;
//
// label16
//
resources.ApplyResources(this.label16, "label16");
this.label16.BackColor = System.Drawing.Color.Transparent;
this.label16.ForeColor = System.Drawing.SystemColors.ActiveCaption;
this.label16.Name = "label16";
//
// label15
//
resources.ApplyResources(this.label15, "label15");
this.label15.BackColor = System.Drawing.Color.Transparent;
this.label15.Name = "label15";
//
// label14
//
resources.ApplyResources(this.label14, "label14");
this.label14.BackColor = System.Drawing.Color.Transparent;
this.label14.Name = "label14";
//
// chkOpenFile
//
resources.ApplyResources(this.chkOpenFile, "chkOpenFile");
this.chkOpenFile.BackColor = System.Drawing.Color.Transparent;
this.chkOpenFile.Checked = true;
this.chkOpenFile.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkOpenFile.Name = "chkOpenFile";
this.chkOpenFile.UseVisualStyleBackColor = false;
//
// lblExportInfo
//
resources.ApplyResources(this.lblExportInfo, "lblExportInfo");
this.lblExportInfo.BackColor = System.Drawing.Color.Transparent;
this.lblExportInfo.Name = "lblExportInfo";
//
// tabPageAdvancedSettings
//
this.tabPageAdvancedSettings.BackColor = System.Drawing.Color.WhiteSmoke;
this.tabPageAdvancedSettings.Controls.Add(this.label10);
this.tabPageAdvancedSettings.Controls.Add(this.label2);
this.tabPageAdvancedSettings.Controls.Add(this.label1);
this.tabPageAdvancedSettings.Controls.Add(this.label9);
this.tabPageAdvancedSettings.Controls.Add(this.label8);
this.tabPageAdvancedSettings.Controls.Add(this.label7);
this.tabPageAdvancedSettings.Controls.Add(this.label6);
this.tabPageAdvancedSettings.Controls.Add(this.label3);
this.tabPageAdvancedSettings.Controls.Add(this.txtAdditionalProperties);
this.tabPageAdvancedSettings.Controls.Add(this.txtPrimaryKeyDescription);
this.tabPageAdvancedSettings.Controls.Add(this.txtForeignKeyDescription);
this.tabPageAdvancedSettings.Controls.Add(this.btnSetKeyDescriptions);
this.tabPageAdvancedSettings.Controls.Add(this.chkOverwriteDescriptions);
this.tabPageAdvancedSettings.Controls.Add(this.lblAutoFill);
resources.ApplyResources(this.tabPageAdvancedSettings, "tabPageAdvancedSettings");
this.tabPageAdvancedSettings.Name = "tabPageAdvancedSettings";
this.tabPageAdvancedSettings.UseVisualStyleBackColor = true;
//
// label10
//
resources.ApplyResources(this.label10, "label10");
this.label10.BackColor = System.Drawing.Color.Transparent;
this.label10.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.label10.Name = "label10";
//
// label2
//
resources.ApplyResources(this.label2, "label2");
this.label2.BackColor = System.Drawing.Color.Transparent;
this.label2.Name = "label2";
//
// label1
//
resources.ApplyResources(this.label1, "label1");
this.label1.BackColor = System.Drawing.Color.Transparent;
this.label1.Name = "label1";
//
// label9
//
resources.ApplyResources(this.label9, "label9");
this.label9.BackColor = System.Drawing.Color.Transparent;
this.label9.ForeColor = System.Drawing.SystemColors.ActiveCaption;
this.label9.Name = "label9";
//
// label8
//
resources.ApplyResources(this.label8, "label8");
this.label8.BackColor = System.Drawing.Color.Transparent;
this.label8.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.label8.Name = "label8";
//
// label7
//
resources.ApplyResources(this.label7, "label7");
this.label7.BackColor = System.Drawing.Color.Transparent;
this.label7.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.label7.Name = "label7";
//
// label6
//
resources.ApplyResources(this.label6, "label6");
this.label6.BackColor = System.Drawing.Color.Transparent;
this.label6.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.label6.Name = "label6";
//
// label3
//
resources.ApplyResources(this.label3, "label3");
this.label3.BackColor = System.Drawing.Color.Transparent;
this.label3.ForeColor = System.Drawing.SystemColors.ActiveCaption;
this.label3.Name = "label3";
//
// btnSetKeyDescriptions
//
resources.ApplyResources(this.btnSetKeyDescriptions, "btnSetKeyDescriptions");
this.btnSetKeyDescriptions.Name = "btnSetKeyDescriptions";
this.btnSetKeyDescriptions.UseVisualStyleBackColor = true;
this.btnSetKeyDescriptions.Click += new System.EventHandler(this.btnSetKeyDescriptions_Click);
//
// lblAutoFill
//
resources.ApplyResources(this.lblAutoFill, "lblAutoFill");
this.lblAutoFill.BackColor = System.Drawing.Color.Transparent;
this.lblAutoFill.Name = "lblAutoFill";
//
// tabPageConnect
//
this.tabPageConnect.BackColor = System.Drawing.Color.WhiteSmoke;
this.tabPageConnect.Controls.Add(this.lblConnectionSuccess);
this.tabPageConnect.Controls.Add(this.btnDocumentDatabase);
this.tabPageConnect.Controls.Add(this.btnAdvancedSettings);
this.tabPageConnect.Controls.Add(this.btnConnect);
this.tabPageConnect.Controls.Add(this.label11);
this.tabPageConnect.Controls.Add(this.txtConnectionString);
this.tabPageConnect.Controls.Add(this.btnSetConnectionString);
this.tabPageConnect.Controls.Add(this.lblConnectDatabaseInstructions);
resources.ApplyResources(this.tabPageConnect, "tabPageConnect");
this.tabPageConnect.Name = "tabPageConnect";
this.tabPageConnect.UseVisualStyleBackColor = true;
//
// lblConnectionSuccess
//
this.lblConnectionSuccess.AutoEllipsis = true;
this.lblConnectionSuccess.BackColor = System.Drawing.Color.Transparent;
resources.ApplyResources(this.lblConnectionSuccess, "lblConnectionSuccess");
this.lblConnectionSuccess.Name = "lblConnectionSuccess";
//
// btnDocumentDatabase
//
resources.ApplyResources(this.btnDocumentDatabase, "btnDocumentDatabase");
this.btnDocumentDatabase.Name = "btnDocumentDatabase";
this.btnDocumentDatabase.UseVisualStyleBackColor = true;
this.btnDocumentDatabase.Click += new System.EventHandler(this.btnDocumentDatabase_Click);
//
// btnAdvancedSettings
//
resources.ApplyResources(this.btnAdvancedSettings, "btnAdvancedSettings");
this.btnAdvancedSettings.Name = "btnAdvancedSettings";
this.btnAdvancedSettings.UseVisualStyleBackColor = true;
this.btnAdvancedSettings.Click += new System.EventHandler(this.btnAdvancedSettings_Click);
//
// btnConnect
//
this.btnConnect.FlatAppearance.BorderSize = 0;
resources.ApplyResources(this.btnConnect, "btnConnect");
this.btnConnect.Name = "btnConnect";
this.btnConnect.UseVisualStyleBackColor = true;
this.btnConnect.Click += new System.EventHandler(this.btnConnect_Click);
//
// label11
//
resources.ApplyResources(this.label11, "label11");
this.label11.BackColor = System.Drawing.Color.Transparent;
this.label11.ForeColor = System.Drawing.SystemColors.ActiveCaption;
this.label11.Name = "label11";
//
// btnSetConnectionString
//
this.btnSetConnectionString.FlatAppearance.BorderSize = 0;
resources.ApplyResources(this.btnSetConnectionString, "btnSetConnectionString");
this.btnSetConnectionString.Name = "btnSetConnectionString";
this.btnSetConnectionString.UseVisualStyleBackColor = true;
this.btnSetConnectionString.Click += new System.EventHandler(this.btnSetConnectionString_Click);
//
// lblConnectDatabaseInstructions
//
this.lblConnectDatabaseInstructions.AutoEllipsis = true;
resources.ApplyResources(this.lblConnectDatabaseInstructions, "lblConnectDatabaseInstructions");
this.lblConnectDatabaseInstructions.BackColor = System.Drawing.Color.Transparent;
this.lblConnectDatabaseInstructions.Name = "lblConnectDatabaseInstructions";
//
// tabContainerMain
//
resources.ApplyResources(this.tabContainerMain, "tabContainerMain");
this.tabContainerMain.Controls.Add(this.tabPageConnect);
this.tabContainerMain.Controls.Add(this.tabPageAdvancedSettings);
this.tabContainerMain.Controls.Add(this.tabPageDocumentDatabase);
this.tabContainerMain.Controls.Add(this.tabPageExportDocumentation);
this.tabContainerMain.Controls.Add(this.tabPageImportDocumentation);
this.tabContainerMain.Name = "tabContainerMain";
this.tabContainerMain.SelectedIndex = 0;
this.tabContainerMain.SelectedIndexChanged += new System.EventHandler(this.tabContainerMain_SelectedIndexChanged);
//
// openFileDialogImport
//
resources.ApplyResources(this.openFileDialogImport, "openFileDialogImport");
//
// openFileDialogImportSample
//
this.openFileDialogImportSample.FileName = "ExcelSample.csv";
resources.ApplyResources(this.openFileDialogImportSample, "openFileDialogImportSample");
//
// bgwUpdater
//
this.bgwUpdater.DoWork += new System.ComponentModel.DoWorkEventHandler(this.bgwUpdater_DoWork);
this.bgwUpdater.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.bgwUpdater_RunWorkerCompleted);
//
// Main
//
this.AllowDrop = true;
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.LightGray;
this.Controls.Add(this.btnExit);
this.Controls.Add(this.lnkException);
this.Controls.Add(this.btnBack);
this.Controls.Add(this.statusStrip);
this.Controls.Add(this.menuStrip1);
this.Controls.Add(this.btnNext);
this.Controls.Add(this.tabContainerMain);
this.MainMenuStrip = this.menuStrip1;
this.Name = "Main";
this.Load += new System.EventHandler(this.MainForm_Load);
this.statusStrip.ResumeLayout(false);
this.statusStrip.PerformLayout();
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.tabPageDocumentDatabase.ResumeLayout(false);
this.tabPageDocumentDatabase.PerformLayout();
this.tabContainerObjects.ResumeLayout(false);
this.tabPageTables.ResumeLayout(false);
this.tabPageTables.PerformLayout();
this.panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dgvColumns)).EndInit();
this.tabPageViews.ResumeLayout(false);
this.tabPageViews.PerformLayout();
this.tabPageImportDocumentation.ResumeLayout(false);
this.tabPageImportDocumentation.PerformLayout();
this.tabPageExportDocumentation.ResumeLayout(false);
this.tabPageExportDocumentation.PerformLayout();
this.tabPageAdvancedSettings.ResumeLayout(false);
this.tabPageAdvancedSettings.PerformLayout();
this.tabPageConnect.ResumeLayout(false);
this.tabPageConnect.PerformLayout();
this.tabContainerMain.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.SaveFileDialog saveFileDialogExport;
private System.Windows.Forms.ToolTip toolTip;
private System.Windows.Forms.StatusStrip statusStrip;
private System.Windows.Forms.ToolStripProgressBar toolStripProgressBar;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel;
private System.Windows.Forms.OpenFileDialog openFileDialogImport;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem connectToDatabaseToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem importDocumentationToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem documentDatabaseToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem exportDocumentationToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem setAdditionalPropertiesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem additionalPropertiesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem autoFillKeysToolStripMenuItem;
private System.Windows.Forms.Button btnNext;
private System.Windows.Forms.Button btnBack;
private System.Windows.Forms.LinkLabel lnkException;
private System.Windows.Forms.OpenFileDialog openFileDialogImportSample;
private System.Windows.Forms.Button btnExit;
private System.Windows.Forms.TabPage tabPageDocumentDatabase;
private System.Windows.Forms.Label label17;
private System.Windows.Forms.TabControl tabContainerObjects;
private System.Windows.Forms.TabPage tabPageViews;
private System.Windows.Forms.TabPage tabPageImportDocumentation;
private System.Windows.Forms.Label label13;
private System.Windows.Forms.Label label12;
private System.Windows.Forms.Label lblImport;
private System.Windows.Forms.Button btnImport;
private System.Windows.Forms.TabPage tabPageExportDocumentation;
private System.Windows.Forms.Label label16;
private System.Windows.Forms.Label label15;
private System.Windows.Forms.Label label14;
private System.Windows.Forms.CheckBox chkOpenFile;
private System.Windows.Forms.Label lblExportInfo;
private System.Windows.Forms.Button btnExport;
private System.Windows.Forms.TabPage tabPageAdvancedSettings;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox txtAdditionalProperties;
private System.Windows.Forms.TextBox txtPrimaryKeyDescription;
private System.Windows.Forms.TextBox txtForeignKeyDescription;
private System.Windows.Forms.Button btnSetKeyDescriptions;
private System.Windows.Forms.CheckBox chkOverwriteDescriptions;
private System.Windows.Forms.Label lblAutoFill;
private System.Windows.Forms.TabPage tabPageConnect;
private System.Windows.Forms.Label lblConnectionSuccess;
private System.Windows.Forms.Button btnDocumentDatabase;
private System.Windows.Forms.Button btnAdvancedSettings;
private System.Windows.Forms.Button btnConnect;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.TextBox txtConnectionString;
private System.Windows.Forms.Button btnSetConnectionString;
private System.Windows.Forms.Label lblConnectDatabaseInstructions;
private System.Windows.Forms.TabControl tabContainerMain;
private System.Windows.Forms.ToolStripMenuItem tablesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem viewsToolStripMenuItem;
private System.Windows.Forms.TabPage tabPageTables;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.DataGridView dgvColumns;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox txtTableDescription;
private System.Windows.Forms.ComboBox ddlTables;
private System.Windows.Forms.Label label18;
private System.Windows.Forms.Label label19;
private System.Windows.Forms.TextBox txtViewDescription;
private System.Windows.Forms.ComboBox ddlViews;
private System.Windows.Forms.CheckBox chkExcludedTable;
private System.Windows.Forms.ToolStripMenuItem updateAvailableToolStripMenuItem;
private System.ComponentModel.BackgroundWorker bgwUpdater;
}
}
| |
//
// ABPerson.cs: Implements the managed ABPerson
//
// Authors: Mono Team
// Marek Safar (marek.safar@gmail.com)
//
// Copyright (C) 2009 Novell, Inc
// Copyright (C) 2012 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using MonoMac.CoreFoundation;
using MonoMac.Foundation;
using MonoMac.ObjCRuntime;
namespace MonoMac.AddressBook {
public enum ABPersonSortBy : uint {
FirstName = 0,
LastName = 1,
}
public enum ABPersonCompositeNameFormat : uint {
FirstNameFirst = 0,
LastNameFirst = 1,
}
public enum ABPersonProperty {
Address,
Birthday,
CreationDate,
Date,
Department,
Email,
FirstName,
FirstNamePhonetic,
InstantMessage,
JobTitle,
Kind,
LastName,
LastNamePhonetic,
MiddleName,
MiddleNamePhonetic,
ModificationDate,
Nickname,
Note,
Organization,
Phone,
Prefix,
RelatedNames,
Suffix,
Url,
SocialProfile
}
[Since (4,1)]
public enum ABPersonImageFormat {
Thumbnail = 0,
OriginalSize = 2
}
static class ABPersonPropertyId {
public static int Address {get; private set;}
public static int Birthday {get; private set;}
public static int CreationDate {get; private set;}
public static int Date {get; private set;}
public static int Department {get; private set;}
public static int Email {get; private set;}
public static int FirstName {get; private set;}
public static int FirstNamePhonetic {get; private set;}
public static int InstantMessage {get; private set;}
public static int JobTitle {get; private set;}
public static int Kind {get; private set;}
public static int LastName {get; private set;}
public static int LastNamePhonetic {get; private set;}
public static int MiddleName {get; private set;}
public static int MiddleNamePhonetic {get; private set;}
public static int ModificationDate {get; private set;}
public static int Nickname {get; private set;}
public static int Note {get; private set;}
public static int Organization {get; private set;}
public static int Phone {get; private set;}
public static int Prefix {get; private set;}
public static int RelatedNames {get; private set;}
public static int Suffix {get; private set;}
public static int Url {get; private set;}
public static int SocialProfile { get; private set; }
static ABPersonPropertyId ()
{
InitConstants.Init ();
}
internal static void Init ()
{
var handle = Dlfcn.dlopen (Constants.AddressBookLibrary, 0);
if (handle == IntPtr.Zero)
return;
try {
Address = Dlfcn.GetInt32 (handle, "kABPersonAddressProperty");
Birthday = Dlfcn.GetInt32 (handle, "kABPersonBirthdayProperty");
CreationDate = Dlfcn.GetInt32 (handle, "kABPersonCreationDateProperty");
Date = Dlfcn.GetInt32 (handle, "kABPersonDateProperty");
Department = Dlfcn.GetInt32 (handle, "kABPersonDepartmentProperty");
Email = Dlfcn.GetInt32 (handle, "kABPersonEmailProperty");
FirstName = Dlfcn.GetInt32 (handle, "kABPersonFirstNameProperty");
FirstNamePhonetic = Dlfcn.GetInt32 (handle, "kABPersonFirstNamePhoneticProperty");
InstantMessage = Dlfcn.GetInt32 (handle, "kABPersonInstantMessageProperty");
JobTitle = Dlfcn.GetInt32 (handle, "kABPersonJobTitleProperty");
Kind = Dlfcn.GetInt32 (handle, "kABPersonKindProperty");
LastName = Dlfcn.GetInt32 (handle, "kABPersonLastNameProperty");
LastNamePhonetic = Dlfcn.GetInt32 (handle, "kABPersonLastNamePhoneticProperty");
MiddleName = Dlfcn.GetInt32 (handle, "kABPersonMiddleNameProperty");
MiddleNamePhonetic = Dlfcn.GetInt32 (handle, "kABPersonMiddleNamePhoneticProperty");
ModificationDate = Dlfcn.GetInt32 (handle, "kABPersonModificationDateProperty");
Nickname = Dlfcn.GetInt32 (handle, "kABPersonNicknameProperty");
Note = Dlfcn.GetInt32 (handle, "kABPersonNoteProperty");
Organization = Dlfcn.GetInt32 (handle, "kABPersonOrganizationProperty");
Phone = Dlfcn.GetInt32 (handle, "kABPersonPhoneProperty");
Prefix = Dlfcn.GetInt32 (handle, "kABPersonPrefixProperty");
RelatedNames = Dlfcn.GetInt32 (handle, "kABPersonRelatedNamesProperty");
Suffix = Dlfcn.GetInt32 (handle, "kABPersonSuffixProperty");
Url = Dlfcn.GetInt32 (handle, "kABPersonURLProperty");
SocialProfile = Dlfcn.GetInt32 (handle, "kABPersonSocialProfileProperty");
}
finally {
Dlfcn.dlclose (handle);
}
}
public static int ToId (ABPersonProperty property)
{
switch (property)
{
case ABPersonProperty.Address: return Address;
case ABPersonProperty.Birthday: return Birthday;
case ABPersonProperty.CreationDate: return CreationDate;
case ABPersonProperty.Date: return Date;
case ABPersonProperty.Department: return Department;
case ABPersonProperty.Email: return Email;
case ABPersonProperty.FirstName: return FirstName;
case ABPersonProperty.FirstNamePhonetic: return FirstNamePhonetic;
case ABPersonProperty.InstantMessage: return InstantMessage;
case ABPersonProperty.JobTitle: return JobTitle;
case ABPersonProperty.Kind: return Kind;
case ABPersonProperty.LastName: return LastName;
case ABPersonProperty.LastNamePhonetic: return LastNamePhonetic;
case ABPersonProperty.MiddleName: return MiddleName;
case ABPersonProperty.MiddleNamePhonetic: return MiddleNamePhonetic;
case ABPersonProperty.ModificationDate: return ModificationDate;
case ABPersonProperty.Nickname: return Nickname;
case ABPersonProperty.Note: return Note;
case ABPersonProperty.Organization: return Organization;
case ABPersonProperty.Phone: return Phone;
case ABPersonProperty.Prefix: return Prefix;
case ABPersonProperty.RelatedNames: return RelatedNames;
case ABPersonProperty.Suffix: return Suffix;
case ABPersonProperty.Url: return Url;
case ABPersonProperty.SocialProfile: return SocialProfile;
}
throw new NotSupportedException ("Invalid ABPersonProperty value: " + property);
}
public static ABPersonProperty ToPersonProperty (int id)
{
if (id == Address) return ABPersonProperty.Address;
if (id == Birthday) return ABPersonProperty.Birthday;
if (id == CreationDate) return ABPersonProperty.CreationDate;
if (id == Date) return ABPersonProperty.Date;
if (id == Department) return ABPersonProperty.Department;
if (id == Email) return ABPersonProperty.Email;
if (id == FirstName) return ABPersonProperty.FirstName;
if (id == FirstNamePhonetic) return ABPersonProperty.FirstNamePhonetic;
if (id == InstantMessage) return ABPersonProperty.InstantMessage;
if (id == JobTitle) return ABPersonProperty.JobTitle;
if (id == Kind) return ABPersonProperty.Kind;
if (id == LastName) return ABPersonProperty.LastName;
if (id == LastNamePhonetic) return ABPersonProperty.LastNamePhonetic;
if (id == MiddleName) return ABPersonProperty.MiddleName;
if (id == MiddleNamePhonetic) return ABPersonProperty.MiddleNamePhonetic;
if (id == ModificationDate) return ABPersonProperty.ModificationDate;
if (id == Nickname) return ABPersonProperty.Nickname;
if (id == Note) return ABPersonProperty.Note;
if (id == Organization) return ABPersonProperty.Organization;
if (id == Phone) return ABPersonProperty.Phone;
if (id == Prefix) return ABPersonProperty.Prefix;
if (id == RelatedNames) return ABPersonProperty.RelatedNames;
if (id == Suffix) return ABPersonProperty.Suffix;
if (id == Url) return ABPersonProperty.Url;
if (id == SocialProfile) return ABPersonProperty.SocialProfile;
throw new NotSupportedException ("Invalid ABPersonPropertyId value: " + id);
}
}
public static class ABPersonAddressKey {
public static NSString City {get; private set;}
public static NSString Country {get; private set;}
public static NSString CountryCode {get; private set;}
public static NSString State {get; private set;}
public static NSString Street {get; private set;}
public static NSString Zip {get; private set;}
static ABPersonAddressKey ()
{
InitConstants.Init ();
}
internal static void Init ()
{
var handle = Dlfcn.dlopen (Constants.AddressBookLibrary, 0);
if (handle == IntPtr.Zero)
return;
try {
City = Dlfcn.GetStringConstant (handle, "kABPersonAddressCityKey");
Country = Dlfcn.GetStringConstant (handle, "kABPersonAddressCountryKey");
CountryCode = Dlfcn.GetStringConstant (handle, "kABPersonAddressCountryCodeKey");
State = Dlfcn.GetStringConstant (handle, "kABPersonAddressStateKey");
Street = Dlfcn.GetStringConstant (handle, "kABPersonAddressStreetKey");
Zip = Dlfcn.GetStringConstant (handle, "kABPersonAddressZIPKey");
}
finally {
Dlfcn.dlclose (handle);
}
}
}
public static class ABPersonDateLabel {
public static NSString Anniversary {get; private set;}
static ABPersonDateLabel ()
{
InitConstants.Init ();
}
internal static void Init ()
{
var handle = Dlfcn.dlopen (Constants.AddressBookLibrary, 0);
if (handle == IntPtr.Zero)
return;
try {
Anniversary = Dlfcn.GetStringConstant (handle, "kABPersonAnniversaryLabel");
}
finally {
Dlfcn.dlclose (handle);
}
}
}
public enum ABPersonKind {
None,
Organization,
Person,
}
static class ABPersonKindId {
public static NSNumber Organization {get; private set;}
public static NSNumber Person {get; private set;}
static ABPersonKindId ()
{
InitConstants.Init ();
}
internal static void Init ()
{
var handle = Dlfcn.dlopen (Constants.AddressBookLibrary, 0);
if (handle == IntPtr.Zero)
return;
try {
Organization = Dlfcn.GetNSNumber (handle, "kABPersonKindOrganization");
Person = Dlfcn.GetNSNumber (handle, "kABPersonKindPerson");
}
finally {
Dlfcn.dlclose (handle);
}
}
public static ABPersonKind ToPersonKind (NSNumber value)
{
if (object.ReferenceEquals (Organization, value))
return ABPersonKind.Organization;
if (object.ReferenceEquals (Person, value))
return ABPersonKind.Person;
return ABPersonKind.None;
}
public static NSNumber FromPersonKind (ABPersonKind value)
{
switch (value) {
case ABPersonKind.Organization: return Organization;
case ABPersonKind.Person: return Person;
}
return null;
}
}
static class ABPersonSocialProfile {
public static readonly NSString URLKey;
public static readonly NSString ServiceKey;
public static readonly NSString UsernameKey;
public static readonly NSString UserIdentifierKey;
static ABPersonSocialProfile ()
{
var handle = Dlfcn.dlopen (Constants.AddressBookLibrary, 0);
if (handle == IntPtr.Zero)
return;
try {
URLKey = Dlfcn.GetStringConstant (handle, "kABPersonSocialProfileURLKey");
ServiceKey = Dlfcn.GetStringConstant (handle, "kABPersonSocialProfileServiceKey");
UsernameKey = Dlfcn.GetStringConstant (handle, "kABPersonSocialProfileUsernameKey");
UserIdentifierKey = Dlfcn.GetStringConstant (handle, "kABPersonSocialProfileUserIdentifierKey");
} finally {
Dlfcn.dlclose (handle);
}
}
}
public static class ABPersonSocialProfileService
{
public static readonly NSString Twitter;
public static readonly NSString GameCenter;
public static readonly NSString Facebook;
public static readonly NSString Myspace;
public static readonly NSString LinkedIn;
public static readonly NSString Flickr;
// Since 6.0
public static readonly NSString SinaWeibo;
static ABPersonSocialProfileService ()
{
var handle = Dlfcn.dlopen (Constants.AddressBookLibrary, 0);
if (handle == IntPtr.Zero)
return;
try {
Twitter = Dlfcn.GetStringConstant (handle, "kABPersonSocialProfileServiceTwitter");
GameCenter = Dlfcn.GetStringConstant (handle, "kABPersonSocialProfileServiceGameCenter");
Facebook = Dlfcn.GetStringConstant (handle, "kABPersonSocialProfileServiceFacebook");
Myspace = Dlfcn.GetStringConstant (handle, "kABPersonSocialProfileServiceMyspace");
LinkedIn = Dlfcn.GetStringConstant (handle, "kABPersonSocialProfileServiceLinkedIn");
Flickr = Dlfcn.GetStringConstant (handle, "kABPersonSocialProfileServiceFlickr");
SinaWeibo = Dlfcn.GetStringConstant (handle, "kABPersonSocialProfileServiceSinaWeibo");
} finally {
Dlfcn.dlclose (handle);
}
}
}
public static class ABPersonPhoneLabel {
public static NSString HomeFax {get; private set;}
public static NSString iPhone {get; private set;}
public static NSString Main {get; private set;}
public static NSString Mobile {get; private set;}
public static NSString Pager {get; private set;}
public static NSString WorkFax {get; private set;}
public static NSString OtherFax { get; private set; }
static ABPersonPhoneLabel ()
{
InitConstants.Init ();
}
internal static void Init ()
{
var handle = Dlfcn.dlopen (Constants.AddressBookLibrary, 0);
if (handle == IntPtr.Zero)
return;
try {
HomeFax = Dlfcn.GetStringConstant (handle, "kABPersonPhoneHomeFAXLabel");
iPhone = Dlfcn.GetStringConstant (handle, "kABPersonPhoneIPhoneLabel");
Main = Dlfcn.GetStringConstant (handle, "kABPersonPhoneMainLabel");
Mobile = Dlfcn.GetStringConstant (handle, "kABPersonPhoneMobileLabel");
Pager = Dlfcn.GetStringConstant (handle, "kABPersonPhonePagerLabel");
WorkFax = Dlfcn.GetStringConstant (handle, "kABPersonPhoneWorkFAXLabel");
// Since 5.0
OtherFax = Dlfcn.GetStringConstant (handle, "kABPersonPhoneOtherFAXLabel");
}
finally {
Dlfcn.dlclose (handle);
}
}
}
public static class ABPersonInstantMessageService {
public static NSString Aim {get; private set;}
public static NSString Icq {get; private set;}
public static NSString Jabber {get; private set;}
public static NSString Msn {get; private set;}
public static NSString Yahoo {get; private set;}
// Since 5.0
public static NSString QQ {get; private set;}
public static NSString GoogleTalk {get; private set;}
public static NSString Skype {get; private set;}
public static NSString Facebook {get; private set;}
public static NSString GaduGadu {get; private set;}
static ABPersonInstantMessageService ()
{
InitConstants.Init ();
}
internal static void Init ()
{
var handle = Dlfcn.dlopen (Constants.AddressBookLibrary, 0);
if (handle == IntPtr.Zero)
return;
try {
Aim = Dlfcn.GetStringConstant (handle, "kABPersonInstantMessageServiceAIM");
Icq = Dlfcn.GetStringConstant (handle, "kABPersonInstantMessageServiceICQ");
Jabber = Dlfcn.GetStringConstant (handle, "kABPersonInstantMessageServiceJabber");
Msn = Dlfcn.GetStringConstant (handle, "kABPersonInstantMessageServiceMSN");
Yahoo = Dlfcn.GetStringConstant (handle, "kABPersonInstantMessageServiceYahoo");
QQ = Dlfcn.GetStringConstant (handle, "kABPersonInstantMessageServiceQQ");
GoogleTalk = Dlfcn.GetStringConstant (handle, "kABPersonInstantMessageServiceGoogleTalk");
Skype = Dlfcn.GetStringConstant (handle, "kABPersonInstantMessageServiceSkype");
Facebook = Dlfcn.GetStringConstant (handle, "kABPersonInstantMessageServiceFacebook");
GaduGadu = Dlfcn.GetStringConstant (handle, "kABPersonInstantMessageServiceGaduGadu");
}
finally {
Dlfcn.dlclose (handle);
}
}
}
public static class ABPersonInstantMessageKey {
public static NSString Service {get; private set;}
public static NSString Username {get; private set;}
static ABPersonInstantMessageKey ()
{
InitConstants.Init ();
}
internal static void Init ()
{
var handle = Dlfcn.dlopen (Constants.AddressBookLibrary, 0);
if (handle == IntPtr.Zero)
return;
try {
Service = Dlfcn.GetStringConstant (handle, "kABPersonInstantMessageServiceKey");
Username = Dlfcn.GetStringConstant (handle, "kABPersonInstantMessageUsernameKey");
}
finally {
Dlfcn.dlclose (handle);
}
}
}
public static class ABPersonUrlLabel {
public static NSString HomePage {get; private set;}
static ABPersonUrlLabel ()
{
InitConstants.Init ();
}
internal static void Init ()
{
var handle = Dlfcn.dlopen (Constants.AddressBookLibrary, 0);
if (handle == IntPtr.Zero)
return;
try {
HomePage = Dlfcn.GetStringConstant (handle, "kABPersonHomePageLabel");
}
finally {
Dlfcn.dlclose (handle);
}
}
}
public static class ABPersonRelatedNamesLabel {
public static NSString Assistant {get; private set;}
public static NSString Brother {get; private set;}
public static NSString Child {get; private set;}
public static NSString Father {get; private set;}
public static NSString Friend {get; private set;}
public static NSString Manager {get; private set;}
public static NSString Mother {get; private set;}
public static NSString Parent {get; private set;}
public static NSString Partner {get; private set;}
public static NSString Sister {get; private set;}
public static NSString Spouse {get; private set;}
static ABPersonRelatedNamesLabel ()
{
InitConstants.Init ();
}
internal static void Init ()
{
var handle = Dlfcn.dlopen (Constants.AddressBookLibrary, 0);
if (handle == IntPtr.Zero)
return;
try {
Assistant = Dlfcn.GetStringConstant (handle, "kABPersonAssistantLabel");
Brother = Dlfcn.GetStringConstant (handle, "kABPersonBrotherLabel");
Child = Dlfcn.GetStringConstant (handle, "kABPersonChildLabel");
Father = Dlfcn.GetStringConstant (handle, "kABPersonFatherLabel");
Friend = Dlfcn.GetStringConstant (handle, "kABPersonFriendLabel");
Manager = Dlfcn.GetStringConstant (handle, "kABPersonManagerLabel");
Mother = Dlfcn.GetStringConstant (handle, "kABPersonMotherLabel");
Parent = Dlfcn.GetStringConstant (handle, "kABPersonParentLabel");
Partner = Dlfcn.GetStringConstant (handle, "kABPersonPartnerLabel");
Sister = Dlfcn.GetStringConstant (handle, "kABPersonSisterLabel");
Spouse = Dlfcn.GetStringConstant (handle, "kABPersonSpouseLabel");
}
finally {
Dlfcn.dlclose (handle);
}
}
}
public static class ABLabel {
public static NSString Home {get; private set;}
public static NSString Other {get; private set;}
public static NSString Work {get; private set;}
static ABLabel ()
{
InitConstants.Init ();
}
internal static void Init ()
{
var handle = Dlfcn.dlopen (Constants.AddressBookLibrary, 0);
if (handle == IntPtr.Zero)
return;
try {
Home = Dlfcn.GetStringConstant (handle, "kABHomeLabel");
Other = Dlfcn.GetStringConstant (handle, "kABOtherLabel");
Work = Dlfcn.GetStringConstant (handle, "kABWorkLabel");
}
finally {
Dlfcn.dlclose (handle);
}
}
}
public class ABPerson : ABRecord, IComparable, IComparable<ABPerson> {
[DllImport (Constants.AddressBookLibrary)]
extern static IntPtr ABPersonCreate ();
public ABPerson ()
: base (ABPersonCreate (), true)
{
InitConstants.Init ();
}
[DllImport (Constants.AddressBookLibrary)]
extern static IntPtr ABPersonCreateInSource (IntPtr source);
[Since (4,0)]
public ABPerson (ABRecord source)
: base (IntPtr.Zero, true)
{
if (source == null)
throw new ArgumentNullException ("source");
Handle = ABPersonCreateInSource (source.Handle);
}
internal ABPerson (IntPtr handle, bool owns)
: base (handle, owns)
{
}
internal ABPerson (IntPtr handle, ABAddressBook addressbook)
: base (handle, false)
{
AddressBook = addressbook;
}
int IComparable.CompareTo (object o)
{
var other = o as ABPerson;
if (other == null)
throw new ArgumentException ("Can only compare to other ABPerson instances.", "o");
return CompareTo (other);
}
public int CompareTo (ABPerson other)
{
return CompareTo (other, ABPersonSortBy.LastName);
}
[DllImport (Constants.AddressBookLibrary)]
extern static int ABPersonComparePeopleByName (IntPtr person1, IntPtr person2, ABPersonSortBy ordering);
public int CompareTo (ABPerson other, ABPersonSortBy ordering)
{
if (other == null)
throw new ArgumentNullException ("other");
if (ordering != ABPersonSortBy.FirstName && ordering != ABPersonSortBy.LastName)
throw new ArgumentException ("Invalid ordering value: " + ordering, "ordering");
return ABPersonComparePeopleByName (Handle, other.Handle, ordering);
}
[DllImport (Constants.AddressBookLibrary)]
extern static IntPtr ABPersonCopyLocalizedPropertyName (int propertyId);
public static string LocalizedPropertyName (ABPersonProperty property)
{
return Runtime.GetNSObject (ABPersonCopyLocalizedPropertyName (ABPersonPropertyId.ToId (property))).ToString ();
}
[DllImport (Constants.AddressBookLibrary)]
extern static ABPropertyType ABPersonGetTypeOfProperty (int propertyId);
public static ABPropertyType GetPropertyType (ABPersonProperty property)
{
return ABPersonGetTypeOfProperty (ABPersonPropertyId.ToId (property));
}
[DllImport (Constants.AddressBookLibrary)]
extern static bool ABPersonSetImageData (IntPtr person, IntPtr imageData, out IntPtr error);
[DllImport (Constants.AddressBookLibrary)]
extern static IntPtr ABPersonCopyImageData (IntPtr person);
public NSData Image {
get {return (NSData) Runtime.GetNSObject (ABPersonCopyImageData (Handle));}
set {
IntPtr error;
if (!ABPersonSetImageData (Handle, value == null ? IntPtr.Zero : value.Handle, out error))
throw CFException.FromCFError (error);
}
}
[DllImport (Constants.AddressBookLibrary)]
extern static bool ABPersonHasImageData (IntPtr person);
public bool HasImage {
get {return ABPersonHasImageData (Handle);}
}
[DllImport (Constants.AddressBookLibrary)]
extern static bool ABPersonRemoveImageData (IntPtr person, out IntPtr error);
public void RemoveImage ()
{
IntPtr error;
if (!ABPersonRemoveImageData (Handle, out error))
throw CFException.FromCFError (error);
}
[DllImport (Constants.AddressBookLibrary)]
extern static ABPersonCompositeNameFormat ABPersonGetCompositeNameFormat ();
public static ABPersonCompositeNameFormat CompositeNameFormat {
get {return ABPersonGetCompositeNameFormat ();}
}
[DllImport (Constants.AddressBookLibrary)]
extern static ABPersonSortBy ABPersonGetSortOrdering ();
public static ABPersonSortBy SortOrdering {
get {return ABPersonGetSortOrdering ();}
}
public string FirstName {
get {return PropertyToString (ABPersonPropertyId.FirstName);}
set {SetValue (ABPersonPropertyId.FirstName, value);}
}
public string FirstNamePhonetic {
get {return PropertyToString (ABPersonPropertyId.FirstNamePhonetic);}
set {SetValue (ABPersonPropertyId.FirstNamePhonetic, value);}
}
public string LastName {
get {return PropertyToString (ABPersonPropertyId.LastName);}
set {SetValue (ABPersonPropertyId.LastName, value);}
}
public string LastNamePhonetic {
get {return PropertyToString (ABPersonPropertyId.LastNamePhonetic);}
set {SetValue (ABPersonPropertyId.LastNamePhonetic, value);}
}
public string MiddleName {
get {return PropertyToString (ABPersonPropertyId.MiddleName);}
set {SetValue (ABPersonPropertyId.MiddleName, value);}
}
public string MiddleNamePhonetic {
get {return PropertyToString (ABPersonPropertyId.MiddleNamePhonetic);}
set {SetValue (ABPersonPropertyId.MiddleNamePhonetic, value);}
}
public string Prefix {
get {return PropertyToString (ABPersonPropertyId.Prefix);}
set {SetValue (ABPersonPropertyId.Prefix, value);}
}
public string Suffix {
get {return PropertyToString (ABPersonPropertyId.Suffix);}
set {SetValue (ABPersonPropertyId.Suffix, value);}
}
public string Nickname {
get {return PropertyToString (ABPersonPropertyId.Nickname);}
set {SetValue (ABPersonPropertyId.Nickname, value);}
}
public string Organization {
get {return PropertyToString (ABPersonPropertyId.Organization);}
set {SetValue (ABPersonPropertyId.Organization, value);}
}
public string JobTitle {
get {return PropertyToString (ABPersonPropertyId.JobTitle);}
set {SetValue (ABPersonPropertyId.JobTitle, value);}
}
public string Department {
get {return PropertyToString (ABPersonPropertyId.Department);}
set {SetValue (ABPersonPropertyId.Department, value);}
}
[DllImport (Constants.AddressBookLibrary)]
extern static IntPtr ABPersonCopySource (IntPtr group);
[Since (4,0)]
public ABRecord Source {
get {
var h = ABPersonCopySource (Handle);
if (h == IntPtr.Zero)
return null;
return FromHandle (h, null);
}
}
internal static string ToString (IntPtr value)
{
if (value == IntPtr.Zero)
return null;
return Runtime.GetNSObject (value).ToString ();
}
internal static IntPtr ToIntPtr (string value)
{
if (value == null)
return IntPtr.Zero;
return new NSString (value).Handle;
}
public ABMultiValue<string> GetEmails ()
{
return CreateStringMultiValue (CopyValue (ABPersonPropertyId.Email));
}
static ABMultiValue<string> CreateStringMultiValue (IntPtr handle)
{
if (handle == IntPtr.Zero)
return null;
return new ABMultiValue<string> (handle, ToString, ToIntPtr);
}
public void SetEmails (ABMultiValue<string> value)
{
SetValue (ABPersonPropertyId.Email, value == null ? IntPtr.Zero : value.Handle);
}
public NSDate Birthday {
get {return PropertyTo<NSDate> (ABPersonPropertyId.Birthday);}
set {SetValue (ABPersonPropertyId.Birthday, value);}
}
public string Note {
get {return PropertyToString (ABPersonPropertyId.Note);}
set {SetValue (ABPersonPropertyId.Note, value);}
}
public NSDate CreationDate {
get {return PropertyTo<NSDate> (ABPersonPropertyId.CreationDate);}
set {SetValue (ABPersonPropertyId.CreationDate, value);}
}
public NSDate ModificationDate {
get {return PropertyTo<NSDate> (ABPersonPropertyId.ModificationDate);}
set {SetValue (ABPersonPropertyId.ModificationDate, value);}
}
[Advice ("Use GetAllAddresses")]
public ABMultiValue<NSDictionary> GetAddresses ()
{
return CreateDictionaryMultiValue (CopyValue (ABPersonPropertyId.Address));
}
public ABMultiValue<PersonAddress> GetAllAddresses ()
{
return CreateDictionaryMultiValue<PersonAddress> (CopyValue (ABPersonPropertyId.Address), l => new PersonAddress (l));
}
// Obsolete
public void SetAddresses (ABMultiValue<NSDictionary> value)
{
SetValue (ABPersonPropertyId.Address, value == null ? IntPtr.Zero : value.Handle);
}
public void SetAddresses (ABMultiValue<PersonAddress> addresses)
{
SetValue (ABPersonPropertyId.Address, addresses == null ? IntPtr.Zero : addresses.Handle);
}
// Obsolete
static ABMultiValue<NSDictionary> CreateDictionaryMultiValue (IntPtr handle)
{
if (handle == IntPtr.Zero)
return null;
return new ABMultiValue<NSDictionary> (handle);
}
static ABMultiValue<T> CreateDictionaryMultiValue<T> (IntPtr handle, Func<NSDictionary, T> factory) where T : DictionaryContainer
{
if (handle == IntPtr.Zero)
return null;
return new ABMultiValue<T> (handle,
l => factory ((NSDictionary) (object) Runtime.GetNSObject (l)),
l => l.Dictionary.Handle);
}
public ABMultiValue<NSDate> GetDates ()
{
return CreateDateMultiValue (CopyValue (ABPersonPropertyId.Date));
}
static ABMultiValue<NSDate> CreateDateMultiValue (IntPtr handle)
{
if (handle == IntPtr.Zero)
return null;
return new ABMultiValue<NSDate> (handle);
}
public void SetDates (ABMultiValue<NSDate> value)
{
SetValue (ABPersonPropertyId.Date, value == null ? IntPtr.Zero : value.Handle);
}
public ABPersonKind PersonKind {
get {return ABPersonKindId.ToPersonKind (PropertyTo<NSNumber> (ABPersonPropertyId.Kind));}
set {SetValue (ABPersonPropertyId.Kind, ABPersonKindId.FromPersonKind (value));}
}
public ABMultiValue<string> GetPhones ()
{
return CreateStringMultiValue (CopyValue (ABPersonPropertyId.Phone));
}
public void SetPhones (ABMultiValue<string> value)
{
SetValue (ABPersonPropertyId.Phone, value == null ? IntPtr.Zero : value.Handle);
}
[Advice ("Use GetInstantMessageServices")]
public ABMultiValue<NSDictionary> GetInstantMessages ()
{
return CreateDictionaryMultiValue (CopyValue (ABPersonPropertyId.InstantMessage));
}
public ABMultiValue<InstantMessageService> GetInstantMessageServices ()
{
return CreateDictionaryMultiValue<InstantMessageService> (CopyValue (ABPersonPropertyId.InstantMessage), l => new InstantMessageService (l));
}
// Obsolete
public void SetInstantMessages (ABMultiValue<NSDictionary> value)
{
SetValue (ABPersonPropertyId.InstantMessage, value == null ? IntPtr.Zero : value.Handle);
}
public void SetInstantMessages (ABMultiValue<InstantMessageService> services)
{
SetValue (ABPersonPropertyId.InstantMessage, services == null ? IntPtr.Zero : services.Handle);
}
[Advice ("Use GetSocialProfiles")]
public ABMultiValue<NSDictionary> GetSocialProfile ()
{
return CreateDictionaryMultiValue (CopyValue (ABPersonPropertyId.SocialProfile));
}
public ABMultiValue<SocialProfile> GetSocialProfiles ()
{
return CreateDictionaryMultiValue<SocialProfile> (CopyValue (ABPersonPropertyId.SocialProfile), l => new SocialProfile (l));
}
// Obsolete
public void SetSocialProfile (ABMultiValue<NSDictionary> value)
{
SetValue (ABPersonPropertyId.SocialProfile, value == null ? IntPtr.Zero : value.Handle);
}
public void SetSocialProfile (ABMultiValue<SocialProfile> profiles)
{
SetValue (ABPersonPropertyId.SocialProfile, profiles == null ? IntPtr.Zero : profiles.Handle);
}
public ABMultiValue<string> GetUrls ()
{
return CreateStringMultiValue (CopyValue (ABPersonPropertyId.Url));
}
public void SetUrls (ABMultiValue<string> value)
{
SetValue (ABPersonPropertyId.Url, value == null ? IntPtr.Zero : value.Handle);
}
public ABMultiValue<string> GetRelatedNames ()
{
return CreateStringMultiValue (CopyValue (ABPersonPropertyId.RelatedNames));
}
public void SetRelatedNames (ABMultiValue<string> value)
{
SetValue (ABPersonPropertyId.RelatedNames, value == null ? IntPtr.Zero : value.Handle);
}
// TODO: Is there a better way to do this?
public object GetProperty (ABPersonProperty property)
{
switch (property) {
case ABPersonProperty.Address: return GetAddresses ();
case ABPersonProperty.Birthday: return Birthday;
case ABPersonProperty.CreationDate: return CreationDate;
case ABPersonProperty.Date: return GetDates ();
case ABPersonProperty.Department: return Department;
case ABPersonProperty.Email: return GetEmails ();
case ABPersonProperty.FirstName: return FirstName;
case ABPersonProperty.FirstNamePhonetic: return FirstNamePhonetic;
case ABPersonProperty.InstantMessage: return GetInstantMessages ();
case ABPersonProperty.JobTitle: return JobTitle;
case ABPersonProperty.Kind: return PersonKind;
case ABPersonProperty.LastName: return LastName;
case ABPersonProperty.LastNamePhonetic: return LastNamePhonetic;
case ABPersonProperty.MiddleName: return MiddleName;
case ABPersonProperty.MiddleNamePhonetic: return MiddleNamePhonetic;
case ABPersonProperty.ModificationDate: return ModificationDate;
case ABPersonProperty.Nickname: return Nickname;
case ABPersonProperty.Note: return Note;
case ABPersonProperty.Organization: return Organization;
case ABPersonProperty.Phone: return GetPhones ();
case ABPersonProperty.Prefix: return Prefix;
case ABPersonProperty.RelatedNames: return GetRelatedNames ();
case ABPersonProperty.Suffix: return Suffix;
case ABPersonProperty.Url: return GetUrls ();
case ABPersonProperty.SocialProfile: return GetSocialProfile ();
}
throw new ArgumentException ("Invalid property value: " + property);
}
[DllImport (Constants.AddressBookLibrary)]
extern static IntPtr ABPersonCopyArrayOfAllLinkedPeople (IntPtr person);
[Since (4,0)]
public ABPerson[] GetLinkedPeople ()
{
var linked = ABPersonCopyArrayOfAllLinkedPeople (Handle);
return NSArray.ArrayFromHandle (linked, l => new ABPerson (l, null));
}
[DllImport (Constants.AddressBookLibrary)]
extern static IntPtr ABPersonCopyImageDataWithFormat (IntPtr handle, ABPersonImageFormat format);
[Since (4,1)]
public NSData GetImage (ABPersonImageFormat format)
{
return (NSData) Runtime.GetNSObject (ABPersonCopyImageDataWithFormat (Handle, format));
}
[DllImport (Constants.AddressBookLibrary)]
extern static IntPtr ABPersonCreateVCardRepresentationWithPeople (IntPtr people);
[Since (5,0)]
public static NSData GetVCards (params ABPerson[] people)
{
if (people == null)
throw new ArgumentNullException ("people");
var ptrs = new IntPtr [people.Length];
for (int i = 0; i < people.Length; ++i) {
ptrs[i] = people[i].Handle;
}
var ptr = ABPersonCreateVCardRepresentationWithPeople (CFArray.Create (ptrs));
return new NSData (ptr, true);
}
[DllImport (Constants.AddressBookLibrary)]
extern static IntPtr ABPersonCreatePeopleInSourceWithVCardRepresentation (IntPtr source, IntPtr vCardData);
[Since (5,0)]
public static ABPerson[] CreateFromVCard (ABRecord source, NSData vCardData)
{
if (vCardData == null)
throw new ArgumentNullException ("vCardData");
// TODO: SIGSEGV when source is not null
var res = ABPersonCreatePeopleInSourceWithVCardRepresentation (source == null ? IntPtr.Zero : source.Handle,
vCardData.Handle);
return NSArray.ArrayFromHandle (res, l => new ABPerson (l, null));
}
}
public class SocialProfile : DictionaryContainer
{
public SocialProfile ()
{
}
public SocialProfile (NSDictionary dictionary)
: base (dictionary)
{
}
public string ServiceName {
get {
return GetStringValue (ABPersonSocialProfile.ServiceKey);
}
set {
SetStringValue (ABPersonSocialProfile.ServiceKey, value);
}
}
// NSString from ABPersonSocialProfileService
public NSString Service {
set {
SetStringValue (ABPersonSocialProfile.ServiceKey, value);
}
}
public string Username {
get {
return GetStringValue (ABPersonSocialProfile.UsernameKey);
}
set {
SetStringValue (ABPersonSocialProfile.UsernameKey, value);
}
}
public string UserIdentifier {
get {
return GetStringValue (ABPersonSocialProfile.UserIdentifierKey);
}
set {
SetStringValue (ABPersonSocialProfile.UserIdentifierKey, value);
}
}
public string Url {
get {
return GetStringValue (ABPersonSocialProfile.URLKey);
}
set {
SetStringValue (ABPersonSocialProfile.URLKey, value);
}
}
}
public class InstantMessageService : DictionaryContainer
{
public InstantMessageService ()
{
}
public InstantMessageService (NSDictionary dictionary)
: base (dictionary)
{
}
public string ServiceName {
get {
// TODO: It does not return ABPersonInstantMessageService value. Underlying
// value is custom string, it coould be MT bug because this makes
// ABPersonInstantMessageService constants useless
return GetStringValue (ABPersonInstantMessageKey.Service);
}
set {
SetStringValue (ABPersonInstantMessageKey.Service, value);
}
}
// NSString from ABPersonInstantMessageService
public NSString Service {
set {
SetStringValue (ABPersonInstantMessageKey.Service, value);
}
}
public string Username {
get {
return GetStringValue (ABPersonInstantMessageKey.Username);
}
set {
SetStringValue (ABPersonInstantMessageKey.Username, value);
}
}
}
public class PersonAddress : DictionaryContainer
{
public PersonAddress ()
{
}
public PersonAddress (NSDictionary dictionary)
: base (dictionary)
{
}
public string City {
get {
return GetStringValue (ABPersonAddressKey.City);
}
set {
SetStringValue (ABPersonAddressKey.City, value);
}
}
public string Country {
get {
return GetStringValue (ABPersonAddressKey.Country);
}
set {
SetStringValue (ABPersonAddressKey.Country, value);
}
}
public string CountryCode {
get {
return GetStringValue (ABPersonAddressKey.CountryCode);
}
set {
SetStringValue (ABPersonAddressKey.CountryCode, value);
}
}
public string State {
get {
return GetStringValue (ABPersonAddressKey.State);
}
set {
SetStringValue (ABPersonAddressKey.State, value);
}
}
public string Street {
get {
return GetStringValue (ABPersonAddressKey.Street);
}
set {
SetStringValue (ABPersonAddressKey.Street, value);
}
}
public string Zip {
get {
return GetStringValue (ABPersonAddressKey.Zip);
}
set {
SetStringValue (ABPersonAddressKey.Zip, value);
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using log4net;
using Nini.Config;
using Nwc.XmlRpc;
using OpenMetaverse;
using Mono.Addins;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Framework.Servers;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenSim.Services.Connectors.Friends;
using OpenSim.Server.Base;
using FriendInfo = OpenSim.Services.Interfaces.FriendInfo;
using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Region.CoreModules.Avatar.Friends
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "FriendsModule")]
public class FriendsModule : ISharedRegionModule, IFriendsModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected bool m_Enabled = false;
protected class UserFriendData
{
public UUID PrincipalID;
public FriendInfo[] Friends;
public int Refcount;
public bool IsFriend(string friend)
{
foreach (FriendInfo fi in Friends)
{
if (fi.Friend == friend)
return true;
}
return false;
}
}
protected static readonly FriendInfo[] EMPTY_FRIENDS = new FriendInfo[0];
protected List<Scene> m_Scenes = new List<Scene>();
protected IPresenceService m_PresenceService = null;
protected IFriendsService m_FriendsService = null;
protected FriendsSimConnector m_FriendsSimConnector;
/// <summary>
/// Cache friends lists for users.
/// </summary>
/// <remarks>
/// This is a complex and error-prone thing to do. At the moment, we assume that the efficiency gained in
/// permissions checks outweighs the disadvantages of that complexity.
/// </remarks>
protected Dictionary<UUID, UserFriendData> m_Friends = new Dictionary<UUID, UserFriendData>();
/// <summary>
/// Maintain a record of clients that need to notify about their online status. This only
/// needs to be done on login. Subsequent online/offline friend changes are sent by a different mechanism.
/// </summary>
protected HashSet<UUID> m_NeedsToNotifyStatus = new HashSet<UUID>();
/// <summary>
/// Maintain a record of viewers that need to be sent notifications for friends that are online. This only
/// needs to be done on login. Subsequent online/offline friend changes are sent by a different mechanism.
/// </summary>
protected HashSet<UUID> m_NeedsListOfOnlineFriends = new HashSet<UUID>();
protected IPresenceService PresenceService
{
get
{
if (m_PresenceService == null)
{
if (m_Scenes.Count > 0)
m_PresenceService = m_Scenes[0].RequestModuleInterface<IPresenceService>();
}
return m_PresenceService;
}
}
public IFriendsService FriendsService
{
get
{
if (m_FriendsService == null)
{
if (m_Scenes.Count > 0)
m_FriendsService = m_Scenes[0].RequestModuleInterface<IFriendsService>();
}
return m_FriendsService;
}
}
protected IGridService GridService
{
get { return m_Scenes[0].GridService; }
}
public IUserAccountService UserAccountService
{
get { return m_Scenes[0].UserAccountService; }
}
public IScene Scene
{
get
{
if (m_Scenes.Count > 0)
return m_Scenes[0];
else
return null;
}
}
#region ISharedRegionModule
public void Initialise(IConfigSource config)
{
IConfig moduleConfig = config.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("FriendsModule", "FriendsModule");
if (name == Name)
{
InitModule(config);
m_Enabled = true;
m_log.DebugFormat("[FRIENDS MODULE]: {0} enabled.", Name);
}
}
}
protected virtual void InitModule(IConfigSource config)
{
IConfig friendsConfig = config.Configs["Friends"];
if (friendsConfig != null)
{
int mPort = friendsConfig.GetInt("Port", 0);
string connector = friendsConfig.GetString("Connector", String.Empty);
Object[] args = new Object[] { config };
m_FriendsService = ServerUtils.LoadPlugin<IFriendsService>(connector, args);
m_FriendsSimConnector = new FriendsSimConnector();
// Instantiate the request handler
IHttpServer server = MainServer.GetHttpServer((uint)mPort);
if (server != null)
server.AddStreamHandler(new FriendsRequestHandler(this));
}
if (m_FriendsService == null)
{
m_log.Error("[FRIENDS]: No Connector defined in section Friends, or failed to load, cannot continue");
throw new Exception("Connector load error");
}
}
public void PostInitialise()
{
}
public void Close()
{
}
public virtual void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
// m_log.DebugFormat("[FRIENDS MODULE]: AddRegion on {0}", Name);
m_Scenes.Add(scene);
scene.RegisterModuleInterface<IFriendsModule>(this);
scene.EventManager.OnNewClient += OnNewClient;
scene.EventManager.OnClientClosed += OnClientClosed;
scene.EventManager.OnMakeRootAgent += OnMakeRootAgent;
scene.EventManager.OnClientLogin += OnClientLogin;
}
public virtual void RegionLoaded(Scene scene) {}
public void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
m_Scenes.Remove(scene);
}
public virtual string Name
{
get { return "FriendsModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
public virtual int GetRightsGrantedByFriend(UUID principalID, UUID friendID)
{
FriendInfo[] friends = GetFriendsFromCache(principalID);
FriendInfo finfo = GetFriend(friends, friendID);
if (finfo != null)
{
return finfo.TheirFlags;
}
return 0;
}
private void OnNewClient(IClientAPI client)
{
client.OnInstantMessage += OnInstantMessage;
client.OnApproveFriendRequest += OnApproveFriendRequest;
client.OnDenyFriendRequest += OnDenyFriendRequest;
client.OnTerminateFriendship += RemoveFriendship;
client.OnGrantUserRights += GrantRights;
// We need to cache information for child agents as well as root agents so that friend edit/move/delete
// permissions will work across borders where both regions are on different simulators.
//
// Do not do this asynchronously. If we do, then subsequent code can outrace CacheFriends() and
// return misleading results from the still empty friends cache.
// If we absolutely need to do this asynchronously, then a signalling mechanism is needed so that calls
// to GetFriends() will wait until CacheFriends() completes. Locks are insufficient.
CacheFriends(client);
}
/// <summary>
/// Cache the friends list or increment the refcount for the existing friends list.
/// </summary>
/// <param name="client">
/// </param>
/// <returns>
/// Returns true if the list was fetched, false if it wasn't
/// </returns>
protected virtual bool CacheFriends(IClientAPI client)
{
UUID agentID = client.AgentId;
lock (m_Friends)
{
UserFriendData friendsData;
if (m_Friends.TryGetValue(agentID, out friendsData))
{
friendsData.Refcount++;
return false;
}
else
{
friendsData = new UserFriendData();
friendsData.PrincipalID = agentID;
friendsData.Friends = GetFriendsFromService(client);
friendsData.Refcount = 1;
m_Friends[agentID] = friendsData;
return true;
}
}
}
private void OnClientClosed(UUID agentID, Scene scene)
{
ScenePresence sp = scene.GetScenePresence(agentID);
if (sp != null && !sp.IsChildAgent)
{
// do this for root agents closing out
StatusChange(agentID, false);
}
lock (m_Friends)
{
UserFriendData friendsData;
if (m_Friends.TryGetValue(agentID, out friendsData))
{
friendsData.Refcount--;
if (friendsData.Refcount <= 0)
m_Friends.Remove(agentID);
}
}
}
private void OnMakeRootAgent(ScenePresence sp)
{
RecacheFriends(sp.ControllingClient);
lock (m_NeedsToNotifyStatus)
{
if (m_NeedsToNotifyStatus.Remove(sp.UUID))
{
// Inform the friends that this user is online. This can only be done once the client is a Root Agent.
StatusChange(sp.UUID, true);
}
}
}
private void OnClientLogin(IClientAPI client)
{
UUID agentID = client.AgentId;
//m_log.DebugFormat("[XXX]: OnClientLogin!");
// Register that we need to send this user's status to friends. This can only be done
// once the client becomes a Root Agent, because as part of sending out the presence
// we also get back the presence of the HG friends, and we need to send that to the
// client, but that can only be done when the client is a Root Agent.
lock (m_NeedsToNotifyStatus)
m_NeedsToNotifyStatus.Add(agentID);
// Register that we need to send the list of online friends to this user
lock (m_NeedsListOfOnlineFriends)
m_NeedsListOfOnlineFriends.Add(agentID);
}
public virtual bool SendFriendsOnlineIfNeeded(IClientAPI client)
{
UUID agentID = client.AgentId;
// Check if the online friends list is needed
lock (m_NeedsListOfOnlineFriends)
{
if (!m_NeedsListOfOnlineFriends.Remove(agentID))
return false;
}
// Send the friends online
List<UUID> online = GetOnlineFriends(agentID);
if (online.Count > 0)
client.SendAgentOnline(online.ToArray());
// Send outstanding friendship offers
List<string> outstanding = new List<string>();
FriendInfo[] friends = GetFriendsFromCache(agentID);
foreach (FriendInfo fi in friends)
{
if (fi.TheirFlags == -1)
outstanding.Add(fi.Friend);
}
GridInstantMessage im = new GridInstantMessage(client.Scene, UUID.Zero, String.Empty, agentID, (byte)InstantMessageDialog.FriendshipOffered,
"Will you be my friend?", true, Vector3.Zero);
foreach (string fid in outstanding)
{
UUID fromAgentID;
string firstname = "Unknown", lastname = "UserFMSFOIN";
if (!GetAgentInfo(client.Scene.RegionInfo.ScopeID, fid, out fromAgentID, out firstname, out lastname))
{
m_log.DebugFormat("[FRIENDS MODULE]: skipping malformed friend {0}", fid);
continue;
}
im.offline = 0;
im.fromAgentID = fromAgentID.Guid;
im.fromAgentName = firstname + " " + lastname;
im.imSessionID = im.fromAgentID;
im.message = FriendshipMessage(fid);
LocalFriendshipOffered(agentID, im);
}
return true;
}
protected virtual string FriendshipMessage(string friendID)
{
return "Will you be my friend?";
}
protected virtual bool GetAgentInfo(UUID scopeID, string fid, out UUID agentID, out string first, out string last)
{
first = "Unknown"; last = "UserFMGAI";
if (!UUID.TryParse(fid, out agentID))
return false;
UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(scopeID, agentID);
if (account != null)
{
first = account.FirstName;
last = account.LastName;
}
return true;
}
List<UUID> GetOnlineFriends(UUID userID)
{
List<string> friendList = new List<string>();
FriendInfo[] friends = GetFriendsFromCache(userID);
foreach (FriendInfo fi in friends)
{
if (((fi.TheirFlags & (int)FriendRights.CanSeeOnline) != 0) && (fi.TheirFlags != -1))
friendList.Add(fi.Friend);
}
List<UUID> online = new List<UUID>();
if (friendList.Count > 0)
GetOnlineFriends(userID, friendList, online);
// m_log.DebugFormat(
// "[FRIENDS MODULE]: User {0} has {1} friends online", userID, online.Count);
return online;
}
protected virtual void GetOnlineFriends(UUID userID, List<string> friendList, /*collector*/ List<UUID> online)
{
// m_log.DebugFormat(
// "[FRIENDS MODULE]: Looking for online presence of {0} users for {1}", friendList.Count, userID);
PresenceInfo[] presence = PresenceService.GetAgents(friendList.ToArray());
foreach (PresenceInfo pi in presence)
{
UUID presenceID;
if (UUID.TryParse(pi.UserID, out presenceID))
online.Add(presenceID);
}
}
/// <summary>
/// Find the client for a ID
/// </summary>
public IClientAPI LocateClientObject(UUID agentID)
{
lock (m_Scenes)
{
foreach (Scene scene in m_Scenes)
{
ScenePresence presence = scene.GetScenePresence(agentID);
if (presence != null && !presence.IsChildAgent)
return presence.ControllingClient;
}
}
return null;
}
/// <summary>
/// Caller beware! Call this only for root agents.
/// </summary>
/// <param name="agentID"></param>
/// <param name="online"></param>
private void StatusChange(UUID agentID, bool online)
{
FriendInfo[] friends = GetFriendsFromCache(agentID);
if (friends.Length > 0)
{
List<FriendInfo> friendList = new List<FriendInfo>();
foreach (FriendInfo fi in friends)
{
if (((fi.MyFlags & (int)FriendRights.CanSeeOnline) != 0) && (fi.TheirFlags != -1))
friendList.Add(fi);
}
Util.FireAndForget(
delegate
{
// m_log.DebugFormat(
// "[FRIENDS MODULE]: Notifying {0} friends of {1} of online status {2}",
// friendList.Count, agentID, online);
// Notify about this user status
StatusNotify(friendList, agentID, online);
}, null, "FriendsModule.StatusChange"
);
}
}
protected virtual void StatusNotify(List<FriendInfo> friendList, UUID userID, bool online)
{
//m_log.DebugFormat("[FRIENDS]: Entering StatusNotify for {0}", userID);
List<string> friendStringIds = friendList.ConvertAll<string>(friend => friend.Friend);
List<string> remoteFriendStringIds = new List<string>();
foreach (string friendStringId in friendStringIds)
{
UUID friendUuid;
if (UUID.TryParse(friendStringId, out friendUuid))
{
if (LocalStatusNotification(userID, friendUuid, online))
continue;
remoteFriendStringIds.Add(friendStringId);
}
else
{
m_log.WarnFormat("[FRIENDS]: Error parsing friend ID {0}", friendStringId);
}
}
// We do this regrouping so that we can efficiently send a single request rather than one for each
// friend in what may be a very large friends list.
PresenceInfo[] friendSessions = PresenceService.GetAgents(remoteFriendStringIds.ToArray());
foreach (PresenceInfo friendSession in friendSessions)
{
// let's guard against sessions-gone-bad
if (friendSession != null && friendSession.RegionID != UUID.Zero)
{
//m_log.DebugFormat("[FRIENDS]: Get region {0}", friendSession.RegionID);
GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
if (region != null)
{
m_FriendsSimConnector.StatusNotify(region, userID, friendSession.UserID, online);
}
}
//else
// m_log.DebugFormat("[FRIENDS]: friend session is null or the region is UUID.Zero");
}
}
protected virtual void OnInstantMessage(IClientAPI client, GridInstantMessage im)
{
if ((InstantMessageDialog)im.dialog == InstantMessageDialog.FriendshipOffered)
{
// we got a friendship offer
UUID principalID = new UUID(im.fromAgentID);
UUID friendID = new UUID(im.toAgentID);
m_log.DebugFormat("[FRIENDS]: {0} ({1}) offered friendship to {2} ({3})", principalID, client.FirstName + client.LastName, friendID, im.fromAgentName);
// Check that the friendship doesn't exist yet
FriendInfo[] finfos = GetFriendsFromCache(principalID);
if (finfos != null)
{
FriendInfo f = GetFriend(finfos, friendID);
if (f != null)
{
client.SendAgentAlertMessage("This person is already your friend. Please delete it first if you want to reestablish the friendship.", false);
return;
}
}
// This user wants to be friends with the other user.
// Let's add the relation backwards, in case the other is not online
StoreBackwards(friendID, principalID);
// Now let's ask the other user to be friends with this user
ForwardFriendshipOffer(principalID, friendID, im);
}
}
protected virtual bool ForwardFriendshipOffer(UUID agentID, UUID friendID, GridInstantMessage im)
{
// !!!!!!!! This is a hack so that we don't have to keep state (transactionID/imSessionID)
// We stick this agent's ID as imSession, so that it's directly available on the receiving end
im.imSessionID = im.fromAgentID;
im.fromAgentName = GetFriendshipRequesterName(agentID);
// Try the local sim
if (LocalFriendshipOffered(friendID, im))
return true;
// The prospective friend is not here [as root]. Let's forward.
PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() });
if (friendSessions != null && friendSessions.Length > 0)
{
PresenceInfo friendSession = friendSessions[0];
if (friendSession != null)
{
GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
m_FriendsSimConnector.FriendshipOffered(region, agentID, friendID, im.message);
return true;
}
}
// If the prospective friend is not online, he'll get the message upon login.
return false;
}
protected virtual string GetFriendshipRequesterName(UUID agentID)
{
UserAccount account = UserAccountService.GetUserAccount(UUID.Zero, agentID);
return (account == null) ? "Unknown" : account.FirstName + " " + account.LastName;
}
protected virtual void OnApproveFriendRequest(IClientAPI client, UUID friendID, List<UUID> callingCardFolders)
{
m_log.DebugFormat("[FRIENDS]: {0} accepted friendship from {1}", client.AgentId, friendID);
AddFriendship(client, friendID);
}
public void AddFriendship(IClientAPI client, UUID friendID)
{
StoreFriendships(client.AgentId, friendID);
ICallingCardModule ccm = client.Scene.RequestModuleInterface<ICallingCardModule>();
if (ccm != null)
{
ccm.CreateCallingCard(client.AgentId, friendID, UUID.Zero);
}
// Update the local cache.
RecacheFriends(client);
//
// Notify the friend
//
// Try Local
if (LocalFriendshipApproved(client.AgentId, client.Name, friendID))
{
client.SendAgentOnline(new UUID[] { friendID });
return;
}
// The friend is not here
PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() });
if (friendSessions != null && friendSessions.Length > 0)
{
PresenceInfo friendSession = friendSessions[0];
if (friendSession != null)
{
GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
m_FriendsSimConnector.FriendshipApproved(region, client.AgentId, client.Name, friendID);
client.SendAgentOnline(new UUID[] { friendID });
}
}
}
private void OnDenyFriendRequest(IClientAPI client, UUID friendID, List<UUID> callingCardFolders)
{
m_log.DebugFormat("[FRIENDS]: {0} denied friendship to {1}", client.AgentId, friendID);
DeleteFriendship(client.AgentId, friendID);
//
// Notify the friend
//
// Try local
if (LocalFriendshipDenied(client.AgentId, client.Name, friendID))
return;
PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() });
if (friendSessions != null && friendSessions.Length > 0)
{
PresenceInfo friendSession = friendSessions[0];
if (friendSession != null)
{
GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
if (region != null)
m_FriendsSimConnector.FriendshipDenied(region, client.AgentId, client.Name, friendID);
else
m_log.WarnFormat("[FRIENDS]: Could not find region {0} in locating {1}", friendSession.RegionID, friendID);
}
}
}
public void RemoveFriendship(IClientAPI client, UUID exfriendID)
{
if (!DeleteFriendship(client.AgentId, exfriendID))
client.SendAlertMessage("Unable to terminate friendship on this sim.");
// Update local cache
RecacheFriends(client);
client.SendTerminateFriend(exfriendID);
//
// Notify the friend
//
// Try local
if (LocalFriendshipTerminated(client.AgentId, exfriendID))
return;
PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { exfriendID.ToString() });
if (friendSessions != null && friendSessions.Length > 0)
{
PresenceInfo friendSession = friendSessions[0];
if (friendSession != null)
{
GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
m_FriendsSimConnector.FriendshipTerminated(region, client.AgentId, exfriendID);
}
}
}
public void GrantRights(IClientAPI remoteClient, UUID friendID, int rights)
{
UUID requester = remoteClient.AgentId;
m_log.DebugFormat(
"[FRIENDS MODULE]: User {0} changing rights to {1} for friend {2}",
requester, rights, friendID);
FriendInfo[] friends = GetFriendsFromCache(requester);
if (friends.Length == 0)
{
return;
}
// Let's find the friend in this user's friend list
FriendInfo friend = GetFriend(friends, friendID);
if (friend != null) // Found it
{
// Store it on the DB
if (!StoreRights(requester, friendID, rights))
{
remoteClient.SendAlertMessage("Unable to grant rights.");
return;
}
// Store it in the local cache
int myFlags = friend.MyFlags;
friend.MyFlags = rights;
// Always send this back to the original client
remoteClient.SendChangeUserRights(requester, friendID, rights);
//
// Notify the friend
//
// Try local
if (LocalGrantRights(requester, friendID, myFlags, rights))
return;
PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() });
if (friendSessions != null && friendSessions.Length > 0)
{
PresenceInfo friendSession = friendSessions[0];
if (friendSession != null)
{
GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
// TODO: You might want to send the delta to save the lookup
// on the other end!!
m_FriendsSimConnector.GrantRights(region, requester, friendID, myFlags, rights);
}
}
}
else
{
m_log.DebugFormat("[FRIENDS MODULE]: friend {0} not found for {1}", friendID, requester);
}
}
protected virtual FriendInfo GetFriend(FriendInfo[] friends, UUID friendID)
{
foreach (FriendInfo fi in friends)
{
if (fi.Friend == friendID.ToString())
return fi;
}
return null;
}
#region Local
public virtual bool LocalFriendshipOffered(UUID toID, GridInstantMessage im)
{
IClientAPI friendClient = LocateClientObject(toID);
if (friendClient != null)
{
// the prospective friend in this sim as root agent
friendClient.SendInstantMessage(im);
// we're done
return true;
}
return false;
}
public bool LocalFriendshipApproved(UUID userID, string userName, UUID friendID)
{
IClientAPI friendClient = LocateClientObject(friendID);
if (friendClient != null)
{
// the prospective friend in this sim as root agent
GridInstantMessage im = new GridInstantMessage(Scene, userID, userName, friendID,
(byte)OpenMetaverse.InstantMessageDialog.FriendshipAccepted, userID.ToString(), false, Vector3.Zero);
friendClient.SendInstantMessage(im);
ICallingCardModule ccm = friendClient.Scene.RequestModuleInterface<ICallingCardModule>();
if (ccm != null)
{
ccm.CreateCallingCard(friendID, userID, UUID.Zero);
}
// Update the local cache
RecacheFriends(friendClient);
// we're done
return true;
}
return false;
}
public bool LocalFriendshipDenied(UUID userID, string userName, UUID friendID)
{
IClientAPI friendClient = LocateClientObject(friendID);
if (friendClient != null)
{
// the prospective friend in this sim as root agent
GridInstantMessage im = new GridInstantMessage(Scene, userID, userName, friendID,
(byte)OpenMetaverse.InstantMessageDialog.FriendshipDeclined, userID.ToString(), false, Vector3.Zero);
friendClient.SendInstantMessage(im);
// we're done
return true;
}
return false;
}
public bool LocalFriendshipTerminated(UUID userID, UUID exfriendID)
{
IClientAPI friendClient = LocateClientObject(exfriendID);
if (friendClient != null)
{
// the friend in this sim as root agent
friendClient.SendTerminateFriend(userID);
// update local cache
RecacheFriends(friendClient);
// we're done
return true;
}
return false;
}
public bool LocalGrantRights(UUID userID, UUID friendID, int userFlags, int rights)
{
IClientAPI friendClient = LocateClientObject(friendID);
if (friendClient != null)
{
bool onlineBitChanged = ((rights ^ userFlags) & (int)FriendRights.CanSeeOnline) != 0;
if (onlineBitChanged)
{
if ((rights & (int)FriendRights.CanSeeOnline) == 1)
friendClient.SendAgentOnline(new UUID[] { userID });
else
friendClient.SendAgentOffline(new UUID[] { userID });
}
else
{
bool canEditObjectsChanged = ((rights ^ userFlags) & (int)FriendRights.CanModifyObjects) != 0;
if (canEditObjectsChanged)
friendClient.SendChangeUserRights(userID, friendID, rights);
}
// Update local cache
UpdateLocalCache(userID, friendID, rights);
return true;
}
return false;
}
public bool LocalStatusNotification(UUID userID, UUID friendID, bool online)
{
//m_log.DebugFormat("[FRIENDS]: Local Status Notify {0} that user {1} is {2}", friendID, userID, online);
IClientAPI friendClient = LocateClientObject(friendID);
if (friendClient != null)
{
// the friend in this sim as root agent
if (online)
friendClient.SendAgentOnline(new UUID[] { userID });
else
friendClient.SendAgentOffline(new UUID[] { userID });
// we're done
return true;
}
return false;
}
#endregion
#region Get / Set friends in several flavours
public FriendInfo[] GetFriendsFromCache(UUID userID)
{
UserFriendData friendsData;
lock (m_Friends)
{
if (m_Friends.TryGetValue(userID, out friendsData))
return friendsData.Friends;
}
return EMPTY_FRIENDS;
}
/// <summary>
/// Update local cache only
/// </summary>
/// <param name="userID"></param>
/// <param name="friendID"></param>
/// <param name="rights"></param>
protected void UpdateLocalCache(UUID userID, UUID friendID, int rights)
{
// Update local cache
lock (m_Friends)
{
FriendInfo[] friends = GetFriendsFromCache(friendID);
FriendInfo finfo = GetFriend(friends, userID);
finfo.TheirFlags = rights;
}
}
public virtual FriendInfo[] GetFriendsFromService(IClientAPI client)
{
return FriendsService.GetFriends(client.AgentId);
}
protected void RecacheFriends(IClientAPI client)
{
// FIXME: Ideally, we want to avoid doing this here since it sits the EventManager.OnMakeRootAgent event
// is on the critical path for transferring an avatar from one region to another.
UUID agentID = client.AgentId;
lock (m_Friends)
{
UserFriendData friendsData;
if (m_Friends.TryGetValue(agentID, out friendsData))
friendsData.Friends = GetFriendsFromService(client);
}
}
public bool AreFriendsCached(UUID userID)
{
lock (m_Friends)
return m_Friends.ContainsKey(userID);
}
protected virtual bool StoreRights(UUID agentID, UUID friendID, int rights)
{
FriendsService.StoreFriend(agentID.ToString(), friendID.ToString(), rights);
return true;
}
protected virtual void StoreBackwards(UUID friendID, UUID agentID)
{
FriendsService.StoreFriend(friendID.ToString(), agentID.ToString(), 0);
}
protected virtual void StoreFriendships(UUID agentID, UUID friendID)
{
FriendsService.StoreFriend(agentID.ToString(), friendID.ToString(), (int)FriendRights.CanSeeOnline);
FriendsService.StoreFriend(friendID.ToString(), agentID.ToString(), (int)FriendRights.CanSeeOnline);
}
protected virtual bool DeleteFriendship(UUID agentID, UUID exfriendID)
{
FriendsService.Delete(agentID, exfriendID.ToString());
FriendsService.Delete(exfriendID, agentID.ToString());
return true;
}
#endregion
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type DriveSpecialCollectionRequest.
/// </summary>
public partial class DriveSpecialCollectionRequest : BaseRequest, IDriveSpecialCollectionRequest
{
/// <summary>
/// Constructs a new DriveSpecialCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public DriveSpecialCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified DriveItem to the collection via POST.
/// </summary>
/// <param name="driveItem">The DriveItem to add.</param>
/// <returns>The created DriveItem.</returns>
public System.Threading.Tasks.Task<DriveItem> AddAsync(DriveItem driveItem)
{
return this.AddAsync(driveItem, CancellationToken.None);
}
/// <summary>
/// Adds the specified DriveItem to the collection via POST.
/// </summary>
/// <param name="driveItem">The DriveItem to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created DriveItem.</returns>
public System.Threading.Tasks.Task<DriveItem> AddAsync(DriveItem driveItem, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
return this.SendAsync<DriveItem>(driveItem, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
public System.Threading.Tasks.Task<IDriveSpecialCollectionPage> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<IDriveSpecialCollectionPage> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var response = await this.SendAsync<DriveSpecialCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response != null && response.Value != null && response.Value.CurrentPage != null)
{
if (response.AdditionalData != null)
{
object nextPageLink;
response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
response.Value.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
}
return response.Value;
}
return null;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IDriveSpecialCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IDriveSpecialCollectionRequest Expand(Expression<Func<DriveItem, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IDriveSpecialCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IDriveSpecialCollectionRequest Select(Expression<Func<DriveItem, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public IDriveSpecialCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public IDriveSpecialCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public IDriveSpecialCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public IDriveSpecialCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace DD.Cloud.VersionManagement.DataAccess.Models
{
[Table("VersionRange")]
public sealed class VersionRangeData
{
public VersionRangeData()
{
}
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
[DefaultValue(VersionComponent.Build)]
public VersionComponent IncrementBy { get; set; } = VersionComponent.Build;
[Required]
public int StartVersionMajor { get; set; }
[Required]
public int StartVersionMinor { get; set; }
[Required]
public int StartVersionBuild { get; set; }
[Required]
public int StartVersionRevision { get; set; }
[Required]
public int NextVersionMajor { get; set; }
[Required]
public int NextVersionMinor { get; set; }
[Required]
public int NextVersionBuild { get; set; }
[Required]
public int NextVersionRevision { get; set; }
[Required]
public int EndVersionMajor { get; set; }
[Required]
public int EndVersionMinor { get; set; }
[Required]
public int EndVersionBuild { get; set; }
[Required]
public int EndVersionRevision { get; set; }
public ICollection<ReleaseData> Releases { get; set; } = new HashSet<ReleaseData>();
[NotMapped]
public Version StartVersion
{
get
{
return new Version(
StartVersionMajor,
StartVersionMinor,
StartVersionBuild,
StartVersionRevision
);
}
set
{
if (value != null)
{
StartVersionMajor = value.Major;
StartVersionMinor = value.Minor;
StartVersionBuild = value.Build;
StartVersionRevision = value.Revision;
}
else
{
StartVersionMajor = 0;
StartVersionMinor = 0;
StartVersionBuild = 0;
StartVersionRevision = 0;
}
}
}
[NotMapped]
public Version NextVersion
{
get
{
return new Version(
NextVersionMajor,
NextVersionMinor,
NextVersionBuild,
NextVersionRevision
);
}
set
{
if (value != null)
{
NextVersionMajor = value.Major;
NextVersionMinor = value.Minor;
NextVersionBuild = value.Build;
NextVersionRevision = value.Revision;
}
else
{
NextVersionMajor = 0;
NextVersionMinor = 0;
NextVersionBuild = 0;
NextVersionRevision = 0;
}
}
}
[NotMapped]
public Version EndVersion
{
get
{
return new Version(
EndVersionMajor,
EndVersionMinor,
EndVersionBuild,
EndVersionRevision
);
}
set
{
if (value != null)
{
EndVersionMajor = value.Major;
EndVersionMinor = value.Minor;
EndVersionBuild = value.Build;
EndVersionRevision = value.Revision;
}
else
{
EndVersionMajor = 0;
EndVersionMinor = 0;
EndVersionBuild = 0;
EndVersionRevision = 0;
}
}
}
public Version GetAndIncrement()
{
Version nextVersion = NextVersion;
switch (IncrementBy)
{
case VersionComponent.Major:
{
if (NextVersionMajor >= EndVersionMajor)
throw new VersionManagementException("The next major version number for range '{0}' is {1}, which would exceed the maximum value for this version range.", Name, NextVersionMajor);
NextVersionMajor++;
break;
}
case VersionComponent.Minor:
{
if (NextVersionMinor >= EndVersionMinor)
throw new VersionManagementException("The next minor version number for range '{0}' is {1}, which would exceed the maximum value for this version range.", Name, NextVersionMinor);
NextVersionMinor++;
break;
}
case VersionComponent.Build:
{
if (NextVersionBuild >= EndVersionBuild)
throw new VersionManagementException("The next build number for range '{0}' is {1}, which would exceed the maximum value for this version range.", Name, NextVersionBuild);
NextVersionBuild++;
break;
}
case VersionComponent.Revision:
{
if (NextVersionRevision >= EndVersionRevision)
throw new VersionManagementException("The next revision number for range '{0}' is {1}, which would exceed the maximum value for this version range.", Name, EndVersionRevision);
NextVersionRevision++;
break;
}
default:
{
throw new InvalidOperationException($"InvalidOperationException value for VersionRange.IncrementBy: {IncrementBy}.");
}
}
return nextVersion;
}
public override string ToString() => $"{Name} ({StartVersion}-{EndVersion}, Next={NextVersion})";
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Xunit;
namespace System.Collections.Immutable.Tests
{
public class ImmutableHashSetTest : ImmutableSetTest
{
protected override bool IncludesGetHashCodeDerivative
{
get { return true; }
}
[Fact]
public void EmptyTest()
{
this.EmptyTestHelper(Empty<int>(), 5, null);
this.EmptyTestHelper(EmptyTyped<string>().WithComparer(StringComparer.OrdinalIgnoreCase), "a", StringComparer.OrdinalIgnoreCase);
}
[Fact]
public void CustomSort()
{
this.CustomSortTestHelper(
ImmutableHashSet<string>.Empty.WithComparer(StringComparer.Ordinal),
false,
new[] { "apple", "APPLE" },
new[] { "apple", "APPLE" });
this.CustomSortTestHelper(
ImmutableHashSet<string>.Empty.WithComparer(StringComparer.OrdinalIgnoreCase),
false,
new[] { "apple", "APPLE" },
new[] { "apple" });
}
[Fact]
public void ChangeUnorderedEqualityComparer()
{
var ordinalSet = ImmutableHashSet<string>.Empty
.WithComparer(StringComparer.Ordinal)
.Add("apple")
.Add("APPLE");
Assert.Equal(2, ordinalSet.Count); // claimed count
Assert.False(ordinalSet.Contains("aPpLe"));
var ignoreCaseSet = ordinalSet.WithComparer(StringComparer.OrdinalIgnoreCase);
Assert.Equal(1, ignoreCaseSet.Count);
Assert.True(ignoreCaseSet.Contains("aPpLe"));
}
[Fact]
public void ToSortTest()
{
var set = ImmutableHashSet<string>.Empty
.Add("apple")
.Add("APPLE");
var sorted = set.ToImmutableSortedSet();
CollectionAssertAreEquivalent(set.ToList(), sorted.ToList());
}
[Fact]
[ActiveIssue("https://github.com/dotnet/corefx/issues/19044 - HashBucket.Equals() always returning true", TargetFrameworkMonikers.UapAot)]
public void EnumeratorWithHashCollisionsTest()
{
var emptySet = this.EmptyTyped<int>().WithComparer(new BadHasher<int>());
this.EnumeratorTestHelper(emptySet, null, 3, 1, 5);
}
[Fact]
public void EnumeratorRecyclingMisuse()
{
var collection = ImmutableHashSet.Create<int>().Add(5);
var enumerator = collection.GetEnumerator();
var enumeratorCopy = enumerator;
Assert.True(enumerator.MoveNext());
Assert.False(enumerator.MoveNext());
enumerator.Dispose();
Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumerator.Reset());
Assert.Throws<ObjectDisposedException>(() => enumerator.Current);
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Reset());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Current);
enumerator.Dispose(); // double-disposal should not throw
enumeratorCopy.Dispose();
// We expect that acquiring a new enumerator will use the same underlying Stack<T> object,
// but that it will not throw exceptions for the new enumerator.
enumerator = collection.GetEnumerator();
Assert.True(enumerator.MoveNext());
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
enumerator.Dispose();
}
[Fact]
public void Create()
{
var comparer = StringComparer.OrdinalIgnoreCase;
var set = ImmutableHashSet.Create<string>();
Assert.Equal(0, set.Count);
Assert.Same(EqualityComparer<string>.Default, set.KeyComparer);
set = ImmutableHashSet.Create<string>(comparer);
Assert.Equal(0, set.Count);
Assert.Same(comparer, set.KeyComparer);
set = ImmutableHashSet.Create("a");
Assert.Equal(1, set.Count);
Assert.Same(EqualityComparer<string>.Default, set.KeyComparer);
set = ImmutableHashSet.Create(comparer, "a");
Assert.Equal(1, set.Count);
Assert.Same(comparer, set.KeyComparer);
set = ImmutableHashSet.Create("a", "b");
Assert.Equal(2, set.Count);
Assert.Same(EqualityComparer<string>.Default, set.KeyComparer);
set = ImmutableHashSet.Create(comparer, "a", "b");
Assert.Equal(2, set.Count);
Assert.Same(comparer, set.KeyComparer);
set = ImmutableHashSet.CreateRange((IEnumerable<string>)new[] { "a", "b" });
Assert.Equal(2, set.Count);
Assert.Same(EqualityComparer<string>.Default, set.KeyComparer);
set = ImmutableHashSet.CreateRange(comparer, (IEnumerable<string>)new[] { "a", "b" });
Assert.Equal(2, set.Count);
Assert.Same(comparer, set.KeyComparer);
}
/// <summary>
/// Verifies the non-removal of an item that does not belong to the set,
/// but which happens to have a colliding hash code with another value
/// that *is* in the set.
/// </summary>
[Fact]
[ActiveIssue("https://github.com/dotnet/corefx/issues/19044 - HashBucket.Equals() always returning true", TargetFrameworkMonikers.UapAot)]
public void RemoveValuesFromCollidedHashCode()
{
var set = ImmutableHashSet.Create<int>(new BadHasher<int>(), 5, 6);
Assert.Same(set, set.Remove(2));
var setAfterRemovingFive = set.Remove(5);
Assert.Equal(1, setAfterRemovingFive.Count);
Assert.Equal(new[] { 6 }, setAfterRemovingFive);
}
[Fact]
public void TryGetValueTest()
{
this.TryGetValueTestHelper(ImmutableHashSet<string>.Empty.WithComparer(StringComparer.OrdinalIgnoreCase));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")]
public void DebuggerAttributesValid()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableHashSet.Create<string>());
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(ImmutableHashSet.Create<int>(1, 2, 3));
}
[Fact]
public void SymmetricExceptWithComparerTests()
{
var set = ImmutableHashSet.Create<string>("a").WithComparer(StringComparer.OrdinalIgnoreCase);
var otherCollection = new[] {"A"};
var expectedSet = new HashSet<string>(set, set.KeyComparer);
expectedSet.SymmetricExceptWith(otherCollection);
var actualSet = set.SymmetricExcept(otherCollection);
CollectionAssertAreEquivalent(expectedSet.ToList(), actualSet.ToList());
}
protected override IImmutableSet<T> Empty<T>()
{
return ImmutableHashSet<T>.Empty;
}
protected ImmutableHashSet<T> EmptyTyped<T>()
{
return ImmutableHashSet<T>.Empty;
}
protected override ISet<T> EmptyMutable<T>()
{
return new HashSet<T>();
}
internal override IBinaryTree GetRootNode<T>(IImmutableSet<T> set)
{
return ((ImmutableHashSet<T>)set).Root;
}
/// <summary>
/// Tests various aspects of an unordered set.
/// </summary>
/// <typeparam name="T">The type of element stored in the set.</typeparam>
/// <param name="emptySet">The empty set.</param>
/// <param name="value">A value that could be placed in the set.</param>
/// <param name="comparer">The comparer used to obtain the empty set, if any.</param>
private void EmptyTestHelper<T>(IImmutableSet<T> emptySet, T value, IEqualityComparer<T> comparer)
{
Assert.NotNull(emptySet);
this.EmptyTestHelper(emptySet);
Assert.Same(emptySet, emptySet.ToImmutableHashSet(comparer));
Assert.Same(comparer ?? EqualityComparer<T>.Default, ((IHashKeyCollection<T>)emptySet).KeyComparer);
if (comparer == null)
{
Assert.Same(emptySet, ImmutableHashSet<T>.Empty);
}
var reemptied = emptySet.Add(value).Clear();
Assert.Same(reemptied, reemptied.ToImmutableHashSet(comparer)); //, "Getting the empty set from a non-empty instance did not preserve the comparer.");
}
}
}
| |
/*
* PrintDocument.cs - Implementation of the
* "System.Drawing.Printing.PrintDocument" class.
*
* Copyright (C) 2003 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.Drawing.Printing
{
using System.ComponentModel;
using System.Drawing.Toolkit;
#if CONFIG_COMPONENT_MODEL
[DefaultEvent("PrintPage")]
[DefaultProperty("DocumentName")]
[ToolboxItemFilter("System.Drawing.Printing")]
#endif
public class PrintDocument
#if CONFIG_COMPONENT_MODEL
: Component
#endif
{
// Internal state.
private PageSettings defaultPageSettings;
private String documentName;
private bool originAtMargins;
private PrintController printController;
private PrinterSettings printerSettings;
internal IToolkitPrintSession session;
// Constructor.
public PrintDocument()
{
this.documentName = "document";
this.originAtMargins = false;
this.printController = null;
this.printerSettings = new PrinterSettings();
this.defaultPageSettings = new PageSettings(printerSettings);
}
// Get or set the document's properties.
#if CONFIG_COMPONENT_MODEL
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Browsable(false)]
#endif
public PageSettings DefaultPageSettings
{
get
{
return defaultPageSettings;
}
set
{
defaultPageSettings = value;
}
}
#if CONFIG_COMPONENT_MODEL
[DefaultValue("document")]
#endif
public String DocumentName
{
get
{
return documentName;
}
set
{
documentName = value;
}
}
#if CONFIG_COMPONENT_MODEL
[DefaultValue(false)]
#endif
public bool OriginAtMargins
{
get
{
return originAtMargins;
}
set
{
originAtMargins = value;
}
}
#if CONFIG_COMPONENT_MODEL
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Browsable(false)]
#endif
public PrintController PrintController
{
get
{
if(printController == null)
{
// Create a standard print controller.
printController = new StandardPrintController();
}
return printController;
}
set
{
printController = value;
}
}
#if CONFIG_COMPONENT_MODEL
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Browsable(false)]
#endif
public PrinterSettings PrinterSettings
{
get
{
return printerSettings;
}
set
{
printerSettings = value;
}
}
// Print the document.
public void Print()
{
PrintController controller = PrintController;
PrintEventArgs printArgs;
QueryPageSettingsEventArgs queryArgs;
PrintPageEventArgs pageArgs;
Graphics graphics;
// Begin the printing process.
printArgs = new PrintEventArgs();
OnBeginPrint(printArgs);
#if CONFIG_COMPONENT_MODEL
if(printArgs.Cancel)
{
return;
}
#endif
controller.OnStartPrint(this, printArgs);
// Wrap the rest in a "try" block so that the controller
// will be properly shut down if an exception occurs.
try
{
queryArgs = new QueryPageSettingsEventArgs
((PageSettings)(DefaultPageSettings.Clone()));
do
{
// Query the page settings for the next page.
OnQueryPageSettings(queryArgs);
#if CONFIG_COMPONENT_MODEL
if(queryArgs.Cancel)
{
break;
}
#endif
// Create the page argument structure.
pageArgs = new PrintPageEventArgs
(queryArgs.PageSettings);
// Get the graphics object to use to draw the page.
graphics = controller.OnStartPage(this, pageArgs);
pageArgs.graphics = graphics;
// Print the page.
try
{
OnPrintPage(pageArgs);
controller.OnEndPage(this, pageArgs);
}
finally
{
graphics.Dispose();
}
}
while(!(pageArgs.Cancel) && pageArgs.HasMorePages);
}
finally
{
try
{
OnEndPrint(printArgs);
}
finally
{
controller.OnEndPrint(this, printArgs);
}
}
}
// Convert this object into a string.
public override String ToString()
{
return "[PrintDocument " + documentName + "]";
}
// Event that is emitted at the beginning of the print process.
public event PrintEventHandler BeginPrint;
// Event that is emitted at the end of the print process.
public event PrintEventHandler EndPrint;
// Event that is emitted to print the current page.
public event PrintPageEventHandler PrintPage;
// Event that is emitted to query page settings prior to printing a page.
public event QueryPageSettingsEventHandler QueryPageSettings;
// Raise the "BeginPrint" event.
protected virtual void OnBeginPrint(PrintEventArgs e)
{
if(BeginPrint != null)
{
BeginPrint(this, e);
}
}
// Raise the "EndPrint" event.
protected virtual void OnEndPrint(PrintEventArgs e)
{
if(EndPrint != null)
{
EndPrint(this, e);
}
}
// Raise the "PrintPage" event.
protected virtual void OnPrintPage(PrintPageEventArgs e)
{
if(PrintPage != null)
{
PrintPage(this, e);
}
}
// Raise the "QueryPageSettings" event.
protected virtual void OnQueryPageSettings(QueryPageSettingsEventArgs e)
{
if(QueryPageSettings != null)
{
QueryPageSettings(this, e);
}
}
}; // class PrintDocument
}; // namespace System.Drawing.Printing
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics.Contracts;
namespace System.Security.Cryptography {
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class SymmetricAlgorithm : IDisposable {
protected int BlockSizeValue;
protected int FeedbackSizeValue;
protected byte[] IVValue;
protected byte[] KeyValue;
protected KeySizes[] LegalBlockSizesValue;
protected KeySizes[] LegalKeySizesValue;
protected int KeySizeValue;
protected CipherMode ModeValue;
protected PaddingMode PaddingValue;
//
// protected constructors
//
protected SymmetricAlgorithm() {
// Default to cipher block chaining (CipherMode.CBC) and
// PKCS-style padding (pad n bytes with value n)
ModeValue = CipherMode.CBC;
PaddingValue = PaddingMode.PKCS7;
}
// SymmetricAlgorithm implements IDisposable
// To keep mscorlib compatibility with Orcas, CoreCLR's SymmetricAlgorithm has an explicit IDisposable
// implementation. Post-Orcas the desktop has an implicit IDispoable implementation.
#if FEATURE_CORECLR
void IDisposable.Dispose()
{
Dispose();
}
#endif // FEATURE_CORECLR
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Clear() {
(this as IDisposable).Dispose();
}
protected virtual void Dispose(bool disposing) {
if (disposing) {
// Note: we always want to zeroize the sensitive key material
if (KeyValue != null) {
Array.Clear(KeyValue, 0, KeyValue.Length);
KeyValue = null;
}
if (IVValue != null) {
Array.Clear(IVValue, 0, IVValue.Length);
IVValue = null;
}
}
}
//
// public properties
//
public virtual int BlockSize {
get { return BlockSizeValue; }
set {
int i;
int j;
for (i=0; i<LegalBlockSizesValue.Length; i++) {
// If a cipher has only one valid key size, MinSize == MaxSize and SkipSize will be 0
if (LegalBlockSizesValue[i].SkipSize == 0) {
if (LegalBlockSizesValue[i].MinSize == value) { // assume MinSize = MaxSize
BlockSizeValue = value;
IVValue = null;
return;
}
} else {
for (j = LegalBlockSizesValue[i].MinSize; j<=LegalBlockSizesValue[i].MaxSize;
j += LegalBlockSizesValue[i].SkipSize) {
if (j == value) {
if (BlockSizeValue != value) {
BlockSizeValue = value;
IVValue = null; // Wrong length now
}
return;
}
}
}
}
throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidBlockSize"));
}
}
public virtual int FeedbackSize {
get { return FeedbackSizeValue; }
set {
if (value <= 0 || value > BlockSizeValue || (value % 8) != 0)
throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidFeedbackSize"));
FeedbackSizeValue = value;
}
}
public virtual byte[] IV {
get {
if (IVValue == null) GenerateIV();
return (byte[]) IVValue.Clone();
}
set {
if (value == null) throw new ArgumentNullException("value");
Contract.EndContractBlock();
if (value.Length != BlockSizeValue / 8)
throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidIVSize"));
IVValue = (byte[]) value.Clone();
}
}
public virtual byte[] Key {
get {
if (KeyValue == null) GenerateKey();
return (byte[]) KeyValue.Clone();
}
set {
if (value == null) throw new ArgumentNullException("value");
Contract.EndContractBlock();
if (!ValidKeySize(value.Length * 8))
throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidKeySize"));
// must convert bytes to bits
KeyValue = (byte[]) value.Clone();
KeySizeValue = value.Length * 8;
}
}
public virtual KeySizes[] LegalBlockSizes {
get { return (KeySizes[]) LegalBlockSizesValue.Clone(); }
}
public virtual KeySizes[] LegalKeySizes {
get { return (KeySizes[]) LegalKeySizesValue.Clone(); }
}
public virtual int KeySize {
get { return KeySizeValue; }
set {
if (!ValidKeySize(value))
throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidKeySize"));
KeySizeValue = value;
KeyValue = null;
}
}
public virtual CipherMode Mode {
get { return ModeValue; }
set {
if ((value < CipherMode.CBC) || (CipherMode.CFB < value))
throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidCipherMode"));
ModeValue = value;
}
}
public virtual PaddingMode Padding {
get { return PaddingValue; }
set {
if ((value < PaddingMode.None) || (PaddingMode.ISO10126 < value))
throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidPaddingMode"));
PaddingValue = value;
}
}
//
// public methods
//
// The following method takes a bit length input and returns whether that length is a valid size
// according to LegalKeySizes
public bool ValidKeySize(int bitLength) {
KeySizes[] validSizes = this.LegalKeySizes;
int i,j;
if (validSizes == null) return false;
for (i=0; i< validSizes.Length; i++) {
if (validSizes[i].SkipSize == 0) {
if (validSizes[i].MinSize == bitLength) { // assume MinSize = MaxSize
return true;
}
} else {
for (j = validSizes[i].MinSize; j<= validSizes[i].MaxSize;
j += validSizes[i].SkipSize) {
if (j == bitLength) {
return true;
}
}
}
}
return false;
}
static public SymmetricAlgorithm Create() {
// use the crypto config system to return an instance of
// the default SymmetricAlgorithm on this machine
return Create("System.Security.Cryptography.SymmetricAlgorithm");
}
static public SymmetricAlgorithm Create(String algName) {
return (SymmetricAlgorithm) CryptoConfig.CreateFromName(algName);
}
public virtual ICryptoTransform CreateEncryptor() {
return CreateEncryptor(Key, IV);
}
public abstract ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV);
public virtual ICryptoTransform CreateDecryptor() {
return CreateDecryptor(Key, IV);
}
public abstract ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV);
public abstract void GenerateKey();
public abstract void GenerateIV();
}
}
| |
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using UnityEngine;
using UnityEditor;
using System;
using System.Collections.Generic;
namespace AmplifyShaderEditor
{
[System.Serializable]
public class DynamicTypeNode : ParentNode
{
protected string m_inputA = string.Empty;
protected string m_inputB = string.Empty;
protected List<string> m_extensibleInputResults;
protected bool m_dynamicOutputType = true;
protected bool m_extensibleInputPorts = false;
//protected bool m_invalidateMatrixOps = false;
protected bool m_allowMatrixCheck = false;
protected bool m_vectorMatrixOps = false;
//[SerializeField]
private int m_inputCount = 2;
//[SerializeField]
private int m_lastInputCount = 2;
private bool m_previouslyDragging = false;
private int m_beforePreviewCount = 0;
protected WirePortDataType[] m_dynamicRestrictions =
{
WirePortDataType.OBJECT,
WirePortDataType.FLOAT,
WirePortDataType.FLOAT2,
WirePortDataType.FLOAT3,
WirePortDataType.FLOAT4,
WirePortDataType.COLOR,
WirePortDataType.INT
};
[UnityEngine.SerializeField]
protected WirePortDataType m_mainDataType = WirePortDataType.FLOAT;
protected override void CommonInit( int uniqueId )
{
base.CommonInit( uniqueId );
m_useInternalPortData = true;
m_textLabelWidth = 35;
AddPorts();
}
protected virtual void AddPorts()
{
AddInputPort( WirePortDataType.FLOAT, false, "A" );
AddInputPort( WirePortDataType.FLOAT, false, "B" );
AddOutputPort( WirePortDataType.FLOAT, Constants.EmptyPortValue );
m_inputPorts[ 0 ].CreatePortRestrictions( m_dynamicRestrictions );
m_inputPorts[ 1 ].CreatePortRestrictions( m_dynamicRestrictions );
}
public override void OnConnectedOutputNodeChanges( int inputPortId, int otherNodeId, int otherPortId, string name, WirePortDataType type )
{
UpdateConnection( inputPortId );
}
public override void OnInputPortConnected( int portId, int otherNodeId, int otherPortId, bool activateNode = true )
{
base.OnInputPortConnected( portId, otherNodeId, otherPortId, activateNode );
UpdateConnection( portId );
}
public override void OnInputPortDisconnected( int portId )
{
base.OnInputPortDisconnected( portId );
UpdateDisconnectedConnection( portId );
UpdateEmptyInputPorts( true );
}
void UpdateDisconnectedConnection( int portId )
{
if ( m_extensibleInputPorts || m_allowMatrixCheck )
{
int higher = 0;
int groupOneType = 0;
int groupTwoType = 0;
for ( int i = 0; i < m_inputPorts.Count; i++ )
{
if ( m_inputPorts[ i ].IsConnected )
{
int currentPriority = UIUtils.GetPriority( m_inputPorts[ i ].DataType );
if ( !m_vectorMatrixOps && currentPriority < 3 )
currentPriority += 7;
if ( currentPriority > higher && currentPriority > 2 )
{
higher = currentPriority;
m_mainDataType = m_inputPorts[ i ].DataType;
}
switch ( m_inputPorts[ i ].DataType )
{
case WirePortDataType.FLOAT2:
case WirePortDataType.FLOAT3:
case WirePortDataType.FLOAT4:
case WirePortDataType.COLOR:
{
groupOneType++;
groupTwoType++;
}
break;
case WirePortDataType.FLOAT3x3:
{
groupOneType++;
}
break;
case WirePortDataType.FLOAT4x4:
{
groupTwoType++;
}
break;
}
}
}
for ( int i = 0; i < m_inputPorts.Count; i++ )
{
if ( !m_inputPorts[ i ].IsConnected )
{
m_inputPorts[ i ].ChangeType( m_mainDataType, false );
}
}
if ( groupOneType > 0 && m_mainDataType == WirePortDataType.FLOAT4x4 )
{
m_errorMessageTooltip = "Doing this operation with FLOAT4x4 value only works against other FLOAT4x4 or FLOAT values";
m_showErrorMessage = true;
}
else if ( groupTwoType > 0 && m_mainDataType == WirePortDataType.FLOAT3x3 )
{
m_errorMessageTooltip = "Doing this operation with FLOAT3x3 value only works against other FLOAT3x3 or FLOAT values";
m_showErrorMessage = true;
}
else
{
m_showErrorMessage = false;
}
if ( m_dynamicOutputType )
m_outputPorts[ 0 ].ChangeType( m_mainDataType, false );
}
else
if ( m_inputPorts[ 0 ].DataType != m_inputPorts[ 1 ].DataType )
{
int otherPortId = ( portId + 1 ) % 2;
if ( m_inputPorts[ otherPortId ].IsConnected )
{
m_mainDataType = m_inputPorts[ otherPortId ].DataType;
m_inputPorts[ portId ].ChangeType( m_mainDataType, false );
if ( m_dynamicOutputType )
m_outputPorts[ 0 ].ChangeType( m_mainDataType, false );
}
else
{
if ( UIUtils.GetPriority( m_inputPorts[ 0 ].DataType ) > UIUtils.GetPriority( m_inputPorts[ 1 ].DataType ) )
{
m_mainDataType = m_inputPorts[ 0 ].DataType;
m_inputPorts[ 1 ].ChangeType( m_mainDataType, false );
}
else
{
m_mainDataType = m_inputPorts[ 1 ].DataType;
m_inputPorts[ 0 ].ChangeType( m_mainDataType, false );
}
if ( m_dynamicOutputType )
{
if ( m_mainDataType != m_outputPorts[ 0 ].DataType )
{
m_outputPorts[ 0 ].ChangeType( m_mainDataType, false );
}
}
}
}
}
void UpdateConnection( int portId )
{
if ( m_extensibleInputPorts || m_allowMatrixCheck )
{
m_inputPorts[ portId ].MatchPortToConnection();
int higher = 0;
int groupOneType = 0;
int groupTwoType = 0;
for ( int i = 0; i < m_inputPorts.Count; i++ )
{
if ( m_inputPorts[ i ].IsConnected )
{
int currentPriority = UIUtils.GetPriority( m_inputPorts[ i ].DataType );
if ( !m_vectorMatrixOps && currentPriority < 3 )
currentPriority += 7;
if ( currentPriority > higher )
{
higher = currentPriority;
m_mainDataType = m_inputPorts[ i ].DataType;
}
switch ( m_inputPorts[ i ].DataType )
{
case WirePortDataType.FLOAT2:
case WirePortDataType.FLOAT3:
case WirePortDataType.FLOAT4:
case WirePortDataType.COLOR:
{
groupOneType++;
groupTwoType++;
}
break;
case WirePortDataType.FLOAT3x3:
{
groupOneType++;
}
break;
case WirePortDataType.FLOAT4x4:
{
groupTwoType++;
}
break;
}
}
}
for ( int i = 0; i < m_inputPorts.Count; i++ )
{
if ( !m_inputPorts[ i ].IsConnected )
{
m_inputPorts[ i ].ChangeType( m_mainDataType, false );
}
}
if ( groupOneType > 0 && m_mainDataType == WirePortDataType.FLOAT4x4 )
{
m_errorMessageTooltip = "Doing this operation with FLOAT4x4 value only works against other FLOAT4x4 or FLOAT values";
m_showErrorMessage = true;
}
else if ( groupTwoType > 0 && m_mainDataType == WirePortDataType.FLOAT3x3 )
{
m_errorMessageTooltip = "Doing this operation with FLOAT3x3 value only works against other FLOAT3x3 or FLOAT values";
m_showErrorMessage = true;
}
else
{
m_showErrorMessage = false;
}
if ( m_dynamicOutputType )
m_outputPorts[ 0 ].ChangeType( m_mainDataType, false );
}
else
{
m_inputPorts[ portId ].MatchPortToConnection();
int otherPortId = ( portId + 1 ) % 2;
if ( !m_inputPorts[ otherPortId ].IsConnected )
{
m_inputPorts[ otherPortId ].ChangeType( m_inputPorts[ portId ].DataType, false );
}
if ( m_inputPorts[ 0 ].DataType == m_inputPorts[ 1 ].DataType )
{
m_mainDataType = m_inputPorts[ 0 ].DataType;
if ( m_dynamicOutputType )
m_outputPorts[ 0 ].ChangeType( InputPorts[ 0 ].DataType, false );
}
else
{
if ( UIUtils.GetPriority( m_inputPorts[ 0 ].DataType ) > UIUtils.GetPriority( m_inputPorts[ 1 ].DataType ) )
{
m_mainDataType = m_inputPorts[ 0 ].DataType;
}
else
{
m_mainDataType = m_inputPorts[ 1 ].DataType;
}
if ( m_dynamicOutputType )
{
if ( m_mainDataType != m_outputPorts[ 0 ].DataType )
{
m_outputPorts[ 0 ].ChangeType( m_mainDataType, false );
}
}
}
}
}
public override void Draw( DrawInfo drawInfo )
{
base.Draw( drawInfo );
if ( !m_extensibleInputPorts )
return;
if ( m_previouslyDragging != UIUtils.OutputPortReference.IsValid && Event.current.type == EventType.layout && UIUtils.OutputPortReference.NodeId != UniqueId )
{
if ( UIUtils.OutputPortReference.IsValid )
{
m_beforePreviewCount = 2;
for ( int i = 2; i < m_inputPorts.Count; i++ )
{
if ( m_inputPorts[ i ].IsConnected )
{
m_beforePreviewCount++;
}
}
m_inputCount = m_beforePreviewCount + 1;
if (/* m_inputCount != m_lastInputCount && */m_inputCount <= 10 )
{
if ( m_inputCount > m_lastInputCount )
{
Undo.RegisterCompleteObjectUndo( m_containerGraph.ParentWindow, Constants.UndoCreateDynamicPortId );
Undo.RecordObject( this, Constants.UndoCreateDynamicPortId );
AddInputPort( m_mainDataType, false, ( ( char ) ( 'A' + m_inputCount - 1 ) ).ToString() );
m_inputPorts[ m_inputCount - 1 ].CreatePortRestrictions( m_dynamicRestrictions );
}
m_lastInputCount = m_inputCount;
m_sizeIsDirty = true;
m_isDirty = true;
SetSaveIsDirty();
}
}
else
{
bool hasEmpty = CheckValidConnections();
if ( hasEmpty )
UpdateEmptyInputPorts( false );
}
m_previouslyDragging = UIUtils.OutputPortReference.IsValid;
}
if ( Event.current.type == EventType.layout )
UpdateEmptyInputPorts( false );
}
private bool CheckValidConnections()
{
if ( !m_extensibleInputPorts )
return false;
bool hasEmptyConnections = false;
bool hasMatrix = m_inputPorts[ 0 ].DataType == WirePortDataType.FLOAT3x3 || m_inputPorts[ 0 ].DataType == WirePortDataType.FLOAT4x4 || m_inputPorts[ 1 ].DataType == WirePortDataType.FLOAT3x3 || m_inputPorts[ 1 ].DataType == WirePortDataType.FLOAT4x4;
if ( m_inputPorts.Count != m_beforePreviewCount )
{
if ( hasMatrix )
{
bool showError = false;
for ( int i = m_inputPorts.Count - 1; i >= 2; i-- )
{
if ( m_inputPorts[ i ].IsConnected )
{
showError = true;
m_inputPorts[ i ].FullDeleteConnections();
}
hasEmptyConnections = true;
}
if ( showError )
m_containerGraph.ParentWindow.ShowMessage( "Matrix operations are only valid for the first two inputs to prevent errors" );
}
else
{
for ( int i = m_inputPorts.Count - 1; i >= 2; i-- )
{
if ( m_inputPorts[ i ].DataType == WirePortDataType.FLOAT3x3 || m_inputPorts[ i ].DataType == WirePortDataType.FLOAT4x4 )
{
m_containerGraph.ParentWindow.ShowMessage( "Matrix operations are only valid for the first two inputs to prevent errors" );
m_inputPorts[ i ].FullDeleteConnections();
hasEmptyConnections = true;
}
else if ( !m_inputPorts[ i ].IsConnected )
{
hasEmptyConnections = true;
}
}
}
}
return hasEmptyConnections;
}
private void UpdateEmptyInputPorts( bool recordUndo )
{
if ( !m_extensibleInputPorts )
return;
if ( !UIUtils.OutputPortReference.IsValid )
{
if( recordUndo )
{
Undo.RegisterCompleteObjectUndo( m_containerGraph.ParentWindow, Constants.UndoDeleteDynamicPortId );
Undo.RecordObject( this, Constants.UndoDeleteDynamicPortId );
}
bool hasDeleted = false;
m_inputCount = 2;
for ( int i = m_inputPorts.Count - 1; i >= 2; i-- )
{
if ( !m_inputPorts[ i ].IsConnected )
{
hasDeleted = true;
DeleteInputPortByArrayIdx( i );
} else
{
m_inputCount++;
}
}
if( hasDeleted || m_inputCount != m_lastInputCount )
{
for ( int i = 2; i < m_inputPorts.Count; i++ )
{
m_inputPorts[ i ].Name = ( ( char ) ( 'A' + i ) ).ToString();
}
m_beforePreviewCount = m_inputPorts.Count;
m_inputCount = m_beforePreviewCount;
m_lastInputCount = m_inputCount;
m_sizeIsDirty = true;
m_isDirty = true;
SetSaveIsDirty();
}
}
m_inputCount = Mathf.Clamp( m_inputCount, 2, 10 );
}
public virtual string BuildResults( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar )
{
if ( !m_extensibleInputPorts )
SetInputData( outputId, ref dataCollector, ignoreLocalvar );
else
SetExtensibleInputData( outputId, ref dataCollector, ignoreLocalvar );
return string.Empty;
}
public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar )
{
string result = BuildResults( outputId, ref dataCollector, ignoreLocalvar );
return CreateOutputLocalVariable( 0, result, ref dataCollector );
}
protected void SetInputData( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar )
{
m_inputA = m_inputPorts[ 0 ].GeneratePortInstructions( ref dataCollector );
if ( m_inputPorts[ 0 ].DataType != m_mainDataType )
{
m_inputA = UIUtils.CastPortType( ref dataCollector, m_currentPrecisionType, new NodeCastInfo( UniqueId, outputId ), m_inputA, m_inputPorts[ 0 ].DataType, m_mainDataType, m_inputA );
}
m_inputB = m_inputPorts[ 1 ].GeneratePortInstructions( ref dataCollector );
if ( m_inputPorts[ 1 ].DataType != m_mainDataType )
{
m_inputB = UIUtils.CastPortType( ref dataCollector, m_currentPrecisionType, new NodeCastInfo( UniqueId, outputId ), m_inputB, m_inputPorts[ 1 ].DataType, m_mainDataType, m_inputB );
}
}
protected void SetExtensibleInputData( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar )
{
m_extensibleInputResults = new List<string>();
for ( int i = 0; i < m_inputPorts.Count; i++ )
{
m_extensibleInputResults.Add( m_inputPorts[ i ].GeneratePortInstructions( ref dataCollector ) );
if ( m_inputPorts[ i ].DataType != m_mainDataType && m_inputPorts[ i ].DataType != WirePortDataType.FLOAT && m_inputPorts[ i ].DataType != WirePortDataType.INT )
{
m_extensibleInputResults[ i ] = UIUtils.CastPortType( ref dataCollector, m_currentPrecisionType, new NodeCastInfo( UniqueId, outputId ), m_extensibleInputResults[ i ], m_inputPorts[ i ].DataType, m_mainDataType, m_extensibleInputResults[ i ] );
}
}
}
void UpdatePorts()
{
m_lastInputCount = Mathf.Clamp( m_inputCount, 2, 10 );
for ( int i = 2; i < m_inputCount; i++ )
{
AddInputPort( m_mainDataType, false, ( ( char ) ( 'A' + i ) ).ToString() );
m_inputPorts[ i ].CreatePortRestrictions( m_dynamicRestrictions );
}
m_sizeIsDirty = true;
SetSaveIsDirty();
}
public override void ReadFromString( ref string[] nodeParams )
{
base.ReadFromString( ref nodeParams );
if ( m_extensibleInputPorts && UIUtils.CurrentShaderVersion() > 10005 )
{
m_inputCount = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
UpdatePorts();
}
}
public override void WriteToString( ref string nodeInfo, ref string connectionsInfo )
{
base.WriteToString( ref nodeInfo, ref connectionsInfo );
if ( m_extensibleInputPorts )
IOUtils.AddFieldValueToString( ref nodeInfo, m_inputCount );
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim 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.
*/
// to build without references to System.Drawing, comment this out
#define SYSTEM_DRAWING
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using BitmapProcessing;
#if SYSTEM_DRAWING
#endif
namespace PrimMesher
{
public class SculptMesh
{
public List<Coord> coords;
public List<Face> faces;
public List<ViewerFace> viewerFaces;
public List<Coord> normals;
public List<UVCoord> uvs;
public enum SculptType
{
sphere = 1,
torus = 2,
plane = 3,
cylinder = 4
};
#if SYSTEM_DRAWING
public SculptMesh SculptMeshFromFile(string fileName, SculptType sculptType, int lod, bool viewerMode)
{
Bitmap bitmap = (Bitmap) Image.FromFile(fileName);
SculptMesh sculptMesh = new SculptMesh(bitmap, sculptType, lod, viewerMode);
bitmap.Dispose();
return sculptMesh;
}
public SculptMesh(string fileName, int sculptType, int lod, int viewerMode, int mirror, int invert)
{
Bitmap bitmap = (Bitmap) Image.FromFile(fileName);
_SculptMesh(bitmap, (SculptType) sculptType, lod, viewerMode != 0, mirror != 0, invert != 0);
bitmap.Dispose();
}
#endif
/// <summary>
/// ** Experimental ** May disappear from future versions ** not recommeneded for use in applications
/// Construct a sculpt mesh from a 2D array of floats
/// </summary>
/// <param name = "zMap"></param>
/// <param name = "xBegin"></param>
/// <param name = "xEnd"></param>
/// <param name = "yBegin"></param>
/// <param name = "yEnd"></param>
/// <param name = "viewerMode"></param>
public SculptMesh(float[,] zMap, float xBegin, float xEnd, float yBegin, float yEnd, bool viewerMode)
{
float xStep, yStep;
float uStep, vStep;
int numYElements = zMap.GetLength(0);
int numXElements = zMap.GetLength(1);
try
{
xStep = (xEnd - xBegin)/(numXElements - 1);
yStep = (yEnd - yBegin)/(numYElements - 1);
uStep = 1.0f/(numXElements - 1);
vStep = 1.0f/(numYElements - 1);
}
catch (DivideByZeroException)
{
return;
}
coords = new List<Coord>();
faces = new List<Face>();
normals = new List<Coord>();
uvs = new List<UVCoord>();
viewerFaces = new List<ViewerFace>();
int p1, p2, p3, p4;
int x, y;
int xStart = 0, yStart = 0;
for (y = yStart; y < numYElements; y++)
{
int rowOffset = y*numXElements;
for (x = xStart; x < numXElements; x++)
{
/*
* p1-----p2
* | \ f2 |
* | \ |
* | f1 \|
* p3-----p4
*/
p4 = rowOffset + x;
p3 = p4 - 1;
p2 = p4 - numXElements;
p1 = p3 - numXElements;
Coord c = new Coord(xBegin + x*xStep, yBegin + y*yStep, zMap[y, x]);
this.coords.Add(c);
if (viewerMode)
{
this.normals.Add(new Coord());
this.uvs.Add(new UVCoord(uStep*x, 1.0f - vStep*y));
}
if (y > 0 && x > 0)
{
Face f1, f2;
if (viewerMode)
{
f1 = new Face(p1, p4, p3, p1, p4, p3) {uv1 = p1, uv2 = p4, uv3 = p3};
f2 = new Face(p1, p2, p4, p1, p2, p4) {uv1 = p1, uv2 = p2, uv3 = p4};
}
else
{
f1 = new Face(p1, p4, p3);
f2 = new Face(p1, p2, p4);
}
this.faces.Add(f1);
this.faces.Add(f2);
}
}
}
if (viewerMode)
calcVertexNormals(SculptType.plane, numXElements, numYElements);
}
#if SYSTEM_DRAWING
public SculptMesh(Bitmap sculptBitmap, SculptType sculptType, int lod, bool viewerMode)
{
_SculptMesh(sculptBitmap, sculptType, lod, viewerMode, false, false);
}
public SculptMesh(Bitmap sculptBitmap, SculptType sculptType, int lod, bool viewerMode, bool mirror, bool invert)
{
_SculptMesh(sculptBitmap, sculptType, lod, viewerMode, mirror, invert);
}
#endif
public SculptMesh(List<List<Coord>> rows, SculptType sculptType, bool viewerMode, bool mirror, bool invert)
{
_SculptMesh(rows, sculptType, viewerMode, mirror, invert);
}
#if SYSTEM_DRAWING
/// <summary>
/// converts a bitmap to a list of lists of coords, while scaling the image.
/// the scaling is done in floating point so as to allow for reduced vertex position
/// quantization as the position will be averaged between pixel values. this routine will
/// likely fail if the bitmap width and height are not powers of 2.
/// </summary>
/// <param name = "bitmap"></param>
/// <param name = "scale"></param>
/// <param name = "mirror"></param>
/// <returns></returns>
private List<List<Coord>> bitmap2Coords(Bitmap bitmap, int scale, bool mirror)
{
int numRows = bitmap.Height/scale;
int numCols = bitmap.Width/scale;
List<List<Coord>> rows = new List<List<Coord>>(numRows);
float pixScale = 1.0f/(scale*scale);
pixScale /= 255;
int imageX, imageY = 0;
int rowNdx, colNdx;
FastBitmap unsafeBMP = new FastBitmap(bitmap);
unsafeBMP.LockBitmap(); //Lock the bitmap for the unsafe operation
for (rowNdx = 0; rowNdx < numRows; rowNdx++)
{
List<Coord> row = new List<Coord>(numCols);
for (colNdx = 0; colNdx < numCols; colNdx++)
{
imageX = colNdx*scale;
int imageYStart = rowNdx*scale;
int imageYEnd = imageYStart + scale;
int imageXEnd = imageX + scale;
float rSum = 0.0f;
float gSum = 0.0f;
float bSum = 0.0f;
for (; imageX < imageXEnd; imageX++)
{
for (imageY = imageYStart; imageY < imageYEnd; imageY++)
{
Color pixel = unsafeBMP.GetPixel(imageX, imageY);
if (pixel.A != 255)
{
pixel = Color.FromArgb(255, pixel.R, pixel.G, pixel.B);
unsafeBMP.SetPixel(imageX, imageY, pixel);
}
rSum += pixel.R;
gSum += pixel.G;
bSum += pixel.B;
}
}
row.Add(mirror
? new Coord(-(rSum*pixScale - 0.5f), gSum*pixScale - 0.5f, bSum*pixScale - 0.5f)
: new Coord(rSum*pixScale - 0.5f, gSum*pixScale - 0.5f, bSum*pixScale - 0.5f));
}
rows.Add(row);
}
unsafeBMP.UnlockBitmap();
return rows;
}
private List<List<Coord>> bitmap2CoordsSampled(Bitmap bitmap, int scale, bool mirror)
{
int numRows = bitmap.Height/scale;
int numCols = bitmap.Width/scale;
List<List<Coord>> rows = new List<List<Coord>>(numRows);
float pixScale = 1.0f/256.0f;
int imageX, imageY = 0;
int rowNdx, colNdx;
FastBitmap unsafeBMP = new FastBitmap(bitmap);
unsafeBMP.LockBitmap(); //Lock the bitmap for the unsafe operation
for (rowNdx = 0; rowNdx <= numRows; rowNdx++)
{
List<Coord> row = new List<Coord>(numCols);
imageY = rowNdx*scale;
if (rowNdx == numRows) imageY--;
for (colNdx = 0; colNdx <= numCols; colNdx++)
{
imageX = colNdx*scale;
if (colNdx == numCols) imageX--;
Color pixel = unsafeBMP.GetPixel(imageX, imageY);
if (pixel.A != 255)
{
pixel = Color.FromArgb(255, pixel.R, pixel.G, pixel.B);
unsafeBMP.SetPixel(imageX, imageY, pixel);
}
row.Add(mirror
? new Coord(-(pixel.R*pixScale - 0.5f), pixel.G*pixScale - 0.5f, pixel.B*pixScale - 0.5f)
: new Coord(pixel.R*pixScale - 0.5f, pixel.G*pixScale - 0.5f, pixel.B*pixScale - 0.5f));
}
rows.Add(row);
}
unsafeBMP.UnlockBitmap();
return rows;
}
private void _SculptMesh(Bitmap sculptBitmap, SculptType sculptType, int lod, bool viewerMode, bool mirror,
bool invert)
{
_SculptMesh(new SculptMap(sculptBitmap, lod).ToRows(mirror), sculptType, viewerMode, mirror, invert);
}
#endif
private void _SculptMesh(List<List<Coord>> rows, SculptType sculptType, bool viewerMode, bool mirror,
bool invert)
{
coords = new List<Coord>();
faces = new List<Face>();
normals = new List<Coord>();
uvs = new List<UVCoord>();
sculptType = (SculptType) (((int) sculptType) & 0x07);
if (mirror)
invert = !invert;
viewerFaces = new List<ViewerFace>();
int width = rows[0].Count;
int p1, p2, p3, p4;
int imageX, imageY;
if (sculptType != SculptType.plane)
{
if (rows.Count%2 == 0)
{
foreach (List<Coord> t in rows)
t.Add(t[0]);
}
else
{
int lastIndex = rows[0].Count - 1;
foreach (List<Coord> t in rows)
t[0] = t[lastIndex];
}
}
Coord topPole = rows[0][width/2];
Coord bottomPole = rows[rows.Count - 1][width/2];
if (sculptType == SculptType.sphere)
{
if (rows.Count%2 == 0)
{
int count = rows[0].Count;
List<Coord> topPoleRow = new List<Coord>(count);
List<Coord> bottomPoleRow = new List<Coord>(count);
for (int i = 0; i < count; i++)
{
topPoleRow.Add(topPole);
bottomPoleRow.Add(bottomPole);
}
rows.Insert(0, topPoleRow);
rows.Add(bottomPoleRow);
}
else
{
int count = rows[0].Count;
List<Coord> topPoleRow = rows[0];
List<Coord> bottomPoleRow = rows[rows.Count - 1];
for (int i = 0; i < count; i++)
{
topPoleRow[i] = topPole;
bottomPoleRow[i] = bottomPole;
}
}
}
if (sculptType == SculptType.torus)
rows.Add(rows[0]);
int coordsDown = rows.Count;
int coordsAcross = rows[0].Count;
float widthUnit = 1.0f/(coordsAcross - 1);
float heightUnit = 1.0f/(coordsDown - 1);
for (imageY = 0; imageY < coordsDown; imageY++)
{
int rowOffset = imageY*coordsAcross;
for (imageX = 0; imageX < coordsAcross; imageX++)
{
/*
* p1-----p2
* | \ f2 |
* | \ |
* | f1 \|
* p3-----p4
*/
p4 = rowOffset + imageX;
p3 = p4 - 1;
p2 = p4 - coordsAcross;
p1 = p3 - coordsAcross;
this.coords.Add(rows[imageY][imageX]);
if (viewerMode)
{
this.normals.Add(new Coord());
this.uvs.Add(new UVCoord(widthUnit*imageX, heightUnit*imageY));
}
if (imageY > 0 && imageX > 0)
{
Face f1, f2;
if (viewerMode)
{
if (invert)
{
f1 = new Face(p1, p4, p3, p1, p4, p3) {uv1 = p1, uv2 = p4, uv3 = p3};
f2 = new Face(p1, p2, p4, p1, p2, p4) {uv1 = p1, uv2 = p2, uv3 = p4};
}
else
{
f1 = new Face(p1, p3, p4, p1, p3, p4) {uv1 = p1, uv2 = p3, uv3 = p4};
f2 = new Face(p1, p4, p2, p1, p4, p2) {uv1 = p1, uv2 = p4, uv3 = p2};
}
}
else
{
if (invert)
{
f1 = new Face(p1, p4, p3);
f2 = new Face(p1, p2, p4);
}
else
{
f1 = new Face(p1, p3, p4);
f2 = new Face(p1, p4, p2);
}
}
this.faces.Add(f1);
this.faces.Add(f2);
}
}
}
if (viewerMode)
calcVertexNormals(sculptType, coordsAcross, coordsDown);
}
/// <summary>
/// Duplicates a SculptMesh object. All object properties are copied by value, including lists.
/// </summary>
/// <returns></returns>
public SculptMesh Copy()
{
return new SculptMesh(this);
}
public SculptMesh(SculptMesh sm)
{
coords = new List<Coord>(sm.coords);
faces = new List<Face>(sm.faces);
viewerFaces = new List<ViewerFace>(sm.viewerFaces);
normals = new List<Coord>(sm.normals);
uvs = new List<UVCoord>(sm.uvs);
}
private void calcVertexNormals(SculptType sculptType, int xSize, int ySize)
{
// compute vertex normals by summing all the surface normals of all the triangles sharing
// each vertex and then normalizing
int numFaces = this.faces.Count;
for (int i = 0; i < numFaces; i++)
{
Face face = this.faces[i];
Coord surfaceNormal = face.SurfaceNormal(this.coords);
this.normals[face.n1] += surfaceNormal;
this.normals[face.n2] += surfaceNormal;
this.normals[face.n3] += surfaceNormal;
}
int numNormals = this.normals.Count;
for (int i = 0; i < numNormals; i++)
this.normals[i] = this.normals[i].Normalize();
if (sculptType != SculptType.plane)
{
// blend the vertex normals at the cylinder seam
for (int y = 0; y < ySize; y++)
{
int rowOffset = y*xSize;
this.normals[rowOffset] =
this.normals[rowOffset + xSize - 1] =
(this.normals[rowOffset] + this.normals[rowOffset + xSize - 1]).Normalize();
}
}
#if (!ISWIN)
foreach(Face face in this.faces)
{
ViewerFace vf = new ViewerFace(0)
{
v1 = this.coords[face.v1],
v2 = this.coords[face.v2],
v3 = this.coords[face.v3],
coordIndex1 = face.v1,
coordIndex2 = face.v2,
coordIndex3 = face.v3,
n1 = this.normals[face.n1],
n2 = this.normals[face.n2],
n3 = this.normals[face.n3],
uv1 = this.uvs[face.uv1],
uv2 = this.uvs[face.uv2],
uv3 = this.uvs[face.uv3]
};
this.viewerFaces.Add(vf);
}
#else
foreach (ViewerFace vf in this.faces.Select(face => new ViewerFace(0)
{
v1 = this.coords[face.v1],
v2 = this.coords[face.v2],
v3 = this.coords[face.v3],
coordIndex1 = face.v1,
coordIndex2 = face.v2,
coordIndex3 = face.v3,
n1 = this.normals[face.n1],
n2 = this.normals[face.n2],
n3 = this.normals[face.n3],
uv1 = this.uvs[face.uv1],
uv2 = this.uvs[face.uv2],
uv3 = this.uvs[face.uv3]
}))
{
this.viewerFaces.Add(vf);
}
#endif
}
/// <summary>
/// Adds a value to each XYZ vertex coordinate in the mesh
/// </summary>
/// <param name = "x"></param>
/// <param name = "y"></param>
/// <param name = "z"></param>
public void AddPos(float x, float y, float z)
{
int i;
int numVerts = this.coords.Count;
Coord vert;
for (i = 0; i < numVerts; i++)
{
vert = this.coords[i];
vert.X += x;
vert.Y += y;
vert.Z += z;
this.coords[i] = vert;
}
if (this.viewerFaces != null)
{
int numViewerFaces = this.viewerFaces.Count;
for (i = 0; i < numViewerFaces; i++)
{
ViewerFace v = this.viewerFaces[i];
v.AddPos(x, y, z);
this.viewerFaces[i] = v;
}
}
}
/// <summary>
/// Rotates the mesh
/// </summary>
/// <param name = "q"></param>
public void AddRot(Quat q)
{
int i;
int numVerts = this.coords.Count;
for (i = 0; i < numVerts; i++)
this.coords[i] *= q;
int numNormals = this.normals.Count;
for (i = 0; i < numNormals; i++)
this.normals[i] *= q;
if (this.viewerFaces != null)
{
int numViewerFaces = this.viewerFaces.Count;
for (i = 0; i < numViewerFaces; i++)
{
ViewerFace v = this.viewerFaces[i];
v.v1 *= q;
v.v2 *= q;
v.v3 *= q;
v.n1 *= q;
v.n2 *= q;
v.n3 *= q;
this.viewerFaces[i] = v;
}
}
}
public void Scale(float x, float y, float z)
{
int i;
int numVerts = this.coords.Count;
Coord m = new Coord(x, y, z);
for (i = 0; i < numVerts; i++)
this.coords[i] *= m;
if (this.viewerFaces != null)
{
int numViewerFaces = this.viewerFaces.Count;
for (i = 0; i < numViewerFaces; i++)
{
ViewerFace v = this.viewerFaces[i];
v.v1 *= m;
v.v2 *= m;
v.v3 *= m;
this.viewerFaces[i] = v;
}
}
}
public void DumpRaw(String path, String name, String title)
{
if (path == null)
return;
String fileName = name + "_" + title + ".raw";
String completePath = System.IO.Path.Combine(path, fileName);
StreamWriter sw = new StreamWriter(completePath);
for (int i = 0; i < this.faces.Count; i++)
{
string s = this.coords[this.faces[i].v1].ToString();
s += " " + this.coords[this.faces[i].v2].ToString();
s += " " + this.coords[this.faces[i].v3].ToString();
sw.WriteLine(s);
}
sw.Close();
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.Venus;
using Microsoft.VisualStudio.Shell;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.TaskList
{
[Export(typeof(IDiagnosticUpdateSource))]
[Export(typeof(ExternalErrorDiagnosticUpdateSource))]
internal class ExternalErrorDiagnosticUpdateSource : IDiagnosticUpdateSource
{
private readonly Workspace _workspace;
private readonly IDiagnosticAnalyzerService _diagnosticService;
private readonly IGlobalOperationNotificationService _notificationService;
private readonly SimpleTaskQueue _taskQueue;
private readonly IAsynchronousOperationListener _listener;
private InprogressState _state = null;
[ImportingConstructor]
public ExternalErrorDiagnosticUpdateSource(
VisualStudioWorkspaceImpl workspace,
IDiagnosticAnalyzerService diagnosticService,
[ImportMany] IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> asyncListeners) :
this(workspace, diagnosticService, new AggregateAsynchronousOperationListener(asyncListeners, FeatureAttribute.ErrorList))
{
Contract.Requires(!KnownUIContexts.SolutionBuildingContext.IsActive);
KnownUIContexts.SolutionBuildingContext.UIContextChanged += OnSolutionBuild;
}
/// <summary>
/// internal for testing
/// </summary>
internal ExternalErrorDiagnosticUpdateSource(
Workspace workspace,
IDiagnosticAnalyzerService diagnosticService,
IAsynchronousOperationListener listener)
{
// use queue to serialize work. no lock needed
_taskQueue = new SimpleTaskQueue(TaskScheduler.Default);
_listener = listener;
_workspace = workspace;
_workspace.WorkspaceChanged += OnWorkspaceChanged;
_diagnosticService = diagnosticService;
_notificationService = _workspace.Services.GetService<IGlobalOperationNotificationService>();
}
public event EventHandler<DiagnosticsUpdatedArgs> DiagnosticsUpdated;
private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs e)
{
switch (e.Kind)
{
case WorkspaceChangeKind.SolutionAdded:
case WorkspaceChangeKind.SolutionRemoved:
case WorkspaceChangeKind.SolutionCleared:
case WorkspaceChangeKind.SolutionReloaded:
{
var asyncToken = _listener.BeginAsyncOperation("OnSolutionChanged");
_taskQueue.ScheduleTask(() => e.OldSolution.ProjectIds.Do(p => ClearProjectErrors(p, e.OldSolution))).CompletesAsyncOperation(asyncToken);
break;
}
case WorkspaceChangeKind.ProjectRemoved:
case WorkspaceChangeKind.ProjectReloaded:
{
var asyncToken = _listener.BeginAsyncOperation("OnProjectChanged");
_taskQueue.ScheduleTask(() => ClearProjectErrors(e.ProjectId, e.OldSolution)).CompletesAsyncOperation(asyncToken);
break;
}
case WorkspaceChangeKind.DocumentRemoved:
case WorkspaceChangeKind.DocumentReloaded:
{
var asyncToken = _listener.BeginAsyncOperation("OnDocumentRemoved");
_taskQueue.ScheduleTask(() => ClearDocumentErrors(e.ProjectId, e.DocumentId)).CompletesAsyncOperation(asyncToken);
break;
}
case WorkspaceChangeKind.ProjectAdded:
case WorkspaceChangeKind.DocumentAdded:
case WorkspaceChangeKind.DocumentChanged:
case WorkspaceChangeKind.ProjectChanged:
case WorkspaceChangeKind.SolutionChanged:
case WorkspaceChangeKind.AdditionalDocumentAdded:
case WorkspaceChangeKind.AdditionalDocumentRemoved:
case WorkspaceChangeKind.AdditionalDocumentReloaded:
case WorkspaceChangeKind.AdditionalDocumentChanged:
break;
default:
Contract.Fail("Unknown workspace events");
break;
}
}
internal void OnSolutionBuild(object sender, UIContextChangedEventArgs e)
{
if (e.Activated)
{
return;
}
// get local copy of inprogress state
var inprogressState = _state;
// building is done. reset the state.
_state = null;
// enqueue build/live sync in the queue.
var asyncToken = _listener.BeginAsyncOperation("OnSolutionBuild");
_taskQueue.ScheduleTask(async () =>
{
// nothing to do
if (inprogressState == null)
{
return;
}
// we are about to update live analyzer data using one from build.
// pause live analyzer
using (var operation = _notificationService.Start("BuildDone"))
{
// we will have a race here since we can't track version of solution the out of proc build actually used.
// result of the race will be us dropping some diagnostics from the build to the floor.
var solution = _workspace.CurrentSolution;
await CleanupAllLiveErrorsIfNeededAsync(solution, inprogressState).ConfigureAwait(false);
var supportedIdMap = GetSupportedLiveDiagnosticId(solution, inprogressState);
Func<DiagnosticData, bool> liveDiagnosticChecker = d =>
{
// REVIEW: we probably need a better design on de-duplicating live and build errors. or don't de-dup at all.
// for now, we are special casing compiler error case.
var project = solution.GetProject(d.ProjectId);
if (project == null)
{
// project doesn't exist
return false;
}
// REVIEW: current design is that we special case compiler analyzer case and we accept only document level
// diagnostic as live. otherwise, we let them be build errors. we changed compiler analyzer accordingly as well
// so that it doesn't report project level diagnostic as live errors.
if (_diagnosticService.IsCompilerDiagnostic(project.Language, d) && d.DocumentId == null)
{
// compiler error but project level error
return false;
}
HashSet<string> set;
if (supportedIdMap.TryGetValue(d.ProjectId, out set) && set.Contains(d.Id))
{
return true;
}
return false;
};
await SyncBuildErrorsAndReportAsync(solution, liveDiagnosticChecker, inprogressState.GetDocumentAndErrors(solution)).ConfigureAwait(false);
await SyncBuildErrorsAndReportAsync(solution, liveDiagnosticChecker, inprogressState.GetProjectAndErrors(solution)).ConfigureAwait(false);
}
}).CompletesAsyncOperation(asyncToken);
}
private async System.Threading.Tasks.Task CleanupAllLiveErrorsIfNeededAsync(Solution solution, InprogressState state)
{
var buildErrorIsTheGod = _workspace.Options.GetOption(InternalDiagnosticsOptions.BuildErrorIsTheGod);
var clearProjectErrors = _workspace.Options.GetOption(InternalDiagnosticsOptions.ClearLiveErrorsForProjectBuilt);
if (!buildErrorIsTheGod && !clearProjectErrors)
{
return;
}
var projects = buildErrorIsTheGod ? solution.Projects :
(clearProjectErrors ? state.GetProjectsBuilt(solution) : SpecializedCollections.EmptyEnumerable<Project>());
// clear all live errors
foreach (var project in projects)
{
foreach (var document in project.Documents)
{
await SynchronizeWithBuildAsync(document, ImmutableArray<DiagnosticData>.Empty).ConfigureAwait(false);
}
await SynchronizeWithBuildAsync(project, ImmutableArray<DiagnosticData>.Empty).ConfigureAwait(false);
}
}
private async System.Threading.Tasks.Task SyncBuildErrorsAndReportAsync<T>(
Solution solution,
Func<DiagnosticData, bool> liveDiagnosticChecker, IEnumerable<KeyValuePair<T, HashSet<DiagnosticData>>> items)
{
foreach (var kv in items)
{
// get errors that can be reported by live diagnostic analyzer
var liveErrors = kv.Value.Where(liveDiagnosticChecker).ToImmutableArray();
// make those errors live errors
await SynchronizeWithBuildAsync(kv.Key, liveErrors).ConfigureAwait(false);
// raise events for ones left-out
if (liveErrors.Length != kv.Value.Count)
{
var buildErrors = kv.Value.Except(liveErrors).ToImmutableArray();
ReportBuildErrors(kv.Key, buildErrors);
}
}
}
private async System.Threading.Tasks.Task SynchronizeWithBuildAsync<T>(T item, ImmutableArray<DiagnosticData> liveErrors)
{
var diagnosticService = _diagnosticService as DiagnosticAnalyzerService;
if (diagnosticService == null)
{
// we don't synchronize if implementation is not DiagnosticAnalyzerService
return;
}
var project = item as Project;
if (project != null)
{
await diagnosticService.SynchronizeWithBuildAsync(project, liveErrors).ConfigureAwait(false);
return;
}
// must be not null
var document = item as Document;
await diagnosticService.SynchronizeWithBuildAsync(document, liveErrors).ConfigureAwait(false);
}
private void ReportBuildErrors<T>(T item, ImmutableArray<DiagnosticData> buildErrors)
{
var project = item as Project;
if (project != null)
{
RaiseDiagnosticsUpdated(project.Id, project.Id, null, buildErrors);
return;
}
// must be not null
var document = item as Document;
RaiseDiagnosticsUpdated(document.Id, document.Project.Id, document.Id, buildErrors);
}
private Dictionary<ProjectId, HashSet<string>> GetSupportedLiveDiagnosticId(Solution solution, InprogressState state)
{
var map = new Dictionary<ProjectId, HashSet<string>>();
// here, we don't care about perf that much since build is already expensive work
foreach (var project in state.GetProjectsWithErrors(solution))
{
var descriptorMap = _diagnosticService.GetDiagnosticDescriptors(project);
map.Add(project.Id, new HashSet<string>(descriptorMap.Values.SelectMany(v => v.Select(d => d.Id))));
}
return map;
}
public void ClearErrors(ProjectId projectId)
{
var asyncToken = _listener.BeginAsyncOperation("ClearErrors");
_taskQueue.ScheduleTask(() =>
{
var state = GetOrCreateInprogressState();
state.Built(projectId);
ClearProjectErrors(projectId);
}).CompletesAsyncOperation(asyncToken);
}
private void ClearProjectErrors(ProjectId projectId, Solution solution = null)
{
// remove all project errors
RaiseDiagnosticsUpdated(projectId, projectId, null, ImmutableArray<DiagnosticData>.Empty);
var project = (solution ?? _workspace.CurrentSolution).GetProject(projectId);
if (project == null)
{
return;
}
// remove all document errors
foreach (var documentId in project.DocumentIds)
{
ClearDocumentErrors(projectId, documentId);
}
}
private void ClearDocumentErrors(ProjectId projectId, DocumentId documentId)
{
RaiseDiagnosticsUpdated(documentId, projectId, documentId, ImmutableArray<DiagnosticData>.Empty);
}
public void AddNewErrors(DocumentId documentId, DiagnosticData diagnostic)
{
var asyncToken = _listener.BeginAsyncOperation("Document New Errors");
_taskQueue.ScheduleTask(() =>
{
GetOrCreateInprogressState().AddError(documentId, diagnostic);
}).CompletesAsyncOperation(asyncToken);
}
public void AddNewErrors(
ProjectId projectId, HashSet<DiagnosticData> projectErrors, Dictionary<DocumentId, HashSet<DiagnosticData>> documentErrorMap)
{
var asyncToken = _listener.BeginAsyncOperation("Project New Errors");
_taskQueue.ScheduleTask(() =>
{
var state = GetOrCreateInprogressState();
foreach (var kv in documentErrorMap)
{
state.AddErrors(kv.Key, kv.Value);
}
state.AddErrors(projectId, projectErrors);
}).CompletesAsyncOperation(asyncToken);
}
private InprogressState GetOrCreateInprogressState()
{
if (_state == null)
{
_state = new InprogressState();
}
return _state;
}
private void RaiseDiagnosticsUpdated(object id, ProjectId projectId, DocumentId documentId, ImmutableArray<DiagnosticData> items)
{
var diagnosticsUpdated = DiagnosticsUpdated;
if (diagnosticsUpdated != null)
{
diagnosticsUpdated(this, new DiagnosticsUpdatedArgs(
new ArgumentKey(id), _workspace, _workspace.CurrentSolution, projectId, documentId, items));
}
}
#region not supported
public bool SupportGetDiagnostics { get { return false; } }
public ImmutableArray<DiagnosticData> GetDiagnostics(
Workspace workspace, ProjectId projectId, DocumentId documentId, object id, CancellationToken cancellationToken)
{
return ImmutableArray<DiagnosticData>.Empty;
}
#endregion
private class InprogressState
{
private readonly HashSet<ProjectId> _builtProjects = new HashSet<ProjectId>();
private readonly Dictionary<ProjectId, HashSet<DiagnosticData>> _projectMap = new Dictionary<ProjectId, HashSet<DiagnosticData>>();
private readonly Dictionary<DocumentId, HashSet<DiagnosticData>> _documentMap = new Dictionary<DocumentId, HashSet<DiagnosticData>>();
public void Built(ProjectId projectId)
{
_builtProjects.Add(projectId);
}
public IEnumerable<Project> GetProjectsBuilt(Solution solution)
{
return solution.Projects.Where(p => _builtProjects.Contains(p.Id));
}
public IEnumerable<Project> GetProjectsWithErrors(Solution solution)
{
foreach (var projectId in _documentMap.Keys.Select(k => k.ProjectId).Concat(_projectMap.Keys).Distinct())
{
var project = solution.GetProject(projectId);
if (project == null)
{
continue;
}
yield return project;
}
}
public IEnumerable<KeyValuePair<Document, HashSet<DiagnosticData>>> GetDocumentAndErrors(Solution solution)
{
foreach (var kv in _documentMap)
{
var document = solution.GetDocument(kv.Key);
if (document == null)
{
continue;
}
yield return KeyValuePair.Create(document, kv.Value);
}
}
public IEnumerable<KeyValuePair<Project, HashSet<DiagnosticData>>> GetProjectAndErrors(Solution solution)
{
foreach (var kv in _projectMap)
{
var project = solution.GetProject(kv.Key);
if (project == null)
{
continue;
}
yield return KeyValuePair.Create(project, kv.Value);
}
}
public void AddErrors(DocumentId key, HashSet<DiagnosticData> diagnostics)
{
AddErrors(_documentMap, key, diagnostics);
}
public void AddErrors(ProjectId key, HashSet<DiagnosticData> diagnostics)
{
AddErrors(_projectMap, key, diagnostics);
}
public void AddError(DocumentId key, DiagnosticData diagnostic)
{
AddError(_documentMap, key, diagnostic);
}
private void AddErrors<T>(Dictionary<T, HashSet<DiagnosticData>> map, T key, HashSet<DiagnosticData> diagnostics)
{
var errors = GetErrors(map, key);
errors.UnionWith(diagnostics);
}
private void AddError<T>(Dictionary<T, HashSet<DiagnosticData>> map, T key, DiagnosticData diagnostic)
{
var errors = GetErrors(map, key);
errors.Add(diagnostic);
}
private HashSet<DiagnosticData> GetErrors<T>(Dictionary<T, HashSet<DiagnosticData>> map, T key)
{
return map.GetOrAdd(key, _ => new HashSet<DiagnosticData>(DiagnosticDataComparer.Instance));
}
}
private class ArgumentKey : ErrorSourceId.Base<object>
{
public ArgumentKey(object key) : base(key)
{
}
public override string ErrorSource
{
get { return PredefinedErrorSources.Build; }
}
public override bool Equals(object obj)
{
var other = obj as ArgumentKey;
if (other == null)
{
return false;
}
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
private class DiagnosticDataComparer : IEqualityComparer<DiagnosticData>
{
public static readonly DiagnosticDataComparer Instance = new DiagnosticDataComparer();
public bool Equals(DiagnosticData item1, DiagnosticData item2)
{
// crash if any one of them is NULL
if ((IsNull(item1.DocumentId) ^ IsNull(item2.DocumentId)) ||
(IsNull(item1.ProjectId) ^ IsNull(item2.ProjectId)))
{
return false;
}
if (item1.DocumentId != null && item2.DocumentId != null)
{
var lineColumn1 = GetOriginalOrMappedLineColumn(item1);
var lineColumn2 = GetOriginalOrMappedLineColumn(item2);
return item1.Id == item2.Id &&
item1.Message == item2.Message &&
item1.ProjectId == item2.ProjectId &&
item1.DocumentId == item2.DocumentId &&
lineColumn1.Item1 == lineColumn2.Item1 &&
lineColumn1.Item2 == lineColumn2.Item2 &&
item1.Severity == item2.Severity;
}
return item1.Id == item2.Id &&
item1.Message == item2.Message &&
item1.ProjectId == item2.ProjectId &&
item1.Severity == item2.Severity;
}
public int GetHashCode(DiagnosticData obj)
{
if (obj.DocumentId != null)
{
var lineColumn = GetOriginalOrMappedLineColumn(obj);
return Hash.Combine(obj.Id,
Hash.Combine(obj.Message,
Hash.Combine(obj.ProjectId,
Hash.Combine(obj.DocumentId,
Hash.Combine(lineColumn.Item1,
Hash.Combine(lineColumn.Item2, (int)obj.Severity))))));
}
return Hash.Combine(obj.Id,
Hash.Combine(obj.Message,
Hash.Combine(obj.ProjectId, (int)obj.Severity)));
}
private static ValueTuple<int, int> GetOriginalOrMappedLineColumn(DiagnosticData data)
{
var workspace = data.Workspace as VisualStudioWorkspaceImpl;
if (workspace == null)
{
return ValueTuple.Create(data.MappedStartLine, data.MappedStartColumn);
}
var containedDocument = workspace.GetHostDocument(data.DocumentId) as ContainedDocument;
if (containedDocument == null)
{
return ValueTuple.Create(data.MappedStartLine, data.MappedStartColumn);
}
return ValueTuple.Create(data.OriginalStartLine, data.OriginalStartColumn);
}
private bool IsNull<T>(T item) where T : class
{
return item == null;
}
}
}
}
| |
namespace EIDSS.Reports.Document.Uni.Outbreak
{
partial class OutbreakReport
{
#region Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(OutbreakReport));
this.OutbreakDataSet = new EIDSS.Reports.Document.Uni.Outbreak.OutBreakDataSet();
this.OutbreakAdapter = new EIDSS.Reports.Document.Uni.Outbreak.OutBreakDataSetTableAdapters.OutbreakAdapter();
this.OutbreakNotesAdapter = new EIDSS.Reports.Document.Uni.Outbreak.OutBreakDataSetTableAdapters.OutbreakNotesAdapter();
this.xrTable1 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTable2 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow4 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTable4 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow5 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell35 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell38 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell37 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell41 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTable5 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow10 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTable6 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow11 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow12 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell();
this.SourceOfCaseSessionCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell40 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell39 = new DevExpress.XtraReports.UI.XRTableCell();
this.AddressCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell42 = new DevExpress.XtraReports.UI.XRTableCell();
this.DetailReport = new DevExpress.XtraReports.UI.DetailReportBand();
this.DetailOutbreak = new DevExpress.XtraReports.UI.DetailBand();
this.xrTable3 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow6 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell();
this.OutbreakDateCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow8 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell24 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow7 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell22 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell23 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTable7 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow9 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell25 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell26 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTable8 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow13 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell27 = new DevExpress.XtraReports.UI.XRTableCell();
this.RelatedReportsCell = new DevExpress.XtraReports.UI.XRTableCell();
this.DetailReport1 = new DevExpress.XtraReports.UI.DetailReportBand();
this.Detail2 = new DevExpress.XtraReports.UI.DetailBand();
this.xrTable10 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow15 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell33 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell34 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell29 = new DevExpress.XtraReports.UI.XRTableCell();
this.ReportHeader1 = new DevExpress.XtraReports.UI.ReportHeaderBand();
this.xrTable9 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow14 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell28 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow16 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell32 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell31 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell30 = new DevExpress.XtraReports.UI.XRTableCell();
((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.OutbreakDataSet)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable4)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable5)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable6)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable3)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable7)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable8)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable10)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable9)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// cellLanguage
//
this.cellLanguage.StylePriority.UseTextAlignment = false;
//
// lblReportName
//
resources.ApplyResources(this.lblReportName, "lblReportName");
this.lblReportName.StylePriority.UseBorders = false;
this.lblReportName.StylePriority.UseBorderWidth = false;
this.lblReportName.StylePriority.UseFont = false;
this.lblReportName.StylePriority.UseTextAlignment = false;
//
// Detail
//
this.Detail.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.Detail, "Detail");
this.Detail.StylePriority.UseBorders = false;
this.Detail.StylePriority.UseFont = false;
this.Detail.StylePriority.UsePadding = false;
this.Detail.StylePriority.UseTextAlignment = false;
//
// PageHeader
//
this.PageHeader.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.PageHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable4});
resources.ApplyResources(this.PageHeader, "PageHeader");
this.PageHeader.StylePriority.UseBorders = false;
this.PageHeader.StylePriority.UseFont = false;
this.PageHeader.StylePriority.UsePadding = false;
this.PageHeader.StylePriority.UseTextAlignment = false;
//
// PageFooter
//
resources.ApplyResources(this.PageFooter, "PageFooter");
this.PageFooter.StylePriority.UseBorders = false;
//
// ReportHeader
//
this.ReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable8,
this.xrTable7,
this.xrTable3,
this.xrTable2,
this.xrTable1});
resources.ApplyResources(this.ReportHeader, "ReportHeader");
this.ReportHeader.Controls.SetChildIndex(this.tableBaseHeader, 0);
this.ReportHeader.Controls.SetChildIndex(this.xrTable1, 0);
this.ReportHeader.Controls.SetChildIndex(this.xrTable2, 0);
this.ReportHeader.Controls.SetChildIndex(this.xrTable3, 0);
this.ReportHeader.Controls.SetChildIndex(this.xrTable7, 0);
this.ReportHeader.Controls.SetChildIndex(this.xrTable8, 0);
//
// xrPageInfo1
//
resources.ApplyResources(this.xrPageInfo1, "xrPageInfo1");
this.xrPageInfo1.StylePriority.UseBorders = false;
//
// cellReportHeader
//
this.cellReportHeader.StylePriority.UseBorders = false;
this.cellReportHeader.StylePriority.UseFont = false;
this.cellReportHeader.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.cellReportHeader, "cellReportHeader");
//
// cellBaseSite
//
this.cellBaseSite.StylePriority.UseBorders = false;
this.cellBaseSite.StylePriority.UseFont = false;
this.cellBaseSite.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.cellBaseSite, "cellBaseSite");
//
// cellBaseCountry
//
resources.ApplyResources(this.cellBaseCountry, "cellBaseCountry");
//
// cellBaseLeftHeader
//
resources.ApplyResources(this.cellBaseLeftHeader, "cellBaseLeftHeader");
//
// tableBaseHeader
//
resources.ApplyResources(this.tableBaseHeader, "tableBaseHeader");
this.tableBaseHeader.StylePriority.UseBorders = false;
this.tableBaseHeader.StylePriority.UseBorderWidth = false;
this.tableBaseHeader.StylePriority.UseFont = false;
this.tableBaseHeader.StylePriority.UsePadding = false;
this.tableBaseHeader.StylePriority.UseTextAlignment = false;
//
// OutbreakDataSet
//
this.OutbreakDataSet.DataSetName = "OutBreakDataSet";
this.OutbreakDataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// OutbreakAdapter
//
this.OutbreakAdapter.ClearBeforeFill = true;
//
// OutbreakNotesAdapter
//
this.OutbreakNotesAdapter.ClearBeforeFill = true;
//
// xrTable1
//
resources.ApplyResources(this.xrTable1, "xrTable1");
this.xrTable1.Name = "xrTable1";
this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow1,
this.xrTableRow2});
this.xrTable1.StylePriority.UseTextAlignment = false;
//
// xrTableRow1
//
this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell1,
this.xrTableCell3});
this.xrTableRow1.Name = "xrTableRow1";
resources.ApplyResources(this.xrTableRow1, "xrTableRow1");
//
// xrTableCell1
//
this.xrTableCell1.Name = "xrTableCell1";
resources.ApplyResources(this.xrTableCell1, "xrTableCell1");
//
// xrTableCell3
//
this.xrTableCell3.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.OutbreakDataSet, "OutbreakReport.strOutbreakID", "*{0}*")});
resources.ApplyResources(this.xrTableCell3, "xrTableCell3");
this.xrTableCell3.Name = "xrTableCell3";
this.xrTableCell3.StylePriority.UseFont = false;
this.xrTableCell3.StylePriority.UseTextAlignment = false;
//
// xrTableRow2
//
this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell2,
this.xrTableCell4});
this.xrTableRow2.Name = "xrTableRow2";
resources.ApplyResources(this.xrTableRow2, "xrTableRow2");
//
// xrTableCell2
//
this.xrTableCell2.Name = "xrTableCell2";
resources.ApplyResources(this.xrTableCell2, "xrTableCell2");
//
// xrTableCell4
//
this.xrTableCell4.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell4.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.OutbreakDataSet, "OutbreakReport.strOutbreakID")});
this.xrTableCell4.Name = "xrTableCell4";
this.xrTableCell4.StylePriority.UseBorders = false;
this.xrTableCell4.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell4, "xrTableCell4");
//
// xrTable2
//
resources.ApplyResources(this.xrTable2, "xrTable2");
this.xrTable2.Name = "xrTable2";
this.xrTable2.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow3});
//
// xrTableRow3
//
this.xrTableRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell5,
this.xrTableCell6});
this.xrTableRow3.Name = "xrTableRow3";
resources.ApplyResources(this.xrTableRow3, "xrTableRow3");
//
// xrTableCell5
//
this.xrTableCell5.Name = "xrTableCell5";
this.xrTableCell5.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell5, "xrTableCell5");
//
// xrTableCell6
//
this.xrTableCell6.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell6.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.OutbreakDataSet, "OutbreakReport.strOutbreakDiagnosis")});
this.xrTableCell6.Name = "xrTableCell6";
this.xrTableCell6.StylePriority.UseBorders = false;
this.xrTableCell6.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell6, "xrTableCell6");
//
// xrTableRow4
//
this.xrTableRow4.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell7,
this.xrTableCell8});
this.xrTableRow4.Name = "xrTableRow4";
resources.ApplyResources(this.xrTableRow4, "xrTableRow4");
//
// xrTableCell7
//
this.xrTableCell7.Name = "xrTableCell7";
resources.ApplyResources(this.xrTableCell7, "xrTableCell7");
//
// xrTableCell8
//
this.xrTableCell8.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.OutbreakDataSet, "spRepUniOutbreakReport.OutbreakStatus")});
this.xrTableCell8.Name = "xrTableCell8";
resources.ApplyResources(this.xrTableCell8, "xrTableCell8");
//
// xrTable4
//
resources.ApplyResources(this.xrTable4, "xrTable4");
this.xrTable4.Name = "xrTable4";
this.xrTable4.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow5});
//
// xrTableRow5
//
this.xrTableRow5.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell9,
this.xrTableCell12,
this.xrTableCell10,
this.xrTableCell35,
this.xrTableCell13,
this.xrTableCell38,
this.xrTableCell37,
this.xrTableCell11,
this.xrTableCell41});
this.xrTableRow5.Name = "xrTableRow5";
resources.ApplyResources(this.xrTableRow5, "xrTableRow5");
//
// xrTableCell9
//
this.xrTableCell9.Name = "xrTableCell9";
resources.ApplyResources(this.xrTableCell9, "xrTableCell9");
//
// xrTableCell12
//
this.xrTableCell12.Name = "xrTableCell12";
resources.ApplyResources(this.xrTableCell12, "xrTableCell12");
//
// xrTableCell10
//
this.xrTableCell10.Name = "xrTableCell10";
resources.ApplyResources(this.xrTableCell10, "xrTableCell10");
//
// xrTableCell35
//
this.xrTableCell35.Name = "xrTableCell35";
resources.ApplyResources(this.xrTableCell35, "xrTableCell35");
//
// xrTableCell13
//
this.xrTableCell13.Name = "xrTableCell13";
resources.ApplyResources(this.xrTableCell13, "xrTableCell13");
//
// xrTableCell38
//
this.xrTableCell38.Name = "xrTableCell38";
resources.ApplyResources(this.xrTableCell38, "xrTableCell38");
//
// xrTableCell37
//
this.xrTableCell37.Name = "xrTableCell37";
resources.ApplyResources(this.xrTableCell37, "xrTableCell37");
//
// xrTableCell11
//
this.xrTableCell11.Name = "xrTableCell11";
resources.ApplyResources(this.xrTableCell11, "xrTableCell11");
//
// xrTableCell41
//
this.xrTableCell41.Name = "xrTableCell41";
resources.ApplyResources(this.xrTableCell41, "xrTableCell41");
//
// xrTable5
//
resources.ApplyResources(this.xrTable5, "xrTable5");
this.xrTable5.Name = "xrTable5";
this.xrTable5.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow10});
//
// xrTableRow10
//
this.xrTableRow10.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell14,
this.xrTableCell15,
this.xrTableCell16,
this.SourceOfCaseSessionCell,
this.xrTableCell17,
this.xrTableCell40,
this.xrTableCell39,
this.AddressCell,
this.xrTableCell42});
this.xrTableRow10.Name = "xrTableRow10";
resources.ApplyResources(this.xrTableRow10, "xrTableRow10");
//
// xrTableCell14
//
this.xrTableCell14.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable6});
this.xrTableCell14.Name = "xrTableCell14";
resources.ApplyResources(this.xrTableCell14, "xrTableCell14");
//
// xrTable6
//
resources.ApplyResources(this.xrTable6, "xrTable6");
this.xrTable6.Name = "xrTable6";
this.xrTable6.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow11,
this.xrTableRow12});
//
// xrTableRow11
//
this.xrTableRow11.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell21});
this.xrTableRow11.Name = "xrTableRow11";
resources.ApplyResources(this.xrTableRow11, "xrTableRow11");
//
// xrTableCell21
//
this.xrTableCell21.Borders = DevExpress.XtraPrinting.BorderSide.None;
this.xrTableCell21.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "OutbreakReport.strCaseSessionID", "*{0}*")});
resources.ApplyResources(this.xrTableCell21, "xrTableCell21");
this.xrTableCell21.Name = "xrTableCell21";
this.xrTableCell21.StylePriority.UseBorders = false;
this.xrTableCell21.StylePriority.UseFont = false;
//
// xrTableRow12
//
this.xrTableRow12.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell19});
this.xrTableRow12.Name = "xrTableRow12";
resources.ApplyResources(this.xrTableRow12, "xrTableRow12");
//
// xrTableCell19
//
this.xrTableCell19.Borders = DevExpress.XtraPrinting.BorderSide.None;
this.xrTableCell19.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "OutbreakReport.strCaseSessionID")});
this.xrTableCell19.Name = "xrTableCell19";
this.xrTableCell19.StylePriority.UseBorders = false;
this.xrTableCell19.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell19, "xrTableCell19");
//
// xrTableCell15
//
this.xrTableCell15.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "OutbreakReport.strCaseSessionType")});
this.xrTableCell15.Name = "xrTableCell15";
resources.ApplyResources(this.xrTableCell15, "xrTableCell15");
//
// xrTableCell16
//
this.xrTableCell16.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "OutbreakReport.datCaseSessionDate", "{0:dd/MM/yyyy}")});
this.xrTableCell16.Name = "xrTableCell16";
resources.ApplyResources(this.xrTableCell16, "xrTableCell16");
//
// SourceOfCaseSessionCell
//
this.SourceOfCaseSessionCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "OutbreakReport.strCaseSessionCalculatedSourceOfDate")});
this.SourceOfCaseSessionCell.Name = "SourceOfCaseSessionCell";
resources.ApplyResources(this.SourceOfCaseSessionCell, "SourceOfCaseSessionCell");
//
// xrTableCell17
//
this.xrTableCell17.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "OutbreakReport.strCaseSessionClassification")});
this.xrTableCell17.Name = "xrTableCell17";
resources.ApplyResources(this.xrTableCell17, "xrTableCell17");
//
// xrTableCell40
//
this.xrTableCell40.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "OutbreakReport.strCaseSessionDiagnosis")});
this.xrTableCell40.Name = "xrTableCell40";
resources.ApplyResources(this.xrTableCell40, "xrTableCell40");
//
// xrTableCell39
//
this.xrTableCell39.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "OutbreakReport.strCaseSessionLocation")});
this.xrTableCell39.Name = "xrTableCell39";
resources.ApplyResources(this.xrTableCell39, "xrTableCell39");
//
// AddressCell
//
this.AddressCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "OutbreakReport.strCaseSessionCalculatedAddress")});
this.AddressCell.Name = "AddressCell";
resources.ApplyResources(this.AddressCell, "AddressCell");
//
// xrTableCell42
//
this.xrTableCell42.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "OutbreakReport.strPatientFarmOwner")});
this.xrTableCell42.Name = "xrTableCell42";
resources.ApplyResources(this.xrTableCell42, "xrTableCell42");
//
// DetailReport
//
this.DetailReport.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.DetailOutbreak});
this.DetailReport.DataAdapter = this.OutbreakAdapter;
this.DetailReport.DataMember = "OutbreakReport";
this.DetailReport.DataSource = this.OutbreakDataSet;
this.DetailReport.Level = 0;
this.DetailReport.Name = "DetailReport";
//
// DetailOutbreak
//
this.DetailOutbreak.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.DetailOutbreak.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable5});
resources.ApplyResources(this.DetailOutbreak, "DetailOutbreak");
this.DetailOutbreak.Name = "DetailOutbreak";
this.DetailOutbreak.StylePriority.UseBorders = false;
this.DetailOutbreak.StylePriority.UseTextAlignment = false;
//
// xrTable3
//
resources.ApplyResources(this.xrTable3, "xrTable3");
this.xrTable3.Name = "xrTable3";
this.xrTable3.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow6,
this.xrTableRow8,
this.xrTableRow7});
this.xrTable3.StylePriority.UseTextAlignment = false;
//
// xrTableRow6
//
this.xrTableRow6.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell18,
this.OutbreakDateCell});
this.xrTableRow6.Name = "xrTableRow6";
resources.ApplyResources(this.xrTableRow6, "xrTableRow6");
//
// xrTableCell18
//
this.xrTableCell18.Name = "xrTableCell18";
this.xrTableCell18.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell18, "xrTableCell18");
//
// OutbreakDateCell
//
this.OutbreakDateCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.OutbreakDateCell.Name = "OutbreakDateCell";
this.OutbreakDateCell.StylePriority.UseBorders = false;
this.OutbreakDateCell.StylePriority.UseFont = false;
this.OutbreakDateCell.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.OutbreakDateCell, "OutbreakDateCell");
//
// xrTableRow8
//
this.xrTableRow8.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell20,
this.xrTableCell24});
this.xrTableRow8.Name = "xrTableRow8";
resources.ApplyResources(this.xrTableRow8, "xrTableRow8");
//
// xrTableCell20
//
this.xrTableCell20.Name = "xrTableCell20";
resources.ApplyResources(this.xrTableCell20, "xrTableCell20");
//
// xrTableCell24
//
this.xrTableCell24.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "sprepGetBaseParameters.strDateFormat")});
resources.ApplyResources(this.xrTableCell24, "xrTableCell24");
this.xrTableCell24.Name = "xrTableCell24";
this.xrTableCell24.StylePriority.UseFont = false;
this.xrTableCell24.StylePriority.UseTextAlignment = false;
//
// xrTableRow7
//
this.xrTableRow7.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell22,
this.xrTableCell23});
this.xrTableRow7.Name = "xrTableRow7";
resources.ApplyResources(this.xrTableRow7, "xrTableRow7");
//
// xrTableCell22
//
this.xrTableCell22.Name = "xrTableCell22";
this.xrTableCell22.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell22, "xrTableCell22");
//
// xrTableCell23
//
this.xrTableCell23.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell23.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.OutbreakDataSet, "OutbreakReport.strOutbreakLocation")});
this.xrTableCell23.Name = "xrTableCell23";
this.xrTableCell23.StylePriority.UseBorders = false;
this.xrTableCell23.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell23, "xrTableCell23");
//
// xrTable7
//
resources.ApplyResources(this.xrTable7, "xrTable7");
this.xrTable7.Name = "xrTable7";
this.xrTable7.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow9});
//
// xrTableRow9
//
this.xrTableRow9.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell25,
this.xrTableCell26});
this.xrTableRow9.Name = "xrTableRow9";
this.xrTableRow9.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableRow9, "xrTableRow9");
//
// xrTableCell25
//
this.xrTableCell25.Name = "xrTableCell25";
resources.ApplyResources(this.xrTableCell25, "xrTableCell25");
//
// xrTableCell26
//
this.xrTableCell26.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell26.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.OutbreakDataSet, "OutbreakReport.strOutbreakDescription")});
this.xrTableCell26.Name = "xrTableCell26";
this.xrTableCell26.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell26, "xrTableCell26");
//
// xrTable8
//
resources.ApplyResources(this.xrTable8, "xrTable8");
this.xrTable8.Name = "xrTable8";
this.xrTable8.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow13});
//
// xrTableRow13
//
this.xrTableRow13.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell27,
this.RelatedReportsCell});
this.xrTableRow13.Name = "xrTableRow13";
resources.ApplyResources(this.xrTableRow13, "xrTableRow13");
//
// xrTableCell27
//
resources.ApplyResources(this.xrTableCell27, "xrTableCell27");
this.xrTableCell27.Name = "xrTableCell27";
this.xrTableCell27.StylePriority.UseFont = false;
this.xrTableCell27.StylePriority.UseTextAlignment = false;
//
// RelatedReportsCell
//
this.RelatedReportsCell.Name = "RelatedReportsCell";
this.RelatedReportsCell.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.RelatedReportsCell, "RelatedReportsCell");
//
// DetailReport1
//
this.DetailReport1.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail2,
this.ReportHeader1});
this.DetailReport1.DataAdapter = this.OutbreakNotesAdapter;
this.DetailReport1.DataMember = "OutbreakNotesReport";
this.DetailReport1.DataSource = this.OutbreakDataSet;
this.DetailReport1.Level = 1;
this.DetailReport1.Name = "DetailReport1";
//
// Detail2
//
this.Detail2.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable10});
resources.ApplyResources(this.Detail2, "Detail2");
this.Detail2.Name = "Detail2";
//
// xrTable10
//
this.xrTable10.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.xrTable10, "xrTable10");
this.xrTable10.Name = "xrTable10";
this.xrTable10.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow15});
this.xrTable10.StylePriority.UseBorders = false;
this.xrTable10.StylePriority.UseTextAlignment = false;
//
// xrTableRow15
//
this.xrTableRow15.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell33,
this.xrTableCell34,
this.xrTableCell29});
this.xrTableRow15.Name = "xrTableRow15";
resources.ApplyResources(this.xrTableRow15, "xrTableRow15");
//
// xrTableCell33
//
this.xrTableCell33.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "OutbreakNotesReport.strNote")});
this.xrTableCell33.Name = "xrTableCell33";
resources.ApplyResources(this.xrTableCell33, "xrTableCell33");
//
// xrTableCell34
//
this.xrTableCell34.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "OutbreakNotesReport.datNoteDate", "{0:dd/MM/yyyy}")});
this.xrTableCell34.Name = "xrTableCell34";
this.xrTableCell34.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell34, "xrTableCell34");
//
// xrTableCell29
//
this.xrTableCell29.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "OutbreakNotesReport.strCreatorName")});
this.xrTableCell29.Name = "xrTableCell29";
this.xrTableCell29.StylePriority.UseFont = false;
this.xrTableCell29.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell29, "xrTableCell29");
//
// ReportHeader1
//
this.ReportHeader1.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable9});
resources.ApplyResources(this.ReportHeader1, "ReportHeader1");
this.ReportHeader1.Name = "ReportHeader1";
//
// xrTable9
//
resources.ApplyResources(this.xrTable9, "xrTable9");
this.xrTable9.Name = "xrTable9";
this.xrTable9.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow14,
this.xrTableRow16});
this.xrTable9.StylePriority.UseFont = false;
//
// xrTableRow14
//
this.xrTableRow14.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell28});
this.xrTableRow14.Name = "xrTableRow14";
resources.ApplyResources(this.xrTableRow14, "xrTableRow14");
//
// xrTableCell28
//
this.xrTableCell28.Name = "xrTableCell28";
this.xrTableCell28.StylePriority.UseFont = false;
this.xrTableCell28.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell28, "xrTableCell28");
//
// xrTableRow16
//
this.xrTableRow16.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableRow16.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell32,
this.xrTableCell31,
this.xrTableCell30});
this.xrTableRow16.Name = "xrTableRow16";
this.xrTableRow16.StylePriority.UseBorders = false;
this.xrTableRow16.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableRow16, "xrTableRow16");
//
// xrTableCell32
//
this.xrTableCell32.Name = "xrTableCell32";
resources.ApplyResources(this.xrTableCell32, "xrTableCell32");
//
// xrTableCell31
//
this.xrTableCell31.Name = "xrTableCell31";
resources.ApplyResources(this.xrTableCell31, "xrTableCell31");
//
// xrTableCell30
//
this.xrTableCell30.Name = "xrTableCell30";
resources.ApplyResources(this.xrTableCell30, "xrTableCell30");
//
// OutbreakReport
//
this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail,
this.PageHeader,
this.PageFooter,
this.ReportHeader,
this.DetailReport,
this.DetailReport1});
resources.ApplyResources(this, "$this");
this.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F);
this.Version = "13.1";
this.Controls.SetChildIndex(this.DetailReport1, 0);
this.Controls.SetChildIndex(this.DetailReport, 0);
this.Controls.SetChildIndex(this.ReportHeader, 0);
this.Controls.SetChildIndex(this.PageFooter, 0);
this.Controls.SetChildIndex(this.PageHeader, 0);
this.Controls.SetChildIndex(this.Detail, 0);
((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.OutbreakDataSet)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable4)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable5)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable6)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable3)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable7)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable8)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable10)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable9)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
private OutBreakDataSet OutbreakDataSet;
private OutBreakDataSetTableAdapters.OutbreakAdapter OutbreakAdapter;
private OutBreakDataSetTableAdapters.OutbreakNotesAdapter OutbreakNotesAdapter;
private DevExpress.XtraReports.UI.XRTable xrTable1;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell3;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell4;
private DevExpress.XtraReports.UI.XRTable xrTable4;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell9;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell12;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell10;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell13;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell11;
private DevExpress.XtraReports.UI.XRTable xrTable2;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow3;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell6;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow4;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell7;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell8;
private DevExpress.XtraReports.UI.XRTable xrTable5;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow10;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell14;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell15;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell16;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell17;
private DevExpress.XtraReports.UI.XRTableCell AddressCell;
private DevExpress.XtraReports.UI.XRTable xrTable6;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow11;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell21;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow12;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell19;
private DevExpress.XtraReports.UI.DetailReportBand DetailReport;
private DevExpress.XtraReports.UI.DetailBand DetailOutbreak;
private DevExpress.XtraReports.UI.XRTable xrTable3;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow6;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell18;
private DevExpress.XtraReports.UI.XRTableCell OutbreakDateCell;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow7;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell22;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell23;
private DevExpress.XtraReports.UI.XRTable xrTable7;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow9;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell25;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell26;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow8;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell20;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell24;
private DevExpress.XtraReports.UI.XRTable xrTable8;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow13;
private DevExpress.XtraReports.UI.XRTableCell RelatedReportsCell;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell27;
private DevExpress.XtraReports.UI.DetailReportBand DetailReport1;
private DevExpress.XtraReports.UI.DetailBand Detail2;
private DevExpress.XtraReports.UI.XRTable xrTable10;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow15;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell33;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell34;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell29;
private DevExpress.XtraReports.UI.ReportHeaderBand ReportHeader1;
private DevExpress.XtraReports.UI.XRTable xrTable9;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow14;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell28;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow16;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell32;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell31;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell30;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell35;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell38;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell37;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell41;
private DevExpress.XtraReports.UI.XRTableCell SourceOfCaseSessionCell;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell40;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell39;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell42;
}
}
| |
using UnityEngine;
using System.Collections.Generic;
#if UNITY_EDITOR
using UnityEditor;
namespace Destructible2D
{
[CanEditMultipleObjects]
[CustomEditor(typeof(D2dQuadFracturer))]
public class D2dQuadFracturer_Editor : D2dEditor<D2dQuadFracturer>
{
protected override void OnInspector()
{
DrawDefault("RequiredDamage");
BeginError(Any(t => t.RequiredDamageMultiplier <= 1.0f));
DrawDefault("RequiredDamageMultiplier");
EndError();
DrawDefault("FractureCount");
BeginError(Any(t => t.FractureCountMultiplier <= 0.0f));
DrawDefault("FractureCountMultiplier");
EndError();
Separator();
DrawDefault("RemainingFractures");
DrawDefault("Irregularity");
}
}
}
#endif
namespace Destructible2D
{
[AddComponentMenu(D2dHelper.ComponentMenuPrefix + "Quad Fracturer")]
public class D2dQuadFracturer : D2dFracturer
{
[Tooltip("This changes how random the fractured shapes will be")]
[Range(0.0f, 0.5f)]
public float Irregularity = 0.25f;
// Temp fracture vars
private static List<D2dQuad> quads = new List<D2dQuad>();
private static List<D2dVector2> points = new List<D2dVector2>();
private static int quadCount;
private static int pointCount;
private static int xMin;
private static int xMax;
private static int yMin;
private static int yMax;
[ContextMenu("Fracture")]
public override void Fracture()
{
base.Fracture();
Fracture(destructible, FractureCount, Irregularity);
}
public static void Fracture(D2dDestructible destructible, int count, float irregularity)
{
if (destructible != null && count > 0)
{
D2dSplitGroup.DespawnTempSplitGroups();
{
var width = destructible.AlphaWidth;
var height = destructible.AlphaHeight;
var mainQuad = new D2dQuad();
quadCount = 1;
pointCount = 0;
xMin = 0;
xMax = width - 1;
yMin = 0;
yMax = height - 1;
mainQuad.BL = new D2dVector2(xMin, yMin);
mainQuad.BR = new D2dVector2(xMax, yMin);
mainQuad.TL = new D2dVector2(xMin, yMax);
mainQuad.TR = new D2dVector2(xMax, yMax);
mainQuad.Calculate();
if (quads.Count > 0)
{
quads[0] = mainQuad;
}
else
{
quads.Add(mainQuad);
}
for (var i = 0; i < count; i++)
{
SplitLargest();
}
if (irregularity > 0.0f)
{
FindPoints();
ShiftPoints(irregularity);
}
for (var i = 0; i < quadCount; i++)
{
var quad = quads[i];
var group = D2dSplitGroup.SpawnTempSplitGroup();
group.AddTriangle(quad.BL, quad.BR, quad.TL);
group.AddTriangle(quad.TR, quad.TL, quad.BR);
}
destructible.Split(null, D2dSplitGroup.TempSplitGroups);
}
D2dSplitGroup.DespawnTempSplitGroups();
}
}
private static void FindPoints()
{
for (var i = 0; i < quadCount; i++)
{
var quad = quads[i];
TryAddPoint(quad.BL);
TryAddPoint(quad.BR);
TryAddPoint(quad.TL);
TryAddPoint(quad.TR);
}
}
private static void ShiftPoints(float irregularity)
{
for (var i = 0; i < pointCount; i++)
{
var point = points[i];
var delta = Random.insideUnitCircle.normalized * FindMaxMovement(point.X, point.Y) * irregularity;
var deltaX = Mathf.RoundToInt(delta.x);
var deltaY = Mathf.RoundToInt(delta.y);
if (point.X <= xMin || point.X >= xMax) deltaX = 0;
if (point.Y <= yMin || point.Y >= yMax) deltaY = 0;
if (deltaX != 0 || deltaY != 0)
{
var newPoint = new D2dVector2(point.X + deltaX, point.Y + deltaY);
MovePoints(point, newPoint);
points[i] = newPoint;
}
}
}
private static void MovePoints(D2dVector2 oldPoint, D2dVector2 newPoint)
{
for (var i = 0; i < quadCount; i++)
{
var quad = quads[i];
TryMovePoint(ref quad.BL, oldPoint, newPoint);
TryMovePoint(ref quad.BR, oldPoint, newPoint);
TryMovePoint(ref quad.TL, oldPoint, newPoint);
TryMovePoint(ref quad.TR, oldPoint, newPoint);
quads[i] = quad;
}
}
private static void TryMovePoint(ref D2dVector2 point, D2dVector2 oldPoint, D2dVector2 newPoint)
{
if (point.X == oldPoint.X && point.Y == oldPoint.Y)
{
point.X = newPoint.X;
point.Y = newPoint.Y;
}
}
private static void TryAddPoint(D2dVector2 newPoint)
{
for (var i = 0; i < pointCount; i++)
{
var point = points[i];
if (point.X == newPoint.X && point.Y == newPoint.Y)
{
return;
}
}
if (points.Count > pointCount)
{
points[pointCount] = newPoint;
}
else
{
points.Add(newPoint);
}
pointCount += 1;
}
private static int FindMaxMovement(int x, int y)
{
var minDistanceSq = int.MaxValue;
for (var i = 0; i < pointCount; i++)
{
var point = points[i];
var distanceX = point.X - x;
var distanceY = point.Y - y;
var distanceSq = distanceX * distanceX + distanceY * distanceY;
if (distanceSq > 0)
{
minDistanceSq = Mathf.Min(minDistanceSq, distanceSq);
}
}
return Mathf.FloorToInt(Mathf.Sqrt(minDistanceSq));
}
private static void SplitLargest()
{
var largestIndex = 0;
var largestArea = 0;
for (var i = 0; i < quadCount; i++)
{
var quad = quads[i];
if (quad.Area > largestArea)
{
largestIndex = i;
largestArea = quad.Area;
}
}
var first = new D2dQuad();
var second = new D2dQuad();
quads[largestIndex].Split(ref first, ref second);
quads[largestIndex] = first;
if (quads.Count > quadCount)
{
quads[quadCount] = second;
}
else
{
quads.Add(second);
}
quadCount += 1;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// System.Net.HttpConnection
//
// Author:
// Gonzalo Paniagua Javier (gonzalo.mono@gmail.com)
//
// Copyright (c) 2005-2009 Novell, Inc. (http://www.novell.com)
// Copyright (c) 2012 Xamarin, Inc. (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.IO;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
namespace System.Net
{
internal sealed class HttpConnection
{
private static AsyncCallback s_onreadCallback = new AsyncCallback(OnRead);
private const int BufferSize = 8192;
private Socket _socket;
private Stream _stream;
private HttpEndPointListener _epl;
private MemoryStream _memoryStream;
private byte[] _buffer;
private HttpListenerContext _context;
private StringBuilder _currentLine;
private ListenerPrefix _prefix;
private HttpRequestStream _requestStream;
private HttpResponseStream _responseStream;
private bool _chunked;
private int _reuses;
private bool _contextBound;
private bool _secure;
private X509Certificate _cert;
private int _timeout = 90000; // 90k ms for first request, 15k ms from then on
private Timer _timer;
private IPEndPoint _localEndPoint;
private HttpListener _lastListener;
private int[] _clientCertErrors;
private X509Certificate2 _clientCert;
private SslStream _sslStream;
private InputState _inputState = InputState.RequestLine;
private LineState _lineState = LineState.None;
private int _position;
public HttpConnection(Socket sock, HttpEndPointListener epl, bool secure, X509Certificate cert)
{
_socket = sock;
_epl = epl;
_secure = secure;
_cert = cert;
if (secure == false)
{
_stream = new NetworkStream(sock, false);
}
else
{
_sslStream = epl.Listener.CreateSslStream(new NetworkStream(sock, false), false, (t, c, ch, e) =>
{
if (c == null)
{
return true;
}
var c2 = c as X509Certificate2;
if (c2 == null)
{
c2 = new X509Certificate2(c.GetRawCertData());
}
_clientCert = c2;
_clientCertErrors = new int[] { (int)e };
return true;
});
_stream = _sslStream;
}
_timer = new Timer(OnTimeout, null, Timeout.Infinite, Timeout.Infinite);
if (_sslStream != null) {
_sslStream.AuthenticateAsServer (_cert, true, (SslProtocols)ServicePointManager.SecurityProtocol, false);
}
Init();
}
internal int[] ClientCertificateErrors
{
get { return _clientCertErrors; }
}
internal X509Certificate2 ClientCertificate
{
get { return _clientCert; }
}
internal SslStream SslStream
{
get { return _sslStream; }
}
private void Init()
{
_contextBound = false;
_requestStream = null;
_responseStream = null;
_prefix = null;
_chunked = false;
_memoryStream = new MemoryStream();
_position = 0;
_inputState = InputState.RequestLine;
_lineState = LineState.None;
_context = new HttpListenerContext(this);
}
public Stream ConnectedStream => _stream;
public bool IsClosed
{
get { return (_socket == null); }
}
public int Reuses
{
get { return _reuses; }
}
public IPEndPoint LocalEndPoint
{
get
{
if (_localEndPoint != null)
return _localEndPoint;
_localEndPoint = (IPEndPoint)_socket.LocalEndPoint;
return _localEndPoint;
}
}
public IPEndPoint RemoteEndPoint
{
get { return (IPEndPoint)_socket.RemoteEndPoint; }
}
public bool IsSecure
{
get { return _secure; }
}
public ListenerPrefix Prefix
{
get { return _prefix; }
set { _prefix = value; }
}
private void OnTimeout(object unused)
{
CloseSocket();
Unbind();
}
public void BeginReadRequest()
{
if (_buffer == null)
_buffer = new byte[BufferSize];
try
{
if (_reuses == 1)
_timeout = 15000;
_timer.Change(_timeout, Timeout.Infinite);
_stream.BeginRead(_buffer, 0, BufferSize, s_onreadCallback, this);
}
catch
{
_timer.Change(Timeout.Infinite, Timeout.Infinite);
CloseSocket();
Unbind();
}
}
public HttpRequestStream GetRequestStream(bool chunked, long contentlength)
{
if (_requestStream == null)
{
byte[] buffer = _memoryStream.GetBuffer();
int length = (int)_memoryStream.Length;
_memoryStream = null;
if (chunked)
{
_chunked = true;
_context.Response.SendChunked = true;
_requestStream = new ChunkedInputStream(_context, _stream, buffer, _position, length - _position);
}
else
{
_requestStream = new HttpRequestStream(_stream, buffer, _position, length - _position, contentlength);
}
}
return _requestStream;
}
public HttpResponseStream GetResponseStream()
{
if (_responseStream == null)
{
HttpListener listener = _context._listener;
if (listener == null)
return new HttpResponseStream(_stream, _context.Response, true);
_responseStream = new HttpResponseStream(_stream, _context.Response, listener.IgnoreWriteExceptions);
}
return _responseStream;
}
private static void OnRead(IAsyncResult ares)
{
HttpConnection cnc = (HttpConnection)ares.AsyncState;
cnc.OnReadInternal(ares);
}
private void OnReadInternal(IAsyncResult ares)
{
_timer.Change(Timeout.Infinite, Timeout.Infinite);
int nread = -1;
try
{
nread = _stream.EndRead(ares);
_memoryStream.Write(_buffer, 0, nread);
if (_memoryStream.Length > 32768)
{
SendError(HttpStatusDescription.Get(400), 400);
Close(true);
return;
}
}
catch
{
if (_memoryStream != null && _memoryStream.Length > 0)
SendError();
if (_socket != null)
{
CloseSocket();
Unbind();
}
return;
}
if (nread == 0)
{
CloseSocket();
Unbind();
return;
}
if (ProcessInput(_memoryStream))
{
if (!_context.HaveError)
_context.Request.FinishInitialization();
if (_context.HaveError)
{
SendError();
Close(true);
return;
}
if (!_epl.BindContext(_context))
{
SendError("Invalid host", 400);
Close(true);
return;
}
HttpListener listener = _context._listener;
if (_lastListener != listener)
{
RemoveConnection();
listener.AddConnection(this);
_lastListener = listener;
}
_contextBound = true;
listener.RegisterContext(_context);
return;
}
_stream.BeginRead(_buffer, 0, BufferSize, s_onreadCallback, this);
}
private void RemoveConnection()
{
if (_lastListener == null)
_epl.RemoveConnection(this);
else
_lastListener.RemoveConnection(this);
}
private enum InputState
{
RequestLine,
Headers
}
private enum LineState
{
None,
CR,
LF
}
// true -> done processing
// false -> need more input
private bool ProcessInput(MemoryStream ms)
{
byte[] buffer = ms.GetBuffer();
int len = (int)ms.Length;
int used = 0;
string line;
while (true)
{
if (_context.HaveError)
return true;
if (_position >= len)
break;
try
{
line = ReadLine(buffer, _position, len - _position, ref used);
_position += used;
}
catch
{
_context.ErrorMessage = HttpStatusDescription.Get(400);
_context.ErrorStatus = 400;
return true;
}
if (line == null)
break;
if (line == "")
{
if (_inputState == InputState.RequestLine)
continue;
_currentLine = null;
ms = null;
return true;
}
if (_inputState == InputState.RequestLine)
{
_context.Request.SetRequestLine(line);
_inputState = InputState.Headers;
}
else
{
try
{
_context.Request.AddHeader(line);
}
catch (Exception e)
{
_context.ErrorMessage = e.Message;
_context.ErrorStatus = 400;
return true;
}
}
}
if (used == len)
{
ms.SetLength(0);
_position = 0;
}
return false;
}
private string ReadLine(byte[] buffer, int offset, int len, ref int used)
{
if (_currentLine == null)
_currentLine = new StringBuilder(128);
int last = offset + len;
used = 0;
for (int i = offset; i < last && _lineState != LineState.LF; i++)
{
used++;
byte b = buffer[i];
if (b == 13)
{
_lineState = LineState.CR;
}
else if (b == 10)
{
_lineState = LineState.LF;
}
else
{
_currentLine.Append((char)b);
}
}
string result = null;
if (_lineState == LineState.LF)
{
_lineState = LineState.None;
result = _currentLine.ToString();
_currentLine.Length = 0;
}
return result;
}
public void SendError(string msg, int status)
{
try
{
HttpListenerResponse response = _context.Response;
response.StatusCode = status;
response.ContentType = "text/html";
string description = HttpStatusDescription.Get(status);
string str;
if (msg != null)
str = string.Format("<h1>{0} ({1})</h1>", description, msg);
else
str = string.Format("<h1>{0}</h1>", description);
byte[] error = Encoding.Default.GetBytes(str);
response.Close(error, false);
}
catch
{
// response was already closed
}
}
public void SendError()
{
SendError(_context.ErrorMessage, _context.ErrorStatus);
}
private void Unbind()
{
if (_contextBound)
{
_epl.UnbindContext(_context);
_contextBound = false;
}
}
public void Close()
{
Close(false);
}
private void CloseSocket()
{
if (_socket == null)
return;
try
{
_socket.Close();
}
catch { }
finally
{
_socket = null;
}
RemoveConnection();
}
internal void Close(bool force)
{
if (_socket != null)
{
Stream st = GetResponseStream();
if (st != null)
st.Close();
_responseStream = null;
}
if (_socket != null)
{
force |= !_context.Request.KeepAlive;
if (!force)
force = (_context.Response.Headers[HttpKnownHeaderNames.Connection] == HttpHeaderStrings.Close);
if (!force && _context.Request.FlushInput())
{
if (_chunked && _context.Response.ForceCloseChunked == false)
{
// Don't close. Keep working.
_reuses++;
Unbind();
Init();
BeginReadRequest();
return;
}
_reuses++;
Unbind();
Init();
BeginReadRequest();
return;
}
Socket s = _socket;
_socket = null;
try
{
if (s != null)
s.Shutdown(SocketShutdown.Both);
}
catch
{
}
finally
{
if (s != null)
s.Close();
}
Unbind();
RemoveConnection();
return;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Data.SqlClient.ManualTesting.Tests
{
public static class TransactionTest
{
public static TheoryData<string> PoolEnabledConnectionStrings =>
new TheoryData<string>
{
new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr)
{
MultipleActiveResultSets = false,
Pooling = true,
MaxPoolSize = 1
}.ConnectionString
, new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr)
{
Pooling = true,
MultipleActiveResultSets = true
}.ConnectionString
};
public static TheoryData<string> PoolDisabledConnectionStrings =>
new TheoryData<string>
{
new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr)
{
Pooling = false,
MultipleActiveResultSets = false
}.ConnectionString
, new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr)
{
Pooling = false,
MultipleActiveResultSets = true
}.ConnectionString
};
[ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))]
[MemberData(nameof(PoolEnabledConnectionStrings))]
public static void ReadNextQueryAfterTxAbortedPoolEnabled(string connString)
=> ReadNextQueryAfterTxAbortedTest(connString);
[ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))]
[MemberData(nameof(PoolDisabledConnectionStrings))]
public static void ReadNextQueryAfterTxAbortedPoolDisabled(string connString)
=> ReadNextQueryAfterTxAbortedTest(connString);
private static void ReadNextQueryAfterTxAbortedTest(string connString)
{
using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope())
{
using (SqlConnection sqlConnection = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand("SELECT 1", sqlConnection);
sqlConnection.Open();
var reader = cmd.ExecuteReader();
// Disposing Transaction Scope before completing read triggers GitHub issue #980 use-case that leads to wrong data in future rounds.
scope.Dispose();
}
using (SqlConnection sqlConnection = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand("SELECT 2", sqlConnection))
{
sqlConnection.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
bool result = reader.Read();
Assert.True(result);
Assert.Equal(2, reader.GetValue(0));
}
}
using (SqlConnection sqlConnection = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand("SELECT 3", sqlConnection))
{
sqlConnection.Open();
using (SqlDataReader reader = cmd.ExecuteReaderAsync().Result)
{
bool result = reader.ReadAsync().Result;
Assert.True(result);
Assert.Equal(3, reader.GetValue(0));
}
}
using (SqlConnection sqlConnection = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand("SELECT TOP(1) 4 Clm0 FROM sysobjects FOR XML AUTO", sqlConnection))
{
sqlConnection.Open();
using (System.Xml.XmlReader reader = cmd.ExecuteXmlReader())
{
bool result = reader.Read();
Assert.True(result);
Assert.Equal("4", reader[0]);
}
}
}
}
[ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
public static void TestMain()
{
new TransactionTestWorker((new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { MultipleActiveResultSets = true }).ConnectionString).StartTest();
}
private sealed class TransactionTestWorker
{
private readonly string _tempTableName1;
private readonly string _tempTableName2;
private string _connectionString;
public TransactionTestWorker(string connectionString)
{
_connectionString = connectionString;
_tempTableName1 = string.Format("TEST_{0}{1}{2}", Environment.GetEnvironmentVariable("ComputerName"), Environment.TickCount, Guid.NewGuid()).Replace('-', '_');
_tempTableName2 = _tempTableName1 + "_2";
}
public void StartTest()
{
try
{
PrepareTables();
CommitTransactionTest();
ResetTables();
RollbackTransactionTest();
ResetTables();
ScopedTransactionTest();
ResetTables();
ExceptionTest();
ResetTables();
ReadUncommitedIsolationLevel_ShouldReturnUncommitedData();
ResetTables();
ReadCommitedIsolationLevel_ShouldReceiveTimeoutExceptionBecauseItWaitsForUncommitedTransaction();
ResetTables();
}
finally
{
//make sure to clean up
DropTempTables();
}
}
private void PrepareTables()
{
using (var conn = new SqlConnection(_connectionString))
{
conn.Open();
SqlCommand command = new SqlCommand(string.Format("CREATE TABLE [{0}]([CustomerID] [nchar](5) NOT NULL PRIMARY KEY, [CompanyName] [nvarchar](40) NOT NULL, [ContactName] [nvarchar](30) NULL)", _tempTableName1), conn);
command.ExecuteNonQuery();
command.CommandText = "create table " + _tempTableName2 + "(col1 int, col2 varchar(32))";
command.ExecuteNonQuery();
}
}
private void DropTempTables()
{
using (var conn = new SqlConnection(_connectionString))
{
SqlCommand command = new SqlCommand(
string.Format("DROP TABLE [{0}]; DROP TABLE [{1}]", _tempTableName1, _tempTableName2), conn);
conn.Open();
command.ExecuteNonQuery();
}
}
public void ResetTables()
{
using (SqlConnection connection = new SqlConnection(_connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(string.Format("TRUNCATE TABLE [{0}]; TRUNCATE TABLE [{1}]", _tempTableName1, _tempTableName2), connection))
{
command.ExecuteNonQuery();
}
}
}
private void CommitTransactionTest()
{
using (SqlConnection connection = new SqlConnection(_connectionString))
{
SqlCommand command = new SqlCommand("select * from " + _tempTableName1 + " where CustomerID='ZYXWV'", connection);
connection.Open();
SqlTransaction tx = connection.BeginTransaction();
command.Transaction = tx;
using (SqlDataReader reader = command.ExecuteReader())
{
Assert.False(reader.HasRows, "Error: table is in incorrect state for test.");
}
using (SqlCommand command2 = connection.CreateCommand())
{
command2.Transaction = tx;
command2.CommandText = "INSERT INTO " + _tempTableName1 + " VALUES ( 'ZYXWV', 'XYZ', 'John' );";
command2.ExecuteNonQuery();
}
tx.Commit();
using (SqlDataReader reader = command.ExecuteReader())
{
int count = 0;
while (reader.Read()) { count++; }
Assert.True(count == 1, "Error: incorrect number of rows in table after update.");
Assert.Equal(count, 1);
}
}
}
private void RollbackTransactionTest()
{
using (SqlConnection connection = new SqlConnection(_connectionString))
{
SqlCommand command = new SqlCommand("select * from " + _tempTableName1 + " where CustomerID='ZYXWV'",
connection);
connection.Open();
SqlTransaction tx = connection.BeginTransaction();
command.Transaction = tx;
using (SqlDataReader reader = command.ExecuteReader())
{
Assert.False(reader.HasRows, "Error: table is in incorrect state for test.");
}
using (SqlCommand command2 = connection.CreateCommand())
{
command2.Transaction = tx;
command2.CommandText = "INSERT INTO " + _tempTableName1 + " VALUES ( 'ZYXWV', 'XYZ', 'John' );";
command2.ExecuteNonQuery();
}
tx.Rollback();
using (SqlDataReader reader = command.ExecuteReader())
{
Assert.False(reader.HasRows, "Error Rollback Test : incorrect number of rows in table after rollback.");
int count = 0;
while (reader.Read()) count++;
Assert.Equal(count, 0);
}
connection.Close();
}
}
private void ScopedTransactionTest()
{
using (SqlConnection connection = new SqlConnection(_connectionString))
{
SqlCommand command = new SqlCommand("select * from " + _tempTableName1 + " where CustomerID='ZYXWV'",
connection);
connection.Open();
SqlTransaction tx = connection.BeginTransaction("transName");
command.Transaction = tx;
using (SqlDataReader reader = command.ExecuteReader())
{
Assert.False(reader.HasRows, "Error: table is in incorrect state for test.");
}
using (SqlCommand command2 = connection.CreateCommand())
{
command2.Transaction = tx;
command2.CommandText = "INSERT INTO " + _tempTableName1 + " VALUES ( 'ZYXWV', 'XYZ', 'John' );";
command2.ExecuteNonQuery();
}
tx.Save("saveName");
//insert another one
using (SqlCommand command2 = connection.CreateCommand())
{
command2.Transaction = tx;
command2.CommandText = "INSERT INTO " + _tempTableName1 + " VALUES ( 'ZYXW2', 'XY2', 'KK' );";
command2.ExecuteNonQuery();
}
tx.Rollback("saveName");
using (SqlDataReader reader = command.ExecuteReader())
{
Assert.True(reader.HasRows, "Error Scoped Transaction Test : incorrect number of rows in table after rollback to save state one.");
int count = 0;
while (reader.Read()) count++;
Assert.Equal(count, 1);
}
tx.Rollback();
connection.Close();
}
}
private void ExceptionTest()
{
using (SqlConnection connection = new SqlConnection(_connectionString))
{
connection.Open();
SqlTransaction tx = connection.BeginTransaction();
string invalidSaveStateMessage = SystemDataResourceManager.Instance.SQL_NullEmptyTransactionName;
string executeCommandWithoutTransactionMessage = SystemDataResourceManager.Instance.ADP_TransactionRequired("ExecuteNonQuery");
string transactionConflictErrorMessage = SystemDataResourceManager.Instance.ADP_TransactionConnectionMismatch;
string parallelTransactionErrorMessage = SystemDataResourceManager.Instance.ADP_ParallelTransactionsNotSupported("SqlConnection");
DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() =>
{
SqlCommand command = new SqlCommand("sql", connection);
command.ExecuteNonQuery();
}, executeCommandWithoutTransactionMessage);
DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() =>
{
SqlConnection con1 = new SqlConnection(_connectionString);
con1.Open();
SqlCommand command = new SqlCommand("sql", con1);
command.Transaction = tx;
command.ExecuteNonQuery();
}, transactionConflictErrorMessage);
DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() =>
{
connection.BeginTransaction(null);
}, parallelTransactionErrorMessage);
DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() =>
{
connection.BeginTransaction("");
}, parallelTransactionErrorMessage);
DataTestUtility.AssertThrowsWrapper<ArgumentException>(() =>
{
tx.Rollback(null);
}, invalidSaveStateMessage);
DataTestUtility.AssertThrowsWrapper<ArgumentException>(() =>
{
tx.Rollback("");
}, invalidSaveStateMessage);
DataTestUtility.AssertThrowsWrapper<ArgumentException>(() =>
{
tx.Save(null);
}, invalidSaveStateMessage);
DataTestUtility.AssertThrowsWrapper<ArgumentException>(() =>
{
tx.Save("");
}, invalidSaveStateMessage);
}
}
private void ReadUncommitedIsolationLevel_ShouldReturnUncommitedData()
{
using (SqlConnection connection1 = new SqlConnection(_connectionString))
{
connection1.Open();
SqlTransaction tx1 = connection1.BeginTransaction();
using (SqlCommand command1 = connection1.CreateCommand())
{
command1.Transaction = tx1;
command1.CommandText = "INSERT INTO " + _tempTableName1 + " VALUES ( 'ZYXWV', 'XYZ', 'John' );";
command1.ExecuteNonQuery();
}
using (SqlConnection connection2 = new SqlConnection(_connectionString))
{
SqlCommand command2 =
new SqlCommand("select * from " + _tempTableName1 + " where CustomerID='ZYXWV'",
connection2);
connection2.Open();
SqlTransaction tx2 = connection2.BeginTransaction(IsolationLevel.ReadUncommitted);
command2.Transaction = tx2;
using (SqlDataReader reader = command2.ExecuteReader())
{
int count = 0;
while (reader.Read()) count++;
Assert.True(count == 1, "Should Expected 1 row because Isolation Level is read uncommitted which should return uncommitted data.");
}
tx2.Rollback();
connection2.Close();
}
tx1.Rollback();
connection1.Close();
}
}
private void ReadCommitedIsolationLevel_ShouldReceiveTimeoutExceptionBecauseItWaitsForUncommitedTransaction()
{
using (SqlConnection connection1 = new SqlConnection(_connectionString))
{
connection1.Open();
SqlTransaction tx1 = connection1.BeginTransaction();
using (SqlCommand command1 = connection1.CreateCommand())
{
command1.Transaction = tx1;
command1.CommandText = "INSERT INTO " + _tempTableName1 + " VALUES ( 'ZYXWV', 'XYZ', 'John' );";
command1.ExecuteNonQuery();
}
using (SqlConnection connection2 = new SqlConnection(_connectionString))
{
SqlCommand command2 =
new SqlCommand("select * from " + _tempTableName1 + " where CustomerID='ZYXWV'",
connection2);
connection2.Open();
SqlTransaction tx2 = connection2.BeginTransaction(IsolationLevel.ReadCommitted);
command2.Transaction = tx2;
DataTestUtility.AssertThrowsWrapper<SqlException>(() => command2.ExecuteReader(), SystemDataResourceManager.Instance.SQL_Timeout as string);
tx2.Rollback();
connection2.Close();
}
tx1.Rollback();
connection1.Close();
}
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
using System;
using System.Collections.Generic;
using System.Text;
using OpenMetaverse;
using OpenSim.Framework;
namespace OpenSim.Region.Physics.BulletSPlugin
{
public abstract class BSMotor
{
// Timescales and other things can be turned off by setting them to 'infinite'.
public const float Infinite = 12345.6f;
public readonly static Vector3 InfiniteVector = new Vector3(BSMotor.Infinite, BSMotor.Infinite, BSMotor.Infinite);
public BSMotor(string useName)
{
UseName = useName;
PhysicsScene = null;
Enabled = true;
}
public virtual bool Enabled { get; set; }
public virtual void Reset() { }
public virtual void Zero() { }
public virtual void GenerateTestOutput(float timeStep) { }
// A name passed at motor creation for easily identifyable debugging messages.
public string UseName { get; private set; }
// Used only for outputting debug information. Might not be set so check for null.
public BSScene PhysicsScene { get; set; }
protected void MDetailLog(string msg, params Object[] parms)
{
if (PhysicsScene != null)
{
PhysicsScene.DetailLog(msg, parms);
}
}
}
// Motor which moves CurrentValue to TargetValue over TimeScale seconds.
// The TargetValue decays in TargetValueDecayTimeScale and
// the CurrentValue will be held back by FrictionTimeScale.
// This motor will "zero itself" over time in that the targetValue will
// decay to zero and the currentValue will follow it to that zero.
// The overall effect is for the returned correction value to go from large
// values (the total difference between current and target minus friction)
// to small and eventually zero values.
// TimeScale and TargetDelayTimeScale may be 'infinite' which means no decay.
// For instance, if something is moving at speed X and the desired speed is Y,
// CurrentValue is X and TargetValue is Y. As the motor is stepped, new
// values of CurrentValue are returned that approach the TargetValue.
// The feature of decaying TargetValue is so vehicles will eventually
// come to a stop rather than run forever. This can be disabled by
// setting TargetValueDecayTimescale to 'infinite'.
// The change from CurrentValue to TargetValue is linear over TimeScale seconds.
public class BSVMotor : BSMotor
{
// public Vector3 FrameOfReference { get; set; }
// public Vector3 Offset { get; set; }
public virtual float TimeScale { get; set; }
public virtual float TargetValueDecayTimeScale { get; set; }
public virtual Vector3 FrictionTimescale { get; set; }
public virtual float Efficiency { get; set; }
public virtual float ErrorZeroThreshold { get; set; }
public virtual Vector3 TargetValue { get; protected set; }
public virtual Vector3 CurrentValue { get; protected set; }
public virtual Vector3 LastError { get; protected set; }
public virtual bool ErrorIsZero()
{
return ErrorIsZero(LastError);
}
public virtual bool ErrorIsZero(Vector3 err)
{
return (err == Vector3.Zero || err.ApproxEquals(Vector3.Zero, ErrorZeroThreshold));
}
public BSVMotor(string useName)
: base(useName)
{
TimeScale = TargetValueDecayTimeScale = BSMotor.Infinite;
Efficiency = 1f;
FrictionTimescale = BSMotor.InfiniteVector;
CurrentValue = TargetValue = Vector3.Zero;
ErrorZeroThreshold = 0.001f;
}
public BSVMotor(string useName, float timeScale, float decayTimeScale, Vector3 frictionTimeScale, float efficiency)
: this(useName)
{
TimeScale = timeScale;
TargetValueDecayTimeScale = decayTimeScale;
FrictionTimescale = frictionTimeScale;
Efficiency = efficiency;
CurrentValue = TargetValue = Vector3.Zero;
}
public void SetCurrent(Vector3 current)
{
CurrentValue = current;
}
public void SetTarget(Vector3 target)
{
TargetValue = target;
}
public override void Zero()
{
base.Zero();
CurrentValue = TargetValue = Vector3.Zero;
}
// Compute the next step and return the new current value.
// Returns the correction needed to move 'current' to 'target'.
public virtual Vector3 Step(float timeStep)
{
if (!Enabled) return TargetValue;
Vector3 origTarget = TargetValue; // DEBUG
Vector3 origCurrVal = CurrentValue; // DEBUG
Vector3 correction = Vector3.Zero;
Vector3 error = TargetValue - CurrentValue;
LastError = error;
if (!ErrorIsZero(error))
{
correction = StepError(timeStep, error);
CurrentValue += correction;
// The desired value reduces to zero which also reduces the difference with current.
// If the decay time is infinite, don't decay at all.
float decayFactor = 0f;
if (TargetValueDecayTimeScale != BSMotor.Infinite)
{
decayFactor = (1.0f / TargetValueDecayTimeScale) * timeStep;
TargetValue *= (1f - decayFactor);
}
// The amount we can correct the error is reduced by the friction
Vector3 frictionFactor = Vector3.Zero;
if (FrictionTimescale != BSMotor.InfiniteVector)
{
// frictionFactor = (Vector3.One / FrictionTimescale) * timeStep;
// Individual friction components can be 'infinite' so compute each separately.
frictionFactor.X = (FrictionTimescale.X == BSMotor.Infinite) ? 0f : (1f / FrictionTimescale.X);
frictionFactor.Y = (FrictionTimescale.Y == BSMotor.Infinite) ? 0f : (1f / FrictionTimescale.Y);
frictionFactor.Z = (FrictionTimescale.Z == BSMotor.Infinite) ? 0f : (1f / FrictionTimescale.Z);
frictionFactor *= timeStep;
CurrentValue *= (Vector3.One - frictionFactor);
}
MDetailLog("{0}, BSVMotor.Step,nonZero,{1},origCurr={2},origTarget={3},timeStep={4},err={5},corr={6}",
BSScene.DetailLogZero, UseName, origCurrVal, origTarget,
timeStep, error, correction);
MDetailLog("{0}, BSVMotor.Step,nonZero,{1},tgtDecayTS={2},decayFact={3},frictTS={4},frictFact={5},tgt={6},curr={7}",
BSScene.DetailLogZero, UseName,
TargetValueDecayTimeScale, decayFactor, FrictionTimescale, frictionFactor,
TargetValue, CurrentValue);
}
else
{
// Difference between what we have and target is small. Motor is done.
if (TargetValue.ApproxEquals(Vector3.Zero, ErrorZeroThreshold))
{
// The target can step down to nearly zero but not get there. If close to zero
// it is really zero.
TargetValue = Vector3.Zero;
}
CurrentValue = TargetValue;
MDetailLog("{0}, BSVMotor.Step,zero,{1},origTgt={2},origCurr={3},currTgt={4},currCurr={5}",
BSScene.DetailLogZero, UseName, origCurrVal, origTarget, TargetValue, CurrentValue);
}
return correction;
}
// version of step that sets the current value before doing the step
public virtual Vector3 Step(float timeStep, Vector3 current)
{
CurrentValue = current;
return Step(timeStep);
}
public virtual Vector3 StepError(float timeStep, Vector3 error)
{
if (!Enabled) return Vector3.Zero;
Vector3 returnCorrection = Vector3.Zero;
if (!ErrorIsZero(error))
{
// correction = error / secondsItShouldTakeToCorrect
Vector3 correctionAmount;
if (TimeScale == 0f || TimeScale == BSMotor.Infinite)
correctionAmount = error * timeStep;
else
correctionAmount = error / TimeScale * timeStep;
returnCorrection = correctionAmount;
MDetailLog("{0}, BSVMotor.Step,nonZero,{1},timeStep={2},timeScale={3},err={4},corr={5}",
BSScene.DetailLogZero, UseName, timeStep, TimeScale, error, correctionAmount);
}
return returnCorrection;
}
// The user sets all the parameters and calls this which outputs values until error is zero.
public override void GenerateTestOutput(float timeStep)
{
// maximum number of outputs to generate.
int maxOutput = 50;
MDetailLog("{0},BSVMotor.Test,{1},===================================== BEGIN Test Output", BSScene.DetailLogZero, UseName);
MDetailLog("{0},BSVMotor.Test,{1},timeScale={2},targDlyTS={3},frictTS={4},eff={5},curr={6},tgt={7}",
BSScene.DetailLogZero, UseName,
TimeScale, TargetValueDecayTimeScale, FrictionTimescale, Efficiency,
CurrentValue, TargetValue);
LastError = BSMotor.InfiniteVector;
while (maxOutput-- > 0 && !LastError.ApproxEquals(Vector3.Zero, ErrorZeroThreshold))
{
Vector3 lastStep = Step(timeStep);
MDetailLog("{0},BSVMotor.Test,{1},cur={2},tgt={3},lastError={4},lastStep={5}",
BSScene.DetailLogZero, UseName, CurrentValue, TargetValue, LastError, lastStep);
}
MDetailLog("{0},BSVMotor.Test,{1},===================================== END Test Output", BSScene.DetailLogZero, UseName);
}
public override string ToString()
{
return String.Format("<{0},curr={1},targ={2},lastErr={3},decayTS={4},frictTS={5}>",
UseName, CurrentValue, TargetValue, LastError, TargetValueDecayTimeScale, FrictionTimescale);
}
}
// ============================================================================
// ============================================================================
public class BSFMotor : BSMotor
{
public virtual float TimeScale { get; set; }
public virtual float TargetValueDecayTimeScale { get; set; }
public virtual float FrictionTimescale { get; set; }
public virtual float Efficiency { get; set; }
public virtual float ErrorZeroThreshold { get; set; }
public virtual float TargetValue { get; protected set; }
public virtual float CurrentValue { get; protected set; }
public virtual float LastError { get; protected set; }
public virtual bool ErrorIsZero()
{
return ErrorIsZero(LastError);
}
public virtual bool ErrorIsZero(float err)
{
return (err >= -ErrorZeroThreshold && err <= ErrorZeroThreshold);
}
public BSFMotor(string useName, float timeScale, float decayTimescale, float friction, float efficiency)
: base(useName)
{
TimeScale = TargetValueDecayTimeScale = BSMotor.Infinite;
Efficiency = 1f;
FrictionTimescale = BSMotor.Infinite;
CurrentValue = TargetValue = 0f;
ErrorZeroThreshold = 0.01f;
}
public void SetCurrent(float current)
{
CurrentValue = current;
}
public void SetTarget(float target)
{
TargetValue = target;
}
public override void Zero()
{
base.Zero();
CurrentValue = TargetValue = 0f;
}
public virtual float Step(float timeStep)
{
if (!Enabled) return TargetValue;
float origTarget = TargetValue; // DEBUG
float origCurrVal = CurrentValue; // DEBUG
float correction = 0f;
float error = TargetValue - CurrentValue;
LastError = error;
if (!ErrorIsZero(error))
{
correction = StepError(timeStep, error);
CurrentValue += correction;
// The desired value reduces to zero which also reduces the difference with current.
// If the decay time is infinite, don't decay at all.
float decayFactor = 0f;
if (TargetValueDecayTimeScale != BSMotor.Infinite)
{
decayFactor = (1.0f / TargetValueDecayTimeScale) * timeStep;
TargetValue *= (1f - decayFactor);
}
// The amount we can correct the error is reduced by the friction
float frictionFactor = 0f;
if (FrictionTimescale != BSMotor.Infinite)
{
// frictionFactor = (Vector3.One / FrictionTimescale) * timeStep;
// Individual friction components can be 'infinite' so compute each separately.
frictionFactor = 1f / FrictionTimescale;
frictionFactor *= timeStep;
CurrentValue *= (1f - frictionFactor);
}
MDetailLog("{0}, BSFMotor.Step,nonZero,{1},origCurr={2},origTarget={3},timeStep={4},err={5},corr={6}",
BSScene.DetailLogZero, UseName, origCurrVal, origTarget,
timeStep, error, correction);
MDetailLog("{0}, BSFMotor.Step,nonZero,{1},tgtDecayTS={2},decayFact={3},frictTS={4},frictFact={5},tgt={6},curr={7}",
BSScene.DetailLogZero, UseName,
TargetValueDecayTimeScale, decayFactor, FrictionTimescale, frictionFactor,
TargetValue, CurrentValue);
}
else
{
// Difference between what we have and target is small. Motor is done.
if (Util.InRange<float>(TargetValue, -ErrorZeroThreshold, ErrorZeroThreshold))
{
// The target can step down to nearly zero but not get there. If close to zero
// it is really zero.
TargetValue = 0f;
}
CurrentValue = TargetValue;
MDetailLog("{0}, BSFMotor.Step,zero,{1},origTgt={2},origCurr={3},ret={4}",
BSScene.DetailLogZero, UseName, origCurrVal, origTarget, CurrentValue);
}
return CurrentValue;
}
public virtual float StepError(float timeStep, float error)
{
if (!Enabled) return 0f;
float returnCorrection = 0f;
if (!ErrorIsZero(error))
{
// correction = error / secondsItShouldTakeToCorrect
float correctionAmount;
if (TimeScale == 0f || TimeScale == BSMotor.Infinite)
correctionAmount = error * timeStep;
else
correctionAmount = error / TimeScale * timeStep;
returnCorrection = correctionAmount;
MDetailLog("{0}, BSFMotor.Step,nonZero,{1},timeStep={2},timeScale={3},err={4},corr={5}",
BSScene.DetailLogZero, UseName, timeStep, TimeScale, error, correctionAmount);
}
return returnCorrection;
}
public override string ToString()
{
return String.Format("<{0},curr={1},targ={2},lastErr={3},decayTS={4},frictTS={5}>",
UseName, CurrentValue, TargetValue, LastError, TargetValueDecayTimeScale, FrictionTimescale);
}
}
// ============================================================================
// ============================================================================
// Proportional, Integral, Derivitive Motor
// Good description at http://www.answers.com/topic/pid-controller . Includes processes for choosing p, i and d factors.
public class BSPIDVMotor : BSVMotor
{
// Larger makes more overshoot, smaller means converge quicker. Range of 0.1 to 10.
public Vector3 proportionFactor { get; set; }
public Vector3 integralFactor { get; set; }
public Vector3 derivFactor { get; set; }
// The factors are vectors for the three dimensions. This is the proportional of each
// that is applied. This could be multiplied through the actual factors but it
// is sometimes easier to manipulate the factors and their mix separately.
// to
public Vector3 FactorMix;
// Arbritrary factor range.
// EfficiencyHigh means move quickly to the correct number. EfficiencyLow means might over correct.
public float EfficiencyHigh = 0.4f;
public float EfficiencyLow = 4.0f;
// Running integration of the error
Vector3 RunningIntegration { get; set; }
public BSPIDVMotor(string useName)
: base(useName)
{
proportionFactor = new Vector3(1.00f, 1.00f, 1.00f);
integralFactor = new Vector3(1.00f, 1.00f, 1.00f);
derivFactor = new Vector3(1.00f, 1.00f, 1.00f);
FactorMix = new Vector3(0.5f, 0.25f, 0.25f);
RunningIntegration = Vector3.Zero;
LastError = Vector3.Zero;
}
public override void Zero()
{
base.Zero();
}
public override float Efficiency
{
get { return base.Efficiency; }
set
{
base.Efficiency = Util.Clamp(value, 0f, 1f);
// Compute factors based on efficiency.
// If efficiency is high (1f), use a factor value that moves the error value to zero with little overshoot.
// If efficiency is low (0f), use a factor value that overcorrects.
// TODO: might want to vary contribution of different factor depending on efficiency.
float factor = ((1f - this.Efficiency) * EfficiencyHigh + EfficiencyLow) / 3f;
// float factor = (1f - this.Efficiency) * EfficiencyHigh + EfficiencyLow;
proportionFactor = new Vector3(factor, factor, factor);
integralFactor = new Vector3(factor, factor, factor);
derivFactor = new Vector3(factor, factor, factor);
MDetailLog("{0},BSPIDVMotor.setEfficiency,eff={1},factor={2}", BSScene.DetailLogZero, Efficiency, factor);
}
}
// Advance the PID computation on this error.
public override Vector3 StepError(float timeStep, Vector3 error)
{
if (!Enabled) return Vector3.Zero;
// Add up the error so we can integrate over the accumulated errors
RunningIntegration += error * timeStep;
// A simple derivitive is the rate of change from the last error.
Vector3 derivitive = (error - LastError) * timeStep;
LastError = error;
// Correction = (proportionOfPresentError + accumulationOfPastError + rateOfChangeOfError)
Vector3 ret = error * timeStep * proportionFactor * FactorMix.X
+ RunningIntegration * integralFactor * FactorMix.Y
+ derivitive * derivFactor * FactorMix.Z
;
MDetailLog("{0},BSPIDVMotor.step,ts={1},err={2},runnInt={3},deriv={4},ret={5}",
BSScene.DetailLogZero, timeStep, error, RunningIntegration, derivitive, ret);
return ret;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System
{
using System;
using System.Reflection;
using System.Runtime;
using System.Threading;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Diagnostics;
[ClassInterface(ClassInterfaceType.AutoDual)]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class Delegate : ICloneable, ISerializable
{
// _target is the object we will invoke on
internal Object _target;
// MethodBase, either cached after first request or assigned from a DynamicMethod
// For open delegates to collectible types, this may be a LoaderAllocator object
internal Object _methodBase;
// _methodPtr is a pointer to the method we will invoke
// It could be a small thunk if this is a static or UM call
internal IntPtr _methodPtr;
// In the case of a static method passed to a delegate, this field stores
// whatever _methodPtr would have stored: and _methodPtr points to a
// small thunk which removes the "this" pointer before going on
// to _methodPtrAux.
internal IntPtr _methodPtrAux;
// This constructor is called from the class generated by the
// compiler generated code
protected Delegate(Object target, String method)
{
if (target == null)
throw new ArgumentNullException(nameof(target));
if (method == null)
throw new ArgumentNullException(nameof(method));
// This API existed in v1/v1.1 and only expected to create closed
// instance delegates. Constrain the call to BindToMethodName to
// such and don't allow relaxed signature matching (which could make
// the choice of target method ambiguous) for backwards
// compatibility. The name matching was case sensitive and we
// preserve that as well.
if (!BindToMethodName(target, (RuntimeType)target.GetType(), method,
DelegateBindingFlags.InstanceMethodOnly |
DelegateBindingFlags.ClosedDelegateOnly))
throw new ArgumentException(SR.Arg_DlgtTargMeth);
}
// This constructor is called from a class to generate a
// delegate based upon a static method name and the Type object
// for the class defining the method.
protected unsafe Delegate(Type target, String method)
{
if (target == null)
throw new ArgumentNullException(nameof(target));
if (target.ContainsGenericParameters)
throw new ArgumentException(SR.Arg_UnboundGenParam, nameof(target));
if (method == null)
throw new ArgumentNullException(nameof(method));
RuntimeType rtTarget = target as RuntimeType;
if (rtTarget == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(target));
// This API existed in v1/v1.1 and only expected to create open
// static delegates. Constrain the call to BindToMethodName to such
// and don't allow relaxed signature matching (which could make the
// choice of target method ambiguous) for backwards compatibility.
// The name matching was case insensitive (no idea why this is
// different from the constructor above) and we preserve that as
// well.
BindToMethodName(null, rtTarget, method,
DelegateBindingFlags.StaticMethodOnly |
DelegateBindingFlags.OpenDelegateOnly |
DelegateBindingFlags.CaselessMatching);
}
// Protect the default constructor so you can't build a delegate
private Delegate()
{
}
public Object DynamicInvoke(params Object[] args)
{
// Theoretically we should set up a LookForMyCaller stack mark here and pass that along.
// But to maintain backward compatibility we can't switch to calling an
// internal overload of DynamicInvokeImpl that takes a stack mark.
// Fortunately the stack walker skips all the reflection invocation frames including this one.
// So this method will never be returned by the stack walker as the caller.
// See SystemDomain::CallersMethodCallbackWithStackMark in AppDomain.cpp.
return DynamicInvokeImpl(args);
}
protected virtual object DynamicInvokeImpl(object[] args)
{
RuntimeMethodHandleInternal method = new RuntimeMethodHandleInternal(GetInvokeMethod());
RuntimeMethodInfo invoke = (RuntimeMethodInfo)RuntimeType.GetMethodBase((RuntimeType)this.GetType(), method);
return invoke.Invoke(this, BindingFlags.Default, null, args, null);
}
public override bool Equals(Object obj)
{
if (obj == null || !InternalEqualTypes(this, obj))
return false;
Delegate d = (Delegate)obj;
// do an optimistic check first. This is hopefully cheap enough to be worth
if (_target == d._target && _methodPtr == d._methodPtr && _methodPtrAux == d._methodPtrAux)
return true;
// even though the fields were not all equals the delegates may still match
// When target carries the delegate itself the 2 targets (delegates) may be different instances
// but the delegates are logically the same
// It may also happen that the method pointer was not jitted when creating one delegate and jitted in the other
// if that's the case the delegates may still be equals but we need to make a more complicated check
if (_methodPtrAux == IntPtr.Zero)
{
if (d._methodPtrAux != IntPtr.Zero)
return false; // different delegate kind
// they are both closed over the first arg
if (_target != d._target)
return false;
// fall through method handle check
}
else
{
if (d._methodPtrAux == IntPtr.Zero)
return false; // different delegate kind
// Ignore the target as it will be the delegate instance, though it may be a different one
/*
if (_methodPtr != d._methodPtr)
return false;
*/
if (_methodPtrAux == d._methodPtrAux)
return true;
// fall through method handle check
}
// method ptrs don't match, go down long path
//
if (_methodBase == null || d._methodBase == null || !(_methodBase is MethodInfo) || !(d._methodBase is MethodInfo))
return Delegate.InternalEqualMethodHandles(this, d);
else
return _methodBase.Equals(d._methodBase);
}
public override int GetHashCode()
{
//
// this is not right in the face of a method being jitted in one delegate and not in another
// in that case the delegate is the same and Equals will return true but GetHashCode returns a
// different hashcode which is not true.
/*
if (_methodPtrAux == IntPtr.Zero)
return unchecked((int)((long)this._methodPtr));
else
return unchecked((int)((long)this._methodPtrAux));
*/
if (_methodPtrAux == IntPtr.Zero)
return ( _target != null ? RuntimeHelpers.GetHashCode(_target) * 33 : 0) + GetType().GetHashCode();
else
return GetType().GetHashCode();
}
public static Delegate Combine(Delegate a, Delegate b)
{
if ((Object)a == null) // cast to object for a more efficient test
return b;
return a.CombineImpl(b);
}
public static Delegate Combine(params Delegate[] delegates)
{
if (delegates == null || delegates.Length == 0)
return null;
Delegate d = delegates[0];
for (int i = 1; i < delegates.Length; i++)
d = Combine(d, delegates[i]);
return d;
}
public virtual Delegate[] GetInvocationList()
{
Delegate[] d = new Delegate[1];
d[0] = this;
return d;
}
// This routine will return the method
public MethodInfo Method
{
get
{
return GetMethodImpl();
}
}
protected virtual MethodInfo GetMethodImpl()
{
if ((_methodBase == null) || !(_methodBase is MethodInfo))
{
IRuntimeMethodInfo method = FindMethodHandle();
RuntimeType declaringType = RuntimeMethodHandle.GetDeclaringType(method);
// need a proper declaring type instance method on a generic type
if (RuntimeTypeHandle.IsGenericTypeDefinition(declaringType) || RuntimeTypeHandle.HasInstantiation(declaringType))
{
bool isStatic = (RuntimeMethodHandle.GetAttributes(method) & MethodAttributes.Static) != (MethodAttributes)0;
if (!isStatic)
{
if (_methodPtrAux == IntPtr.Zero)
{
// The target may be of a derived type that doesn't have visibility onto the
// target method. We don't want to call RuntimeType.GetMethodBase below with that
// or reflection can end up generating a MethodInfo where the ReflectedType cannot
// see the MethodInfo itself and that breaks an important invariant. But the
// target type could include important generic type information we need in order
// to work out what the exact instantiation of the method's declaring type is. So
// we'll walk up the inheritance chain (which will yield exactly instantiated
// types at each step) until we find the declaring type. Since the declaring type
// we get from the method is probably shared and those in the hierarchy we're
// walking won't be we compare using the generic type definition forms instead.
Type currentType = _target.GetType();
Type targetType = declaringType.GetGenericTypeDefinition();
while (currentType != null)
{
if (currentType.IsGenericType &&
currentType.GetGenericTypeDefinition() == targetType)
{
declaringType = currentType as RuntimeType;
break;
}
currentType = currentType.BaseType;
}
// RCWs don't need to be "strongly-typed" in which case we don't find a base type
// that matches the declaring type of the method. This is fine because interop needs
// to work with exact methods anyway so declaringType is never shared at this point.
Debug.Assert(currentType != null || _target.GetType().IsCOMObject, "The class hierarchy should declare the method");
}
else
{
// it's an open one, need to fetch the first arg of the instantiation
MethodInfo invoke = this.GetType().GetMethod("Invoke");
declaringType = (RuntimeType)invoke.GetParameters()[0].ParameterType;
}
}
}
_methodBase = (MethodInfo)RuntimeType.GetMethodBase(declaringType, method);
}
return (MethodInfo)_methodBase;
}
public Object Target
{
get
{
return GetTarget();
}
}
public static Delegate Remove(Delegate source, Delegate value)
{
if (source == null)
return null;
if (value == null)
return source;
if (!InternalEqualTypes(source, value))
throw new ArgumentException(SR.Arg_DlgtTypeMis);
return source.RemoveImpl(value);
}
public static Delegate RemoveAll(Delegate source, Delegate value)
{
Delegate newDelegate = null;
do
{
newDelegate = source;
source = Remove(source, value);
}
while (newDelegate != source);
return newDelegate;
}
protected virtual Delegate CombineImpl(Delegate d)
{
throw new MulticastNotSupportedException(SR.Multicast_Combine);
}
protected virtual Delegate RemoveImpl(Delegate d)
{
return (d.Equals(this)) ? null : this;
}
public virtual Object Clone()
{
return MemberwiseClone();
}
// V1 API.
public static Delegate CreateDelegate(Type type, Object target, String method)
{
return CreateDelegate(type, target, method, false, true);
}
// V1 API.
public static Delegate CreateDelegate(Type type, Object target, String method, bool ignoreCase)
{
return CreateDelegate(type, target, method, ignoreCase, true);
}
// V1 API.
public static Delegate CreateDelegate(Type type, Object target, String method, bool ignoreCase, bool throwOnBindFailure)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
if (target == null)
throw new ArgumentNullException(nameof(target));
if (method == null)
throw new ArgumentNullException(nameof(method));
RuntimeType rtType = type as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type));
if (!rtType.IsDelegate())
throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(type));
Delegate d = InternalAlloc(rtType);
// This API existed in v1/v1.1 and only expected to create closed
// instance delegates. Constrain the call to BindToMethodName to such
// and don't allow relaxed signature matching (which could make the
// choice of target method ambiguous) for backwards compatibility.
// We never generate a closed over null delegate and this is
// actually enforced via the check on target above, but we pass
// NeverCloseOverNull anyway just for clarity.
if (!d.BindToMethodName(target, (RuntimeType)target.GetType(), method,
DelegateBindingFlags.InstanceMethodOnly |
DelegateBindingFlags.ClosedDelegateOnly |
DelegateBindingFlags.NeverCloseOverNull |
(ignoreCase ? DelegateBindingFlags.CaselessMatching : 0)))
{
if (throwOnBindFailure)
throw new ArgumentException(SR.Arg_DlgtTargMeth);
d = null;
}
return d;
}
// V1 API.
public static Delegate CreateDelegate(Type type, Type target, String method)
{
return CreateDelegate(type, target, method, false, true);
}
// V1 API.
public static Delegate CreateDelegate(Type type, Type target, String method, bool ignoreCase)
{
return CreateDelegate(type, target, method, ignoreCase, true);
}
// V1 API.
public static Delegate CreateDelegate(Type type, Type target, String method, bool ignoreCase, bool throwOnBindFailure)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
if (target == null)
throw new ArgumentNullException(nameof(target));
if (target.ContainsGenericParameters)
throw new ArgumentException(SR.Arg_UnboundGenParam, nameof(target));
if (method == null)
throw new ArgumentNullException(nameof(method));
RuntimeType rtType = type as RuntimeType;
RuntimeType rtTarget = target as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type));
if (rtTarget == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(target));
if (!rtType.IsDelegate())
throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(type));
Delegate d = InternalAlloc(rtType);
// This API existed in v1/v1.1 and only expected to create open
// static delegates. Constrain the call to BindToMethodName to such
// and don't allow relaxed signature matching (which could make the
// choice of target method ambiguous) for backwards compatibility.
if (!d.BindToMethodName(null, rtTarget, method,
DelegateBindingFlags.StaticMethodOnly |
DelegateBindingFlags.OpenDelegateOnly |
(ignoreCase ? DelegateBindingFlags.CaselessMatching : 0)))
{
if (throwOnBindFailure)
throw new ArgumentException(SR.Arg_DlgtTargMeth);
d = null;
}
return d;
}
// V1 API.
public static Delegate CreateDelegate(Type type, MethodInfo method, bool throwOnBindFailure)
{
// Validate the parameters.
if (type == null)
throw new ArgumentNullException(nameof(type));
if (method == null)
throw new ArgumentNullException(nameof(method));
RuntimeType rtType = type as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type));
RuntimeMethodInfo rmi = method as RuntimeMethodInfo;
if (rmi == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, nameof(method));
if (!rtType.IsDelegate())
throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(type));
// This API existed in v1/v1.1 and only expected to create closed
// instance delegates. Constrain the call to BindToMethodInfo to
// open delegates only for backwards compatibility. But we'll allow
// relaxed signature checking and open static delegates because
// there's no ambiguity there (the caller would have to explicitly
// pass us a static method or a method with a non-exact signature
// and the only change in behavior from v1.1 there is that we won't
// fail the call).
Delegate d = CreateDelegateInternal(
rtType,
rmi,
null,
DelegateBindingFlags.OpenDelegateOnly | DelegateBindingFlags.RelaxedSignature);
if (d == null && throwOnBindFailure)
throw new ArgumentException(SR.Arg_DlgtTargMeth);
return d;
}
// V2 API.
public static Delegate CreateDelegate(Type type, Object firstArgument, MethodInfo method)
{
return CreateDelegate(type, firstArgument, method, true);
}
// V2 API.
public static Delegate CreateDelegate(Type type, Object firstArgument, MethodInfo method, bool throwOnBindFailure)
{
// Validate the parameters.
if (type == null)
throw new ArgumentNullException(nameof(type));
if (method == null)
throw new ArgumentNullException(nameof(method));
RuntimeType rtType = type as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type));
RuntimeMethodInfo rmi = method as RuntimeMethodInfo;
if (rmi == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, nameof(method));
if (!rtType.IsDelegate())
throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(type));
// This API is new in Whidbey and allows the full range of delegate
// flexability (open or closed delegates binding to static or
// instance methods with relaxed signature checking. The delegate
// can also be closed over null. There's no ambiguity with all these
// options since the caller is providing us a specific MethodInfo.
Delegate d = CreateDelegateInternal(
rtType,
rmi,
firstArgument,
DelegateBindingFlags.RelaxedSignature);
if (d == null && throwOnBindFailure)
throw new ArgumentException(SR.Arg_DlgtTargMeth);
return d;
}
public static bool operator ==(Delegate d1, Delegate d2)
{
if ((Object)d1 == null)
return (Object)d2 == null;
return d1.Equals(d2);
}
public static bool operator !=(Delegate d1, Delegate d2)
{
if ((Object)d1 == null)
return (Object)d2 != null;
return !d1.Equals(d2);
}
//
// Implementation of ISerializable
//
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
//
// internal implementation details (FCALLS and utilities)
//
// V2 internal API.
// This is Critical because it skips the security check when creating the delegate.
internal unsafe static Delegate CreateDelegateNoSecurityCheck(Type type, Object target, RuntimeMethodHandle method)
{
// Validate the parameters.
if (type == null)
throw new ArgumentNullException(nameof(type));
if (method.IsNullHandle())
throw new ArgumentNullException(nameof(method));
RuntimeType rtType = type as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type));
if (!rtType.IsDelegate())
throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(type));
// Initialize the method...
Delegate d = InternalAlloc(rtType);
// This is a new internal API added in Whidbey. Currently it's only
// used by the dynamic method code to generate a wrapper delegate.
// Allow flexible binding options since the target method is
// unambiguously provided to us.
if (!d.BindToMethodInfo(target,
method.GetMethodInfo(),
RuntimeMethodHandle.GetDeclaringType(method.GetMethodInfo()),
DelegateBindingFlags.RelaxedSignature | DelegateBindingFlags.SkipSecurityChecks))
throw new ArgumentException(SR.Arg_DlgtTargMeth);
return d;
}
// Caution: this method is intended for deserialization only, no security checks are performed.
internal static Delegate CreateDelegateNoSecurityCheck(RuntimeType type, Object firstArgument, MethodInfo method)
{
// Validate the parameters.
if (type == null)
throw new ArgumentNullException(nameof(type));
if (method == null)
throw new ArgumentNullException(nameof(method));
RuntimeMethodInfo rtMethod = method as RuntimeMethodInfo;
if (rtMethod == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, nameof(method));
if (!type.IsDelegate())
throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(type));
// This API is used by the formatters when deserializing a delegate.
// They pass us the specific target method (that was already the
// target in a valid delegate) so we should bind with the most
// relaxed rules available (the result will never be ambiguous, it
// just increases the chance of success with minor (compatible)
// signature changes). We explicitly skip security checks here --
// we're not really constructing a delegate, we're cloning an
// existing instance which already passed its checks.
Delegate d = CreateDelegateInternal(type, rtMethod, firstArgument,
DelegateBindingFlags.SkipSecurityChecks |
DelegateBindingFlags.RelaxedSignature);
if (d == null)
throw new ArgumentException(SR.Arg_DlgtTargMeth);
return d;
}
// V1 API.
public static Delegate CreateDelegate(Type type, MethodInfo method)
{
return CreateDelegate(type, method, true);
}
internal static Delegate CreateDelegateInternal(RuntimeType rtType, RuntimeMethodInfo rtMethod, Object firstArgument, DelegateBindingFlags flags)
{
Delegate d = InternalAlloc(rtType);
if (d.BindToMethodInfo(firstArgument, rtMethod, rtMethod.GetDeclaringTypeInternal(), flags))
return d;
else
return null;
}
//
// internal implementation details (FCALLS and utilities)
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool BindToMethodName(Object target, RuntimeType methodType, String method, DelegateBindingFlags flags);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool BindToMethodInfo(Object target, IRuntimeMethodInfo method, RuntimeType methodType, DelegateBindingFlags flags);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static MulticastDelegate InternalAlloc(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static MulticastDelegate InternalAllocLike(Delegate d);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool InternalEqualTypes(object a, object b);
// Used by the ctor. Do not call directly.
// The name of this function will appear in managed stacktraces as delegate constructor.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void DelegateConstruct(Object target, IntPtr slot);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern IntPtr GetMulticastInvoke();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern IntPtr GetInvokeMethod();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern IRuntimeMethodInfo FindMethodHandle();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool InternalEqualMethodHandles(Delegate left, Delegate right);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern IntPtr AdjustTarget(Object target, IntPtr methodPtr);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern IntPtr GetCallStub(IntPtr methodPtr);
internal virtual Object GetTarget()
{
return (_methodPtrAux == IntPtr.Zero) ? _target : null;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool CompareUnmanagedFunctionPtrs(Delegate d1, Delegate d2);
}
// These flags effect the way BindToMethodInfo and BindToMethodName are allowed to bind a delegate to a target method. Their
// values must be kept in sync with the definition in vm\comdelegate.h.
internal enum DelegateBindingFlags
{
StaticMethodOnly = 0x00000001, // Can only bind to static target methods
InstanceMethodOnly = 0x00000002, // Can only bind to instance (including virtual) methods
OpenDelegateOnly = 0x00000004, // Only allow the creation of delegates open over the 1st argument
ClosedDelegateOnly = 0x00000008, // Only allow the creation of delegates closed over the 1st argument
NeverCloseOverNull = 0x00000010, // A null target will never been considered as a possible null 1st argument
CaselessMatching = 0x00000020, // Use case insensitive lookup for methods matched by name
SkipSecurityChecks = 0x00000040, // Skip security checks (visibility, link demand etc.)
RelaxedSignature = 0x00000080, // Allow relaxed signature matching (co/contra variance)
}
}
| |
#if !SILVERLIGHT && !NETFX_CORE
using NUnit.Framework;
#endif
using System;
using System.Windows;
using DevExpress.Mvvm.UI;
#if NETFX_CORE
using DevExpress.TestFramework.NUnit;
using Windows.UI.Xaml;
using System.Globalization;
using Windows.UI.Xaml.Data;
#else
using System.Globalization;
using System.Windows.Data;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Moq;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using DevExpress.Mvvm.Native;
#endif
namespace DevExpress.Mvvm.Tests {
[TestFixture]
public class ConvertersTest {
#if !NETFX_CORE && !SILVERLIGHT
[Test]
public void ReflectionConverterShouldNotPassNullIntoContructorIfTargetTypeIsNotValueType() {
var converter1 = new ReflectionConverter();
Assert.AreEqual(null, (FromString)converter1.Convert(null, typeof(FromString), null, null));
}
[Test]
public void ReflectionConverterTest() {
var converter1 = new ReflectionConverter();
Assert.IsNull(converter1.Convert(null, null, null, null));
Assert.IsNull(converter1.ConvertBack(null, null, null, null));
Assert.AreEqual(15, converter1.Convert(15, null, null, null));
Assert.AreEqual(15, converter1.ConvertBack(15, null, null, null));
Assert.AreEqual("abc", ((FromString)converter1.Convert("abc", typeof(FromString), null, null)).S);
Assert.AreEqual("abc", ((FromString)converter1.ConvertBack("abc", typeof(FromString), null, null)).S);
var converter2 = new ReflectionConverter() { ConvertMethod = "ToString", ConvertBackMethodOwner = typeof(FromString) };
Assert.AreEqual("15", converter2.Convert(new FromString("15"), null, null, null));
Assert.AreEqual("abc", ((FromString)converter2.ConvertBack("abc", null, null, null)).S);
var converter3 = new ReflectionConverter() { ConvertMethodOwner = typeof(FromString), ConvertBackMethod = "ToString", ConvertBackMethodOwner = null };
Assert.AreEqual("abc", ((FromString)converter3.Convert("abc", null, null, null)).S);
Assert.AreEqual("15", converter3.ConvertBack(new FromString("15"), null, null, null));
var converter4 = new ReflectionConverter() { ConvertMethodOwner = typeof(ReflectionConverterTestMethods), ConvertMethod = "IntToString", ConvertBackMethod = "StringToInt" };
Assert.AreEqual("S15", converter4.Convert(15, null, null, null));
Assert.AreEqual(15, converter4.ConvertBack("S15", null, null, null));
}
[Test]
public void ReflectionConverter_ConvertBackMethodOwnerTest() {
Assert.AreEqual(typeof(int), new ReflectionConverter() { ConvertMethodOwner = typeof(int) }.ConvertBackMethodOwner);
Assert.AreEqual(null, new ReflectionConverter() { ConvertMethodOwner = typeof(int), ConvertBackMethodOwner = null }.ConvertBackMethodOwner);
Assert.AreEqual(typeof(int), new ReflectionConverterExtension() { ConvertMethodOwner = typeof(int) }.ConvertBackMethodOwner);
Assert.AreEqual(null, new ReflectionConverterExtension() { ConvertMethodOwner = typeof(int), ConvertBackMethodOwner = null }.ConvertBackMethodOwner);
Assert.AreEqual(typeof(int), new ReflectionConverterExtension() { ConvertMethodOwner = typeof(int) }.ProvideValue(null).With(x => (ReflectionConverter)x).ConvertBackMethodOwner);
Assert.AreEqual(null, new ReflectionConverterExtension() { ConvertMethodOwner = typeof(int), ConvertBackMethodOwner = null }.ProvideValue(null).With(x => (ReflectionConverter)x).ConvertBackMethodOwner);
}
[Test]
public void ReflectionConverter_ConvertMethodParametersTest() {
ReflectionConverter_ConvertMethodParametersTest(m => m.Setup(c => c.Convert01(22)).Returns((int v) => ReflectionConverter_Result(v, null)), "Convert01", false);
ReflectionConverter_ConvertMethodParametersTest(m => m.Setup(c => c.Convert02(22)).Returns((object v) => ReflectionConverter_Result(v, null)), "Convert02", false);
ReflectionConverter_ConvertMethodParametersTest(m => m.Setup(c => c.Convert03(22, 14)).Returns((int v, int p) => ReflectionConverter_Result(v, p)), "Convert03", true);
ReflectionConverter_ConvertMethodParametersTest(m => m.Setup(c => c.Convert04(22, 14)).Returns((int v, object p) => ReflectionConverter_Result(v, p)), "Convert04", true);
ReflectionConverter_ConvertMethodParametersTest(m => m.Setup(c => c.Convert05(22, 14)).Returns((object v, object p) => ReflectionConverter_Result(v, p)), "Convert05", true);
ReflectionConverter_ConvertMethodParametersTest(m => m.Setup(c => c.Convert06(22, typeof(string), 14)).Returns((object v, Type t, int p) => ReflectionConverter_Result(v, p)), "Convert06", true);
ReflectionConverter_ConvertMethodParametersTest(m => m.Setup(c => c.Convert07(22, typeof(string), 14)).Returns((object v, Type t, object p) => ReflectionConverter_Result(v, p)), "Convert07", true);
ReflectionConverter_ConvertMethodParametersTest(m => m.Setup(c => c.Convert08(22, typeof(string), 14)).Returns((int v, Type t, object p) => ReflectionConverter_Result(v, p)), "Convert08", true);
ReflectionConverter_ConvertMethodParametersTest(m => m.Setup(c => c.Convert17(22, typeof(string))).Returns((object v, Type t) => ReflectionConverter_Result(v, null)), "Convert17", false);
ReflectionConverter_ConvertMethodParametersTest(m => m.Setup(c => c.Convert18(22, typeof(string))).Returns((int v, Type t) => ReflectionConverter_Result(v, null)), "Convert18", false);
ReflectionConverter_ConvertMethodParametersTest(m => m.Setup(c => c.Convert09(22, CultureInfo.InvariantCulture)).Returns((object v, CultureInfo c) => ReflectionConverter_Result(v, null)), "Convert09", false);
ReflectionConverter_ConvertMethodParametersTest(m => m.Setup(c => c.Convert10(22, CultureInfo.InvariantCulture)).Returns((int v, CultureInfo c) => ReflectionConverter_Result(v, null)), "Convert10", false);
ReflectionConverter_ConvertMethodParametersTest(m => m.Setup(c => c.Convert11(22, 14, CultureInfo.InvariantCulture)).Returns((int v, int p, CultureInfo c) => ReflectionConverter_Result(v, p)), "Convert11", true);
ReflectionConverter_ConvertMethodParametersTest(m => m.Setup(c => c.Convert12(22, 14, CultureInfo.InvariantCulture)).Returns((int v, object p, CultureInfo c) => ReflectionConverter_Result(v, p)), "Convert12", true);
ReflectionConverter_ConvertMethodParametersTest(m => m.Setup(c => c.Convert13(22, 14, CultureInfo.InvariantCulture)).Returns((object v, int p, CultureInfo c) => ReflectionConverter_Result(v, p)), "Convert13", true);
ReflectionConverter_ConvertMethodParametersTest(m => m.Setup(c => c.Convert14(22, typeof(string), 14, CultureInfo.InvariantCulture)).Returns((object v, Type t, int p, CultureInfo c) => ReflectionConverter_Result(v, p)), "Convert14", true);
ReflectionConverter_ConvertMethodParametersTest(m => m.Setup(c => c.Convert15(22, typeof(string), 14, CultureInfo.InvariantCulture)).Returns((object v, Type t, object p, CultureInfo c) => ReflectionConverter_Result(v, p)), "Convert15", true);
ReflectionConverter_ConvertMethodParametersTest(m => m.Setup(c => c.Convert16(22, typeof(string), 14, CultureInfo.InvariantCulture)).Returns((int v, Type t, object p, CultureInfo c) => ReflectionConverter_Result(v, p)), "Convert16", true);
}
void ReflectionConverter_ConvertMethodParametersTest(Action<Mock<IReflectionConverterTestMock>> setup, string method, bool withParameter) {
var mock = new Mock<IReflectionConverterTestMock>(MockBehavior.Strict);
ReflectionConvertTestMockStatic.Mock = mock.Object;
setup(mock);
IValueConverter reflectionConverter = new ReflectionConverter() { ConvertMethodOwner = typeof(ReflectionConvertTestMockStatic), ConvertMethod = method };
Assert.AreEqual(withParameter ? "36" : "22", reflectionConverter.Convert(22, typeof(string), 14, CultureInfo.InvariantCulture));
}
string ReflectionConverter_Result(object value, object parameter) {
int p = parameter == null ? 0 : (int)parameter;
return ((int)value + p).ToString();
}
[Test]
public void EnumerableConverter_ConvertToEnumerableTest() {
var converter = new EnumerableConverter() { TargetItemType = typeof(string), ItemConverter = new ToStringConverter() };
Assert.AreEqual(null, converter.Convert(null, null, null, null));
AssertHelper.AssertEnumerablesAreEqual(new string[] { }, converter.Convert(Enumerable.Empty<int>(), null, null, null).With(x => (IEnumerable<string>)x).With(x => x.ToArray()));
AssertHelper.AssertEnumerablesAreEqual(new string[] { "0", "1", "2" }, (IEnumerable<string>)converter.Convert(new int[] { 0, 1, 2 }, null, null, null));
}
IEnumerable<int> GetInfiniteEnumerable() {
for(int i = 0; ; ++i)
yield return i;
}
[Test]
public void EnumerableConverter_ConvertInfiniteEnumerableTest() {
foreach(var targetType in new Type[] { null, typeof(IEnumerable<string>) }) {
var converter = new EnumerableConverter() { TargetItemType = typeof(string), ItemConverter = new ToStringConverter() };
var result = (IEnumerable<string>)converter.Convert(GetInfiniteEnumerable(), null, null, null);
string[] array500 = result.Take(500).ToArray();
for(int i = 0; i < 500; ++i)
Assert.AreEqual(i.ToString(), array500[i]);
}
}
[Test]
public void EnumerableConverter_ConvertToCollectionTest() {
var converter = new EnumerableConverter() { TargetItemType = typeof(string), ItemConverter = new ToStringConverter() };
TestEnumerableConverter<IList<string>>(converter);
TestEnumerableConverter<ICollection<string>>(converter);
TestEnumerableConverter<IEnumerable<string>>(converter);
TestEnumerableConverter<List<string>>(converter);
TestEnumerableConverter<Collection<string>>(converter);
TestEnumerableConverter<ObservableCollection<string>>(converter);
TestEnumerableConverter<ReadOnlyCollection<string>>(converter);
TestEnumerableConverter<StringCollection>(converter);
TestEnumerableConverter<ArrayList>(converter);
TestEnumerableConverter<Queue>(converter);
TestEnumerableConverter<Queue<string>>(converter);
}
[Test]
public void EnumerableConverter_TryConvertToAbstractCollectionTest() {
var converter = new EnumerableConverter() { TargetItemType = typeof(string), ItemConverter = new ToStringConverter() };
AssertHelper.AssertThrows<NotSupportedCollectionException>(() => {
converter.Convert(new int[] { 0, 1, 2 }, typeof(ReadOnlyCollectionBase), null, null);
}, e => {
Assert.AreEqual("Cannot create an abstract class.", e.InnerException.Message);
});
}
[Test, ExpectedException(typeof(NotSupportedCollectionException))]
public void EnumerableConverter_TryConvertToInvalidCollectionTest() {
var converter = new EnumerableConverter() { TargetItemType = typeof(string), ItemConverter = new ToStringConverter() };
converter.Convert(new int[] { 0, 1, 2 }, Enumerable.Empty<string>().GetType(), null, null);
}
[Test]
public void EnumerableConverter_DetectTargetItemTypeTest() {
var converter = new EnumerableConverter() { ItemConverter = new ToStringConverter() };
TestEnumerableConverter<IList<string>>(converter);
TestEnumerableConverter<ICollection<string>>(converter);
TestEnumerableConverter<IEnumerable<string>>(converter);
TestEnumerableConverter<List<string>>(converter);
TestEnumerableConverter<Collection<string>>(converter);
TestEnumerableConverter<ObservableCollection<string>>(converter);
TestEnumerableConverter<ReadOnlyCollection<string>>(converter);
}
[Test, ExpectedException(typeof(InvalidOperationException))]
public void EnumerableConverter_DetectTargetItemTypeFailTest() {
var converter = new EnumerableConverter() { ItemConverter = new ToStringConverter() };
converter.Convert(new int[] { 0, 1, 2 }, typeof(StringCollection), null, null);
}
void TestEnumerableConverter<TCollection>(IValueConverter converter) where TCollection : IEnumerable {
AssertHelper.AssertEnumerablesAreEqual(new string[] { "0", "1", "2" }, (TCollection)converter.Convert(new int[] { 0, 1, 2 }, typeof(TCollection), null, null));
}
#endif
#if !NETFX_CORE && !FREE
[Test]
public void CriteriaOperatorConverter_ToUpperCaseTest() {
var converter = new CriteriaOperatorConverter() { Expression = "Upper(This)" };
Assert.AreEqual("ABCD", converter.Convert("abcd", null, null, null));
}
#endif
[Test]
public void BooleanToVisibilityConverter() {
var converter = new BooleanToVisibilityConverter();
Assert.AreEqual(Visibility.Visible, converter.Convert(true, typeof(Visibility), null, null));
Assert.AreEqual(Visibility.Collapsed, converter.Convert(false, typeof(Visibility), null, null));
Assert.AreEqual(Visibility.Visible, converter.Convert(new Nullable<bool>(true), typeof(Visibility), null, null));
Assert.AreEqual(Visibility.Collapsed, converter.Convert(new Nullable<bool>(false), typeof(Visibility), null, null));
Assert.AreEqual(Visibility.Collapsed, converter.Convert(new Nullable<bool>(), typeof(Visibility), null, null));
Assert.AreEqual(Visibility.Collapsed, converter.Convert(null, typeof(Visibility), null, null));
Assert.AreEqual(Visibility.Collapsed, converter.Convert("test", typeof(Visibility), null, null));
Assert.AreEqual(true, converter.ConvertBack(Visibility.Visible, typeof(bool), null, null));
Assert.AreEqual(false, converter.ConvertBack(Visibility.Collapsed, typeof(bool), null, null));
Assert.AreEqual(false, converter.ConvertBack("test", typeof(bool), null, null));
Assert.AreEqual(new bool?(true), converter.ConvertBack(Visibility.Visible, typeof(bool?), null, null));
Assert.AreEqual(new bool?(false), converter.ConvertBack(Visibility.Collapsed, typeof(bool?), null, null));
#if !SILVERLIGHT && !NETFX_CORE
Assert.AreEqual(false, converter.ConvertBack(Visibility.Hidden, typeof(bool), null, null));
Assert.AreEqual(new bool?(false), converter.ConvertBack(Visibility.Hidden, typeof(bool?), null, null));
#endif
converter.Inverse = true;
Assert.AreEqual(Visibility.Collapsed, converter.Convert(true, typeof(Visibility), null, null));
Assert.AreEqual(Visibility.Visible, converter.Convert(false, typeof(Visibility), null, null));
Assert.AreEqual(false, converter.ConvertBack(Visibility.Visible, typeof(bool), null, null));
Assert.AreEqual(true, converter.ConvertBack(Visibility.Collapsed, typeof(bool), null, null));
#if !SILVERLIGHT && !NETFX_CORE
Assert.AreEqual(true, converter.ConvertBack(Visibility.Hidden, typeof(bool), null, null));
#endif
converter.Inverse = false;
converter.HiddenInsteadOfCollapsed = true;
Assert.AreEqual(Visibility.Visible, converter.Convert(true, typeof(Visibility), null, null));
Assert.AreEqual(true, converter.ConvertBack(Visibility.Visible, typeof(bool), null, null));
Assert.AreEqual(false, converter.ConvertBack(Visibility.Collapsed, typeof(bool), null, null));
#if !SILVERLIGHT && !NETFX_CORE
Assert.AreEqual(Visibility.Hidden, converter.Convert(false, typeof(Visibility), null, null));
Assert.AreEqual(false, converter.ConvertBack(Visibility.Hidden, typeof(bool), null, null));
#endif
}
[Test]
public void NegationConverter_Convert_NoTargetType() {
var converter = new BooleanNegationConverter();
Assert.AreEqual(null, converter.Convert(null, null, null, null));
Assert.AreEqual(false, converter.Convert(true, null, null, null));
Assert.AreEqual(true, converter.Convert(false, null, null, null));
Assert.AreEqual(false, converter.Convert(new Nullable<bool>(true), null, null, null));
Assert.AreEqual(true, converter.Convert(new Nullable<bool>(false), null, null, null));
Assert.AreEqual(null, converter.Convert(new Nullable<bool>(), null, null, null));
Assert.AreEqual(null, converter.Convert("test", null, null, null));
}
[Test]
public void NegationConverter_Convert_TargetTypeBool() {
var converter = new BooleanNegationConverter();
Assert.AreEqual(true, converter.Convert(null, typeof(bool), null, null));
Assert.AreEqual(false, converter.Convert(true, typeof(bool), null, null));
Assert.AreEqual(true, converter.Convert(false, typeof(bool), null, null));
Assert.AreEqual(false, converter.Convert(new Nullable<bool>(true), typeof(bool), null, null));
Assert.AreEqual(true, converter.Convert(new Nullable<bool>(false), typeof(bool), null, null));
Assert.AreEqual(true, converter.Convert(new Nullable<bool>(), typeof(bool), null, null));
Assert.AreEqual(true, converter.Convert("test", typeof(bool), null, null));
}
[Test]
public void NegationConverter_Convert_TargetTypeNullableBool() {
var converter = new BooleanNegationConverter();
Assert.AreEqual(null, converter.Convert(null, typeof(bool?), null, null));
Assert.AreEqual(false, converter.Convert(true, typeof(bool?), null, null));
Assert.AreEqual(true, converter.Convert(false, typeof(bool?), null, null));
Assert.AreEqual(false, converter.Convert(new Nullable<bool>(true), typeof(bool?), null, null));
Assert.AreEqual(true, converter.Convert(new Nullable<bool>(false), typeof(bool?), null, null));
Assert.AreEqual(null, converter.Convert(new Nullable<bool>(), typeof(bool?), null, null));
Assert.AreEqual(null, converter.Convert("test", typeof(bool?), null, null));
}
[Test]
public void NegationConverter_ConvertBack_NoTargetType() {
var converter = new BooleanNegationConverter();
Assert.AreEqual(null, converter.ConvertBack(null, null, null, null));
Assert.AreEqual(false, converter.ConvertBack(true, null, null, null));
Assert.AreEqual(true, converter.ConvertBack(false, null, null, null));
Assert.AreEqual(false, converter.ConvertBack(new Nullable<bool>(true), null, null, null));
Assert.AreEqual(true, converter.ConvertBack(new Nullable<bool>(false), null, null, null));
Assert.AreEqual(null, converter.ConvertBack(new Nullable<bool>(), null, null, null));
Assert.AreEqual(null, converter.ConvertBack("test", null, null, null));
}
[Test]
public void NegationConverter_ConvertBack_TargetTypeBool() {
var converter = new BooleanNegationConverter();
Assert.AreEqual(true, converter.ConvertBack(null, typeof(bool), null, null));
Assert.AreEqual(false, converter.ConvertBack(true, typeof(bool), null, null));
Assert.AreEqual(true, converter.ConvertBack(false, typeof(bool), null, null));
Assert.AreEqual(false, converter.ConvertBack(new Nullable<bool>(true), typeof(bool), null, null));
Assert.AreEqual(true, converter.ConvertBack(new Nullable<bool>(false), typeof(bool), null, null));
Assert.AreEqual(true, converter.ConvertBack(new Nullable<bool>(), typeof(bool), null, null));
Assert.AreEqual(true, converter.ConvertBack("test", typeof(bool), null, null));
}
[Test]
public void NegationConverter_ConvertBack_TargetTypeNullableBool() {
var converter = new BooleanNegationConverter();
Assert.AreEqual(null, converter.ConvertBack(null, typeof(bool?), null, null));
Assert.AreEqual(false, converter.ConvertBack(true, typeof(bool?), null, null));
Assert.AreEqual(true, converter.ConvertBack(false, typeof(bool?), null, null));
Assert.AreEqual(false, converter.ConvertBack(new Nullable<bool>(true), typeof(bool?), null, null));
Assert.AreEqual(true, converter.ConvertBack(new Nullable<bool>(false), typeof(bool?), null, null));
Assert.AreEqual(null, converter.ConvertBack(new Nullable<bool>(), typeof(bool?), null, null));
Assert.AreEqual(null, converter.ConvertBack("test", typeof(bool?), null, null));
}
[Test]
public void DefaultBooleanToBooleanConverter_Convert_NoTargetType() {
var converter = new DefaultBooleanToBooleanConverter();
Assert.AreEqual(null, converter.Convert(null, null, null, null));
Assert.AreEqual(true, converter.Convert(true, null, null, null));
Assert.AreEqual(false, converter.Convert(false, null, null, null));
Assert.AreEqual(true, converter.Convert(new Nullable<bool>(true), null, null, null));
Assert.AreEqual(false, converter.Convert(new Nullable<bool>(false), null, null, null));
Assert.AreEqual(null, converter.Convert(new Nullable<bool>(), null, null, null));
Assert.AreEqual(null, converter.Convert("test", null, null, null));
}
[Test]
public void DefaultBooleanToBooleanConverter_Convert_TargetTypeBool() {
var converter = new DefaultBooleanToBooleanConverter();
Assert.AreEqual(false, converter.Convert(null, typeof(bool), null, null));
Assert.AreEqual(true, converter.Convert(true, typeof(bool), null, null));
Assert.AreEqual(false, converter.Convert(false, typeof(bool), null, null));
Assert.AreEqual(true, converter.Convert(new Nullable<bool>(true), typeof(bool), null, null));
Assert.AreEqual(false, converter.Convert(new Nullable<bool>(false), typeof(bool), null, null));
Assert.AreEqual(false, converter.Convert(new Nullable<bool>(), typeof(bool), null, null));
Assert.AreEqual(false, converter.Convert("test", typeof(bool), null, null));
}
[Test]
public void DefaultBooleanToBooleanConverter_Convert_TargetTypeNullableBool() {
var converter = new DefaultBooleanToBooleanConverter();
Assert.AreEqual(null, converter.Convert(null, typeof(bool?), null, null));
Assert.AreEqual(true, converter.Convert(true, typeof(bool?), null, null));
Assert.AreEqual(false, converter.Convert(false, typeof(bool?), null, null));
Assert.AreEqual(true, converter.Convert(new Nullable<bool>(true), typeof(bool?), null, null));
Assert.AreEqual(false, converter.Convert(new Nullable<bool>(false), typeof(bool?), null, null));
Assert.AreEqual(null, converter.Convert(new Nullable<bool>(), typeof(bool?), null, null));
Assert.AreEqual(null, converter.Convert("test", typeof(bool?), null, null));
}
[Test]
public void DefaultBooleanToBooleanConverter_ConvertBack_TargetTypeBool() {
var converter = new DefaultBooleanToBooleanConverter();
Assert.AreEqual(false, converter.ConvertBack(null, typeof(bool), null, null));
Assert.AreEqual(true, converter.ConvertBack(true, typeof(bool), null, null));
Assert.AreEqual(false, converter.ConvertBack(false, typeof(bool), null, null));
Assert.AreEqual(true, converter.ConvertBack(new Nullable<bool>(true), typeof(bool), null, null));
Assert.AreEqual(false, converter.ConvertBack(new Nullable<bool>(false), typeof(bool), null, null));
Assert.AreEqual(false, converter.ConvertBack(new Nullable<bool>(), typeof(bool), null, null));
Assert.AreEqual(false, converter.ConvertBack("test", typeof(bool), null, null));
}
[Test]
public void DefaultBooleanToBooleanConverter_ConvertBack_TargetTypeNullableBool() {
var converter = new DefaultBooleanToBooleanConverter();
Assert.AreEqual(null, converter.ConvertBack(null, typeof(bool?), null, null));
Assert.AreEqual(true, converter.ConvertBack(true, typeof(bool?), null, null));
Assert.AreEqual(false, converter.ConvertBack(false, typeof(bool?), null, null));
Assert.AreEqual(true, converter.ConvertBack(new Nullable<bool>(true), typeof(bool?), null, null));
Assert.AreEqual(false, converter.ConvertBack(new Nullable<bool>(false), typeof(bool?), null, null));
Assert.AreEqual(null, converter.ConvertBack(new Nullable<bool>(), typeof(bool?), null, null));
Assert.AreEqual(null, converter.ConvertBack("test", typeof(bool?), null, null));
}
enum MyColorEnum {
Red, Green, Blue
}
[Test]
public void ObjectToObjectConverter() {
var converter = new ObjectToObjectConverter();
Assert.AreEqual(null, converter.Convert(10, typeof(object), null, null));
Assert.AreEqual(null, converter.ConvertBack(10, typeof(object), null, null));
var instance1 = new MyClass("same");
var instance2 = new MyClass("same");
string converted1 = "converted";
string converted2 = "converted";
converter.Map.Add(new MapItem { Source = instance1, Target = "converted" });
Assert.AreEqual(converted1, converter.Convert(instance1, typeof(object), null, null));
Assert.AreEqual(converted1, converter.Convert(instance2, typeof(object), null, null));
Assert.AreEqual(converted2, converter.Convert(instance1, typeof(object), null, null));
Assert.AreEqual(converted2, converter.Convert(instance2, typeof(object), null, null));
Assert.AreEqual(instance1, converter.ConvertBack(converted1, typeof(object), null, null));
Assert.AreEqual(instance1, converter.ConvertBack(converted2, typeof(object), null, null));
Assert.AreEqual(instance2, converter.ConvertBack(converted1, typeof(object), null, null));
Assert.AreEqual(instance2, converter.ConvertBack(converted2, typeof(object), null, null));
converter.Map.Add(new MapItem { Source = null, Target = "nullto" });
converter.Map.Add(new MapItem { Source = "nullfrom", Target = null });
Assert.AreEqual("nullto", converter.Convert(null, typeof(object), null, null));
Assert.AreEqual("nullfrom", converter.ConvertBack(null, typeof(object), null, null));
converter.DefaultSource = "defsource";
converter.DefaultTarget = "deftarget";
Assert.AreEqual("deftarget", converter.Convert("nonexistent", typeof(object), null, null));
Assert.AreEqual("defsource", converter.ConvertBack("nonexistent", typeof(object), null, null));
converter = new ObjectToObjectConverter();
converter.Map.Add(new MapItem { Source = "true", Target = 1 });
converter.Map.Add(new MapItem { Source = "FALSE", Target = 15 });
Assert.AreEqual(1, converter.Convert(true, typeof(int), null, null));
Assert.AreEqual(15, converter.Convert(false, typeof(int), null, null));
converter = new ObjectToObjectConverter();
converter.DefaultTarget = Visibility.Visible;
converter.Map.Add(new MapItem { Source = 0, Target = Visibility.Collapsed });
Assert.AreEqual(Visibility.Visible, converter.Convert(null, typeof(Visibility), null, null));
Assert.AreEqual(Visibility.Visible, converter.Convert(10, typeof(Visibility), null, null));
Assert.AreEqual(Visibility.Collapsed, converter.Convert(0, typeof(Visibility), null, null));
}
[Test]
public void ObjectToObjectCoercions() {
var converter = new ObjectToObjectConverter();
converter.Map.Add(new MapItem { Source = "Red", Target = "1" });
converter.Map.Add(new MapItem { Source = "Green", Target = "2" });
converter.Map.Add(new MapItem { Source = MyColorEnum.Blue, Target = "3" });
Assert.AreEqual("1", converter.Convert("Red", typeof(string), null, null));
Assert.AreEqual("2", converter.Convert(MyColorEnum.Green, typeof(string), null, null));
Assert.AreEqual("3", converter.Convert("Blue", typeof(string), null, null));
Assert.AreEqual(null, converter.Convert(null, typeof(string), null, null));
converter.DefaultTarget = "def";
Assert.AreEqual("def", converter.Convert(null, typeof(string), null, null));
converter.Map.Add(new MapItem { Source = null, Target = "nullvalue" });
Assert.AreEqual("nullvalue", converter.Convert(null, typeof(string), null, null));
}
#if NETFX_CORE
[Test]
public void FormatStringConverter() {
var savedCulture = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol;
try {
FormatStringConverter converter = new FormatStringConverter();
converter.FormatString = "C0";
System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol = "#test currency symbol#";
string s = (string)converter.Convert(13, typeof(string), null, System.Globalization.CultureInfo.InvariantCulture.NativeName);
Assert.IsTrue(s.Contains("#test currency symbol#"));
} finally {
System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol = savedCulture;
}
}
#else
[Test]
public void FormatStringConverter() {
var savedCulture = System.Threading.Thread.CurrentThread.CurrentUICulture;
try {
FormatStringConverter converter = new FormatStringConverter();
converter.FormatString = "C0";
var changedCulture = (System.Globalization.CultureInfo)System.Threading.Thread.CurrentThread.CurrentUICulture.Clone();
changedCulture.NumberFormat.CurrencySymbol = "#test currency symbol#";
System.Threading.Thread.CurrentThread.CurrentUICulture = changedCulture;
string s = (string)converter.Convert(13, typeof(string), null, System.Globalization.CultureInfo.InvariantCulture);
Assert.IsTrue(s.Contains("#test currency symbol#"));
} finally {
System.Threading.Thread.CurrentThread.CurrentUICulture = savedCulture;
}
}
#endif
class MyClass {
string id;
public MyClass(string id) {
this.id = id;
}
public override bool Equals(object obj) {
if(obj is MyClass) {
return ((MyClass)obj).id == id;
}
return base.Equals(obj);
}
public override int GetHashCode() {
return id.GetHashCode();
}
}
[Test]
public void NotNullObjectConverter() {
var converter = new ObjectToBooleanConverter();
Assert.AreEqual(true, converter.Convert("not null", typeof(bool), null, null));
Assert.AreEqual(false, converter.Convert(null, typeof(bool), null, null));
Assert.AreEqual(true, converter.Convert(new object(), typeof(bool), null, null));
}
[Test]
public void NotEmptyStringConverter() {
var converter = new StringToBooleanConverter();
Assert.AreEqual(true, converter.Convert("not null", typeof(bool), null, null));
Assert.AreEqual(false, converter.Convert(null, typeof(bool), null, null));
Assert.AreEqual(false, converter.Convert("", typeof(bool), null, null));
Assert.AreEqual(null, converter.ConvertBack(null, typeof(bool), null, null));
}
[Test]
public void NotZeroBooleanConverter() {
var converter = new NumericToBooleanConverter();
Assert.AreEqual(false, converter.Convert(null, typeof(bool), null, null));
Assert.AreEqual(false, converter.Convert(0, typeof(bool), null, null));
Assert.AreEqual(false, converter.Convert(0f, typeof(bool), null, null));
Assert.AreEqual(false, converter.Convert(0d, typeof(bool), null, null));
Assert.AreEqual(true, converter.Convert(10, typeof(bool), null, null));
Assert.AreEqual(true, converter.Convert(-10, typeof(bool), null, null));
Assert.AreEqual(true, converter.Convert(5d, typeof(bool), null, null));
}
[Test]
public void BooleanToObjectConverter() {
var converter = new BooleanToObjectConverter();
Assert.AreEqual(null, converter.Convert(null, typeof(string), null, null));
Assert.AreEqual(null, converter.Convert("s1", typeof(string), null, null));
converter.TrueValue = "trueValue";
converter.FalseValue = "falseValue";
Assert.AreEqual("trueValue", converter.Convert(true, typeof(string), null, null));
Assert.AreEqual("falseValue", converter.Convert(false, typeof(string), null, null));
Assert.AreEqual(null, converter.Convert("garbage", typeof(string), null, null));
converter.NullValue = "nullvalue";
Assert.AreEqual("nullvalue", converter.Convert(null, typeof(string), null, null));
}
[Test]
public void NumericToBooleanConverter() {
NumericToBooleanConverter converter = new NumericToBooleanConverter();
Assert.AreEqual(false, converter.Convert(0, null, null, null));
Assert.AreEqual(true, converter.Convert(-1, null, null, null));
Assert.AreEqual(true, converter.Convert(1, null, null, null));
Assert.AreEqual(true, converter.Convert(2, null, null, null));
}
[Test]
public void NumericToVisibilityConverter() {
NumericToVisibilityConverter converter = new NumericToVisibilityConverter();
Assert.AreEqual(Visibility.Collapsed, converter.Convert(0, null, null, null));
Assert.AreEqual(Visibility.Visible, converter.Convert(-1, null, null, null));
Assert.AreEqual(Visibility.Visible, converter.Convert(1, null, null, null));
Assert.AreEqual(Visibility.Visible, converter.Convert(2, null, null, null));
converter.Inverse = true;
Assert.AreEqual(Visibility.Visible, converter.Convert(0, null, null, null));
Assert.AreEqual(Visibility.Collapsed, converter.Convert(-1, null, null, null));
Assert.AreEqual(Visibility.Collapsed, converter.Convert(1, null, null, null));
Assert.AreEqual(Visibility.Collapsed, converter.Convert(2, null, null, null));
}
}
public class ToStringConverter : IValueConverter {
#if !NETFX_CORE
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
return value.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
throw new NotSupportedException();
}
#else
public object Convert(object value, Type targetType, object parameter, string language) {
return value.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, string language) {
throw new NotImplementedException();
}
#endif
}
public class FromString {
public FromString(string s) {
S = s;
}
public string S { get; set; }
public override string ToString() {
return S;
}
}
public static class ReflectionConverterTestMethods {
public static string IntToString(int i) { return "S" + i.ToString(); }
public static int StringToInt(string s) { return int.Parse(s.Substring(1)); }
}
public interface IReflectionConverterTestMock {
string Convert01(object value);
string Convert02(int value);
string Convert03(int value, int parameter);
string Convert04(int value, object parameter);
string Convert05(object value, int parameter);
string Convert06(object value, Type targetType, int parameter);
string Convert07(object value, Type targetType, object parameter);
string Convert08(int value, Type targetType, object parameter);
string Convert09(object value, CultureInfo culture);
string Convert10(int value, CultureInfo culture);
string Convert11(int value, int parameter, CultureInfo culture);
string Convert12(int value, object parameter, CultureInfo culture);
string Convert13(object value, int parameter, CultureInfo culture);
string Convert14(object value, Type targetType, int parameter, CultureInfo culture);
string Convert15(object value, Type targetType, object parameter, CultureInfo culture);
string Convert16(int value, Type targetType, object parameter, CultureInfo culture);
string Convert17(object value, Type targetType);
string Convert18(int value, Type targetType);
}
public static class ReflectionConvertTestMockStatic {
public static IReflectionConverterTestMock Mock { get; set; }
public static string Convert01(object value) { return Mock.Convert01(value); }
public static string Convert02(int value) { return Mock.Convert02(value); }
public static string Convert03(int value, int parameter) { return Mock.Convert03(value, parameter); }
public static string Convert04(int value, object parameter) { return Mock.Convert04(value, parameter); }
public static string Convert05(object value, int parameter) { return Mock.Convert05(value, parameter); }
public static string Convert06(object value, Type targetType, int parameter) { return Mock.Convert06(value, targetType, parameter); }
public static string Convert07(object value, Type targetType, object parameter) { return Mock.Convert07(value, targetType, parameter); }
public static string Convert08(int value, Type targetType, object parameter) { return Mock.Convert08(value, targetType, parameter); }
public static string Convert09(object value, CultureInfo culture) { return Mock.Convert09(value, culture); }
public static string Convert10(int value, CultureInfo culture) { return Mock.Convert10(value, culture); }
public static string Convert11(int value, int parameter, CultureInfo culture) { return Mock.Convert11(value, parameter, culture); }
public static string Convert12(int value, object parameter, CultureInfo culture) { return Mock.Convert12(value, parameter, culture); }
public static string Convert13(object value, int parameter, CultureInfo culture) { return Mock.Convert13(value, parameter, culture); }
public static string Convert14(object value, Type targetType, int parameter, CultureInfo culture) { return Mock.Convert14(value, targetType, parameter, culture); }
public static string Convert15(object value, Type targetType, object parameter, CultureInfo culture) { return Mock.Convert15(value, targetType, parameter, culture); }
public static string Convert16(int value, Type targetType, object parameter, CultureInfo culture) { return Mock.Convert16(value, targetType, parameter, culture); }
public static string Convert17(object value, Type targetType) { return Mock.Convert17(value, targetType); }
public static string Convert18(int value, Type targetType) { return Mock.Convert18(value, targetType); }
}
}
| |
//
// Copyright (c)1998-2011 Pearson Education, Inc. or its affiliate(s).
// All rights reserved.
//
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Threading;
namespace OpenADK.Library.Tools
{
/// <summary> A LoadBalancer manages a free pool of <i>Baton</i> objects representing the
/// right of a thread to perform a resource-intensive task.</summary>
/// <remarks>
/// <para>
/// For example, you
/// could create a LoadBalancer that represents the task "query all students"
/// and assign it an initial pool of 5 Batons, meaning at most 5 threads will be
/// able to carry out this task at once. A thread must check out a Baton in
/// order to perform the task, and must release it back to the LoadBalancer
/// when finished.
/// </para>
/// <para>
/// Refer to the Baton class for a description of how to use the LoadBalancer
/// and Baton classes and the LoadBalancerListener interface. These classes can
/// be used to introduce internal load balancing into an agent to significantly
/// improve scalability when connecting to tens or hundreds of zones
/// concurrently.
/// </para>
/// </remarks>
/// <author> Data Solutions
/// </author>
/// <since> ADK 1.0
/// </since>
public class LoadBalancer
{
/// <summary> Gets the current load (the number of Batons in use)</summary>
public virtual int Load
{
get
{
lock ( fPool.SyncRoot ) {
return fSize - fPool.Count;
}
}
}
/// <summary> Gets the total number of Batons</summary>
public virtual int TotalBatons
{
get { return fSize; }
}
/// <summary> Gets the number of Batons</summary>
public virtual int FreeBatons
{
get
{
lock ( fPool.SyncRoot ) {
return fPool.Count;
}
}
}
public static bool TRACE = false;
/// <summary> LoadBalancer ID</summary>
protected internal Object fID;
/// <summary> Pool of batons</summary>
protected internal Stack fPool = new Stack();
/// <summary> Maximum number of Batons</summary>
protected internal int fSize;
/// <summary> checkoutBaton timeout value</summary>
protected internal long fTimeout;
/// <summary> Global dictionary of LoadBalancers</summary>
/// <seealso cref="Define">
/// </seealso>
protected internal static IDictionary sDict = new HybridDictionary();
/// <summary> Flagged true when the pool is emptied</summary>
protected internal bool fEmptied = false;
/// <summary> Listeners</summary>
protected internal ArrayList fListeners = null;
/// <summary> Constructs a LoadBalancer to represent a specific logical task.
///
/// </summary>
/// <param name="id">A unique arbitrary ID that the agent will use to request this
/// LoadBalancer (e.g. "Request_StudentPersonal")
/// </param>
/// <param name="batons">The number of Batons that will be available to threads
/// </param>
/// <param name="timeout">The timeout period (in milliseconds) applied to the
/// <c>checkoutBaton</c> method. The timeout period should be less
/// than the HTTP or other transport timeout period so that the connection
/// to the ZIS does not timeout before the load balancer does.
/// </param>
public LoadBalancer( Object id,
int batons,
long timeout )
{
if ( id == null ) {
throw new ArgumentException( "id cannot be null" );
}
fID = id;
fTimeout = timeout;
fSize = batons;
// Create pool of batons
int _batons = Math.Max( 1, batons );
for ( int i = 0; i < _batons; i++ ) {
fPool.Push( new Baton() );
}
}
/// <summary> Define a LoadBalancer that may be subsequently returned by the <c>lookup</c> method.</summary>
/// <param name="balancer">A LoadBalancer instance
/// </param>
public static void Define( LoadBalancer balancer )
{
lock ( sDict.SyncRoot ) {
sDict[balancer.fID] = balancer;
}
}
/// <summary> Lookup a LoadBalancer that was previously defined by the <c>define</c> method.</summary>
/// <param name="id">The ID of the LoadBalancer to obtain
/// </param>
/// <returns> The LoadBalancer or null if no LoadBalancer with this id has been
/// previously defined by the <c>define</c> method
/// </returns>
public static LoadBalancer lookup( Object id )
{
lock ( sDict.SyncRoot ) {
return (LoadBalancer) sDict[id];
}
}
/// <summary> Check-out a Baton.</summary>
public virtual Baton CheckoutBaton()
{
Baton b = null;
lock ( fPool.SyncRoot ) {
if ( fPool.Count == 0 ) {
try {
// Wait for an instance to become available
if ( TRACE ) {
Console.Out.WriteLine
( "Waiting for baton to become available (" +
Thread.CurrentThread.Name + ")" );
}
Monitor.Wait( fPool.SyncRoot, TimeSpan.FromMilliseconds( fTimeout ) );
if ( TRACE ) {
Console.Out.WriteLine
( "Done waiting for baton to become available (" +
Thread.CurrentThread.Name + ")" );
}
}
catch ( ThreadInterruptedException ) {}
}
if ( fPool.Count > 0 ) {
b = (Baton) fPool.Pop();
}
if ( TRACE ) {
Console.Out.WriteLine
( b == null
? "No baton available"
: "Got a baton (there are " + fPool.Count + " left)" );
}
if ( fPool.Count == 0 ) {
fEmptied = true;
}
}
return b;
}
/// <summary> Check-in a Baton.</summary>
public virtual void CheckinBaton( Baton baton )
{
if ( baton != null ) {
lock ( fPool.SyncRoot ) {
fPool.Push( baton );
if ( TRACE ) {
Console.Out.WriteLine( "Baton checked in; there are now " + fPool.Count );
}
if ( fEmptied && fPool.Count >= (fSize == 1 ? 1 : 2) ) {
if ( TRACE ) {
Console.Out.WriteLine
( "Notifying listeners that batons are now available" );
}
// Notify all listeners that Batons are once again available
fEmptied = false;
if ( fListeners != null ) {
lock ( fListeners.SyncRoot ) {
for ( int i = 0; i < fListeners.Count; i++ ) {
ILoadBalancerListener l = (ILoadBalancerListener) fListeners[i];
l.OnBatonsAvailable( this );
}
}
}
}
try {
// Notify all waiting threads that a Baton is available
if ( TRACE ) {
Console.Out.WriteLine
( "Notifying threads that baton is returned to free pool" );
}
Monitor.PulseAll( fPool );
}
catch ( Exception ) {}
}
}
}
/// <summary> Register a LoadBalancerListener with this LoadBalancer. The listener will
/// be called when the free pool is empty and subsequently contains at least
/// two Batons (or one Baton if this LoadBalancer was defined to have a pool
/// size of one).
/// </summary>
public virtual void AddLoadBalancerListener( ILoadBalancerListener listener )
{
if ( fListeners == null ) {
fListeners = new ArrayList();
}
fListeners.Add( listener );
}
/// <summary> Remove a LoadBalancerListener previously registered with the <c>
/// addLoadBalancerListener</c> method
/// </summary>
public virtual void removeLoadBalancerListener( ILoadBalancerListener listener )
{
if ( fListeners != null ) {
if ( fListeners.Contains( listener ) ) {
fListeners.Remove( listener );
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.Build.BackEnd;
using Microsoft.Build.Framework;
using Microsoft.Build.Framework.Profiler;
using Microsoft.Build.Logging;
using Microsoft.Build.Shared;
using Microsoft.Build.UnitTests.BackEnd;
using Xunit;
namespace Microsoft.Build.UnitTests
{
public class BuildEventArgsSerializationTests
{
public BuildEventArgsSerializationTests()
{
// touch the type so that static constructor runs
_ = ItemGroupLoggingHelper.ItemGroupIncludeLogMessagePrefix;
}
[Fact]
public void RoundtripBuildStartedEventArgs()
{
var args = new BuildStartedEventArgs(
"Message",
"HelpKeyword",
DateTime.Parse("3/1/2017 11:11:56 AM"));
Roundtrip(args,
e => e.Message,
e => e.HelpKeyword,
e => e.Timestamp.ToString());
args = new BuildStartedEventArgs(
"M",
null,
new Dictionary<string, string>
{
{ "SampleName", "SampleValue" }
});
Roundtrip(args,
e => TranslationHelpers.ToString(e.BuildEnvironment),
e => e.HelpKeyword,
e => e.ThreadId.ToString(),
e => e.SenderName);
}
[Fact]
public void RoundtripBuildFinishedEventArgs()
{
var args = new BuildFinishedEventArgs(
"Message",
null,
succeeded: true,
eventTimestamp: DateTime.Parse("12/12/2015 06:11:56 PM"));
args.BuildEventContext = new BuildEventContext(1, 2, 3, 4, 5, 6);
Roundtrip(args,
e => ToString(e.BuildEventContext),
e => e.Succeeded.ToString());
}
[Fact]
public void RoundtripProjectStartedEventArgs()
{
var args = new ProjectStartedEventArgs(
projectId: 42,
message: "Project \"test.proj\" (Build target(s)):",
helpKeyword: "help",
projectFile: Path.Combine("a", "test.proj"),
targetNames: "Build",
properties: new List<DictionaryEntry>() { new DictionaryEntry("Key", "Value") },
items: new List<DictionaryEntry>() { new DictionaryEntry("Key", new MyTaskItem() { ItemSpec = "TestItemSpec" }) },
parentBuildEventContext: new BuildEventContext(7, 8, 9, 10, 11, 12),
globalProperties: new Dictionary<string, string>() { { "GlobalKey", "GlobalValue" } },
toolsVersion: "Current");
args.BuildEventContext = new BuildEventContext(1, 2, 3, 4, 5, 6);
Roundtrip<ProjectStartedEventArgs>(args,
e => ToString(e.BuildEventContext),
e => TranslationHelpers.GetPropertiesString(e.GlobalProperties),
e => TranslationHelpers.GetMultiItemsString(e.Items),
e => e.Message,
e => ToString(e.ParentProjectBuildEventContext),
e => e.ProjectFile,
e => e.ProjectId.ToString(),
e => TranslationHelpers.GetPropertiesString(e.Properties),
e => e.TargetNames,
e => e.ThreadId.ToString(),
e => e.Timestamp.ToString(),
e => e.ToolsVersion);
}
[Fact]
public void RoundtripProjectFinishedEventArgs()
{
var args = new ProjectFinishedEventArgs(
"Message",
null,
"C:\\projectfile.proj",
true,
DateTime.Parse("12/12/2015 06:11:56 PM"));
Roundtrip(args,
e => e.ProjectFile,
e => e.Succeeded.ToString());
}
[Fact]
public void RoundtripTargetStartedEventArgs()
{
var args = new TargetStartedEventArgs(
"Message",
"Help",
"Build",
"C:\\projectfile.proj",
"C:\\Common.targets",
"ParentTarget",
TargetBuiltReason.AfterTargets,
DateTime.Parse("12/12/2015 06:11:56 PM"));
Roundtrip(args,
e => e.ParentTarget,
e => e.ProjectFile,
e => e.TargetFile,
e => e.TargetName,
e => e.BuildReason.ToString(),
e => e.Timestamp.ToString());
}
[Fact]
public void RoundtripTargetFinishedEventArgs()
{
var args = new TargetFinishedEventArgs(
"Message",
null,
"TargetName",
"C:\\Project.proj",
"C:\\TargetFile.targets",
true,
new List<ITaskItem> { new MyTaskItem() });
Roundtrip(args,
e => e.ProjectFile,
e => e.Succeeded.ToString(),
e => e.TargetFile,
e => e.TargetName,
e => ToString(e.TargetOutputs.OfType<ITaskItem>()));
}
[Fact]
public void RoundtripTaskStartedEventArgs()
{
var args = new TaskStartedEventArgs(
"Message",
null,
projectFile: "C:\\project.proj",
taskFile: "C:\\common.targets",
taskName: "Csc");
args.LineNumber = 42;
args.ColumnNumber = 999;
Roundtrip(args,
e => e.ProjectFile,
e => e.TaskFile,
e => e.TaskName,
e => e.LineNumber.ToString(),
e => e.ColumnNumber.ToString());
}
[Fact]
public void RoundtripTaskFinishedEventArgs()
{
var args = new TaskFinishedEventArgs(
"Message",
null,
"C:\\project.proj",
"C:\\common.tasks",
"Csc",
succeeded: false);
Roundtrip(args,
e => e.ProjectFile,
e => e.TaskFile,
e => e.TaskName,
e => e.ThreadId.ToString());
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void RoundtripBuildErrorEventArgs(bool useArguments)
{
var args = new BuildErrorEventArgs(
"Subcategory",
"Code",
"File",
1,
2,
3,
4,
"Message with arguments: '{0}'",
"Help",
"SenderName",
DateTime.Parse("9/1/2021 12:02:07 PM"),
useArguments ? new object[] { "argument0" } : null);
Roundtrip(args,
e => e.Code,
e => e.ColumnNumber.ToString(),
e => e.EndColumnNumber.ToString(),
e => e.EndLineNumber.ToString(),
e => e.File,
e => e.LineNumber.ToString(),
e => e.Message,
e => e.ProjectFile,
e => e.Subcategory,
e => string.Join(", ", e.RawArguments ?? Array.Empty<object>()));
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void RoundtripBuildWarningEventArgs(bool useArguments)
{
var args = new BuildWarningEventArgs(
"Subcategory",
"Code",
"File",
1,
2,
3,
4,
"Message with arguments: '{0}'",
"Help",
"SenderName",
DateTime.Parse("9/1/2021 12:02:07 PM"),
useArguments ? new object[] { "argument0" } : null);
Roundtrip(args,
e => e.Code,
e => e.ColumnNumber.ToString(),
e => e.EndColumnNumber.ToString(),
e => e.EndLineNumber.ToString(),
e => e.File,
e => e.LineNumber.ToString(),
e => e.Message,
e => e.ProjectFile,
e => e.Subcategory,
e => string.Join(", ", e.RawArguments ?? Array.Empty<object>()));
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void RoundtripBuildMessageEventArgs(bool useArguments)
{
var args = new BuildMessageEventArgs(
"Subcategory",
"Code",
"File",
1,
2,
3,
4,
"Message",
"Help",
"SenderName",
MessageImportance.High,
DateTime.Parse("12/12/2015 06:11:56 PM"),
useArguments ? new object[] { "argument0" } : null);
Roundtrip(args,
e => e.Code,
e => e.ColumnNumber.ToString(),
e => e.EndColumnNumber.ToString(),
e => e.EndLineNumber.ToString(),
e => e.File,
e => e.LineNumber.ToString(),
e => e.Message,
e => e.Importance.ToString(),
e => e.ProjectFile,
e => e.Subcategory,
e => string.Join(", ", e.RawArguments ?? Array.Empty<object>()));
}
[Fact]
public void RoundtripCriticalBuildMessageEventArgs()
{
var args = new CriticalBuildMessageEventArgs(
"Subcategory",
"Code",
"File",
1,
2,
3,
4,
"Message",
"Help",
"SenderName",
DateTime.Parse("12/12/2015 06:11:56 PM"));
Roundtrip(args,
e => e.Code,
e => e.ColumnNumber.ToString(),
e => e.EndColumnNumber.ToString(),
e => e.EndLineNumber.ToString(),
e => e.File,
e => e.LineNumber.ToString(),
e => e.Message,
e => e.ProjectFile,
e => e.Subcategory);
}
[Fact]
public void RoundtripTaskCommandLineEventArgs()
{
var args = new TaskCommandLineEventArgs(
"/bl /noconlog /v:diag",
"Csc",
MessageImportance.Low,
DateTime.Parse("12/12/2015 06:11:56 PM"));
Roundtrip(args,
e => e.CommandLine,
e => e.TaskName,
e => e.Importance.ToString(),
e => e.EndLineNumber.ToString(),
e => e.File,
e => e.LineNumber.ToString(),
e => e.Message,
e => e.ProjectFile,
e => e.Subcategory);
}
[Fact]
public void RoundtripTaskParameterEventArgs()
{
var items = new ITaskItem[]
{
new TaskItemData("ItemSpec1", null),
new TaskItemData("ItemSpec2", Enumerable.Range(1,3).ToDictionary(i => i.ToString(), i => i.ToString() + "value"))
};
var args = new TaskParameterEventArgs(TaskParameterMessageKind.TaskOutput, "ItemName", items, true, DateTime.MinValue);
args.LineNumber = 265;
args.ColumnNumber = 6;
Roundtrip(args,
e => e.Kind.ToString(),
e => e.ItemType,
e => e.LogItemMetadata.ToString(),
e => e.LineNumber.ToString(),
e => e.ColumnNumber.ToString(),
e => TranslationHelpers.GetItemsString(e.Items));
}
[Fact]
public void RoundtripProjectEvaluationStartedEventArgs()
{
var projectFile = @"C:\foo\bar.proj";
var args = new ProjectEvaluationStartedEventArgs(
ResourceUtilities.GetResourceString("EvaluationStarted"),
projectFile)
{
BuildEventContext = BuildEventContext.Invalid,
ProjectFile = projectFile,
};
Roundtrip(args,
e => e.Message,
e => e.ProjectFile);
}
[Fact]
public void RoundtripProjectEvaluationFinishedEventArgs()
{
var projectFile = @"C:\foo\bar.proj";
var args = new ProjectEvaluationFinishedEventArgs(
ResourceUtilities.GetResourceString("EvaluationFinished"),
projectFile)
{
BuildEventContext = BuildEventContext.Invalid,
ProjectFile = @"C:\foo\bar.proj",
GlobalProperties = new Dictionary<string, string>() { { "GlobalKey", "GlobalValue" } },
Properties = new List<DictionaryEntry>() { new DictionaryEntry("Key", "Value") },
Items = new List<DictionaryEntry>() { new DictionaryEntry("Key", new MyTaskItem() { ItemSpec = "TestItemSpec" }) }
};
Roundtrip(args,
e => e.Message,
e => e.ProjectFile,
e => TranslationHelpers.GetPropertiesString(e.GlobalProperties),
e => TranslationHelpers.GetPropertiesString(e.Properties),
e => TranslationHelpers.GetMultiItemsString(e.Items));
}
[Fact]
public void RoundtripProjectEvaluationFinishedEventArgsWithProfileData()
{
var projectFile = @"C:\foo\bar.proj";
var args = new ProjectEvaluationFinishedEventArgs(
ResourceUtilities.GetResourceString("EvaluationFinished"),
projectFile)
{
BuildEventContext = BuildEventContext.Invalid,
ProjectFile = @"C:\foo\bar.proj",
ProfilerResult = new ProfilerResult(new Dictionary<EvaluationLocation, ProfiledLocation>
{
{
new EvaluationLocation(1, 0, EvaluationPass.InitialProperties, "desc1", "file1", 7, "element1", "description", EvaluationLocationKind.Condition),
new ProfiledLocation(TimeSpan.FromSeconds(1), TimeSpan.FromHours(2), 1)
},
{
new EvaluationLocation(0, null, EvaluationPass.LazyItems, "desc2", "file1", null, "element2", "description2", EvaluationLocationKind.Glob),
new ProfiledLocation(TimeSpan.FromSeconds(1), TimeSpan.FromHours(2), 2)
},
{
new EvaluationLocation(2, 0, EvaluationPass.Properties, "desc2", "file1", null, "element2", "description2", EvaluationLocationKind.Element),
new ProfiledLocation(TimeSpan.FromSeconds(1), TimeSpan.FromHours(2), 2)
}
})
};
Roundtrip(args,
e => e.Message,
e => e.ProjectFile,
e => ToString(e.ProfilerResult.Value.ProfiledLocations));
}
[Fact]
public void RoundtripProjectImportedEventArgs()
{
var args = new ProjectImportedEventArgs(
1,
2,
"Message")
{
BuildEventContext = BuildEventContext.Invalid,
ImportedProjectFile = "foo.props",
ProjectFile = "foo.csproj",
UnexpandedProject = "$(Something)"
};
Roundtrip(args,
e => e.ImportedProjectFile,
e => e.UnexpandedProject,
e => e.Importance.ToString(),
e => e.LineNumber.ToString(),
e => e.ColumnNumber.ToString(),
e => e.LineNumber.ToString(),
e => e.Message,
e => e.ProjectFile);
}
[Fact]
public void RoundtripTargetSkippedEventArgs()
{
var args = new TargetSkippedEventArgs(
"Target \"target\" skipped. Previously built unsuccessfully.")
{
BuildEventContext = BuildEventContext.Invalid,
ProjectFile = "foo.csproj",
TargetName = "target",
ParentTarget = "bar",
BuildReason = TargetBuiltReason.DependsOn,
SkipReason = TargetSkipReason.PreviouslyBuiltSuccessfully,
Condition = "$(condition) == true",
EvaluatedCondition = "true == true",
OriginalBuildEventContext = new BuildEventContext(1, 2, 3, 4, 5, 6, 7),
OriginallySucceeded = false,
TargetFile = "foo.csproj"
};
Roundtrip(args,
e => e.BuildEventContext.ToString(),
e => e.ParentTarget,
e => e.Importance.ToString(),
e => e.LineNumber.ToString(),
e => e.ColumnNumber.ToString(),
e => e.Message,
e => e.ProjectFile,
e => e.TargetFile,
e => e.TargetName,
e => e.BuildReason.ToString(),
e => e.SkipReason.ToString(),
e => e.Condition,
e => e.EvaluatedCondition,
e => e.OriginalBuildEventContext.ToString(),
e => e.OriginallySucceeded.ToString());
}
[Fact]
public void RoundTripEnvironmentVariableReadEventArgs()
{
var args = new EnvironmentVariableReadEventArgs(
environmentVariableName: Guid.NewGuid().ToString(),
message: Guid.NewGuid().ToString(),
helpKeyword: Guid.NewGuid().ToString(),
senderName: Guid.NewGuid().ToString());
Roundtrip(args,
e => e.EnvironmentVariableName,
e => e.Message,
e => e.HelpKeyword,
e => e.SenderName);
}
[Fact]
public void RoundTripPropertyReassignmentEventArgs()
{
var args = new PropertyReassignmentEventArgs(
propertyName: "a",
previousValue: "b",
newValue: "c",
location: "d",
message: "Property reassignment: $(a)=\"c\" (previous value: \"b\") at d",
helpKeyword: "e",
senderName: "f");
Roundtrip(args,
e => e.PropertyName,
e => e.PreviousValue,
e => e.NewValue,
e => e.Location,
e => e.Message,
e => e.HelpKeyword,
e => e.SenderName);
}
[Fact]
public void UninitializedPropertyReadEventArgs()
{
var args = new UninitializedPropertyReadEventArgs(
propertyName: Guid.NewGuid().ToString(),
message: Guid.NewGuid().ToString(),
helpKeyword: Guid.NewGuid().ToString(),
senderName: Guid.NewGuid().ToString());
Roundtrip(args,
e => e.PropertyName,
e => e.Message,
e => e.HelpKeyword,
e => e.SenderName);
}
[Fact]
public void PropertyInitialValueEventArgs()
{
var args = new PropertyInitialValueSetEventArgs(
propertyName: Guid.NewGuid().ToString(),
propertyValue: Guid.NewGuid().ToString(),
propertySource: Guid.NewGuid().ToString(),
message: Guid.NewGuid().ToString(),
helpKeyword: Guid.NewGuid().ToString(),
senderName: Guid.NewGuid().ToString());
Roundtrip(args,
e => e.PropertyName,
e => e.PropertyValue,
e => e.PropertySource,
e => e.Message,
e => e.HelpKeyword,
e => e.SenderName);
}
[Fact]
public void ReadingCorruptedStreamThrows()
{
var memoryStream = new MemoryStream();
var binaryWriter = new BinaryWriter(memoryStream);
var buildEventArgsWriter = new BuildEventArgsWriter(binaryWriter);
var args = new BuildStartedEventArgs(
"Message",
"HelpKeyword",
DateTime.Parse("3/1/2017 11:11:56 AM"));
buildEventArgsWriter.Write(args);
long length = memoryStream.Length;
for (long i = length - 1; i >= 0; i--) // try all possible places where a stream might end abruptly
{
memoryStream.SetLength(i); // pretend that the stream abruptly ends
memoryStream.Position = 0;
var binaryReader = new BinaryReader(memoryStream);
using var buildEventArgsReader = new BuildEventArgsReader(binaryReader, BinaryLogger.FileFormatVersion);
Assert.Throws<EndOfStreamException>(() => buildEventArgsReader.Read());
}
}
private string ToString(BuildEventContext context)
{
return $"{context.BuildRequestId} {context.NodeId} {context.ProjectContextId} {context.ProjectInstanceId} {context.SubmissionId} {context.TargetId} {context.TaskId}";
}
private string ToString(IEnumerable<ITaskItem> items)
{
return string.Join(";", items.Select(i => ToString(i)));
}
private string ToString(ITaskItem i)
{
return i.ItemSpec + string.Join(";", i.CloneCustomMetadata().Keys.OfType<string>().Select(k => i.GetMetadata(k)));
}
private string ToString(IReadOnlyDictionary<EvaluationLocation, ProfiledLocation> items)
{
StringBuilder sb = new StringBuilder();
foreach (var item in items)
{
sb.AppendLine(item.Key.ToString());
sb.AppendLine(item.Value.ToString());
}
return sb.ToString();
}
private void Roundtrip<T>(T args, params Func<T, string>[] fieldsToCompare)
where T : BuildEventArgs
{
var memoryStream = new MemoryStream();
var binaryWriter = new BinaryWriter(memoryStream);
var buildEventArgsWriter = new BuildEventArgsWriter(binaryWriter);
buildEventArgsWriter.Write(args);
long length = memoryStream.Length;
memoryStream.Position = 0;
var binaryReader = new BinaryReader(memoryStream);
using var buildEventArgsReader = new BuildEventArgsReader(binaryReader, BinaryLogger.FileFormatVersion);
var deserializedArgs = (T)buildEventArgsReader.Read();
Assert.Equal(length, memoryStream.Position);
Assert.NotNull(deserializedArgs);
Assert.Equal(args.GetType(), deserializedArgs.GetType());
foreach (var field in fieldsToCompare)
{
var expected = field(args);
var actual = field(deserializedArgs);
Assert.Equal(expected, actual);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using CURLAUTH = Interop.libcurl.CURLAUTH;
using CURLcode = Interop.libcurl.CURLcode;
using CurlFeatures = Interop.libcurl.CURL_VERSION_Features;
using CURLMcode = Interop.libcurl.CURLMcode;
using CURLoption = Interop.libcurl.CURLoption;
using CurlVersionInfoData = Interop.libcurl.curl_version_info_data;
namespace System.Net.Http
{
internal partial class CurlHandler : HttpMessageHandler
{
#region Constants
private const string VerboseDebuggingConditional = "CURLHANDLER_VERBOSE";
private const string HttpPrefix = "HTTP/";
private const char SpaceChar = ' ';
private const int StatusCodeLength = 3;
private const string UriSchemeHttp = "http";
private const string UriSchemeHttps = "https";
private const string EncodingNameGzip = "gzip";
private const string EncodingNameDeflate = "deflate";
private const int RequestBufferSize = 16384; // Default used by libcurl
private const string NoTransferEncoding = HttpKnownHeaderNames.TransferEncoding + ":";
private const string NoContentType = HttpKnownHeaderNames.ContentType + ":";
private const int CurlAge = 5;
private const int MinCurlAge = 3;
#endregion
#region Fields
private readonly static char[] s_newLineCharArray = new char[] { HttpRuleParser.CR, HttpRuleParser.LF };
private readonly static string[] s_authenticationSchemes = { "Negotiate", "Digest", "Basic" }; // the order in which libcurl goes over authentication schemes
private readonly static ulong[] s_authSchemePriorityOrder = { CURLAUTH.Negotiate, CURLAUTH.Digest, CURLAUTH.Basic };
private readonly static CurlVersionInfoData s_curlVersionInfoData;
private readonly static bool s_supportsAutomaticDecompression;
private readonly static bool s_supportsSSL;
private readonly MultiAgent _agent = new MultiAgent();
private volatile bool _anyOperationStarted;
private volatile bool _disposed;
private IWebProxy _proxy = null;
private ICredentials _serverCredentials = null;
private ProxyUsePolicy _proxyPolicy = ProxyUsePolicy.UseDefaultProxy;
private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression;
private bool _preAuthenticate = HttpHandlerDefaults.DefaultPreAuthenticate;
private CredentialCache _credentialCache = null; // protected by LockObject
private CookieContainer _cookieContainer = null;
private bool _useCookie = HttpHandlerDefaults.DefaultUseCookies;
private bool _automaticRedirection = HttpHandlerDefaults.DefaultAutomaticRedirection;
private int _maxAutomaticRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections;
private object LockObject { get { return _agent; } }
#endregion
static CurlHandler()
{
// curl_global_init call handled by Interop.libcurl's cctor
// Verify the version of curl we're using is new enough
s_curlVersionInfoData = Marshal.PtrToStructure<CurlVersionInfoData>(Interop.libcurl.curl_version_info(CurlAge));
if (s_curlVersionInfoData.age < MinCurlAge)
{
throw new InvalidOperationException(SR.net_http_unix_https_libcurl_too_old);
}
// Feature detection
s_supportsSSL = (CurlFeatures.CURL_VERSION_SSL & s_curlVersionInfoData.features) != 0;
s_supportsAutomaticDecompression = (CurlFeatures.CURL_VERSION_LIBZ & s_curlVersionInfoData.features) != 0;
}
#region Properties
internal bool AutomaticRedirection
{
get
{
return _automaticRedirection;
}
set
{
CheckDisposedOrStarted();
_automaticRedirection = value;
}
}
internal bool SupportsProxy
{
get
{
return true;
}
}
internal bool UseProxy
{
get
{
return _proxyPolicy != ProxyUsePolicy.DoNotUseProxy;
}
set
{
CheckDisposedOrStarted();
_proxyPolicy = value ?
ProxyUsePolicy.UseCustomProxy :
ProxyUsePolicy.DoNotUseProxy;
}
}
internal IWebProxy Proxy
{
get
{
return _proxy;
}
set
{
CheckDisposedOrStarted();
_proxy = value;
}
}
internal ICredentials Credentials
{
get
{
return _serverCredentials;
}
set
{
_serverCredentials = value;
}
}
internal ClientCertificateOption ClientCertificateOptions
{
get
{
return ClientCertificateOption.Manual;
}
set
{
if (ClientCertificateOption.Manual != value)
{
throw new PlatformNotSupportedException(SR.net_http_unix_invalid_client_cert_option);
}
}
}
internal bool SupportsAutomaticDecompression
{
get
{
return s_supportsAutomaticDecompression;
}
}
internal DecompressionMethods AutomaticDecompression
{
get
{
return _automaticDecompression;
}
set
{
CheckDisposedOrStarted();
_automaticDecompression = value;
}
}
internal bool PreAuthenticate
{
get
{
return _preAuthenticate;
}
set
{
CheckDisposedOrStarted();
_preAuthenticate = value;
if (value && _credentialCache == null)
{
_credentialCache = new CredentialCache();
}
}
}
internal bool UseCookie
{
get
{
return _useCookie;
}
set
{
CheckDisposedOrStarted();
_useCookie = value;
}
}
internal CookieContainer CookieContainer
{
get
{
return LazyInitializer.EnsureInitialized(ref _cookieContainer);
}
set
{
CheckDisposedOrStarted();
_cookieContainer = value;
}
}
internal int MaxAutomaticRedirections
{
get
{
return _maxAutomaticRedirections;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
"value",
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxAutomaticRedirections = value;
}
}
#endregion
protected override void Dispose(bool disposing)
{
_disposed = true;
base.Dispose(disposing);
}
protected internal override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
if (request == null)
{
throw new ArgumentNullException("request", SR.net_http_handler_norequest);
}
if ((request.RequestUri.Scheme != UriSchemeHttp) && (request.RequestUri.Scheme != UriSchemeHttps))
{
throw NotImplemented.ByDesignWithMessage(SR.net_http_client_http_baseaddress_required);
}
if (request.RequestUri.Scheme == UriSchemeHttps && !s_supportsSSL)
{
throw new PlatformNotSupportedException(SR.net_http_unix_https_support_unavailable_libcurl);
}
if (request.Headers.TransferEncodingChunked.GetValueOrDefault() && (request.Content == null))
{
throw new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content);
}
// TODO: Check that SendAsync is not being called again for same request object.
// Probably fix is needed in WinHttpHandler as well
CheckDisposed();
SetOperationStarted();
// Do an initial cancellation check to avoid initiating the async operation if
// cancellation has already been requested. After this, we'll rely on CancellationToken.Register
// to notify us of cancellation requests and shut down the operation if possible.
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<HttpResponseMessage>(cancellationToken);
}
// Create the easy request. This associates the easy request with this handler and configures
// it based on the settings configured for the handler.
var easy = new EasyRequest(this, request, cancellationToken);
// Submit the easy request to the multi agent.
if (request.Content != null)
{
// If there is request content to be sent, preload the stream
// and submit the request to the multi agent. This is separated
// out into a separate async method to avoid associated overheads
// in the case where there is no request content stream.
return QueueOperationWithRequestContentAsync(easy);
}
else
{
// Otherwise, just submit the request.
ConfigureAndQueue(easy);
return easy.Task;
}
}
private void ConfigureAndQueue(EasyRequest easy)
{
try
{
easy.InitializeCurl();
_agent.Queue(new MultiAgent.IncomingRequest { Easy = easy, Type = MultiAgent.IncomingRequestType.New });
}
catch (Exception exc)
{
easy.FailRequest(exc);
easy.Cleanup(); // no active processing remains, so we can cleanup
}
}
/// <summary>
/// Loads the request's request content stream asynchronously and
/// then submits the request to the multi agent.
/// </summary>
private async Task<HttpResponseMessage> QueueOperationWithRequestContentAsync(EasyRequest easy)
{
Debug.Assert(easy._requestMessage.Content != null, "Expected request to have non-null request content");
easy._requestContentStream = await easy._requestMessage.Content.ReadAsStreamAsync().ConfigureAwait(false);
if (easy._cancellationToken.IsCancellationRequested)
{
easy.FailRequest(new OperationCanceledException(easy._cancellationToken));
easy.Cleanup(); // no active processing remains, so we can cleanup
}
else
{
ConfigureAndQueue(easy);
}
return await easy.Task.ConfigureAwait(false);
}
#region Private methods
private void SetOperationStarted()
{
if (!_anyOperationStarted)
{
_anyOperationStarted = true;
}
}
private NetworkCredential GetNetworkCredentials(ICredentials credentials, Uri requestUri)
{
if (_preAuthenticate)
{
NetworkCredential nc = null;
lock (LockObject)
{
Debug.Assert(_credentialCache != null, "Expected non-null credential cache");
nc = GetCredentials(_credentialCache, requestUri);
}
if (nc != null)
{
return nc;
}
}
return GetCredentials(credentials, requestUri);
}
private void AddCredentialToCache(Uri serverUri, ulong authAvail, NetworkCredential nc)
{
lock (LockObject)
{
for (int i=0; i < s_authSchemePriorityOrder.Length; i++)
{
if ((authAvail & s_authSchemePriorityOrder[i]) != 0)
{
Debug.Assert(_credentialCache != null, "Expected non-null credential cache");
_credentialCache.Add(serverUri, s_authenticationSchemes[i], nc);
}
}
}
}
private static NetworkCredential GetCredentials(ICredentials credentials, Uri requestUri)
{
if (credentials == null)
{
return null;
}
foreach (var authScheme in s_authenticationSchemes)
{
NetworkCredential networkCredential = credentials.GetCredential(requestUri, authScheme);
if (networkCredential != null)
{
return networkCredential;
}
}
return null;
}
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
}
private void CheckDisposedOrStarted()
{
CheckDisposed();
if (_anyOperationStarted)
{
throw new InvalidOperationException(SR.net_http_operation_started);
}
}
private static void ThrowIfCURLEError(int error)
{
if (error != CURLcode.CURLE_OK)
{
var inner = new CurlException(error, isMulti: false);
VerboseTrace(inner.Message);
throw CreateHttpRequestException(inner);
}
}
private static void ThrowIfCURLMError(int error)
{
if (error != CURLMcode.CURLM_OK)
{
string msg = CurlException.GetCurlErrorString(error, true);
VerboseTrace(msg);
switch (error)
{
case CURLMcode.CURLM_ADDED_ALREADY:
case CURLMcode.CURLM_BAD_EASY_HANDLE:
case CURLMcode.CURLM_BAD_HANDLE:
case CURLMcode.CURLM_BAD_SOCKET:
throw new ArgumentException(msg);
case CURLMcode.CURLM_UNKNOWN_OPTION:
throw new ArgumentOutOfRangeException(msg);
case CURLMcode.CURLM_OUT_OF_MEMORY:
throw new OutOfMemoryException(msg);
case CURLMcode.CURLM_INTERNAL_ERROR:
default:
throw CreateHttpRequestException(new CurlException(error, msg));
}
}
}
[Conditional(VerboseDebuggingConditional)]
private static void VerboseTrace(string text = null, [CallerMemberName] string memberName = null, EasyRequest easy = null, MultiAgent agent = null)
{
// If we weren't handed a multi agent, see if we can get one from the EasyRequest
if (agent == null && easy != null && easy._associatedMultiAgent != null)
{
agent = easy._associatedMultiAgent;
}
int? agentId = agent != null ? agent.RunningWorkerId : null;
// Get an ID string that provides info about which MultiAgent worker and which EasyRequest this trace is about
string ids = "";
if (agentId != null || easy != null)
{
ids = "(" +
(agentId != null ? "M#" + agentId : "") +
(agentId != null && easy != null ? ", " : "") +
(easy != null ? "E#" + easy.Task.Id : "") +
")";
}
// Create the message and trace it out
string msg = string.Format("[{0, -30}]{1, -16}: {2}", memberName, ids, text);
Interop.libc.printf("%s\n", msg);
}
[Conditional(VerboseDebuggingConditional)]
private static void VerboseTraceIf(bool condition, string text = null, [CallerMemberName] string memberName = null, EasyRequest easy = null)
{
if (condition)
{
VerboseTrace(text, memberName, easy, agent: null);
}
}
private static Exception CreateHttpRequestException(Exception inner = null)
{
return new HttpRequestException(SR.net_http_client_execution_error, inner);
}
private static bool TryParseStatusLine(HttpResponseMessage response, string responseHeader, EasyRequest state)
{
if (!responseHeader.StartsWith(HttpPrefix, StringComparison.OrdinalIgnoreCase))
{
return false;
}
// Clear the header if status line is recieved again. This signifies that there are multiple response headers (like in redirection).
response.Headers.Clear();
response.Content.Headers.Clear();
int responseHeaderLength = responseHeader.Length;
// Check if line begins with HTTP/1.1 or HTTP/1.0
int prefixLength = HttpPrefix.Length;
int versionIndex = prefixLength + 2;
if ((versionIndex < responseHeaderLength) && (responseHeader[prefixLength] == '1') && (responseHeader[prefixLength + 1] == '.'))
{
response.Version =
responseHeader[versionIndex] == '1' ? HttpVersion.Version11 :
responseHeader[versionIndex] == '0' ? HttpVersion.Version10 :
new Version(0, 0);
}
else
{
response.Version = new Version(0, 0);
}
// TODO: Parsing errors are treated as fatal. Find right behaviour
int spaceIndex = responseHeader.IndexOf(SpaceChar);
if (spaceIndex > -1)
{
int codeStartIndex = spaceIndex + 1;
int statusCode = 0;
// Parse first 3 characters after a space as status code
if (TryParseStatusCode(responseHeader, codeStartIndex, out statusCode))
{
response.StatusCode = (HttpStatusCode)statusCode;
// For security reasons, we drop the server credential if it is a
// NetworkCredential. But we allow credentials in a CredentialCache
// since they are specifically tied to URI's.
if ((response.StatusCode == HttpStatusCode.Redirect) && !(state._handler.Credentials is CredentialCache))
{
state.SetCurlOption(CURLoption.CURLOPT_HTTPAUTH, CURLAUTH.None);
state.SetCurlOption(CURLoption.CURLOPT_USERNAME, IntPtr.Zero);
state.SetCurlOption(CURLoption.CURLOPT_PASSWORD, IntPtr.Zero);
state._networkCredential = null;
}
int codeEndIndex = codeStartIndex + StatusCodeLength;
int reasonPhraseIndex = codeEndIndex + 1;
if (reasonPhraseIndex < responseHeaderLength && responseHeader[codeEndIndex] == SpaceChar)
{
int newLineCharIndex = responseHeader.IndexOfAny(s_newLineCharArray, reasonPhraseIndex);
int reasonPhraseEnd = newLineCharIndex >= 0 ? newLineCharIndex : responseHeaderLength;
response.ReasonPhrase = responseHeader.Substring(reasonPhraseIndex, reasonPhraseEnd - reasonPhraseIndex);
}
}
}
return true;
}
private static bool TryParseStatusCode(string responseHeader, int statusCodeStartIndex, out int statusCode)
{
if (statusCodeStartIndex + StatusCodeLength > responseHeader.Length)
{
statusCode = 0;
return false;
}
char c100 = responseHeader[statusCodeStartIndex];
char c10 = responseHeader[statusCodeStartIndex + 1];
char c1 = responseHeader[statusCodeStartIndex + 2];
if (c100 < '0' || c100 > '9' ||
c10 < '0' || c10 > '9' ||
c1 < '0' || c1 > '9')
{
statusCode = 0;
return false;
}
statusCode = (c100 - '0') * 100 + (c10 - '0') * 10 + (c1 - '0');
return true;
}
private static void SetChunkedModeForSend(HttpRequestMessage request)
{
bool chunkedMode = request.Headers.TransferEncodingChunked.GetValueOrDefault();
HttpContent requestContent = request.Content;
Debug.Assert(requestContent != null, "request is null");
// Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics.
// libcurl adds a Tranfer-Encoding header by default and the request fails if both are set.
if (requestContent.Headers.ContentLength.HasValue)
{
if (chunkedMode)
{
// Same behaviour as WinHttpHandler
requestContent.Headers.ContentLength = null;
}
else
{
// Prevent libcurl from adding Transfer-Encoding header
request.Headers.TransferEncodingChunked = false;
}
}
else if (!chunkedMode)
{
// Make sure Transfer-Encoding: chunked header is set,
// as we have content to send but no known length for it.
request.Headers.TransferEncodingChunked = true;
}
}
#endregion
private enum ProxyUsePolicy
{
DoNotUseProxy = 0, // Do not use proxy. Ignores the value set in the environment.
UseDefaultProxy = 1, // Do not set the proxy parameter. Use the value of environment variable, if any.
UseCustomProxy = 2 // Use The proxy specified by the user.
}
}
}
| |
/*
*
* (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.Globalization;
using System.Linq;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using ASC.ActiveDirectory.Base;
using ASC.ActiveDirectory.Base.Settings;
using ASC.ActiveDirectory.Novell;
using ASC.Common.Logging;
using ASC.Common.Security.Authorizing;
using ASC.Common.Threading;
using ASC.Core;
using ASC.Core.Tenants;
using SecurityContext = ASC.Core.SecurityContext;
namespace ASC.ActiveDirectory.ComplexOperations
{
public abstract class LdapOperation : IDisposable
{
public const string OWNER = "LDAPOwner";
public const string OPERATION_TYPE = "LDAPOperationType";
public const string SOURCE = "LDAPSource";
public const string PROGRESS = "LDAPProgress";
public const string RESULT = "LDAPResult";
public const string ERROR = "LDAPError";
public const string WARNING = "LDAPWarning";
public const string CERT_REQUEST = "LDAPCertRequest";
public const string FINISHED = "LDAPFinished";
private readonly string _culture;
public LdapSettings LDAPSettings { get; private set; }
public LdapUserImporter Importer { get; private set; }
public LdapUserManager LDAPUserManager { get; private set; }
protected DistributedTask TaskInfo { get; private set; }
protected int Progress { get; private set; }
protected string Source { get; private set; }
protected string Status { get; set; }
protected string Error { get; set; }
protected string Warning { get; set; }
protected Tenant CurrentTenant { get; private set; }
protected ILog Logger { get; private set; }
protected CancellationToken CancellationToken { get; private set; }
public LdapOperationType OperationType { get; private set; }
public static LdapLocalization Resource { get; private set; }
protected LdapOperation(LdapSettings settings, Tenant tenant, LdapOperationType operationType, LdapLocalization resource = null)
{
CurrentTenant = tenant;
OperationType = operationType;
_culture = Thread.CurrentThread.CurrentCulture.Name;
LDAPSettings = settings;
Source = "";
Progress = 0;
Status = "";
Error = "";
Warning = "";
Source = "";
TaskInfo = new DistributedTask();
Resource = resource ?? new LdapLocalization();
LDAPUserManager = new LdapUserManager(Resource);
}
public void RunJob(DistributedTask _, CancellationToken cancellationToken)
{
try
{
CancellationToken = cancellationToken;
CoreContext.TenantManager.SetCurrentTenant(CurrentTenant);
SecurityContext.AuthenticateMe(Core.Configuration.Constants.CoreSystem);
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(_culture);
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(_culture);
Logger = LogManager.GetLogger("ASC");
if (LDAPSettings == null)
{
Error = Resource.LdapSettingsErrorCantGetLdapSettings;
Logger.Error("Can't save default LDAP settings.");
return;
}
switch (OperationType)
{
case LdapOperationType.Save:
case LdapOperationType.SaveTest:
Logger.InfoFormat("Start '{0}' operation",
Enum.GetName(typeof(LdapOperationType), OperationType));
SetProgress(1, Resource.LdapSettingsStatusCheckingLdapSettings);
Logger.Debug("PrepareSettings()");
PrepareSettings(LDAPSettings);
if (!string.IsNullOrEmpty(Error))
{
Logger.DebugFormat("PrepareSettings() Error: {0}", Error);
return;
}
Importer = new NovellLdapUserImporter(LDAPSettings, Resource);
if (LDAPSettings.EnableLdapAuthentication)
{
var ldapSettingsChecker = new NovellLdapSettingsChecker(Importer);
SetProgress(5, Resource.LdapSettingsStatusLoadingBaseInfo);
var result = ldapSettingsChecker.CheckSettings();
if (result != LdapSettingsStatus.Ok)
{
if (result == LdapSettingsStatus.CertificateRequest)
{
TaskInfo.SetProperty(CERT_REQUEST,
ldapSettingsChecker.CertificateConfirmRequest);
}
Error = GetError(result);
Logger.DebugFormat("ldapSettingsChecker.CheckSettings() Error: {0}", Error);
return;
}
}
break;
case LdapOperationType.Sync:
case LdapOperationType.SyncTest:
Logger.InfoFormat("Start '{0}' operation",
Enum.GetName(typeof(LdapOperationType), OperationType));
Importer = new NovellLdapUserImporter(LDAPSettings, Resource);
break;
default:
throw new ArgumentOutOfRangeException();
}
Do();
}
catch (AuthorizingException authError)
{
Error = Resource.ErrorAccessDenied;
Logger.Error(Error, new SecurityException(Error, authError));
}
catch (AggregateException ae)
{
ae.Flatten().Handle(e => e is TaskCanceledException || e is OperationCanceledException);
}
catch (TenantQuotaException e)
{
Error = Resource.LdapSettingsTenantQuotaSettled;
Logger.ErrorFormat("TenantQuotaException. {0}", e);
}
catch (FormatException e)
{
Error = Resource.LdapSettingsErrorCantCreateUsers;
Logger.ErrorFormat("FormatException error. {0}", e);
}
catch (Exception e)
{
Error = Resource.LdapSettingsInternalServerError;
Logger.ErrorFormat("Internal server error. {0}", e);
}
finally
{
try
{
TaskInfo.SetProperty(FINISHED, true);
PublishTaskInfo();
Dispose();
SecurityContext.Logout();
}
catch (Exception ex)
{
Logger.ErrorFormat("LdapOperation finalization problem. {0}", ex);
}
}
}
public virtual DistributedTask GetDistributedTask()
{
FillDistributedTask();
return TaskInfo;
}
protected virtual void FillDistributedTask()
{
TaskInfo.SetProperty(SOURCE, Source);
TaskInfo.SetProperty(OPERATION_TYPE, OperationType);
TaskInfo.SetProperty(OWNER, CurrentTenant.TenantId);
TaskInfo.SetProperty(PROGRESS, Progress < 100 ? Progress : 100);
TaskInfo.SetProperty(RESULT, Status);
TaskInfo.SetProperty(ERROR, Error);
TaskInfo.SetProperty(WARNING, Warning);
//TaskInfo.SetProperty(PROCESSED, successProcessed);
}
protected int GetProgress()
{
return Progress;
}
const string PROGRESS_STRING = "Progress: {0}% {1} {2}";
public void SetProgress(int? currentPercent = null, string currentStatus = null, string currentSource = null)
{
if (!currentPercent.HasValue && currentStatus == null && currentSource == null)
return;
if (currentPercent.HasValue)
Progress = currentPercent.Value;
if (currentStatus != null)
Status = currentStatus;
if (currentSource != null)
Source = currentSource;
Logger.InfoFormat(PROGRESS_STRING, Progress, Status, Source);
PublishTaskInfo();
}
protected void PublishTaskInfo()
{
FillDistributedTask();
TaskInfo.PublishChanges();
}
protected abstract void Do();
private void PrepareSettings(LdapSettings settings)
{
if (settings == null)
{
Logger.Error("Wrong LDAP settings were received from client.");
Error = Resource.LdapSettingsErrorCantGetLdapSettings;
return;
}
if (!settings.EnableLdapAuthentication)
{
settings.Password = string.Empty;
return;
}
if (!string.IsNullOrWhiteSpace(settings.Server))
settings.Server = settings.Server.Trim();
else
{
Logger.Error("settings.Server is null or empty.");
Error = Resource.LdapSettingsErrorCantGetLdapSettings;
return;
}
if (!settings.Server.StartsWith("LDAP://"))
settings.Server = "LDAP://" + settings.Server.Trim();
if (!string.IsNullOrWhiteSpace(settings.UserDN))
settings.UserDN = settings.UserDN.Trim();
else
{
Logger.Error("settings.UserDN is null or empty.");
Error = Resource.LdapSettingsErrorCantGetLdapSettings;
return;
}
if (!string.IsNullOrWhiteSpace(settings.LoginAttribute))
settings.LoginAttribute = settings.LoginAttribute.Trim();
else
{
Logger.Error("settings.LoginAttribute is null or empty.");
Error = Resource.LdapSettingsErrorCantGetLdapSettings;
return;
}
if (!string.IsNullOrWhiteSpace(settings.UserFilter))
settings.UserFilter = settings.UserFilter.Trim();
if (!string.IsNullOrWhiteSpace(settings.FirstNameAttribute))
settings.FirstNameAttribute = settings.FirstNameAttribute.Trim();
if (!string.IsNullOrWhiteSpace(settings.SecondNameAttribute))
settings.SecondNameAttribute = settings.SecondNameAttribute.Trim();
if (!string.IsNullOrWhiteSpace(settings.MailAttribute))
settings.MailAttribute = settings.MailAttribute.Trim();
if (!string.IsNullOrWhiteSpace(settings.TitleAttribute))
settings.TitleAttribute = settings.TitleAttribute.Trim();
if (!string.IsNullOrWhiteSpace(settings.MobilePhoneAttribute))
settings.MobilePhoneAttribute = settings.MobilePhoneAttribute.Trim();
if (settings.GroupMembership)
{
if (!string.IsNullOrWhiteSpace(settings.GroupDN))
settings.GroupDN = settings.GroupDN.Trim();
else
{
Logger.Error("settings.GroupDN is null or empty.");
Error = Resource.LdapSettingsErrorCantGetLdapSettings;
return;
}
if (!string.IsNullOrWhiteSpace(settings.GroupFilter))
settings.GroupFilter = settings.GroupFilter.Trim();
if (!string.IsNullOrWhiteSpace(settings.GroupAttribute))
settings.GroupAttribute = settings.GroupAttribute.Trim();
else
{
Logger.Error("settings.GroupAttribute is null or empty.");
Error = Resource.LdapSettingsErrorCantGetLdapSettings;
return;
}
if (!string.IsNullOrWhiteSpace(settings.UserAttribute))
settings.UserAttribute = settings.UserAttribute.Trim();
else
{
Logger.Error("settings.UserAttribute is null or empty.");
Error = Resource.LdapSettingsErrorCantGetLdapSettings;
return;
}
}
if (!settings.Authentication)
{
settings.Password = string.Empty;
return;
}
if (!string.IsNullOrWhiteSpace(settings.Login))
settings.Login = settings.Login.Trim();
else
{
Logger.Error("settings.Login is null or empty.");
Error = Resource.LdapSettingsErrorCantGetLdapSettings;
return;
}
if (settings.PasswordBytes == null || !settings.PasswordBytes.Any())
{
if (!string.IsNullOrEmpty(settings.Password))
{
settings.PasswordBytes = LdapHelper.GetPasswordBytes(settings.Password);
if (settings.PasswordBytes == null)
{
Logger.Error("settings.PasswordBytes is null.");
Error = Resource.LdapSettingsErrorCantGetLdapSettings;
return;
}
}
else
{
Logger.Error("settings.Password is null or empty.");
Error = Resource.LdapSettingsErrorCantGetLdapSettings;
return;
}
}
settings.Password = string.Empty;
}
private static string GetError(LdapSettingsStatus result)
{
switch (result)
{
case LdapSettingsStatus.Ok:
return string.Empty;
case LdapSettingsStatus.WrongServerOrPort:
return Resource.LdapSettingsErrorWrongServerOrPort;
case LdapSettingsStatus.WrongUserDn:
return Resource.LdapSettingsErrorWrongUserDn;
case LdapSettingsStatus.IncorrectLDAPFilter:
return Resource.LdapSettingsErrorIncorrectLdapFilter;
case LdapSettingsStatus.UsersNotFound:
return Resource.LdapSettingsErrorUsersNotFound;
case LdapSettingsStatus.WrongLoginAttribute:
return Resource.LdapSettingsErrorWrongLoginAttribute;
case LdapSettingsStatus.WrongGroupDn:
return Resource.LdapSettingsErrorWrongGroupDn;
case LdapSettingsStatus.IncorrectGroupLDAPFilter:
return Resource.LdapSettingsErrorWrongGroupFilter;
case LdapSettingsStatus.GroupsNotFound:
return Resource.LdapSettingsErrorGroupsNotFound;
case LdapSettingsStatus.WrongGroupAttribute:
return Resource.LdapSettingsErrorWrongGroupAttribute;
case LdapSettingsStatus.WrongUserAttribute:
return Resource.LdapSettingsErrorWrongUserAttribute;
case LdapSettingsStatus.WrongGroupNameAttribute:
return Resource.LdapSettingsErrorWrongGroupNameAttribute;
case LdapSettingsStatus.CredentialsNotValid:
return Resource.LdapSettingsErrorCredentialsNotValid;
case LdapSettingsStatus.ConnectError:
return Resource.LdapSettingsConnectError;
case LdapSettingsStatus.StrongAuthRequired:
return Resource.LdapSettingsStrongAuthRequired;
case LdapSettingsStatus.WrongSidAttribute:
return Resource.LdapSettingsWrongSidAttribute;
case LdapSettingsStatus.TlsNotSupported:
return Resource.LdapSettingsTlsNotSupported;
case LdapSettingsStatus.DomainNotFound:
return Resource.LdapSettingsErrorDomainNotFound;
case LdapSettingsStatus.CertificateRequest:
return Resource.LdapSettingsStatusCertificateVerification;
default:
return Resource.LdapSettingsErrorUnknownError;
}
}
public void Dispose()
{
if (Importer != null)
Importer.Dispose();
}
}
}
| |
// The MIT License (MIT)
//
// CoreTweet - A .NET Twitter Library supporting Twitter API 1.1
// Copyright (c) 2013-2015 CoreTweet Development Team
//
// 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.Globalization;
using Newtonsoft.Json;
namespace CoreTweet.Core
{
/// <summary>
/// Provides the <see cref="System.DateTimeOffset"/> converter of the <see cref="Newtonsoft.Json.JsonSerializer"/>.
/// </summary>
public class DateTimeOffsetConverter : JsonConverter
{
/// <summary>
/// Returns whether this converter can convert the object to the specified type.
/// </summary>
/// <param name="objectType">A <see cref="System.Type"/> that represents the type you want to convert to.</param>
/// <returns>
/// <c>true</c> if this converter can perform the conversion; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type objectType)
{
return objectType == typeof(DateTimeOffset);
}
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="Newtonsoft.Json.JsonReader"/> to read from.</param>
/// <param name="objectType">The <see cref="System.Type"/> of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
switch(reader.TokenType)
{
case JsonToken.String:
return DateTimeOffset.ParseExact(reader.Value as string, "ddd MMM dd HH:mm:ss K yyyy",
DateTimeFormatInfo.InvariantInfo,
DateTimeStyles.AllowWhiteSpaces);
case JsonToken.Date:
if (reader.Value is DateTimeOffset)
return (DateTimeOffset)reader.Value;
else
return new DateTimeOffset(((DateTime)reader.Value).ToUniversalTime(), TimeSpan.Zero);
case JsonToken.Integer:
return InternalUtils.GetUnixTime((long)reader.Value);
case JsonToken.Null:
return DateTimeOffset.Now;
}
throw new InvalidOperationException("This object is not a DateTimeOffset");
}
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="Newtonsoft.Json.JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if(value is DateTimeOffset)
writer.WriteValue((DateTimeOffset)value);
else
throw new InvalidOperationException("This object is not a DateTimeOffset");
}
}
/// <summary>
/// Provides the <see cref="Contributors"/> converter of the <see cref="Newtonsoft.Json.JsonSerializer"/>.
/// </summary>
public class ContributorsConverter : JsonConverter
{
/// <summary>
/// Returns whether this converter can convert the object to the specified type.
/// </summary>
/// <param name="objectType">A <see cref="System.Type"/> that represents the type you want to convert to.</param>
/// <returns>
/// <c>true</c> if this converter can perform the conversion; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Contributors);
}
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="Newtonsoft.Json.JsonReader"/> to read from.</param>
/// <param name="objectType">The <see cref="System.Type"/> of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
switch(reader.TokenType)
{
case JsonToken.Integer:
return new Contributors { Id = (long)reader.Value };
case JsonToken.StartObject:
reader.Read();
var value = new Contributors();
while(reader.TokenType != JsonToken.EndObject)
{
if(reader.TokenType != JsonToken.PropertyName)
throw new FormatException("The format of this object is wrong");
switch((string)reader.Value)
{
case "id":
value.Id = (long)reader.ReadAsDecimal();
break;
case "screen_name":
value.ScreenName = reader.ReadAsString();
break;
default:
reader.Read();
break;
}
reader.Read();
}
return value;
}
throw new InvalidOperationException("This object is not a Contributors");
}
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="Newtonsoft.Json.JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
/// <summary>
/// Provides the <see cref="System.DateTimeOffset"/> converter of the <see cref="Newtonsoft.Json.JsonSerializer"/>.
/// </summary>
public class TimestampConverter : JsonConverter
{
/// <summary>
/// Returns whether this converter can convert the object to the specified type.
/// </summary>
/// <param name="objectType">A <see cref="System.Type"/> that represents the type you want to convert to.</param>
/// <returns>
/// <c>true</c> if this converter can perform the conversion; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type objectType)
{
return objectType == typeof(DateTimeOffset);
}
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="Newtonsoft.Json.JsonReader"/> to read from.</param>
/// <param name="objectType">The <see cref="System.Type"/> of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
long ms;
switch(reader.TokenType)
{
case JsonToken.String:
ms = long.Parse(reader.Value.ToString());
break;
case JsonToken.Integer:
ms = (long)reader.Value;
break;
default:
throw new InvalidOperationException("This object is not a timestamp");
}
return InternalUtils.GetUnixTimeMs(ms);
}
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="Newtonsoft.Json.JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if(value is DateTimeOffset)
writer.WriteValue(((((DateTimeOffset)value).Ticks - InternalUtils.unixEpoch.Ticks) / 10000).ToString("D"));
else
throw new InvalidOperationException("This object is not a DateTimeOffset");
}
}
}
| |
// 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.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.NodejsTools.Debugger
{
internal sealed class NodeBreakpointBinding
{
private readonly NodeBreakpoint _breakpoint;
private readonly int _breakpointId;
private readonly bool _fullyBould;
private readonly FilePosition _position;
private readonly int? _scriptId;
private readonly FilePosition _target;
private BreakOn _breakOn;
private string _condition;
private bool _enabled;
private bool _engineEnabled;
private uint _engineHitCount;
private int _engineIgnoreCount;
private uint _hitCountDelta;
public NodeBreakpointBinding(NodeBreakpoint breakpoint, FilePosition target, FilePosition position, int breakpointId, int? scriptId, bool fullyBound)
{
this._breakpoint = breakpoint;
this._target = target;
this._position = position;
this._breakpointId = breakpointId;
this._scriptId = scriptId;
this._enabled = breakpoint.Enabled;
this._breakOn = breakpoint.BreakOn;
this._condition = breakpoint.Condition;
this._engineEnabled = GetEngineEnabled();
this._engineIgnoreCount = GetEngineIgnoreCount();
this._fullyBould = fullyBound;
}
public NodeDebugger Process => this._breakpoint.Process;
public NodeBreakpoint Breakpoint => this._breakpoint;
/// <summary>
/// Line and column number that corresponds with the actual JavaScript code
/// </summary>
public FilePosition Position => this._position;
/// <summary>
/// Line and column number that corresponds to the file the breakpoint was requested in
/// </summary>
public FilePosition Target => this._target;
public bool Enabled => this._enabled;
public BreakOn BreakOn => this._breakOn;
public string Condition => this._condition;
public int BreakpointId => this._breakpointId;
internal int? ScriptId => this._scriptId;
private uint HitCount => this._engineHitCount - this._hitCountDelta;
internal bool FullyBound => this._fullyBould;
public bool Unbound { get; set; }
public Task Remove()
{
return this.Process.RemoveBreakpointAsync(this).WaitAsync(System.TimeSpan.FromSeconds(2));
}
public uint GetHitCount()
{
SyncCounts();
return this.HitCount;
}
internal async Task<bool> SetEnabledAsync(bool enabled)
{
if (this._enabled == enabled)
{
return true;
}
SyncCounts();
var engineEnabled = GetEngineEnabled(enabled, this._breakOn, this.HitCount);
if (this._engineEnabled != engineEnabled)
{
await this.Process.UpdateBreakpointBindingAsync(this._breakpointId, engineEnabled, validateSuccess: true).ConfigureAwait(false);
this._engineEnabled = engineEnabled;
}
this._enabled = enabled;
return true;
}
internal async Task<bool> SetBreakOnAsync(BreakOn breakOn, bool force = false)
{
if (!force && this._breakOn.Kind == breakOn.Kind && this._breakOn.Count == breakOn.Count)
{
return true;
}
SyncCounts();
var engineEnabled = GetEngineEnabled(this._enabled, breakOn, this.HitCount);
var enabled = (this._engineEnabled != engineEnabled) ? (bool?)engineEnabled : null;
var engineIgnoreCount = GetEngineIgnoreCount(breakOn, this.HitCount);
await this.Process.UpdateBreakpointBindingAsync(this._breakpointId, ignoreCount: engineIgnoreCount, enabled: enabled, validateSuccess: true).ConfigureAwait(false);
this._engineEnabled = engineEnabled;
this._engineIgnoreCount = engineIgnoreCount;
this._breakOn = breakOn;
return true;
}
internal async Task<bool> SetHitCountAsync(uint hitCount)
{
SyncCounts();
if (this.HitCount == hitCount)
{
return true;
}
if (this._breakOn.Kind != BreakOnKind.Always)
{
// When BreakOn (not BreakOnKind.Always), handle change to hit count by resetting ignore count
var engineEnabled = GetEngineEnabled(this._enabled, this._breakOn, hitCount);
var enabled = (this._engineEnabled != engineEnabled) ? (bool?)engineEnabled : null;
var engineIgnoreCount = GetEngineIgnoreCount(this._breakOn, hitCount);
await this.Process.UpdateBreakpointBindingAsync(this._breakpointId, ignoreCount: engineIgnoreCount, enabled: enabled, validateSuccess: true).ConfigureAwait(false);
this._engineEnabled = engineEnabled;
this._engineIgnoreCount = engineIgnoreCount;
}
this._hitCountDelta = this._engineHitCount - hitCount;
return true;
}
internal async Task<bool> SetConditionAsync(string condition)
{
await this.Process.UpdateBreakpointBindingAsync(this._breakpointId, condition: condition, validateSuccess: true).ConfigureAwait(false);
this._condition = condition;
return true;
}
private void UpdatedEngineState(bool engineEnabled, uint engineHitCount, int engineIgnoreCount)
{
this._engineEnabled = engineEnabled;
this._engineHitCount = engineHitCount;
this._engineIgnoreCount = engineIgnoreCount;
}
internal async Task ProcessBreakpointHitAsync(CancellationToken cancellationToken = new CancellationToken())
{
Debug.Assert(GetEngineEnabled(this._enabled, this._breakOn, this.HitCount));
// Compose followup handler
var engineHitCount = this._engineHitCount + (uint)this._engineIgnoreCount + 1;
var engineIgnoreCount = 0;
// Handle pass count
switch (this._breakOn.Kind)
{
case BreakOnKind.Always:
case BreakOnKind.GreaterThanOrEqual:
UpdatedEngineState(true, engineHitCount, engineIgnoreCount);
break;
case BreakOnKind.Equal:
await this.Process.UpdateBreakpointBindingAsync(this._breakpointId, false, cancellationToken: cancellationToken).ConfigureAwait(false);
UpdatedEngineState(false, engineHitCount, engineIgnoreCount);
break;
case BreakOnKind.Mod:
var hitCount = engineHitCount - this._hitCountDelta;
engineIgnoreCount = GetEngineIgnoreCount(this._breakOn, hitCount);
await this.Process.UpdateBreakpointBindingAsync(this._breakpointId, ignoreCount: engineIgnoreCount, cancellationToken: cancellationToken).ConfigureAwait(false);
UpdatedEngineState(true, engineHitCount, engineIgnoreCount);
break;
}
}
internal bool GetEngineEnabled()
{
return GetEngineEnabled(this._enabled, this._breakOn, this.HitCount);
}
internal static bool GetEngineEnabled(bool enabled, BreakOn breakOn, uint hitCount)
{
if (enabled && breakOn.Kind == BreakOnKind.Equal && hitCount >= breakOn.Count)
{
// Disable BreakOnKind.Equal breakpoints if hit count "exceeds" pass count
return false;
}
return enabled;
}
internal int GetEngineIgnoreCount()
{
return GetEngineIgnoreCount(this._breakOn, this.HitCount);
}
internal static int GetEngineIgnoreCount(BreakOn breakOn, uint hitCount)
{
var count = 0;
switch (breakOn.Kind)
{
case BreakOnKind.Always:
count = 0;
break;
case BreakOnKind.Equal:
case BreakOnKind.GreaterThanOrEqual:
count = (int)breakOn.Count - (int)hitCount - 1;
if (count < 0)
{
count = 0;
}
break;
case BreakOnKind.Mod:
count = (int)(breakOn.Count - hitCount % breakOn.Count - 1);
break;
}
return count;
}
private async Task<bool> TestHitAsync()
{
// Not hit if any ignore count
if (GetEngineIgnoreCount() > 0)
{
return false;
}
// Not hit if false condition
if (!string.IsNullOrEmpty(this._condition))
{
return await this.Process.TestPredicateAsync(this._condition).ConfigureAwait(false);
}
// Otherwise, hit
return true;
}
/// <summary>
/// Process based on whether hit (based on hit count and/or condition predicates)
/// </summary>
/// <returns>Whether break should be handled.</returns>
internal async Task<bool> TestAndProcessHitAsync()
{
if (await TestHitAsync().ConfigureAwait(false))
{
// Fixup hit count
this._hitCountDelta = this._engineHitCount > 0 ? this._engineHitCount - 1 : 0;
return true;
}
// Process as not hit
return false;
}
/// <summary>
/// Called after we auto resume a breakpoint because it wasn't really hit.
/// </summary>
internal void FixupHitCount()
{
this._hitCountDelta++;
}
private void SyncCounts()
{
if (this._engineIgnoreCount <= 0)
{
return;
}
var hitCount = this.Process.GetBreakpointHitCountAsync(this._breakpointId).Result;
if (hitCount == null)
{
return;
}
this._engineIgnoreCount -= hitCount.Value - (int)this._engineHitCount;
this._engineHitCount = (uint)hitCount;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.ReferenceHighlighting
{
internal abstract class AbstractDocumentHighlightsService : IDocumentHighlightsService
{
public async Task<IEnumerable<DocumentHighlights>> GetDocumentHighlightsAsync(Document document, int position, IEnumerable<Document> documentsToSearch, CancellationToken cancellationToken)
{
// use speculative semantic model to see whether we are on a symbol we can do HR
var span = new TextSpan(position, 0);
var solution = document.Project.Solution;
var semanticModel = await document.GetSemanticModelForSpanAsync(span, cancellationToken).ConfigureAwait(false);
var symbol = SymbolFinder.FindSymbolAtPosition(semanticModel, position, solution.Workspace, cancellationToken: cancellationToken);
if (symbol == null)
{
return SpecializedCollections.EmptyEnumerable<DocumentHighlights>();
}
symbol = await GetSymbolToSearchAsync(document, position, semanticModel, symbol, cancellationToken).ConfigureAwait(false);
if (symbol == null)
{
return SpecializedCollections.EmptyEnumerable<DocumentHighlights>();
}
// Get unique tags for referenced symbols
return await GetTagsForReferencedSymbolAsync(symbol, ImmutableHashSet.CreateRange(documentsToSearch), solution, cancellationToken).ConfigureAwait(false);
}
private async Task<ISymbol> GetSymbolToSearchAsync(Document document, int position, SemanticModel semanticModel, ISymbol symbol, CancellationToken cancellationToken)
{
// see whether we can use the symbol as it is
var currentSemanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
if (currentSemanticModel == semanticModel)
{
return symbol;
}
// get symbols from current document again
return SymbolFinder.FindSymbolAtPosition(currentSemanticModel, position, document.Project.Solution.Workspace, cancellationToken: cancellationToken);
}
private async Task<IEnumerable<DocumentHighlights>> GetTagsForReferencedSymbolAsync(
ISymbol symbol,
IImmutableSet<Document> documentsToSearch,
Solution solution,
CancellationToken cancellationToken)
{
Contract.ThrowIfNull(symbol);
if (ShouldConsiderSymbol(symbol))
{
var references = await SymbolFinder.FindReferencesAsync(
symbol, solution, progress: null, documents: documentsToSearch, cancellationToken: cancellationToken).ConfigureAwait(false);
return await FilterAndCreateSpansAsync(references, solution, documentsToSearch, symbol, cancellationToken).ConfigureAwait(false);
}
return SpecializedCollections.EmptyEnumerable<DocumentHighlights>();
}
private bool ShouldConsiderSymbol(ISymbol symbol)
{
switch (symbol.Kind)
{
case SymbolKind.Method:
switch (((IMethodSymbol)symbol).MethodKind)
{
case MethodKind.AnonymousFunction:
case MethodKind.PropertyGet:
case MethodKind.PropertySet:
case MethodKind.EventAdd:
case MethodKind.EventRaise:
case MethodKind.EventRemove:
return false;
default:
return true;
}
default:
return true;
}
}
private async Task<IEnumerable<DocumentHighlights>> FilterAndCreateSpansAsync(
IEnumerable<ReferencedSymbol> references, Solution solution, IImmutableSet<Document> documentsToSearch, ISymbol symbol, CancellationToken cancellationToken)
{
references = references.FilterUnreferencedSyntheticDefinitions();
references = references.FilterNonMatchingMethodNames(solution, symbol);
references = references.FilterToAliasMatches(symbol as IAliasSymbol);
if (symbol.IsConstructor())
{
references = references.Where(r => r.Definition.OriginalDefinition.Equals(symbol.OriginalDefinition));
}
var additionalReferences = new List<Location>();
foreach (var document in documentsToSearch)
{
additionalReferences.AddRange(await GetAdditionalReferencesAsync(document, symbol, cancellationToken).ConfigureAwait(false));
}
return await CreateSpansAsync(solution, symbol, references, additionalReferences, documentsToSearch, cancellationToken).ConfigureAwait(false);
}
private Task<IEnumerable<Location>> GetAdditionalReferencesAsync(
Document document, ISymbol symbol, CancellationToken cancellationToken)
{
var additionalReferenceProvider = document.Project.LanguageServices.GetService<IReferenceHighlightingAdditionalReferenceProvider>();
if (additionalReferenceProvider != null)
{
return additionalReferenceProvider.GetAdditionalReferencesAsync(document, symbol, cancellationToken);
}
return Task.FromResult(SpecializedCollections.EmptyEnumerable<Location>());
}
private async Task<IEnumerable<DocumentHighlights>> CreateSpansAsync(
Solution solution,
ISymbol symbol,
IEnumerable<ReferencedSymbol> references,
IEnumerable<Location> additionalReferences,
IImmutableSet<Document> documentToSearch,
CancellationToken cancellationToken)
{
var spanSet = new HashSet<ValueTuple<Document, TextSpan>>();
var tagMap = new MultiDictionary<Document, HighlightSpan>();
bool addAllDefinitions = true;
// Add definitions
// Filter out definitions that cannot be highlighted. e.g: alias symbols defined via project property pages.
if (symbol.Kind == SymbolKind.Alias &&
symbol.Locations.Length > 0)
{
addAllDefinitions = false;
if (symbol.Locations.First().IsInSource)
{
// For alias symbol we want to get the tag only for the alias definition, not the target symbol's definition.
await AddLocationSpan(symbol.Locations.First(), solution, spanSet, tagMap, HighlightSpanKind.Definition, cancellationToken).ConfigureAwait(false);
}
}
// Add references and definitions
foreach (var reference in references)
{
if (addAllDefinitions && ShouldIncludeDefinition(reference.Definition))
{
foreach (var location in reference.Definition.Locations)
{
if (location.IsInSource)
{
var document = solution.GetDocument(location.SourceTree);
// GetDocument will return null for locations in #load'ed trees.
// TODO: Remove this check and add logic to fetch the #load'ed tree's
// Document once https://github.com/dotnet/roslyn/issues/5260 is fixed.
if (document == null)
{
Debug.Assert(solution.Workspace.Kind == "Interactive");
continue;
}
if (documentToSearch.Contains(document))
{
await AddLocationSpan(location, solution, spanSet, tagMap, HighlightSpanKind.Definition, cancellationToken).ConfigureAwait(false);
}
}
}
}
foreach (var referenceLocation in reference.Locations)
{
var referenceKind = referenceLocation.IsWrittenTo ? HighlightSpanKind.WrittenReference : HighlightSpanKind.Reference;
await AddLocationSpan(referenceLocation.Location, solution, spanSet, tagMap, referenceKind, cancellationToken).ConfigureAwait(false);
}
}
// Add additional references
foreach (var location in additionalReferences)
{
await AddLocationSpan(location, solution, spanSet, tagMap, HighlightSpanKind.Reference, cancellationToken).ConfigureAwait(false);
}
var list = new List<DocumentHighlights>(tagMap.Count);
foreach (var kvp in tagMap)
{
var spans = new List<HighlightSpan>(kvp.Value.Count);
foreach (var span in kvp.Value)
{
spans.Add(span);
}
list.Add(new DocumentHighlights(kvp.Key, spans));
}
return list;
}
private static bool ShouldIncludeDefinition(ISymbol symbol)
{
switch (symbol.Kind)
{
case SymbolKind.Namespace:
return false;
case SymbolKind.NamedType:
return !((INamedTypeSymbol)symbol).IsScriptClass;
case SymbolKind.Parameter:
// If it's an indexer parameter, we will have also cascaded to the accessor
// one that actually receives the references
var containingProperty = symbol.ContainingSymbol as IPropertySymbol;
if (containingProperty != null && containingProperty.IsIndexer)
{
return false;
}
break;
}
return true;
}
private async Task AddLocationSpan(Location location, Solution solution, HashSet<ValueTuple<Document, TextSpan>> spanSet, MultiDictionary<Document, HighlightSpan> tagList, HighlightSpanKind kind, CancellationToken cancellationToken)
{
var span = await GetLocationSpanAsync(solution, location, cancellationToken).ConfigureAwait(false);
if (span != null && !spanSet.Contains(span.Value))
{
spanSet.Add(span.Value);
tagList.Add(span.Value.Item1, new HighlightSpan(span.Value.Item2, kind));
}
}
private async Task<ValueTuple<Document, TextSpan>?> GetLocationSpanAsync(Solution solution, Location location, CancellationToken cancellationToken)
{
try
{
if (location != null && location.IsInSource)
{
var tree = location.SourceTree;
var document = solution.GetDocument(tree);
var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>();
if (syntaxFacts != null)
{
// Specify findInsideTrivia: true to ensure that we search within XML doc comments.
var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false);
var token = root.FindToken(location.SourceSpan.Start, findInsideTrivia: true);
return syntaxFacts.IsGenericName(token.Parent) || syntaxFacts.IsIndexerMemberCRef(token.Parent)
? ValueTuple.Create(document, token.Span)
: ValueTuple.Create(document, location.SourceSpan);
}
}
}
catch (NullReferenceException e) when (FatalError.ReportWithoutCrash(e))
{
// We currently are seeing a strange null references crash in this code. We have
// a strong belief that this is recoverable, but we'd like to know why it is
// happening. This exception filter allows us to report the issue and continue
// without damaging the user experience. Once we get more crash reports, we
// can figure out the root cause and address appropriately. This is preferable
// to just using conditionl access operators to be resilient (as we won't actually
// know why this is happening).
}
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.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Threading;
namespace System.Drawing
{
public class ColorConverter : TypeConverter
{
private static readonly Lazy<StandardValuesCollection> s_valuesLazy = new Lazy<StandardValuesCollection>(() => {
// We must take the value from each hashtable and combine them.
//
HashSet<Color> set = new HashSet<Color>(ColorTable.Colors.Values.Concat(ColorTable.SystemColors.Values));
return new StandardValuesCollection(set.OrderBy(c => c, new ColorComparer()).ToList());
});
public ColorConverter()
{
}
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(InstanceDescriptor))
{
return true;
}
return base.CanConvertTo(context, destinationType);
}
[SuppressMessage("Microsoft.Performance", "CA1808:AvoidCallsThatBoxValueTypes")]
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
string strValue = value as string;
if (strValue != null)
{
string text = strValue.Trim();
if (text.Length == 0)
{
return Color.Empty;
}
{
Color c;
// First, check to see if this is a standard name.
//
if (ColorTable.TryGetNamedColor(text, out c))
{
return c;
}
}
if (culture == null)
{
culture = CultureInfo.CurrentCulture;
}
char sep = culture.TextInfo.ListSeparator[0];
TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int));
// If the value is a 6 digit hex number only, then
// we want to treat the Alpha as 255, not 0
//
if (text.IndexOf(sep) == -1)
{
// text can be '' (empty quoted string)
if (text.Length >= 2 && (text[0] == '\'' || text[0] == '"') && text[0] == text[text.Length - 1])
{
// In quotes means a named value
string colorName = text.Substring(1, text.Length - 2);
return Color.FromName(colorName);
}
else if ((text.Length == 7 && text[0] == '#') ||
(text.Length == 8 && (text.StartsWith("0x") || text.StartsWith("0X"))) ||
(text.Length == 8 && (text.StartsWith("&h") || text.StartsWith("&H"))))
{
// Note: ConvertFromString will raise exception if value cannot be converted.
return PossibleKnownColor(Color.FromArgb(unchecked((int)(0xFF000000 | (uint)(int)intConverter.ConvertFromString(context, culture, text)))));
}
}
// Nope. Parse the RGBA from the text.
//
string[] tokens = text.Split(sep);
int[] values = new int[tokens.Length];
for (int i = 0; i < values.Length; i++)
{
values[i] = unchecked((int)intConverter.ConvertFromString(context, culture, tokens[i]));
}
// We should now have a number of parsed integer values.
// We support 1, 3, or 4 arguments:
//
// 1 -- full ARGB encoded
// 3 -- RGB
// 4 -- ARGB
//
switch (values.Length)
{
case 1:
return PossibleKnownColor(Color.FromArgb(values[0]));
case 3:
return PossibleKnownColor(Color.FromArgb(values[0], values[1], values[2]));
case 4:
return PossibleKnownColor(Color.FromArgb(values[0], values[1], values[2], values[3]));
}
throw new ArgumentException(SR.Format(SR.InvalidColor, text));
}
return base.ConvertFrom(context, culture, value);
}
private Color PossibleKnownColor(Color color)
{
// Now check to see if this color matches one of our known colors.
// If it does, then substitute it. We can only do this for "Colors"
// because system colors morph with user settings.
//
int targetARGB = color.ToArgb();
foreach (Color c in ColorTable.Colors.Values)
{
if (c.ToArgb() == targetARGB)
{
return c;
}
}
return color;
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == null)
{
throw new ArgumentNullException(nameof(destinationType));
}
if (value is Color)
{
if (destinationType == typeof(string))
{
Color c = (Color)value;
if (c == Color.Empty)
{
return string.Empty;
}
else
{
// If this is a known color, then Color can provide its own
// name. Otherwise, we fabricate an ARGB value for it.
//
if (c.IsKnownColor)
{
return c.Name;
}
else if (c.IsNamedColor)
{
return "'" + c.Name + "'";
}
else
{
if (culture == null)
{
culture = CultureInfo.CurrentCulture;
}
string sep = culture.TextInfo.ListSeparator + " ";
TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int));
string[] args;
int nArg = 0;
if (c.A < 255)
{
args = new string[4];
args[nArg++] = intConverter.ConvertToString(context, culture, (object)c.A);
}
else
{
args = new string[3];
}
// Note: ConvertToString will raise exception if value cannot be converted.
args[nArg++] = intConverter.ConvertToString(context, culture, (object)c.R);
args[nArg++] = intConverter.ConvertToString(context, culture, (object)c.G);
args[nArg++] = intConverter.ConvertToString(context, culture, (object)c.B);
// Now slam all of these together with the fantastic Join
// method.
//
return string.Join(sep, args);
}
}
}
if (destinationType == typeof(InstanceDescriptor))
{
MemberInfo member = null;
object[] args = null;
Color c = (Color)value;
if (c.IsEmpty)
{
member = typeof(Color).GetField("Empty");
}
else if (c.IsSystemColor)
{
member = typeof(SystemColors).GetProperty(c.Name);
}
else if (c.IsKnownColor)
{
member = typeof(Color).GetProperty(c.Name);
}
else if (c.A != 255)
{
member = typeof(Color).GetMethod("FromArgb", new Type[] { typeof(int), typeof(int), typeof(int), typeof(int) });
args = new object[] { c.A, c.R, c.G, c.B };
}
else if (c.IsNamedColor)
{
member = typeof(Color).GetMethod("FromName", new Type[] { typeof(string) });
args = new object[] { c.Name };
}
else
{
member = typeof(Color).GetMethod("FromArgb", new Type[] { typeof(int), typeof(int), typeof(int) });
args = new object[] { c.R, c.G, c.B };
}
Debug.Assert(member != null, "Could not convert color to member. Did someone change method name / signature and not update Colorconverter?");
if (member != null)
{
return new InstanceDescriptor(member, args);
}
else
{
return null;
}
}
}
return base.ConvertTo(context, culture, value, destinationType);
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
return s_valuesLazy.Value;
}
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
private class ColorComparer : IComparer<Color>
{
public int Compare(Color left, Color right)
{
return string.CompareOrdinal(left.Name, right.Name);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Net;
using LumiSoft.Net.SIP.Stack;
namespace LumiSoft.Net.SIP.Message
{
/// <summary>
/// Implements SIP "via-parm" value. Defined in RFC 3261.
/// </summary>
/// <remarks>
/// <code>
/// RFC 3261 Syntax:
/// via-parm = sent-protocol LWS sent-by *( SEMI via-params )
/// via-params = via-ttl / via-maddr / via-received / via-branch / via-extension
/// via-ttl = "ttl" EQUAL ttl
/// via-maddr = "maddr" EQUAL host
/// via-received = "received" EQUAL (IPv4address / IPv6address)
/// via-branch = "branch" EQUAL token
/// via-extension = generic-param
/// sent-protocol = protocol-name SLASH protocol-version SLASH transport
/// protocol-name = "SIP" / token
/// protocol-version = token
/// transport = "UDP" / "TCP" / "TLS" / "SCTP" / other-transport
/// sent-by = host [ COLON port ]
/// ttl = 1*3DIGIT ; 0 to 255
///
/// Via extentions:
/// // RFC 3486
/// via-compression = "comp" EQUAL ("sigcomp" / other-compression)
/// // RFC 3581
/// response-port = "rport" [EQUAL 1*DIGIT]
/// </code>
/// </remarks>
public class SIP_t_ViaParm : SIP_t_ValueWithParams
{
private string m_ProtocolName = "";
private string m_ProtocolVersion = "";
private string m_ProtocolTransport = "";
private HostEndPoint m_pSentBy = null;
/// <summary>
/// Defualt constructor.
/// </summary>
public SIP_t_ViaParm()
{
m_ProtocolName = "SIP";
m_ProtocolVersion = "2.0";
m_ProtocolTransport = "UDP";
m_pSentBy = new HostEndPoint("localhost",-1);
}
#region static method CreateBranch
/// <summary>
/// Creates new branch paramter value.
/// </summary>
/// <returns></returns>
public static string CreateBranch()
{
// The value of the branch parameter MUST start with the magic cookie "z9hG4bK".
return "z9hG4bK-" + Guid.NewGuid().ToString().Replace("-","");
}
#endregion
#region method Parse
/// <summary>
/// Parses "via-parm" from specified value.
/// </summary>
/// <param name="value">SIP "via-parm" value.</param>
/// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception>
/// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception>
public void Parse(string value)
{
if(value == null){
throw new ArgumentNullException("reader");
}
Parse(new StringReader(value));
}
/// <summary>
/// Parses "via-parm" from specified reader.
/// </summary>
/// <param name="reader">Reader from where to parse.</param>
/// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception>
/// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception>
public override void Parse(StringReader reader)
{
/*
via-parm = sent-protocol LWS sent-by *( SEMI via-params )
via-params = via-ttl / via-maddr / via-received / via-branch / via-extension
via-ttl = "ttl" EQUAL ttl
via-maddr = "maddr" EQUAL host
via-received = "received" EQUAL (IPv4address / IPv6address)
via-branch = "branch" EQUAL token
via-extension = generic-param
sent-protocol = protocol-name SLASH protocol-version
SLASH transport
protocol-name = "SIP" / token
protocol-version = token
transport = "UDP" / "TCP" / "TLS" / "SCTP" / other-transport
sent-by = host [ COLON port ]
ttl = 1*3DIGIT ; 0 to 255
Via extentions:
// RFC 3486
via-compression = "comp" EQUAL ("sigcomp" / other-compression)
// RFC 3581
response-port = "rport" [EQUAL 1*DIGIT]
Examples:
Via: SIP/2.0/UDP 127.0.0.1:58716;branch=z9hG4bK-d87543-4d7e71216b27df6e-1--d87543-
// Specifically, LWS on either side of the ":" or "/" is allowed.
Via: SIP / 2.0 / UDP 127.0.0.1:58716;branch=z9hG4bK-d87543-4d7e71216b27df6e-1--d87543-
*/
if(reader == null){
throw new ArgumentNullException("reader");
}
// protocol-name
string word = reader.QuotedReadToDelimiter('/');
if(word == null){
throw new SIP_ParseException("Via header field protocol-name is missing !");
}
this.ProtocolName = word.Trim();
// protocol-version
word = reader.QuotedReadToDelimiter('/');
if(word == null){
throw new SIP_ParseException("Via header field protocol-version is missing !");
}
this.ProtocolVersion = word.Trim();
// transport
word = reader.ReadWord();
if(word == null){
throw new SIP_ParseException("Via header field transport is missing !");
}
this.ProtocolTransport = word.Trim();
// sent-by
word = reader.QuotedReadToDelimiter(new char[]{';',','},false);
if(word == null){
throw new SIP_ParseException("Via header field sent-by is missing !");
}
this.SentBy = HostEndPoint.Parse(word.Trim());
// Parse parameters
this.ParseParameters(reader);
}
#endregion
#region method ToStringValue
/// <summary>
/// Converts this to valid "via-parm" value.
/// </summary>
/// <returns>Returns "via-parm" value.</returns>
public override string ToStringValue()
{
/*
Via = ( "Via" / "v" ) HCOLON via-parm *(COMMA via-parm)
via-parm = sent-protocol LWS sent-by *( SEMI via-params )
via-params = via-ttl / via-maddr / via-received / via-branch / via-extension
via-ttl = "ttl" EQUAL ttl
via-maddr = "maddr" EQUAL host
via-received = "received" EQUAL (IPv4address / IPv6address)
via-branch = "branch" EQUAL token
via-extension = generic-param
sent-protocol = protocol-name SLASH protocol-version
SLASH transport
protocol-name = "SIP" / token
protocol-version = token
transport = "UDP" / "TCP" / "TLS" / "SCTP" / other-transport
sent-by = host [ COLON port ]
ttl = 1*3DIGIT ; 0 to 255
Via extentions:
// RFC 3486
via-compression = "comp" EQUAL ("sigcomp" / other-compression)
// RFC 3581
response-port = "rport" [EQUAL 1*DIGIT]
Examples:
Via: SIP/2.0/UDP 127.0.0.1:58716;branch=z9hG4bK-d87543-4d7e71216b27df6e-1--d87543-
// Specifically, LWS on either side of the ":" or "/" is allowed.
Via: SIP / 2.0 / UDP 127.0.0.1:58716;branch=z9hG4bK-d87543-4d7e71216b27df6e-1--d87543-
*/
StringBuilder retVal = new StringBuilder();
retVal.Append(this.ProtocolName + "/" + this.ProtocolVersion + "/" + this.ProtocolTransport + " ");
retVal.Append(this.SentBy.ToString());
retVal.Append(this.ParametersToString());
return retVal.ToString();
}
#endregion
#region Properties Implementation
/// <summary>
/// Gets sent protocol name. Normally this is always SIP.
/// </summary>
public string ProtocolName
{
get{ return m_ProtocolName; }
set{
if(string.IsNullOrEmpty(value)){
throw new ArgumentException("Property ProtocolName can't be null or empty !");
}
m_ProtocolName = value;
}
}
/// <summary>
/// Gets sent protocol version.
/// </summary>
public string ProtocolVersion
{
get{ return m_ProtocolVersion; }
set{
if(string.IsNullOrEmpty(value)){
throw new ArgumentException("Property ProtocolVersion can't be null or empty !");
}
m_ProtocolVersion = value;
}
}
/// <summary>
/// Gets sent protocol transport. Currently known values are: UDP,TCP,TLS,SCTP. This value is always in upper-case.
/// </summary>
public string ProtocolTransport
{
get{ return m_ProtocolTransport.ToUpper(); }
set{
if(string.IsNullOrEmpty(value)){
throw new ArgumentException("Property ProtocolTransport can't be null or empty !");
}
m_ProtocolTransport = value;
}
}
/// <summary>
/// Gets host name or IP with optional port. Examples: lumiosft.ee,10.0.0.1:80.
/// </summary>
/// <exception cref="ArgumentNullException">Is raised when null reference passed.</exception>
public HostEndPoint SentBy
{
get{ return m_pSentBy; }
set{
if(value == null){
throw new ArgumentNullException("value");
}
m_pSentBy = value;
}
}
/// <summary>
/// Gets sent-by port, if no port explicity set, transport default is returned.
/// </summary>
public int SentByPortWithDefault
{
get{
if(m_pSentBy.Port != -1){
return m_pSentBy.Port;
}
else{
if(this.ProtocolTransport == SIP_Transport.TLS){
return 5061;
}
else{
return 5060;
}
}
}
}
/// <summary>
/// Gets or sets 'branch' parameter value. The branch parameter in the Via header field values
/// serves as a transaction identifier. The value of the branch parameter MUST start
/// with the magic cookie "z9hG4bK". Value null means that branch paramter doesn't exist.
/// </summary>
public string Branch
{
get{
SIP_Parameter parameter = this.Parameters["branch"];
if(parameter != null){
return parameter.Value;
}
else{
return null;
}
}
set{
if(string.IsNullOrEmpty(value)){
this.Parameters.Remove("branch");
}
else{
if(!value.StartsWith("z9hG4bK")){
throw new ArgumentException("Property Branch value must start with magic cookie 'z9hG4bK' !");
}
this.Parameters.Set("branch",value);
}
}
}
/// <summary>
/// Gets or sets 'comp' parameter value. Value null means not specified. Defined in RFC 3486.
/// </summary>
public string Comp
{
get{
SIP_Parameter parameter = this.Parameters["comp"];
if(parameter != null){
return parameter.Value;
}
else{
return null;
}
}
set{
if(string.IsNullOrEmpty(value)){
this.Parameters.Remove("comp");
}
else{
this.Parameters.Set("comp",value);
}
}
}
/// <summary>
/// Gets or sets 'maddr' parameter value. Value null means not specified.
/// </summary>
public string Maddr
{
get{
SIP_Parameter parameter = this.Parameters["maddr"];
if(parameter != null){
return parameter.Value;
}
else{
return null;
}
}
set{
if(string.IsNullOrEmpty(value)){
this.Parameters.Remove("maddr");
}
else{
this.Parameters.Set("maddr",value);
}
}
}
/// <summary>
/// Gets or sets 'received' parameter value. Value null means not specified.
/// </summary>
public IPAddress Received
{
get{
SIP_Parameter parameter = this.Parameters["received"];
if(parameter != null){
return IPAddress.Parse(parameter.Value);
}
else{
return null;
}
}
set{
if(value == null){
this.Parameters.Remove("received");
}
else{
this.Parameters.Set("received",value.ToString());
}
}
}
/// <summary>
/// Gets or sets 'rport' parameter value. Value -1 means not specified and value 0 means empty "" rport.
/// </summary>
public int RPort
{
get{
SIP_Parameter parameter = this.Parameters["rport"];
if(parameter != null){
if(parameter.Value == ""){
return 0;
}
else{
return Convert.ToInt32(parameter.Value);
}
}
else{
return -1;
}
}
set{
if(value < 0){
this.Parameters.Remove("rport");
}
else if(value == 0){
this.Parameters.Set("rport","");
}
else{
this.Parameters.Set("rport",value.ToString());
}
}
}
/// <summary>
/// Gets or sets 'ttl' parameter value. Value -1 means not specified.
/// </summary>
public int Ttl
{
get{
SIP_Parameter parameter = this.Parameters["ttl"];
if(parameter != null){
return Convert.ToInt32(parameter.Value);
}
else{
return -1;
}
}
set{
if(value < 0){
this.Parameters.Remove("ttl");
}
else{
this.Parameters.Set("ttl",value.ToString());
}
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Reflection.Internal;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Reflection.Metadata
{
[DebuggerDisplay("{GetDebuggerDisplay(),nq}")]
public unsafe struct BlobReader
{
/// <summary>An array containing the '\0' character.</summary>
private static readonly char[] s_nullCharArray = new char[1] { '\0' };
internal const int InvalidCompressedInteger = Int32.MaxValue;
private readonly MemoryBlock _block;
// Points right behind the last byte of the block.
private readonly byte* _endPointer;
private byte* _currentPointer;
public unsafe BlobReader(byte* buffer, int length)
: this(MemoryBlock.CreateChecked(buffer, length))
{
}
internal BlobReader(MemoryBlock block)
{
Debug.Assert(BitConverter.IsLittleEndian && block.Length >= 0 && (block.Pointer != null || block.Length == 0));
_block = block;
_currentPointer = block.Pointer;
_endPointer = block.Pointer + block.Length;
}
internal string GetDebuggerDisplay()
{
if (_block.Pointer == null)
{
return "<null>";
}
int displayedBytes;
string display = _block.GetDebuggerDisplay(out displayedBytes);
if (this.Offset < displayedBytes)
{
display = display.Insert(this.Offset * 3, "*");
}
else if (displayedBytes == _block.Length)
{
display += "*";
}
else
{
display += "*...";
}
return display;
}
#region Offset, Skipping, Marking, Alignment, Bounds Checking
/// <summary>
/// Pointer to the byte at the start of the underlying memory block.
/// </summary>
public byte* StartPointer => _block.Pointer;
/// <summary>
/// Pointer to the byte at the current position of the reader.
/// </summary>
public byte* CurrentPointer => _currentPointer;
/// <summary>
/// The total length of the underlying memory block.
/// </summary>
public int Length => _block.Length;
/// <summary>
/// Offset from start of underlying memory block to current position.
/// </summary>
public int Offset => (int)(_currentPointer - _block.Pointer);
/// <summary>
/// Bytes remaining from current position to end of underlying memory block.
/// </summary>
public int RemainingBytes => (int)(_endPointer - _currentPointer);
/// <summary>
/// Repositions the reader to the start of the underluing memory block.
/// </summary>
public void Reset()
{
_currentPointer = _block.Pointer;
}
/// <summary>
/// Repositions the reader to the given offset from the start of the underlying memory block.
/// </summary>
/// <exception cref="BadImageFormatException">Offset is outside the bounds of underlying reader.</exception>
public void SeekOffset(int offset)
{
if (!TrySeekOffset(offset))
{
Throw.OutOfBounds();
}
}
internal bool TrySeekOffset(int offset)
{
if (unchecked((uint)offset) >= (uint)_block.Length)
{
return false;
}
_currentPointer = _block.Pointer + offset;
return true;
}
/// <summary>
/// Repositions the reader forward by the given number of bytes.
/// </summary>
public void SkipBytes(int count)
{
GetCurrentPointerAndAdvance(count);
}
/// <summary>
/// Repositions the reader forward by the number of bytes required to satisfy the given alignment.
/// </summary>
public void Align(byte alignment)
{
if (!TryAlign(alignment))
{
Throw.OutOfBounds();
}
}
internal bool TryAlign(byte alignment)
{
int remainder = this.Offset & (alignment - 1);
Debug.Assert((alignment & (alignment - 1)) == 0, "Alignment must be a power of two.");
Debug.Assert(remainder >= 0 && remainder < alignment);
if (remainder != 0)
{
int bytesToSkip = alignment - remainder;
if (bytesToSkip > RemainingBytes)
{
return false;
}
_currentPointer += bytesToSkip;
}
return true;
}
internal MemoryBlock GetMemoryBlockAt(int offset, int length)
{
CheckBounds(offset, length);
return new MemoryBlock(_currentPointer + offset, length);
}
#endregion
#region Bounds Checking
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void CheckBounds(int offset, int byteCount)
{
if (unchecked((ulong)(uint)offset + (uint)byteCount) > (ulong)(_endPointer - _currentPointer))
{
Throw.OutOfBounds();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void CheckBounds(int byteCount)
{
if (unchecked((uint)byteCount) > (_endPointer - _currentPointer))
{
Throw.OutOfBounds();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private byte* GetCurrentPointerAndAdvance(int length)
{
byte* p = _currentPointer;
if (unchecked((uint)length) > (uint)(_endPointer - p))
{
Throw.OutOfBounds();
}
_currentPointer = p + length;
return p;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private byte* GetCurrentPointerAndAdvance1()
{
byte* p = _currentPointer;
if (p == _endPointer)
{
Throw.OutOfBounds();
}
_currentPointer = p + 1;
return p;
}
#endregion
#region Read Methods
public bool ReadBoolean()
{
// It's not clear from the ECMA spec what exactly is the encoding of Boolean.
// Some metadata writers encode "true" as 0xff, others as 1. So we treat all non-zero values as "true".
//
// We propose to clarify and relax the current wording in the spec as follows:
//
// Chapter II.16.2 "Field init metadata"
// ... bool '(' true | false ')' Boolean value stored in a single byte, 0 represents false, any non-zero value represents true ...
//
// Chapter 23.3 "Custom attributes"
// ... A bool is a single byte with value 0 representing false and any non-zero value representing true ...
return ReadByte() != 0;
}
public sbyte ReadSByte()
{
return *(sbyte*)GetCurrentPointerAndAdvance1();
}
public byte ReadByte()
{
return *(byte*)GetCurrentPointerAndAdvance1();
}
public char ReadChar()
{
return *(char*)GetCurrentPointerAndAdvance(sizeof(char));
}
public short ReadInt16()
{
return *(short*)GetCurrentPointerAndAdvance(sizeof(short));
}
public ushort ReadUInt16()
{
return *(ushort*)GetCurrentPointerAndAdvance(sizeof(ushort));
}
public int ReadInt32()
{
return *(int*)GetCurrentPointerAndAdvance(sizeof(int));
}
public uint ReadUInt32()
{
return *(uint*)GetCurrentPointerAndAdvance(sizeof(uint));
}
public long ReadInt64()
{
return *(long*)GetCurrentPointerAndAdvance(sizeof(long));
}
public ulong ReadUInt64()
{
return *(ulong*)GetCurrentPointerAndAdvance(sizeof(ulong));
}
public float ReadSingle()
{
int val = ReadInt32();
return *(float*)&val;
}
public double ReadDouble()
{
long val = ReadInt64();
return *(double*)&val;
}
public Guid ReadGuid()
{
const int size = 16;
return *(Guid*)GetCurrentPointerAndAdvance(size);
}
/// <summary>
/// Reads <see cref="decimal"/> number.
/// </summary>
/// <remarks>
/// Decimal number is encoded in 13 bytes as follows:
/// - byte 0: highest bit indicates sign (1 for negative, 0 for non-negative); the remaining 7 bits encode scale
/// - bytes 1..12: 96-bit unsigned integer in little endian encoding.
/// </remarks>
/// <exception cref="BadImageFormatException">The data at the current position was not a valid <see cref="decimal"/> number.</exception>
public decimal ReadDecimal()
{
byte* ptr = GetCurrentPointerAndAdvance(13);
byte scale = (byte)(*ptr & 0x7f);
if (scale > 28)
{
throw new BadImageFormatException(SR.ValueTooLarge);
}
return new decimal(
*(int*)(ptr + 1),
*(int*)(ptr + 5),
*(int*)(ptr + 9),
isNegative: (*ptr & 0x80) != 0,
scale: scale);
}
public DateTime ReadDateTime()
{
return new DateTime(ReadInt64());
}
public SignatureHeader ReadSignatureHeader()
{
return new SignatureHeader(ReadByte());
}
/// <summary>
/// Reads UTF8 encoded string starting at the current position.
/// </summary>
/// <param name="byteCount">The number of bytes to read.</param>
/// <returns>The string.</returns>
/// <exception cref="BadImageFormatException"><paramref name="byteCount"/> bytes not available.</exception>
public string ReadUTF8(int byteCount)
{
string s = _block.PeekUtf8(this.Offset, byteCount);
_currentPointer += byteCount;
return s;
}
/// <summary>
/// Reads UTF16 (little-endian) encoded string starting at the current position.
/// </summary>
/// <param name="byteCount">The number of bytes to read.</param>
/// <returns>The string.</returns>
/// <exception cref="BadImageFormatException"><paramref name="byteCount"/> bytes not available.</exception>
public string ReadUTF16(int byteCount)
{
string s = _block.PeekUtf16(this.Offset, byteCount);
_currentPointer += byteCount;
return s;
}
/// <summary>
/// Reads bytes starting at the current position.
/// </summary>
/// <param name="byteCount">The number of bytes to read.</param>
/// <returns>The byte array.</returns>
/// <exception cref="BadImageFormatException"><paramref name="byteCount"/> bytes not available.</exception>
public byte[] ReadBytes(int byteCount)
{
byte[] bytes = _block.PeekBytes(this.Offset, byteCount);
_currentPointer += byteCount;
return bytes;
}
/// <summary>
/// Reads bytes starting at the current position in to the given buffer at the given offset;
/// </summary>
/// <param name="byteCount">The number of bytes to read.</param>
/// <param name="buffer">The destination buffer the bytes read will be written.</param>
/// <param name="bufferOffset">The offset in the destination buffer where the bytes read will be written.</param>
/// <exception cref="BadImageFormatException"><paramref name="byteCount"/> bytes not available.</exception>
public void ReadBytes(int byteCount, byte[] buffer, int bufferOffset)
{
Marshal.Copy((IntPtr)GetCurrentPointerAndAdvance(byteCount), buffer, bufferOffset, byteCount);
}
internal string ReadUtf8NullTerminated()
{
int bytesRead;
string value = _block.PeekUtf8NullTerminated(this.Offset, null, MetadataStringDecoder.DefaultUTF8, out bytesRead, '\0');
_currentPointer += bytesRead;
return value;
}
private int ReadCompressedIntegerOrInvalid()
{
int bytesRead;
int value = _block.PeekCompressedInteger(this.Offset, out bytesRead);
_currentPointer += bytesRead;
return value;
}
/// <summary>
/// Reads an unsigned compressed integer value.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
/// <param name="value">The value of the compressed integer that was read.</param>
/// <returns>true if the value was read successfully. false if the data at the current position was not a valid compressed integer.</returns>
public bool TryReadCompressedInteger(out int value)
{
value = ReadCompressedIntegerOrInvalid();
return value != InvalidCompressedInteger;
}
/// <summary>
/// Reads an unsigned compressed integer value.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
/// <returns>The value of the compressed integer that was read.</returns>
/// <exception cref="BadImageFormatException">The data at the current position was not a valid compressed integer.</exception>
public int ReadCompressedInteger()
{
int value;
if (!TryReadCompressedInteger(out value))
{
Throw.InvalidCompressedInteger();
}
return value;
}
/// <summary>
/// Reads a signed compressed integer value.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
/// <param name="value">The value of the compressed integer that was read.</param>
/// <returns>true if the value was read successfully. false if the data at the current position was not a valid compressed integer.</returns>
public bool TryReadCompressedSignedInteger(out int value)
{
int bytesRead;
value = _block.PeekCompressedInteger(this.Offset, out bytesRead);
if (value == InvalidCompressedInteger)
{
return false;
}
bool signExtend = (value & 0x1) != 0;
value >>= 1;
if (signExtend)
{
switch (bytesRead)
{
case 1:
value |= unchecked((int)0xffffffc0);
break;
case 2:
value |= unchecked((int)0xffffe000);
break;
default:
Debug.Assert(bytesRead == 4);
value |= unchecked((int)0xf0000000);
break;
}
}
_currentPointer += bytesRead;
return true;
}
/// <summary>
/// Reads a signed compressed integer value.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
/// <returns>The value of the compressed integer that was read.</returns>
/// <exception cref="BadImageFormatException">The data at the current position was not a valid compressed integer.</exception>
public int ReadCompressedSignedInteger()
{
int value;
if (!TryReadCompressedSignedInteger(out value))
{
Throw.InvalidCompressedInteger();
}
return value;
}
/// <summary>
/// Reads type code encoded in a serialized custom attribute value.
/// </summary>
/// <returns><see cref="SerializationTypeCode.Invalid"/> if the encoding is invalid.</returns>
public SerializationTypeCode ReadSerializationTypeCode()
{
int value = ReadCompressedIntegerOrInvalid();
if (value > byte.MaxValue)
{
return SerializationTypeCode.Invalid;
}
return unchecked((SerializationTypeCode)value);
}
/// <summary>
/// Reads type code encoded in a signature.
/// </summary>
/// <returns><see cref="SignatureTypeCode.Invalid"/> if the encoding is invalid.</returns>
public SignatureTypeCode ReadSignatureTypeCode()
{
int value = ReadCompressedIntegerOrInvalid();
switch (value)
{
case (int)CorElementType.ELEMENT_TYPE_CLASS:
case (int)CorElementType.ELEMENT_TYPE_VALUETYPE:
return SignatureTypeCode.TypeHandle;
default:
if (value > byte.MaxValue)
{
return SignatureTypeCode.Invalid;
}
return unchecked((SignatureTypeCode)value);
}
}
/// <summary>
/// Reads a string encoded as a compressed integer containing its length followed by
/// its contents in UTF8. Null strings are encoded as a single 0xFF byte.
/// </summary>
/// <remarks>Defined as a 'SerString' in the ECMA CLI specification.</remarks>
/// <returns>String value or null.</returns>
/// <exception cref="BadImageFormatException">If the encoding is invalid.</exception>
public string ReadSerializedString()
{
int length;
if (TryReadCompressedInteger(out length))
{
// Removal of trailing '\0' is a departure from the spec, but required
// for compatibility with legacy compilers.
return ReadUTF8(length).TrimEnd(s_nullCharArray);
}
if (ReadByte() != 0xFF)
{
Throw.InvalidSerializedString();
}
return null;
}
/// <summary>
/// Reads a type handle encoded in a signature as TypeDefOrRefOrSpecEncoded (see ECMA-335 II.23.2.8).
/// </summary>
/// <returns>The handle or nil if the encoding is invalid.</returns>
public EntityHandle ReadTypeHandle()
{
uint value = (uint)ReadCompressedIntegerOrInvalid();
uint tokenType = s_corEncodeTokenArray[value & 0x3];
if (value == InvalidCompressedInteger || tokenType == 0)
{
return default(EntityHandle);
}
return new EntityHandle(tokenType | (value >> 2));
}
private static readonly uint[] s_corEncodeTokenArray = new uint[] { TokenTypeIds.TypeDef, TokenTypeIds.TypeRef, TokenTypeIds.TypeSpec, 0 };
/// <summary>
/// Reads a #Blob heap handle encoded as a compressed integer.
/// </summary>
/// <remarks>
/// Blobs that contain references to other blobs are used in Portable PDB format, for example <see cref="Document.Name"/>.
/// </remarks>
public BlobHandle ReadBlobHandle()
{
return BlobHandle.FromOffset(ReadCompressedInteger());
}
/// <summary>
/// Reads a constant value (see ECMA-335 Partition II section 22.9) from the current position.
/// </summary>
/// <exception cref="BadImageFormatException">Error while reading from the blob.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="typeCode"/> is not a valid <see cref="ConstantTypeCode"/>.</exception>
/// <returns>
/// Boxed constant value. To avoid allocating the object use Read* methods directly.
/// Constants of type <see cref="ConstantTypeCode.String"/> are encoded as UTF16 strings, use <see cref="ReadUTF16(int)"/> to read them.
/// </returns>
public object ReadConstant(ConstantTypeCode typeCode)
{
// Partition II section 22.9:
//
// Type shall be exactly one of: ELEMENT_TYPE_BOOLEAN, ELEMENT_TYPE_CHAR, ELEMENT_TYPE_I1,
// ELEMENT_TYPE_U1, ELEMENT_TYPE_I2, ELEMENT_TYPE_U2, ELEMENT_TYPE_I4, ELEMENT_TYPE_U4,
// ELEMENT_TYPE_I8, ELEMENT_TYPE_U8, ELEMENT_TYPE_R4, ELEMENT_TYPE_R8, or ELEMENT_TYPE_STRING;
// or ELEMENT_TYPE_CLASS with a Value of zero (23.1.16)
switch (typeCode)
{
case ConstantTypeCode.Boolean:
return ReadBoolean();
case ConstantTypeCode.Char:
return ReadChar();
case ConstantTypeCode.SByte:
return ReadSByte();
case ConstantTypeCode.Int16:
return ReadInt16();
case ConstantTypeCode.Int32:
return ReadInt32();
case ConstantTypeCode.Int64:
return ReadInt64();
case ConstantTypeCode.Byte:
return ReadByte();
case ConstantTypeCode.UInt16:
return ReadUInt16();
case ConstantTypeCode.UInt32:
return ReadUInt32();
case ConstantTypeCode.UInt64:
return ReadUInt64();
case ConstantTypeCode.Single:
return ReadSingle();
case ConstantTypeCode.Double:
return ReadDouble();
case ConstantTypeCode.String:
return ReadUTF16(RemainingBytes);
case ConstantTypeCode.NullReference:
// Partition II section 22.9:
// The encoding of Type for the nullref value is ELEMENT_TYPE_CLASS with a Value of a 4-byte zero.
// Unlike uses of ELEMENT_TYPE_CLASS in signatures, this one is not followed by a type token.
if (ReadUInt32() != 0)
{
throw new BadImageFormatException(SR.InvalidConstantValue);
}
return null;
default:
throw new ArgumentOutOfRangeException(nameof(typeCode));
}
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.CoreModules.World.Wind;
namespace OpenSim.Region.CoreModules
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "WindModule")]
public class WindModule : IWindModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private uint m_frame = 0;
private int m_dataVersion = 0;
private int m_regionID = 0;
private int m_frameUpdateRate = 150;
//private Random m_rndnums = new Random(Environment.TickCount);
private Scene m_scene = null;
private bool m_ready = false;
private bool m_inUpdate = false;
private bool m_enabled = false;
private IConfig m_windConfig;
private IWindModelPlugin m_activeWindPlugin = null;
private string m_dWindPluginName = "SimpleRandomWind";
private Dictionary<string, IWindModelPlugin> m_availableWindPlugins = new Dictionary<string, IWindModelPlugin>();
// Simplified windSpeeds based on the fact that the client protocal tracks at a resolution of 16m
private Vector2[] windSpeeds = new Vector2[16 * 16];
#region INonSharedRegionModule Methods
public void Initialise(IConfigSource config)
{
m_windConfig = config.Configs["Wind"];
// string desiredWindPlugin = m_dWindPluginName;
if (m_windConfig != null)
{
m_enabled = m_windConfig.GetBoolean("enabled", true);
m_frameUpdateRate = m_windConfig.GetInt("wind_update_rate", 150);
// Determine which wind model plugin is desired
if (m_windConfig.Contains("wind_plugin"))
{
m_dWindPluginName = m_windConfig.GetString("wind_plugin", m_dWindPluginName);
}
}
if (m_enabled)
{
m_log.InfoFormat("[WIND] Enabled with an update rate of {0} frames.", m_frameUpdateRate);
}
}
public void AddRegion(Scene scene)
{
if (!m_enabled)
return;
m_scene = scene;
m_frame = 0;
// Register all the Wind Model Plug-ins
foreach (IWindModelPlugin windPlugin in AddinManager.GetExtensionObjects("/OpenSim/WindModule", false))
{
m_log.InfoFormat("[WIND] Found Plugin: {0}", windPlugin.Name);
m_availableWindPlugins.Add(windPlugin.Name, windPlugin);
}
// Check for desired plugin
if (m_availableWindPlugins.ContainsKey(m_dWindPluginName))
{
m_activeWindPlugin = m_availableWindPlugins[m_dWindPluginName];
m_log.InfoFormat("[WIND] {0} plugin found, initializing.", m_dWindPluginName);
if (m_windConfig != null)
{
m_activeWindPlugin.Initialise();
m_activeWindPlugin.WindConfig(m_scene, m_windConfig);
}
}
// if the plug-in wasn't found, default to no wind.
if (m_activeWindPlugin == null)
{
m_log.ErrorFormat("[WIND] Could not find specified wind plug-in: {0}", m_dWindPluginName);
m_log.ErrorFormat("[WIND] Defaulting to no wind.");
}
// This one puts an entry in the main help screen
// m_scene.AddCommand("Regions", this, "wind", "wind", "Usage: wind <plugin> <param> [value] - Get or Update Wind paramaters", null);
// This one enables the ability to type just the base command without any parameters
// m_scene.AddCommand("Regions", this, "wind", "", "", HandleConsoleCommand);
// Get a list of the parameters for each plugin
foreach (IWindModelPlugin windPlugin in m_availableWindPlugins.Values)
{
// m_scene.AddCommand("Regions", this, String.Format("wind base wind_plugin {0}", windPlugin.Name), String.Format("{0} - {1}", windPlugin.Name, windPlugin.Description), "", HandleConsoleBaseCommand);
m_scene.AddCommand(
"Regions",
this,
"wind base wind_update_rate",
"wind base wind_update_rate [<value>]",
"Get or set the wind update rate.",
"",
HandleConsoleBaseCommand);
foreach (KeyValuePair<string, string> kvp in windPlugin.WindParams())
{
string windCommand = String.Format("wind {0} {1}", windPlugin.Name, kvp.Key);
m_scene.AddCommand("Regions", this, windCommand, string.Format("{0} [<value>]", windCommand), kvp.Value, "", HandleConsoleParamCommand);
}
}
// Register event handlers for when Avatars enter the region, and frame ticks
m_scene.EventManager.OnFrame += WindUpdate;
// Register the wind module
m_scene.RegisterModuleInterface<IWindModule>(this);
// Generate initial wind values
GenWind();
// hopefully this will not be the same for all regions on same instance
m_dataVersion = (int)m_scene.AllocateLocalId();
// Mark Module Ready for duty
m_ready = true;
}
public void RemoveRegion(Scene scene)
{
if (!m_enabled)
return;
m_ready = false;
// REVIEW: If a region module is closed, is there a possibility that it'll re-open/initialize ??
m_activeWindPlugin = null;
foreach (IWindModelPlugin windPlugin in m_availableWindPlugins.Values)
{
windPlugin.Dispose();
}
m_availableWindPlugins.Clear();
// Remove our hooks
m_scene.EventManager.OnFrame -= WindUpdate;
// m_scene.EventManager.OnMakeRootAgent -= OnAgentEnteredRegion;
}
public void Close()
{
}
public string Name
{
get { return "WindModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void RegionLoaded(Scene scene)
{
}
#endregion
#region Console Commands
private void ValidateConsole()
{
if (m_scene.ConsoleScene() == null)
{
// FIXME: If console region is root then this will be printed by every module. Currently, there is no
// way to prevent this, short of making the entire module shared (which is complete overkill).
// One possibility is to return a bool to signal whether the module has completely handled the command
MainConsole.Instance.Output("Please change to a specific region in order to set Sun parameters.");
return;
}
if (m_scene.ConsoleScene() != m_scene)
{
MainConsole.Instance.Output("Console Scene is not my scene.");
return;
}
}
/// <summary>
/// Base console command handler, only used if a person specifies the base command with now options
/// </summary>
private void HandleConsoleCommand(string module, string[] cmdparams)
{
ValidateConsole();
MainConsole.Instance.Output(
"The wind command can be used to change the currently active wind model plugin and update the parameters for wind plugins.");
}
/// <summary>
/// Called to change the active wind model plugin
/// </summary>
private void HandleConsoleBaseCommand(string module, string[] cmdparams)
{
ValidateConsole();
if ((cmdparams.Length != 4)
|| !cmdparams[1].Equals("base"))
{
MainConsole.Instance.Output(
"Invalid parameters to change parameters for Wind module base, usage: wind base <parameter> <value>");
return;
}
switch (cmdparams[2])
{
case "wind_update_rate":
int newRate = 1;
if (int.TryParse(cmdparams[3], out newRate))
{
m_frameUpdateRate = newRate;
}
else
{
MainConsole.Instance.OutputFormat(
"Invalid value {0} specified for {1}", cmdparams[3], cmdparams[2]);
return;
}
break;
case "wind_plugin":
string desiredPlugin = cmdparams[3];
if (desiredPlugin.Equals(m_activeWindPlugin.Name))
{
MainConsole.Instance.OutputFormat("Wind model plugin {0} is already active", cmdparams[3]);
return;
}
if (m_availableWindPlugins.ContainsKey(desiredPlugin))
{
m_activeWindPlugin = m_availableWindPlugins[cmdparams[3]];
MainConsole.Instance.OutputFormat("{0} wind model plugin now active", m_activeWindPlugin.Name);
}
else
{
MainConsole.Instance.OutputFormat("Could not find wind model plugin {0}", desiredPlugin);
}
break;
}
}
/// <summary>
/// Called to change plugin parameters.
/// </summary>
private void HandleConsoleParamCommand(string module, string[] cmdparams)
{
ValidateConsole();
// wind <plugin> <param> [value]
if ((cmdparams.Length != 4)
&& (cmdparams.Length != 3))
{
MainConsole.Instance.Output("Usage: wind <plugin> <param> [value]");
return;
}
string plugin = cmdparams[1];
string param = cmdparams[2];
float value = 0f;
if (cmdparams.Length == 4)
{
if (!float.TryParse(cmdparams[3], out value))
{
MainConsole.Instance.OutputFormat("Invalid value {0}", cmdparams[3]);
}
try
{
WindParamSet(plugin, param, value);
MainConsole.Instance.OutputFormat("{0} set to {1}", param, value);
}
catch (Exception e)
{
MainConsole.Instance.OutputFormat("{0}", e.Message);
}
}
else
{
try
{
value = WindParamGet(plugin, param);
MainConsole.Instance.OutputFormat("{0} : {1}", param, value);
}
catch (Exception e)
{
MainConsole.Instance.OutputFormat("{0}", e.Message);
}
}
}
#endregion
#region IWindModule Methods
/// <summary>
/// Retrieve the wind speed at the given region coordinate. This
/// implimentation ignores Z.
/// </summary>
/// <param name="x">0...255</param>
/// <param name="y">0...255</param>
public Vector3 WindSpeed(int x, int y, int z)
{
if (m_activeWindPlugin != null)
{
return m_activeWindPlugin.WindSpeed(x, y, z);
}
else
{
return new Vector3(0.0f, 0.0f, 0.0f);
}
}
public void WindParamSet(string plugin, string param, float value)
{
if (m_availableWindPlugins.ContainsKey(plugin))
{
IWindModelPlugin windPlugin = m_availableWindPlugins[plugin];
windPlugin.WindParamSet(param, value);
}
else
{
throw new Exception(String.Format("Could not find plugin {0}", plugin));
}
}
public float WindParamGet(string plugin, string param)
{
if (m_availableWindPlugins.ContainsKey(plugin))
{
IWindModelPlugin windPlugin = m_availableWindPlugins[plugin];
return windPlugin.WindParamGet(param);
}
else
{
throw new Exception(String.Format("Could not find plugin {0}", plugin));
}
}
public string WindActiveModelPluginName
{
get
{
if (m_activeWindPlugin != null)
{
return m_activeWindPlugin.Name;
}
else
{
return String.Empty;
}
}
}
#endregion
/// <summary>
/// Called on each frame update. Updates the wind model and clients as necessary.
/// </summary>
public void WindUpdate()
{
if ((!m_ready || m_inUpdate || (m_frame++ % m_frameUpdateRate) != 0))
return;
m_inUpdate = true;
Util.FireAndForget(delegate
{
try
{
GenWind();
m_scene.ForEachClient(delegate(IClientAPI client)
{
client.SendWindData(m_dataVersion, windSpeeds);
});
}
finally
{
m_inUpdate = false;
}
},
null, "WindModuleUpdate");
}
/// <summary>
/// Calculate new wind
/// returns false if no change
/// </summary>
private bool GenWind()
{
if (m_activeWindPlugin != null && m_activeWindPlugin.WindUpdate(m_frame))
{
windSpeeds = m_activeWindPlugin.WindLLClientArray();
m_dataVersion++;
return true;
}
return false;
}
}
}
| |
using System;
using System.Collections;
using System.Workflow.ComponentModel.Compiler;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Workflow.ComponentModel.Serialization;
using System.ComponentModel.Design;
using System.Xml;
using System.Diagnostics;
using System.Collections.Generic;
namespace System.Workflow.ComponentModel.Serialization
{
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class XmlnsDefinitionAttribute : Attribute
{
public XmlnsDefinitionAttribute(string xmlNamespace, string clrNamespace)
{
if (xmlNamespace == null)
throw new ArgumentNullException("xmlNamespace");
if (clrNamespace == null)
throw new ArgumentNullException("clrNamespace");
this.xmlNamespace = xmlNamespace;
this.clrNamespace = clrNamespace;
}
public string XmlNamespace
{
get { return this.xmlNamespace; }
}
public string ClrNamespace
{
get { return this.clrNamespace; }
}
public string AssemblyName
{
get { return this.assemblyName; }
set { this.assemblyName = value; }
}
private string xmlNamespace;
private string clrNamespace;
private string assemblyName;
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class XmlnsPrefixAttribute : Attribute
{
private string xmlNamespace;
private string prefix;
public XmlnsPrefixAttribute(string xmlNamespace, string prefix)
{
if (xmlNamespace == null)
throw new ArgumentNullException("xmlNamespace");
if (prefix == null)
throw new ArgumentNullException("prefix");
this.xmlNamespace = xmlNamespace;
this.prefix = prefix;
}
public string XmlNamespace
{
get { return this.xmlNamespace; }
}
public string Prefix
{
get { return this.prefix; }
}
}
[AttributeUsage(AttributeTargets.Class)]
public sealed class RuntimeNamePropertyAttribute : Attribute
{
private string name = null;
public RuntimeNamePropertyAttribute(string name)
{
this.name = name;
}
public string Name
{
get
{
return this.name;
}
}
}
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public sealed class ContentPropertyAttribute : Attribute
{
private string name;
public ContentPropertyAttribute() { }
public ContentPropertyAttribute(string name)
{
this.name = name;
}
public string Name
{
get { return this.name; }
}
}
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public sealed class ConstructorArgumentAttribute : Attribute
{
private string argumentName;
public ConstructorArgumentAttribute(string argumentName)
{
this.argumentName = argumentName;
}
public string ArgumentName
{
get { return this.argumentName; }
}
}
public abstract class MarkupExtension
{
public abstract object ProvideValue(IServiceProvider provider);
}
[DesignerSerializer(typeof(MarkupExtensionSerializer), typeof(WorkflowMarkupSerializer))]
internal sealed class NullExtension : MarkupExtension
{
public NullExtension() { }
public override object ProvideValue(IServiceProvider serviceProvider)
{
return null;
}
}
[DesignerSerializer(typeof(TypeExtensionSerializer), typeof(WorkflowMarkupSerializer))]
internal sealed class TypeExtension : MarkupExtension
{
private string typeName;
private Type type;
public TypeExtension() { }
public TypeExtension(string type)
{
if (type == null)
throw new ArgumentNullException("typeName");
this.typeName = type;
}
public TypeExtension(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
this.type = type;
}
public override object ProvideValue(IServiceProvider provider)
{
if (this.type != null)
return this.type;
if (provider == null)
throw new ArgumentNullException("provider");
if (this.typeName == null)
throw new InvalidOperationException("typename");
WorkflowMarkupSerializationManager manager = provider as WorkflowMarkupSerializationManager;
if (manager == null)
throw new ArgumentNullException("provider");
XmlReader reader = manager.WorkflowMarkupStack[typeof(XmlReader)] as XmlReader;
if (reader == null)
{
Debug.Assert(false);
return this.typeName;
}
string typename = this.typeName.Trim();
string prefix = String.Empty;
int typeIndex = typename.IndexOf(':');
if (typeIndex >= 0)
{
prefix = typename.Substring(0, typeIndex);
typename = typename.Substring(typeIndex + 1);
type = manager.GetType(new XmlQualifiedName(typename, reader.LookupNamespace(prefix)));
if (type != null)
return type;
// To Support types whose assembly is not available, we need to still resolve the clr namespace
List<WorkflowMarkupSerializerMapping> xmlnsMappings = null;
if (manager.XmlNamespaceBasedMappings.TryGetValue(reader.LookupNamespace(prefix), out xmlnsMappings) && xmlnsMappings != null && xmlnsMappings.Count > 0)
return xmlnsMappings[0].ClrNamespace + "." + typename;
else
return typename;
}
type = manager.GetType(new XmlQualifiedName(typename, reader.LookupNamespace(string.Empty)));
// To Support Beta2 format
if (type == null)
{
ITypeProvider typeProvider = provider.GetService(typeof(ITypeProvider)) as ITypeProvider;
if (typeProvider != null)
type = typeProvider.GetType(typename);
// If not design mode, get the value from serialization manager
// At design time, we need to get the type from ITypeProvider else
// we need to store the string in the hashtable we maintain internally
if (type == null && manager.GetService(typeof(ITypeResolutionService)) == null)
type = manager.SerializationManager.GetType(typename);
}
if (type != null)
return type;
return this.typeName;
}
[DefaultValue(null)]
[ConstructorArgument("type")]
public string TypeName
{
get
{
if (this.type != null)
return this.type.FullName;
return this.typeName;
}
set
{
if (value == null)
throw new ArgumentNullException("value");
this.typeName = value;
}
}
internal Type Type
{
get { return this.type; }
}
}
[ContentProperty("Items")]
internal sealed class ArrayExtension : MarkupExtension
{
private ArrayList arrayElementList = new ArrayList();
private Type arrayType;
public ArrayExtension()
{
}
public ArrayExtension(Type arrayType)
{
if (arrayType == null)
throw new ArgumentNullException("arrayType");
this.arrayType = arrayType;
}
public ArrayExtension(Array elements)
{
if (elements == null)
throw new ArgumentNullException("elements");
arrayElementList.AddRange(elements);
this.arrayType = elements.GetType().GetElementType();
}
//
public Type Type
{
get
{
return this.arrayType;
}
set
{
this.arrayType = value;
}
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public IList Items
{
get
{
return arrayElementList;
}
}
public override object ProvideValue(IServiceProvider provider)
{
if (provider == null)
throw new ArgumentNullException("provider");
if (this.arrayType == null)
throw new InvalidOperationException("ArrayType needs to be set.");
object retArray = null;
try
{
retArray = arrayElementList.ToArray(this.arrayType);
}
catch (System.InvalidCastException)
{
//
throw new InvalidOperationException();
}
return retArray;
}
}
}
| |
using Discord.API.Voice;
using Discord.Audio.Streams;
using Discord.Logging;
using Discord.Net.Converters;
using Discord.WebSocket;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
namespace Discord.Audio
{
//TODO: Add audio reconnecting
internal partial class AudioClient : IAudioClient
{
internal struct StreamPair
{
public AudioInStream Reader;
public AudioOutStream Writer;
public StreamPair(AudioInStream reader, AudioOutStream writer)
{
Reader = reader;
Writer = writer;
}
}
private readonly Logger _audioLogger;
private readonly JsonSerializer _serializer;
private readonly ConnectionManager _connection;
private readonly SemaphoreSlim _stateLock;
private readonly ConcurrentQueue<long> _heartbeatTimes;
private readonly ConcurrentQueue<KeyValuePair<ulong, int>> _keepaliveTimes;
private readonly ConcurrentDictionary<uint, ulong> _ssrcMap;
private readonly ConcurrentDictionary<ulong, StreamPair> _streams;
private Task _heartbeatTask, _keepaliveTask;
private long _lastMessageTime;
private string _url, _sessionId, _token;
private ulong _userId;
private uint _ssrc;
private bool _isSpeaking;
public SocketGuild Guild { get; }
public DiscordVoiceAPIClient ApiClient { get; private set; }
public int Latency { get; private set; }
public int UdpLatency { get; private set; }
public ulong ChannelId { get; internal set; }
internal byte[] SecretKey { get; private set; }
private DiscordSocketClient Discord => Guild.Discord;
public ConnectionState ConnectionState => _connection.State;
/// <summary> Creates a new REST/WebSocket discord client. </summary>
internal AudioClient(SocketGuild guild, int clientId, ulong channelId)
{
Guild = guild;
ChannelId = channelId;
_audioLogger = Discord.LogManager.CreateLogger($"Audio #{clientId}");
ApiClient = new DiscordVoiceAPIClient(guild.Id, Discord.WebSocketProvider, Discord.UdpSocketProvider);
ApiClient.SentGatewayMessage += async opCode => await _audioLogger.DebugAsync($"Sent {opCode}").ConfigureAwait(false);
ApiClient.SentDiscovery += async () => await _audioLogger.DebugAsync("Sent Discovery").ConfigureAwait(false);
//ApiClient.SentData += async bytes => await _audioLogger.DebugAsync($"Sent {bytes} Bytes").ConfigureAwait(false);
ApiClient.ReceivedEvent += ProcessMessageAsync;
ApiClient.ReceivedPacket += ProcessPacketAsync;
_stateLock = new SemaphoreSlim(1, 1);
_connection = new ConnectionManager(_stateLock, _audioLogger, 30000,
OnConnectingAsync, OnDisconnectingAsync, x => ApiClient.Disconnected += x);
_connection.Connected += () => _connectedEvent.InvokeAsync();
_connection.Disconnected += (ex, recon) => _disconnectedEvent.InvokeAsync(ex);
_heartbeatTimes = new ConcurrentQueue<long>();
_keepaliveTimes = new ConcurrentQueue<KeyValuePair<ulong, int>>();
_ssrcMap = new ConcurrentDictionary<uint, ulong>();
_streams = new ConcurrentDictionary<ulong, StreamPair>();
_serializer = new JsonSerializer { ContractResolver = new DiscordContractResolver() };
_serializer.Error += (s, e) =>
{
_audioLogger.WarningAsync(e.ErrorContext.Error).GetAwaiter().GetResult();
e.ErrorContext.Handled = true;
};
LatencyUpdated += async (old, val) => await _audioLogger.DebugAsync($"Latency = {val} ms").ConfigureAwait(false);
UdpLatencyUpdated += async (old, val) => await _audioLogger.DebugAsync($"UDP Latency = {val} ms").ConfigureAwait(false);
}
internal async Task StartAsync(string url, ulong userId, string sessionId, string token)
{
_url = url;
_userId = userId;
_sessionId = sessionId;
_token = token;
await _connection.StartAsync().ConfigureAwait(false);
}
public IReadOnlyDictionary<ulong, AudioInStream> GetStreams()
{
return _streams.ToDictionary(pair => pair.Key, pair => pair.Value.Reader);
}
public async Task StopAsync()
{
await _connection.StopAsync().ConfigureAwait(false);
}
private async Task OnConnectingAsync()
{
await _audioLogger.DebugAsync("Connecting ApiClient").ConfigureAwait(false);
await ApiClient.ConnectAsync("wss://" + _url + "?v=" + DiscordConfig.VoiceAPIVersion).ConfigureAwait(false);
await _audioLogger.DebugAsync("Listening on port " + ApiClient.UdpPort).ConfigureAwait(false);
await _audioLogger.DebugAsync("Sending Identity").ConfigureAwait(false);
await ApiClient.SendIdentityAsync(_userId, _sessionId, _token).ConfigureAwait(false);
//Wait for READY
await _connection.WaitAsync().ConfigureAwait(false);
}
private async Task OnDisconnectingAsync(Exception ex)
{
await _audioLogger.DebugAsync("Disconnecting ApiClient").ConfigureAwait(false);
await ApiClient.DisconnectAsync().ConfigureAwait(false);
//Wait for tasks to complete
await _audioLogger.DebugAsync("Waiting for heartbeater").ConfigureAwait(false);
var heartbeatTask = _heartbeatTask;
if (heartbeatTask != null)
await heartbeatTask.ConfigureAwait(false);
_heartbeatTask = null;
var keepaliveTask = _keepaliveTask;
if (keepaliveTask != null)
await keepaliveTask.ConfigureAwait(false);
_keepaliveTask = null;
while (_heartbeatTimes.TryDequeue(out _)) { }
_lastMessageTime = 0;
await ClearInputStreamsAsync().ConfigureAwait(false);
await _audioLogger.DebugAsync("Sending Voice State").ConfigureAwait(false);
await Discord.ApiClient.SendVoiceStateUpdateAsync(Guild.Id, null, false, false).ConfigureAwait(false);
}
public AudioOutStream CreateOpusStream(int bufferMillis)
{
var outputStream = new OutputStream(ApiClient); //Ignores header
var sodiumEncrypter = new SodiumEncryptStream( outputStream, this); //Passes header
var rtpWriter = new RTPWriteStream(sodiumEncrypter, _ssrc); //Consumes header, passes
return new BufferedWriteStream(rtpWriter, this, bufferMillis, _connection.CancelToken, _audioLogger); //Generates header
}
public AudioOutStream CreateDirectOpusStream()
{
var outputStream = new OutputStream(ApiClient); //Ignores header
var sodiumEncrypter = new SodiumEncryptStream(outputStream, this); //Passes header
return new RTPWriteStream(sodiumEncrypter, _ssrc); //Consumes header (external input), passes
}
public AudioOutStream CreatePCMStream(AudioApplication application, int? bitrate, int bufferMillis, int packetLoss)
{
var outputStream = new OutputStream(ApiClient); //Ignores header
var sodiumEncrypter = new SodiumEncryptStream(outputStream, this); //Passes header
var rtpWriter = new RTPWriteStream(sodiumEncrypter, _ssrc); //Consumes header, passes
var bufferedStream = new BufferedWriteStream(rtpWriter, this, bufferMillis, _connection.CancelToken, _audioLogger); //Ignores header, generates header
return new OpusEncodeStream(bufferedStream, bitrate ?? (96 * 1024), application, packetLoss); //Generates header
}
public AudioOutStream CreateDirectPCMStream(AudioApplication application, int? bitrate, int packetLoss)
{
var outputStream = new OutputStream(ApiClient); //Ignores header
var sodiumEncrypter = new SodiumEncryptStream(outputStream, this); //Passes header
var rtpWriter = new RTPWriteStream(sodiumEncrypter, _ssrc); //Consumes header, passes
return new OpusEncodeStream(rtpWriter, bitrate ?? (96 * 1024), application, packetLoss); //Generates header
}
internal async Task CreateInputStreamAsync(ulong userId)
{
//Assume Thread-safe
if (!_streams.ContainsKey(userId))
{
var readerStream = new InputStream(); //Consumes header
var opusDecoder = new OpusDecodeStream(readerStream); //Passes header
//var jitterBuffer = new JitterBuffer(opusDecoder, _audioLogger);
var rtpReader = new RTPReadStream(opusDecoder); //Generates header
var decryptStream = new SodiumDecryptStream(rtpReader, this); //No header
_streams.TryAdd(userId, new StreamPair(readerStream, decryptStream));
await _streamCreatedEvent.InvokeAsync(userId, readerStream);
}
}
internal AudioInStream GetInputStream(ulong id)
{
if (_streams.TryGetValue(id, out StreamPair streamPair))
return streamPair.Reader;
return null;
}
internal async Task RemoveInputStreamAsync(ulong userId)
{
if (_streams.TryRemove(userId, out var pair))
{
await _streamDestroyedEvent.InvokeAsync(userId).ConfigureAwait(false);
pair.Reader.Dispose();
}
}
internal async Task ClearInputStreamsAsync()
{
foreach (var pair in _streams)
{
await _streamDestroyedEvent.InvokeAsync(pair.Key).ConfigureAwait(false);
pair.Value.Reader.Dispose();
}
_ssrcMap.Clear();
_streams.Clear();
}
private async Task ProcessMessageAsync(VoiceOpCode opCode, object payload)
{
_lastMessageTime = Environment.TickCount;
try
{
switch (opCode)
{
case VoiceOpCode.Ready:
{
await _audioLogger.DebugAsync("Received Ready").ConfigureAwait(false);
var data = (payload as JToken).ToObject<ReadyEvent>(_serializer);
_ssrc = data.SSRC;
if (!data.Modes.Contains(DiscordVoiceAPIClient.Mode))
throw new InvalidOperationException($"Discord does not support {DiscordVoiceAPIClient.Mode}");
ApiClient.SetUdpEndpoint(data.Ip, data.Port);
await ApiClient.SendDiscoveryAsync(_ssrc).ConfigureAwait(false);
_heartbeatTask = RunHeartbeatAsync(41250, _connection.CancelToken);
}
break;
case VoiceOpCode.SessionDescription:
{
await _audioLogger.DebugAsync("Received SessionDescription").ConfigureAwait(false);
var data = (payload as JToken).ToObject<SessionDescriptionEvent>(_serializer);
if (data.Mode != DiscordVoiceAPIClient.Mode)
throw new InvalidOperationException($"Discord selected an unexpected mode: {data.Mode}");
SecretKey = data.SecretKey;
_isSpeaking = false;
await ApiClient.SendSetSpeaking(false).ConfigureAwait(false);
_keepaliveTask = RunKeepaliveAsync(5000, _connection.CancelToken);
var _ = _connection.CompleteAsync();
}
break;
case VoiceOpCode.HeartbeatAck:
{
await _audioLogger.DebugAsync("Received HeartbeatAck").ConfigureAwait(false);
if (_heartbeatTimes.TryDequeue(out long time))
{
int latency = (int)(Environment.TickCount - time);
int before = Latency;
Latency = latency;
await _latencyUpdatedEvent.InvokeAsync(before, latency).ConfigureAwait(false);
}
}
break;
case VoiceOpCode.Speaking:
{
await _audioLogger.DebugAsync("Received Speaking").ConfigureAwait(false);
var data = (payload as JToken).ToObject<SpeakingEvent>(_serializer);
_ssrcMap[data.Ssrc] = data.UserId; //TODO: Memory Leak: SSRCs are never cleaned up
await _speakingUpdatedEvent.InvokeAsync(data.UserId, data.Speaking);
}
break;
default:
await _audioLogger.WarningAsync($"Unknown OpCode ({opCode})").ConfigureAwait(false);
return;
}
}
catch (Exception ex)
{
await _audioLogger.ErrorAsync($"Error handling {opCode}", ex).ConfigureAwait(false);
return;
}
}
private async Task ProcessPacketAsync(byte[] packet)
{
try
{
if (_connection.State == ConnectionState.Connecting)
{
if (packet.Length != 70)
{
await _audioLogger.DebugAsync("Malformed Packet").ConfigureAwait(false);
return;
}
string ip;
int port;
try
{
ip = Encoding.UTF8.GetString(packet, 4, 70 - 6).TrimEnd('\0');
port = (packet[69] << 8) | packet[68];
}
catch (Exception ex)
{
await _audioLogger.DebugAsync("Malformed Packet", ex).ConfigureAwait(false);
return;
}
await _audioLogger.DebugAsync("Received Discovery").ConfigureAwait(false);
await ApiClient.SendSelectProtocol(ip, port).ConfigureAwait(false);
}
else if (_connection.State == ConnectionState.Connected)
{
if (packet.Length == 8)
{
await _audioLogger.DebugAsync("Received Keepalive").ConfigureAwait(false);
ulong value =
((ulong)packet[0] >> 0) |
((ulong)packet[1] >> 8) |
((ulong)packet[2] >> 16) |
((ulong)packet[3] >> 24) |
((ulong)packet[4] >> 32) |
((ulong)packet[5] >> 40) |
((ulong)packet[6] >> 48) |
((ulong)packet[7] >> 56);
while (_keepaliveTimes.TryDequeue(out var pair))
{
if (pair.Key == value)
{
int latency = Environment.TickCount - pair.Value;
int before = UdpLatency;
UdpLatency = latency;
await _udpLatencyUpdatedEvent.InvokeAsync(before, latency).ConfigureAwait(false);
break;
}
}
}
else
{
if (!RTPReadStream.TryReadSsrc(packet, 0, out var ssrc))
{
await _audioLogger.DebugAsync("Malformed Frame").ConfigureAwait(false);
return;
}
if (!_ssrcMap.TryGetValue(ssrc, out var userId))
{
await _audioLogger.DebugAsync($"Unknown SSRC {ssrc}").ConfigureAwait(false);
return;
}
if (!_streams.TryGetValue(userId, out var pair))
{
await _audioLogger.DebugAsync($"Unknown User {userId}").ConfigureAwait(false);
return;
}
try
{
await pair.Writer.WriteAsync(packet, 0, packet.Length).ConfigureAwait(false);
}
catch (Exception ex)
{
await _audioLogger.DebugAsync("Malformed Frame", ex).ConfigureAwait(false);
return;
}
//await _audioLogger.DebugAsync($"Received {packet.Length} bytes from user {userId}").ConfigureAwait(false);
}
}
}
catch (Exception ex)
{
await _audioLogger.WarningAsync("Failed to process UDP packet", ex).ConfigureAwait(false);
return;
}
}
private async Task RunHeartbeatAsync(int intervalMillis, CancellationToken cancelToken)
{
// TODO: Clean this up when Discord's session patch is live
try
{
await _audioLogger.DebugAsync("Heartbeat Started").ConfigureAwait(false);
while (!cancelToken.IsCancellationRequested)
{
var now = Environment.TickCount;
//Did server respond to our last heartbeat?
if (_heartbeatTimes.Count != 0 && (now - _lastMessageTime) > intervalMillis &&
ConnectionState == ConnectionState.Connected)
{
_connection.Error(new Exception("Server missed last heartbeat"));
return;
}
_heartbeatTimes.Enqueue(now);
try
{
await ApiClient.SendHeartbeatAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
await _audioLogger.WarningAsync("Failed to send heartbeat", ex).ConfigureAwait(false);
}
await Task.Delay(intervalMillis, cancelToken).ConfigureAwait(false);
}
await _audioLogger.DebugAsync("Heartbeat Stopped").ConfigureAwait(false);
}
catch (OperationCanceledException)
{
await _audioLogger.DebugAsync("Heartbeat Stopped").ConfigureAwait(false);
}
catch (Exception ex)
{
await _audioLogger.ErrorAsync("Heartbeat Errored", ex).ConfigureAwait(false);
}
}
private async Task RunKeepaliveAsync(int intervalMillis, CancellationToken cancelToken)
{
try
{
await _audioLogger.DebugAsync("Keepalive Started").ConfigureAwait(false);
while (!cancelToken.IsCancellationRequested)
{
var now = Environment.TickCount;
try
{
ulong value = await ApiClient.SendKeepaliveAsync().ConfigureAwait(false);
if (_keepaliveTimes.Count < 12) //No reply for 60 Seconds
_keepaliveTimes.Enqueue(new KeyValuePair<ulong, int>(value, now));
}
catch (Exception ex)
{
await _audioLogger.WarningAsync("Failed to send keepalive", ex).ConfigureAwait(false);
}
await Task.Delay(intervalMillis, cancelToken).ConfigureAwait(false);
}
await _audioLogger.DebugAsync("Keepalive Stopped").ConfigureAwait(false);
}
catch (OperationCanceledException)
{
await _audioLogger.DebugAsync("Keepalive Stopped").ConfigureAwait(false);
}
catch (Exception ex)
{
await _audioLogger.ErrorAsync("Keepalive Errored", ex).ConfigureAwait(false);
}
}
public async Task SetSpeakingAsync(bool value)
{
if (_isSpeaking != value)
{
_isSpeaking = value;
await ApiClient.SendSetSpeaking(value).ConfigureAwait(false);
}
}
internal void Dispose(bool disposing)
{
if (disposing)
{
StopAsync().GetAwaiter().GetResult();
ApiClient.Dispose();
_stateLock?.Dispose();
}
}
/// <inheritdoc />
public void Dispose() => Dispose(true);
}
}
| |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System.Collections.Generic;
using System.Threading.Tasks;
using FluentAssertions;
using IdentityServer.UnitTests.Validation.Setup;
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Stores;
using Xunit;
namespace IdentityServer.UnitTests.Validation
{
public class ScopeValidation
{
private const string Category = "Scope Validation";
private List<IdentityResource> _identityResources = new List<IdentityResource>
{
new IdentityResource
{
Name = "openid",
Required = true
},
new IdentityResource
{
Name = "email"
}
};
private List<ApiResource> _apiResources = new List<ApiResource>
{
new ApiResource
{
Name = "api",
Scopes =
{
new Scope
{
Name = "resource1",
Required = true
},
new Scope
{
Name = "resource2"
}
}
},
new ApiResource
{
Name = "disabled_api",
Enabled = false,
Scopes =
{
new Scope
{
Name = "disabled"
}
}
}
};
private Client _restrictedClient = new Client
{
ClientId = "restricted",
AllowedScopes = new List<string>
{
"openid",
"resource1",
"disabled"
}
};
private IResourceStore _store;
public ScopeValidation()
{
_store = new InMemoryResourcesStore(_identityResources, _apiResources);
}
[Fact]
[Trait("Category", Category)]
public void Parse_Scopes_with_Empty_Scope_List()
{
var scopes = string.Empty.ParseScopesString();
scopes.Should().BeNull();
}
[Fact]
[Trait("Category", Category)]
public void Parse_Scopes_with_Sorting()
{
var scopes = "scope3 scope2 scope1".ParseScopesString();
scopes.Count.Should().Be(3);
scopes[0].Should().Be("scope1");
scopes[1].Should().Be("scope2");
scopes[2].Should().Be("scope3");
}
[Fact]
[Trait("Category", Category)]
public void Parse_Scopes_with_Extra_Spaces()
{
var scopes = " scope3 scope2 scope1 ".ParseScopesString();
scopes.Count.Should().Be(3);
scopes[0].Should().Be("scope1");
scopes[1].Should().Be("scope2");
scopes[2].Should().Be("scope3");
}
[Fact]
[Trait("Category", Category)]
public void Parse_Scopes_with_Duplicate_Scope()
{
var scopes = "scope2 scope1 scope2".ParseScopesString();
scopes.Count.Should().Be(2);
scopes[0].Should().Be("scope1");
scopes[1].Should().Be("scope2");
}
[Fact]
[Trait("Category", Category)]
public async Task Only_Offline_Access_Requested()
{
var scopes = "offline_access".ParseScopesString();
var validator = Factory.CreateScopeValidator(_store);
var result = await validator.AreScopesValidAsync(scopes);
result.Should().BeFalse();
}
[Fact]
[Trait("Category", Category)]
public async Task All_Scopes_Valid()
{
var scopes = "openid email resource1 resource2".ParseScopesString();
var validator = Factory.CreateScopeValidator(_store);
var result = await validator.AreScopesValidAsync(scopes);
result.Should().BeTrue();
}
[Fact]
[Trait("Category", Category)]
public async Task Invalid_Scope()
{
var scopes = "openid email resource1 resource2 unknown".ParseScopesString();
var validator = Factory.CreateScopeValidator(_store);
var result = await validator.AreScopesValidAsync(scopes);
result.Should().BeFalse();
}
[Fact]
[Trait("Category", Category)]
public async Task Disabled_Scope()
{
var scopes = "openid email resource1 resource2 disabled".ParseScopesString();
var validator = Factory.CreateScopeValidator(_store);
var result = await validator.AreScopesValidAsync(scopes);
result.Should().BeFalse();
}
[Fact]
[Trait("Category", Category)]
public async Task All_Scopes_Allowed_For_Restricted_Client()
{
var scopes = "openid resource1".ParseScopesString();
var validator = Factory.CreateScopeValidator(_store);
var result = await validator.AreScopesAllowedAsync(_restrictedClient, scopes);
result.Should().BeTrue();
}
[Fact]
[Trait("Category", Category)]
public async Task Restricted_Scopes()
{
var scopes = "openid email resource1 resource2".ParseScopesString();
var validator = Factory.CreateScopeValidator(_store);
var result = await validator.AreScopesAllowedAsync(_restrictedClient, scopes);
result.Should().BeFalse();
}
[Fact]
[Trait("Category", Category)]
public async Task Contains_Resource_and_Identity_Scopes()
{
var scopes = "openid email resource1 resource2".ParseScopesString();
var validator = Factory.CreateScopeValidator(_store);
var result = await validator.AreScopesValidAsync(scopes);
result.Should().BeTrue();
validator.ContainsOpenIdScopes.Should().BeTrue();
validator.ContainsApiResourceScopes.Should().BeTrue();
}
[Fact]
[Trait("Category", Category)]
public async Task Contains_Resource_Scopes_Only()
{
var scopes = "resource1 resource2".ParseScopesString();
var validator = Factory.CreateScopeValidator(_store);
var result = await validator.AreScopesValidAsync(scopes);
result.Should().BeTrue();
validator.ContainsOpenIdScopes.Should().BeFalse();
validator.ContainsApiResourceScopes.Should().BeTrue();
}
[Fact]
[Trait("Category", Category)]
public async Task Contains_Identity_Scopes_Only()
{
var scopes = "openid email".ParseScopesString();
var validator = Factory.CreateScopeValidator(_store);
var result = await validator.AreScopesValidAsync(scopes);
result.Should().BeTrue();
validator.ContainsOpenIdScopes.Should().BeTrue();
validator.ContainsApiResourceScopes.Should().BeFalse();
}
[Fact]
[Trait("Category", Category)]
public void ValidateRequiredScopes_required_scopes_present_should_succeed()
{
var validator = Factory.CreateScopeValidator(_store);
validator.RequestedResources = new Resources(_identityResources, _apiResources);
validator.ValidateRequiredScopes(new string[] { "openid", "email", "resource1", "resource2" }).Should().BeTrue();
validator.ValidateRequiredScopes(new string[] { "openid", "email", "resource1" }).Should().BeTrue();
validator.ValidateRequiredScopes(new string[] { "openid", "resource1", "resource2" }).Should().BeTrue();
validator.ValidateRequiredScopes(new string[] { "openid", "resource1" }).Should().BeTrue();
}
[Fact]
[Trait("Category", Category)]
public void ValidateRequiredScopes_required_scopes_absent_should_fail()
{
var validator = Factory.CreateScopeValidator(_store);
validator.RequestedResources = new Resources(_identityResources, _apiResources);
validator.ValidateRequiredScopes(new string[] { "email", "resource2" }).Should().BeFalse();
validator.ValidateRequiredScopes(new string[] { "email", "resource1", "resource2" }).Should().BeFalse();
validator.ValidateRequiredScopes(new string[] { "openid", "resource2" }).Should().BeFalse();
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using WebApplication.Data;
namespace WebApplication.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.0.0-rc2-20901");
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.HasIndex("UserId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<string>("Value");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("WebApplication.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.HasName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.HasOne("WebApplication.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.HasOne("WebApplication.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("WebApplication.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
| |
using System;
using System.Linq;
namespace GlmNet
{
/// <summary>
/// Represents a 2x2 matrix.
/// </summary>
public struct mat2
{
#region Construction
/// <summary>
/// Initializes a new instance of the <see cref="mat2"/> struct.
/// This matrix is the identity matrix scaled by <paramref name="scale"/>.
/// </summary>
/// <param name="scale">The scale.</param>
public mat2(float scale)
{
cols = new[]
{
new vec2(scale, 0.0f),
new vec2(0.0f, scale)
};
}
/// <summary>
/// Initializes a new instance of the <see cref="mat2"/> struct.
/// The matrix is initialised with the <paramref name="cols"/>.
/// </summary>
/// <param name="cols">The colums of the matrix.</param>
public mat2(vec2[] cols)
{
this.cols = new[]
{
cols[0],
cols[1]
};
}
public mat2(vec2 a, vec2 b)
{
this.cols = new[]
{
a, b
};
}
public mat2(float a, float b, float c, float d)
{
this.cols = new[]
{
new vec2(a,b), new vec2(c,d)
};
}
/// <summary>
/// Creates an identity matrix.
/// </summary>
/// <returns>A new identity matrix.</returns>
public static mat2 identity()
{
return new mat2
{
cols = new[]
{
new vec2(1,0),
new vec2(0,1)
}
};
}
#endregion
#region Index Access
/// <summary>
/// Gets or sets the <see cref="vec2"/> column at the specified index.
/// </summary>
/// <value>
/// The <see cref="vec2"/> column.
/// </value>
/// <param name="column">The column index.</param>
/// <returns>The column at index <paramref name="column"/>.</returns>
public vec2 this[int column]
{
get { return cols[column]; }
set { cols[column] = value; }
}
/// <summary>
/// Gets or sets the element at <paramref name="column"/> and <paramref name="row"/>.
/// </summary>
/// <value>
/// The element at <paramref name="column"/> and <paramref name="row"/>.
/// </value>
/// <param name="column">The column index.</param>
/// <param name="row">The row index.</param>
/// <returns>
/// The element at <paramref name="column"/> and <paramref name="row"/>.
/// </returns>
public float this[int column, int row]
{
get { return cols[column][row]; }
set { cols[column][row] = value; }
}
#endregion
#region Conversion
/// <summary>
/// Returns the matrix as a flat array of elements, column major.
/// </summary>
/// <returns></returns>
public float[] to_array()
{
return cols.SelectMany(v => v.to_array()).ToArray();
}
#endregion
#region Multiplication
/// <summary>
/// Multiplies the <paramref name="lhs"/> matrix by the <paramref name="rhs"/> vector.
/// </summary>
/// <param name="lhs">The LHS matrix.</param>
/// <param name="rhs">The RHS vector.</param>
/// <returns>The product of <paramref name="lhs"/> and <paramref name="rhs"/>.</returns>
public static vec2 operator *(mat2 lhs, vec2 rhs)
{
return new vec2(
lhs[0, 0] * rhs[0] + lhs[1, 0] * rhs[1],
lhs[0, 1] * rhs[0] + lhs[1, 1] * rhs[1]
);
}
/// <summary>
/// Multiplies the <paramref name="lhs"/> matrix by the <paramref name="rhs"/> matrix.
/// </summary>
/// <param name="lhs">The LHS matrix.</param>
/// <param name="rhs">The RHS matrix.</param>
/// <returns>The product of <paramref name="lhs"/> and <paramref name="rhs"/>.</returns>
public static mat2 operator *(mat2 lhs, mat2 rhs)
{
return new mat2(new[]
{
lhs[0][0] * rhs[0] + lhs[1][0] * rhs[1],
lhs[0][1] * rhs[0] + lhs[1][1] * rhs[1]
});
}
public static mat2 operator *(mat2 lhs, float s)
{
return new mat2(new[]
{
lhs[0]*s,
lhs[1]*s
});
}
#endregion
#region ToString support
public override string ToString()
{
return String.Format(
"[{0}, {1}; {2}, {3}]",
this[0, 0], this[1, 0],
this[0, 1], this[1, 1]
);
}
#endregion
#region comparision
/// <summary>
/// Determines whether the specified <see cref="System.Object" />, is equal to this instance.
/// The Difference is detected by the different values
/// </summary>
/// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
if (obj.GetType() == typeof(mat2))
{
var mat = (mat2)obj;
if (mat[0] == this[0] && mat[1] == this[1])
return true;
}
return false;
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="m1">The first Matrix.</param>
/// <param name="m2">The second Matrix.</param>
/// <returns>
/// The result of the operator.
/// </returns>
public static bool operator ==(mat2 m1, mat2 m2)
{
return m1.Equals(m2);
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="m1">The first Matrix.</param>
/// <param name="m2">The second Matrix.</param>
/// <returns>
/// The result of the operator.
/// </returns>
public static bool operator !=(mat2 m1, mat2 m2)
{
return !m1.Equals(m2);
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
return this[0].GetHashCode() ^ this[1].GetHashCode();
}
#endregion
/// <summary>
/// The columms of the matrix.
/// </summary>
private vec2[] cols;
}
}
| |
#region Header
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Copyright (c) 2007-2008 James Nies and NArrange contributors.
* All rights reserved.
*
* This program and the accompanying materials are made available under
* the terms of the Common Public License v1.0 which accompanies this
* distribution.
*
* 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
* 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.
*
*<author>James Nies</author>
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
#endregion Header
namespace NArrange.Core
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
/// <summary>
/// Class for backing up and restoring source files. Utilizes zip archives.
/// </summary>
public static class BackupUtilities
{
#region Fields
/// <summary>
/// Default backup root directory.
/// </summary>
public static readonly string BackupRoot = Path.Combine(
Path.GetTempPath(), "NArrange");
/// <summary>
/// Backup index file name.
/// </summary>
private const string IndexFileName = "index.txt";
/// <summary>
/// Index file token separator.
/// </summary>
private const char IndexSeparator = ',';
/// <summary>
/// Backup zip file name.
/// </summary>
private const string ZipFileName = "files.zip";
/// <summary>
/// Max string length for an integer.
/// </summary>
private static readonly int MaxIntLength =
int.MinValue.ToString(CultureInfo.InvariantCulture).Length;
#endregion Fields
#region Methods
/// <summary>
/// Creates a backup of the specified files using the specified key.
/// </summary>
/// <param name="backupRoot">Backup root directory.</param>
/// <param name="key">Backup key.</param>
/// <param name="fileNames">Files to backup.</param>
/// <returns>Backup location</returns>
public static string BackupFiles(
string backupRoot,
string key,
IEnumerable<string> fileNames)
{
if (backupRoot == null || backupRoot.Trim().Length == 0)
{
throw new ArgumentException("Invalid backup location", "backupRoot");
}
else if (key == null || key.Trim().Length == 0)
{
throw new ArgumentException("Invalid backup key", "key");
}
if (!Directory.Exists(backupRoot))
{
Directory.CreateDirectory(backupRoot);
}
DateTime backupDate = DateTime.Now;
string dateDirectory = backupDate.ToFileTime().ToString(CultureInfo.InvariantCulture);
string keyRoot = Path.Combine(backupRoot, key);
if (!Directory.Exists(keyRoot))
{
Directory.CreateDirectory(keyRoot);
}
string backupLocation = Path.Combine(keyRoot, dateDirectory);
Directory.CreateDirectory(backupLocation);
string zipFile = Path.Combine(backupLocation, ZipFileName);
// Copy all files to a temporary working directory
string workingDirectory = CreateTempFilePath();
Directory.CreateDirectory(workingDirectory);
try
{
string indexFile = Path.Combine(backupLocation, IndexFileName);
using (FileStream fs = new FileStream(indexFile, FileMode.Create))
{
using (StreamWriter writer = new StreamWriter(fs))
{
foreach (string fileName in fileNames)
{
string fileKey = CreateFileNameKey(fileName);
string fileBackupName = fileKey + "." + ProjectManager.GetExtension(fileName);
writer.WriteLine(fileBackupName + IndexSeparator + fileName);
string fileBackupPath =
Path.Combine(workingDirectory, fileBackupName);
File.Copy(fileName, fileBackupPath);
}
}
}
// Zip up all files to backup
ZipUtilities.Zip(workingDirectory, zipFile);
}
finally
{
TryDeleteDirectory(workingDirectory);
}
return backupLocation;
}
/// <summary>
/// Creates a system unique key for the specified fileName.
/// </summary>
/// <param name="fileName">File name or path.</param>
/// <returns>Unique key for the file name (hash).</returns>
public static string CreateFileNameKey(string fileName)
{
if (fileName == null)
{
throw new ArgumentNullException("fileName");
}
else if (fileName.Trim().Length == 0)
{
throw new ArgumentException("Invalid fileName", "fileName");
}
return fileName.ToUpperInvariant().GetHashCode()
.ToString(CultureInfo.InvariantCulture)
.Replace('-', '_').PadLeft(MaxIntLength, '_');
}
/// <summary>
/// Gets a new temporary file path for use as a directory or filename.
/// </summary>
/// <returns>Temp file path.</returns>
public static string CreateTempFilePath()
{
string fileName = Path.Combine(
Path.GetTempPath(),
Guid.NewGuid().ToString().Replace('-', '_'));
return fileName;
}
/// <summary>
/// Restores all files associated with the specified key.
/// </summary>
/// <param name="backupRoot">Backup root directory.</param>
/// <param name="key">Backup key.</param>
/// <returns>A boolean value indicating whether or not the operation was succesful.</returns>
public static bool RestoreFiles(string backupRoot, string key)
{
bool success = false;
if (backupRoot == null || backupRoot.Trim().Length == 0)
{
throw new ArgumentException("Invalid backup location", "backupRoot");
}
else if (key == null || key.Trim().Length == 0)
{
throw new ArgumentException("Invalid backup key", "key");
}
string keyRoot = Path.Combine(backupRoot, key);
// Find the most recent timestamped folder
DirectoryInfo keyDirectory = new DirectoryInfo(keyRoot);
SortedList<string, DirectoryInfo> timestampedDirectories =
new SortedList<string, DirectoryInfo>();
DirectoryInfo[] childDirectories = keyDirectory.GetDirectories();
foreach (DirectoryInfo childDirectory in childDirectories)
{
timestampedDirectories.Add(childDirectory.Name, childDirectory);
}
if (timestampedDirectories.Count > 0)
{
string dateDirectory = timestampedDirectories.Values[timestampedDirectories.Count - 1].Name;
string backupLocation = Path.Combine(keyRoot, dateDirectory);
string zipFile = Path.Combine(backupLocation, ZipFileName);
// Extract all files to a temporary working directory
string workingDirectory = CreateTempFilePath();
Directory.CreateDirectory(workingDirectory);
try
{
// Unzip and copy all files to restore
ZipUtilities.Unzip(zipFile, workingDirectory);
string indexFile = Path.Combine(backupLocation, IndexFileName);
using (FileStream fs = new FileStream(indexFile, FileMode.Open))
{
using (StreamReader reader = new StreamReader(fs))
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
int separatorIndex = line.IndexOf(IndexSeparator);
string fileBackupName = line.Substring(0, separatorIndex);
string fileBackupPath =
Path.Combine(workingDirectory, fileBackupName);
string restorePath = line.Substring(separatorIndex + 1);
string backupText = File.ReadAllText(fileBackupPath);
string restoreText = null;
if (File.Exists(restorePath))
{
restoreText = File.ReadAllText(restorePath);
File.SetAttributes(restorePath, FileAttributes.Normal);
}
if (backupText != restoreText)
{
File.Copy(fileBackupPath, restorePath, true);
}
}
}
}
// Remove the restored backup so that a consecutive restore
// will process the next in the history
Directory.Delete(backupLocation, true);
success = true;
}
finally
{
TryDeleteDirectory(workingDirectory);
}
}
return success;
}
/// <summary>
/// Attempts to delete a directory, catching any exceptions.
/// </summary>
/// <param name="workingDirectory">Working directory path.</param>
/// <returns>Returns a value indicating whether or not the directory was deleted.</returns>
private static bool TryDeleteDirectory(string workingDirectory)
{
try
{
Directory.Delete(workingDirectory, true);
return true;
}
catch
{
return false;
}
}
#endregion Methods
}
}
| |
//
// MediaPlayer.cs
//
// Authors:
// John Millikin <jmillikin@gmail.com>
// Bertrand Lorentz <bertrand.lorentz@gmail.com>
//
// Copyright (C) 2009 John Millikin
// Copyright (C) 2010 Bertrand Lorentz
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DBus;
using Hyena;
using Banshee.Gui;
using Banshee.MediaEngine;
using Banshee.PlaybackController;
using Banshee.Playlist;
using Banshee.ServiceStack;
using Banshee.Sources;
namespace Banshee.Mpris
{
public class MediaPlayer : IMediaPlayer, IPlayer, IPlaylists, IProperties
{
private static string mediaplayer_interface_name = "org.mpris.MediaPlayer2";
private static string player_interface_name = "org.mpris.MediaPlayer2.Player";
private static string playlists_interface_name = "org.mpris.MediaPlayer2.Playlists";
private PlaybackControllerService playback_service;
private PlayerEngineService engine_service;
private Gtk.ToggleAction fullscreen_action;
private Dictionary<string, AbstractPlaylistSource> playlist_sources;
private Dictionary<string, object> current_properties;
private Dictionary<string, object> changed_properties;
private List<string> invalidated_properties;
private static ObjectPath path = new ObjectPath ("/org/mpris/MediaPlayer2");
public static ObjectPath Path {
get { return path; }
}
private event PropertiesChangedHandler properties_changed;
event PropertiesChangedHandler IProperties.PropertiesChanged {
add { properties_changed += value; }
remove { properties_changed -= value; }
}
private event DBusPlayerSeekedHandler dbus_seeked;
event DBusPlayerSeekedHandler IPlayer.Seeked {
add { dbus_seeked += value; }
remove { dbus_seeked -= value; }
}
private event PlaylistChangedHandler playlist_changed;
event PlaylistChangedHandler IPlaylists.PlaylistChanged {
add { playlist_changed += value; }
remove { playlist_changed -= value; }
}
public MediaPlayer ()
{
playback_service = ServiceManager.PlaybackController;
engine_service = ServiceManager.PlayerEngine;
playlist_sources = new Dictionary<string, AbstractPlaylistSource> ();
changed_properties = new Dictionary<string, object> ();
current_properties = new Dictionary<string, object> ();
invalidated_properties = new List<string> ();
var interface_service = ServiceManager.Get<InterfaceActionService> ();
fullscreen_action = interface_service.ViewActions["FullScreenAction"] as Gtk.ToggleAction;
}
#region IMediaPlayer
public bool CanQuit {
get { return true; }
}
public bool CanRaise {
get { return true; }
}
public bool Fullscreen {
get {
if (fullscreen_action != null) {
return fullscreen_action.Active;
}
return false;
}
set {
if (fullscreen_action != null) {
fullscreen_action.Active = value;
}
}
}
public bool CanSetFullscreen {
get { return true; }
}
public bool HasTrackList {
get { return false; }
}
public string Identity {
get { return "Banshee"; }
}
public string DesktopEntry {
get { return "banshee"; }
}
// This is just a list of commonly supported MIME types.
// We don't know exactly which ones are supported by the PlayerEngine
private static string [] supported_mimetypes = { "application/ogg", "audio/flac",
"audio/mp3", "audio/mp4", "audio/mpeg", "audio/ogg", "audio/vorbis", "audio/wav",
"audio/x-flac", "audio/x-vorbis+ogg",
"video/avi", "video/mp4", "video/mpeg" };
public string [] SupportedMimeTypes {
get { return supported_mimetypes; }
}
// We can't use the PlayerEngine.SourceCapabilities property here, because
// the OpenUri method only supports "file" and "http".
private static string [] supported_uri_schemes = { "file", "http" };
public string [] SupportedUriSchemes {
get { return supported_uri_schemes; }
}
public void Raise ()
{
if (!CanRaise) {
return;
}
ServiceManager.Get<GtkElementsService> ().PrimaryWindow.SetVisible (true);
}
public void Quit ()
{
if (!CanQuit) {
return;
}
Application.Shutdown ();
}
#endregion
#region IPlayer
public bool CanControl {
get { return true; }
}
// We don't really know if we can actually go next or previous
public bool CanGoNext {
get { return CanControl; }
}
public bool CanGoPrevious {
get { return CanControl; }
}
public bool CanPause {
get { return engine_service.CanPause; }
}
public bool CanPlay {
get { return CanControl; }
}
public bool CanSeek {
get { return engine_service.CanSeek; }
}
public double MaximumRate {
get { return 1.0; }
}
public double MinimumRate {
get { return 1.0; }
}
public double Rate {
get { return 1.0; }
set {}
}
public bool Shuffle {
get { return !(playback_service.ShuffleMode == "off"); }
set { playback_service.ShuffleMode = value ? "song" : "off"; }
}
public string LoopStatus {
get {
string loop_status;
switch (playback_service.RepeatMode) {
case PlaybackRepeatMode.None:
loop_status = "None";
break;
case PlaybackRepeatMode.RepeatSingle:
loop_status = "Track";
break;
case PlaybackRepeatMode.RepeatAll:
loop_status = "Playlist";
break;
default:
loop_status = "None";
break;
}
return loop_status;
}
set {
switch (value) {
case "None":
playback_service.RepeatMode = PlaybackRepeatMode.None;
break;
case "Track":
playback_service.RepeatMode = PlaybackRepeatMode.RepeatSingle;
break;
case "Playlist":
playback_service.RepeatMode = PlaybackRepeatMode.RepeatAll;
break;
}
}
}
public string PlaybackStatus {
get {
string status;
switch (engine_service.CurrentState) {
case PlayerState.Playing:
status = "Playing";
break;
case PlayerState.Paused:
status = "Paused";
break;
default:
status = "Stopped";
break;
}
return status;
}
}
public IDictionary<string, object> Metadata {
get {
var metadata = new Metadata (engine_service.CurrentTrack);
return metadata.DataStore;
}
}
public double Volume {
get { return engine_service.Volume / 100.0; }
set { engine_service.Volume = (ushort)Math.Round (value * 100); }
}
// Position is expected in microseconds
public long Position {
get { return (long)engine_service.Position * 1000; }
}
public void Next ()
{
playback_service.Next ();
}
public void Previous ()
{
playback_service.Previous ();
}
public void Pause ()
{
engine_service.Pause ();
}
public void PlayPause ()
{
engine_service.TogglePlaying ();
}
public void Stop ()
{
engine_service.Close ();
}
public void Play ()
{
engine_service.Play ();
}
public void SetPosition (ObjectPath trackid, long position)
{
if (!CanSeek) {
return;
}
if (trackid == null || trackid != (ObjectPath)Metadata["mpris:trackid"]) {
return;
}
// position is in microseconds, we speak in milliseconds
long position_ms = position / 1000;
if (position_ms < 0 || position_ms > engine_service.CurrentTrack.Duration.TotalMilliseconds) {
return;
}
engine_service.Position = (uint)position_ms;
}
public void Seek (long position)
{
if (!CanSeek) {
return;
}
// position is in microseconds, relative to the current position and can be negative
long new_pos = (int)engine_service.Position + (position / 1000);
if (new_pos < 0) {
engine_service.Position = 0;
} else {
engine_service.Position = (uint)new_pos;
}
}
public void OpenUri (string uri)
{
Banshee.Streaming.RadioTrackInfo.OpenPlay (uri);
}
#endregion
#region IPlaylists
public uint PlaylistCount {
get {
return (uint)ServiceManager.SourceManager.FindSources<AbstractPlaylistSource> ().Count ();
}
}
private static string [] supported_playlist_orderings = { "Alphabetical", "UserDefined" };
public string [] Orderings {
get { return supported_playlist_orderings; }
}
private static Playlist dummy_playlist = new Playlist {
Id = new ObjectPath (DBusServiceManager.ObjectRoot),
Name = "",
Icon = "" };
public MaybePlaylist ActivePlaylist {
get {
// We want the source that is currently playing
var playlist_source = ServiceManager.PlaybackController.Source as AbstractPlaylistSource;
if (playlist_source == null) {
return new MaybePlaylist { Valid = false, Playlist = dummy_playlist };
} else {
return new MaybePlaylist { Valid = true,
Playlist = BuildPlaylistFromSource (playlist_source) };
}
}
}
private ObjectPath MakeObjectPath (AbstractPlaylistSource playlist)
{
StringBuilder object_path_builder = new StringBuilder ();
object_path_builder.Append (DBusServiceManager.ObjectRoot);
if (playlist.Parent != null) {
object_path_builder.AppendFormat ("/{0}", DBusServiceManager.MakeDBusSafeString (playlist.Parent.TypeName));
}
object_path_builder.Append ("/Playlists/");
object_path_builder.Append (DBusServiceManager.MakeDBusSafeString (playlist.UniqueId));
string object_path = object_path_builder.ToString ();
playlist_sources[object_path] = playlist;
return new ObjectPath (object_path);
}
private string GetIconPath (Source source)
{
string icon_name = "image-missing";
Type icon_type = source.Properties.GetType ("Icon.Name");
if (icon_type == typeof (string)) {
icon_name = source.Properties.Get<string> ("Icon.Name");
} else if (icon_type == typeof (string [])) {
icon_name = source.Properties.Get<string[]> ("Icon.Name")[0];
}
string icon_path = Paths.Combine (Paths.GetInstalledDataDirectory ("icons"),
"hicolor", "22x22", "categories",
String.Concat (icon_name, ".png"));
return String.Concat ("file://", icon_path);
}
private Playlist BuildPlaylistFromSource (AbstractPlaylistSource source)
{
var mpris_playlist = new Playlist ();
mpris_playlist.Name = source.Name;
mpris_playlist.Id = MakeObjectPath (source);
mpris_playlist.Icon = GetIconPath (source);
return mpris_playlist;
}
public void ActivatePlaylist (ObjectPath playlist_id)
{
// TODO: Maybe try to find the playlist if it's not in the dictionary ?
var playlist = playlist_sources[playlist_id.ToString ()];
if (playlist != null) {
Log.DebugFormat ("MPRIS activating playlist {0}", playlist.Name);
ServiceManager.SourceManager.SetActiveSource (playlist);
ServiceManager.PlaybackController.Source = playlist;
ServiceManager.PlaybackController.First ();
}
}
public Playlist [] GetPlaylists (uint index, uint max_count, string order, bool reverse_order)
{
var playlist_sources = ServiceManager.SourceManager.FindSources<AbstractPlaylistSource> ();
switch (order) {
case "Alphabetical":
playlist_sources = playlist_sources.OrderBy (p => p.Name);
break;
case "UserDefined":
playlist_sources = playlist_sources.OrderBy (p => p.Order);
break;
}
if (reverse_order) {
playlist_sources = playlist_sources.Reverse ();
}
var playlists = new List<Playlist> ();
foreach (var pl in playlist_sources.Skip ((int)index).Take ((int)max_count)) {
playlists.Add (BuildPlaylistFromSource (pl));
}
return playlists.ToArray ();
}
#endregion
#region Signals
private void HandlePropertiesChange (string interface_name)
{
PropertiesChangedHandler handler = properties_changed;
if (handler != null) {
lock (changed_properties) {
try {
handler (interface_name, changed_properties, invalidated_properties.ToArray ());
} catch (Exception e) {
Log.Error (e);
}
changed_properties.Clear ();
invalidated_properties.Clear ();
}
}
}
public void HandleSeek ()
{
DBusPlayerSeekedHandler dbus_handler = dbus_seeked;
if (dbus_handler != null) {
dbus_handler (Position);
}
}
public void HandlePlaylistChange (AbstractPlaylistSource source)
{
PlaylistChangedHandler playlist_handler = playlist_changed;
if (playlist_handler != null) {
try {
playlist_handler (BuildPlaylistFromSource (source));
} catch (Exception e) {
Log.Error (e);
}
}
}
public void AddPropertyChange (params PlayerProperties [] properties)
{
AddPropertyChange (player_interface_name, properties.Select (p => p.ToString()));
}
public void AddPropertyChange (params MediaPlayerProperties [] properties)
{
AddPropertyChange (mediaplayer_interface_name, properties.Select (p => p.ToString()));
}
public void AddPropertyChange (params PlaylistProperties [] properties)
{
AddPropertyChange (playlists_interface_name, properties.Select (p => p.ToString()));
}
private void AddPropertyChange (string interface_name, IEnumerable<string> property_names)
{
lock (changed_properties) {
foreach (string prop_name in property_names) {
object current_value = null;
current_properties.TryGetValue (prop_name, out current_value);
var new_value = Get (interface_name, prop_name);
if ((current_value == null) || !(current_value.Equals (new_value))) {
changed_properties [prop_name] = new_value;
current_properties [prop_name] = new_value;
}
}
if (changed_properties.Count > 0) {
HandlePropertiesChange (interface_name);
}
}
}
#endregion
#region Dbus.Properties
private static string [] mediaplayer_properties = { "CanQuit", "CanRaise", "CanSetFullscreen", "Fullscreen",
"HasTrackList", "Identity", "DesktopEntry", "SupportedMimeTypes", "SupportedUriSchemes" };
private static string [] player_properties = { "CanControl", "CanGoNext", "CanGoPrevious", "CanPause",
"CanPlay", "CanSeek", "LoopStatus", "MaximumRate", "Metadata", "MinimumRate", "PlaybackStatus",
"Position", "Rate", "Shuffle", "Volume" };
private static string [] playlist_properties = { "Orderings", "PlaylistCount", "ActivePlaylist" };
public object Get (string interface_name, string propname)
{
if (interface_name == mediaplayer_interface_name) {
switch (propname) {
case "CanQuit":
return CanQuit;
case "CanRaise":
return CanRaise;
case "Fullscreen":
return Fullscreen;
case "CanSetFullscreen":
return CanSetFullscreen;
case "HasTrackList":
return HasTrackList;
case "Identity":
return Identity;
case "DesktopEntry":
return DesktopEntry;
case "SupportedMimeTypes":
return SupportedMimeTypes;
case "SupportedUriSchemes":
return SupportedUriSchemes;
default:
return null;
}
} else if (interface_name == player_interface_name) {
switch (propname) {
case "CanControl":
return CanControl;
case "CanGoNext":
return CanGoNext;
case "CanGoPrevious":
return CanGoPrevious;
case "CanPause":
return CanPause;
case "CanPlay":
return CanPlay;
case "CanSeek":
return CanSeek;
case "MinimumRate":
return MinimumRate;
case "MaximumRate":
return MaximumRate;
case "Rate":
return Rate;
case "Shuffle":
return Shuffle;
case "LoopStatus":
return LoopStatus;
case "PlaybackStatus":
return PlaybackStatus;
case "Position":
return Position;
case "Metadata":
return Metadata;
case "Volume":
return Volume;
default:
return null;
}
} else if (interface_name == playlists_interface_name) {
switch (propname) {
case "Orderings":
return Orderings;
case "PlaylistCount":
return PlaylistCount;
case "ActivePlaylist":
return ActivePlaylist;
default:
return null;
}
} else {
return null;
}
}
public void Set (string interface_name, string propname, object value)
{
if (interface_name == player_interface_name) {
switch (propname) {
case "LoopStatus":
string s = value as string;
if (!String.IsNullOrEmpty (s)) {
LoopStatus = s;
}
break;
case "Shuffle":
if (value is bool) {
Shuffle = (bool)value;
}
break;
case "Volume":
if (value is double) {
Volume = (double)value;
}
break;
}
} else if (interface_name == mediaplayer_interface_name) {
switch (propname) {
case "Fullscreen":
if (value is bool) {
Fullscreen = (bool)value;
}
break;
}
}
}
public IDictionary<string, object> GetAll (string interface_name)
{
var props = new Dictionary<string, object> ();
if (interface_name == mediaplayer_interface_name) {
foreach (string prop in mediaplayer_properties) {
props.Add (prop, Get (interface_name, prop));
}
} else if (interface_name == player_interface_name) {
foreach (string prop in player_properties) {
props.Add (prop, Get (interface_name, prop));
}
} else if (interface_name == playlists_interface_name) {
foreach (string prop in playlist_properties) {
props.Add (prop, Get (interface_name, prop));
}
}
return props;
}
}
#endregion
// Those are all the properties from the Player interface that can trigger the PropertiesChanged signal
// The names must match exactly the names of the properties
public enum PlayerProperties
{
CanControl,
CanGoNext,
CanGoPrevious,
CanPause,
CanPlay,
CanSeek,
MinimumRate,
MaximumRate,
Rate,
Shuffle,
LoopStatus,
PlaybackStatus,
Metadata,
Volume
}
// Those are all the properties from the MediaPlayer interface that can trigger the PropertiesChanged signal
// The names must match exactly the names of the properties
public enum MediaPlayerProperties
{
Fullscreen
}
// Those are all the properties from the Playlist interface that can trigger the PropertiesChanged signal
// The names must match exactly the names of the properties
public enum PlaylistProperties
{
PlaylistCount,
ActivePlaylist
}
}
| |
// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they bagin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace MetroFramework.Drawing.Html.Core.Parse
{
/// <summary>
/// Collection of regular expressions used when parsing
/// </summary>
internal static class RegexParserHelper
{
#region Fields and Consts
/// <summary>
/// Extracts CSS style comments; e.g. /* comment */
/// </summary>
public const string CssComments = @"/\*[^*/]*\*/";
/// <summary>
/// Extracts the media types from a media at-rule; e.g. @media print, 3d, screen {
/// </summary>
public const string CssMediaTypes = @"@media[^\{\}]*\{";
/// <summary>
/// Extracts defined blocks in CSS.
/// WARNING: Blocks will include blocks inside at-rules.
/// </summary>
public const string CssBlocks = @"[^\{\}]*\{[^\{\}]*\}";
/// <summary>
/// Extracts a number; e.g. 5, 6, 7.5, 0.9
/// </summary>
public const string CssNumber = @"{[0-9]+|[0-9]*\.[0-9]+}";
/// <summary>
/// Extracts css percentages from the string; e.g. 100% .5% 5.4%
/// </summary>
public const string CssPercentage = @"([0-9]+|[0-9]*\.[0-9]+)\%"; //TODO: Check if works fine
/// <summary>
/// Extracts CSS lengths; e.g. 9px 3pt .89em
/// </summary>
public const string CssLength = @"([0-9]+|[0-9]*\.[0-9]+)(em|ex|px|in|cm|mm|pt|pc)";
/// <summary>
/// Extracts CSS colors; e.g. black white #fff #fe98cd rgb(5,5,5) rgb(45%, 0, 0)
/// </summary>
public const string CssColors = @"(#\S{6}|#\S{3}|rgb\(\s*[0-9]{1,3}\%?\s*\,\s*[0-9]{1,3}\%?\s*\,\s*[0-9]{1,3}\%?\s*\)|maroon|red|orange|yellow|olive|purple|fuchsia|white|lime|green|navy|blue|aqua|teal|black|silver|gray)";
/// <summary>
/// Extracts line-height values (normal, numbers, lengths, percentages)
/// </summary>
public const string CssLineHeight = "(normal|" + CssNumber + "|" + CssLength + "|" + CssPercentage + ")";
/// <summary>
/// Extracts CSS border styles; e.g. solid none dotted
/// </summary>
public const string CssBorderStyle = @"(none|hidden|dotted|dashed|solid|double|groove|ridge|inset|outset)";
/// <summary>
/// Extracts CSS border widthe; e.g. 1px thin 3em
/// </summary>
public const string CssBorderWidth = "(" + CssLength + "|thin|medium|thick)";
/// <summary>
/// Extracts font-family values
/// </summary>
public const string CssFontFamily = "(\"[^\"]*\"|'[^']*'|\\S+\\s*)(\\s*\\,\\s*(\"[^\"]*\"|'[^']*'|\\S+))*";
/// <summary>
/// Extracts CSS font-styles; e.g. normal italic oblique
/// </summary>
public const string CssFontStyle = "(normal|italic|oblique)";
/// <summary>
/// Extracts CSS font-variant values; e.g. normal, small-caps
/// </summary>
public const string CssFontVariant = "(normal|small-caps)";
/// <summary>
/// Extracts font-weight values; e.g. normal, bold, bolder...
/// </summary>
public const string CssFontWeight = "(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)";
/// <summary>
/// Exracts font sizes: xx-small, larger, small, 34pt, 30%, 2em
/// </summary>
public const string CssFontSize = "(" + CssLength + "|" + CssPercentage + "|xx-small|x-small|small|medium|large|x-large|xx-large|larger|smaller)";
/// <summary>
/// Gets the font-size[/line-height]? on the font shorthand property.
/// Check http://www.w3.org/TR/CSS21/fonts.html#font-shorthand
/// </summary>
public const string CssFontSizeAndLineHeight = CssFontSize + @"(\/" + CssLineHeight + @")?(\s|$)";
/// <summary>
/// Extracts HTML tags
/// </summary>
public const string HtmlTag = @"<[^<>]*>";
/// <summary>
/// Extracts attributes from a HTML tag; e.g. att=value, att="value"
/// </summary>
public const string HmlTagAttributes = "(?<name>\\b\\w+\\b)\\s*=\\s*(?<value>\"[^\"]*\"|'[^']*'|[^\"'<>\\s]+)";
/// <summary>
/// the regexes cache that is used by the parser so not to create regex each time
/// </summary>
private static readonly Dictionary<string, Regex> _regexes = new Dictionary<string, Regex>();
#endregion
/// <summary>
/// Get CSS at rule from the given stylesheet.
/// </summary>
/// <param name="stylesheet">the stylesheet data to retrieve the rule from</param>
/// <param name="startIdx">the index to start the search for the rule, on return will be the value of the end of the found rule</param>
/// <returns>the found at rule or null if not exists</returns>
public static string GetCssAtRules(string stylesheet, ref int startIdx)
{
startIdx = stylesheet.IndexOf('@', startIdx);
if (startIdx > -1)
{
int count = 1;
int endIdx = stylesheet.IndexOf('{', startIdx);
if (endIdx > -1)
{
while (count > 0 && endIdx < stylesheet.Length)
{
endIdx++;
if (stylesheet[endIdx] == '{')
{
count++;
}
else if (stylesheet[endIdx] == '}')
{
count--;
}
}
if (endIdx < stylesheet.Length)
{
var atrule = stylesheet.Substring(startIdx, endIdx - startIdx + 1);
startIdx = endIdx;
return atrule;
}
}
}
return null;
}
/// <summary>
/// Extracts matches from the specified source
/// </summary>
/// <param name="regex">Regular expression to extract matches</param>
/// <param name="source">Source to extract matches</param>
/// <returns>Collection of matches</returns>
public static MatchCollection Match(string regex, string source)
{
var r = GetRegex(regex);
return r.Matches(source);
}
/// <summary>
/// Searches the specified regex on the source
/// </summary>
/// <param name="regex"></param>
/// <param name="source"></param>
/// <returns></returns>
public static string Search(string regex, string source)
{
int position;
return Search(regex, source, out position);
}
/// <summary>
/// Searches the specified regex on the source
/// </summary>
/// <param name="regex"></param>
/// <param name="source"></param>
/// <param name="position"> </param>
/// <returns></returns>
public static string Search(string regex, string source, out int position)
{
MatchCollection matches = Match(regex, source);
if (matches.Count > 0)
{
position = matches[0].Index;
return matches[0].Value;
}
else
{
position = -1;
}
return null;
}
/// <summary>
/// Get regex instance for the given regex string.
/// </summary>
/// <param name="regex">the regex string to use</param>
/// <returns>the regex instance</returns>
private static Regex GetRegex(string regex)
{
Regex r;
if (!_regexes.TryGetValue(regex, out r))
{
r = new Regex(regex, RegexOptions.IgnoreCase | RegexOptions.Singleline);
_regexes[regex] = r;
}
return r;
}
}
}
| |
/*
* Regex.cs - Implementation of the "System.Private.Regex" class.
*
* Copyright (C) 2003 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
{
using System;
using System.Text;
using Platform;
internal sealed class Regex : IDisposable
{
// Internal state.
private IntPtr handle;
private RegexSyntax syntax;
// Constructors.
public Regex(String pattern) : this(pattern, RegexSyntax.PosixBasic) {}
public Regex(String pattern, RegexSyntax syntax)
{
if(pattern == null)
{
throw new ArgumentNullException("pattern");
}
this.syntax = syntax;
if((syntax & RegexSyntax.IgnoreCase) != 0)
{
pattern = pattern.ToLower();
}
if((syntax & RegexSyntax.Wildcard) != 0)
{
pattern = FileSystemToPosix(pattern);
syntax = RegexSyntax.PosixExtended;
}
syntax &= (RegexSyntax.All &
~(RegexSyntax.Debug | RegexSyntax.IgnoreCase));
lock(typeof(Regex))
{
// We lock down "Regex" while we do this because the
// syntax setting in the GNU regex routines is not
// thread-safe without it.
handle = RegexpMethods.CompileWithSyntaxInternal
(pattern, (int)syntax);
}
if(handle == IntPtr.Zero)
{
throw new ArgumentException(S._("Arg_InvalidRegex"));
}
}
// Destructor.
~Regex()
{
Dispose();
}
// Implement the IDisposable interface.
public void Dispose()
{
lock(this)
{
if(handle != IntPtr.Zero)
{
RegexpMethods.FreeInternal(handle);
handle = IntPtr.Zero;
}
}
}
// Determine if a string matches this regular expression.
public bool Match(String str)
{
if(str == null)
{
throw new ArgumentNullException("str");
}
if((syntax & RegexSyntax.IgnoreCase) != 0)
{
str = str.ToLower();
}
lock(this)
{
if(handle != IntPtr.Zero)
{
return (RegexpMethods.ExecInternal
(handle, str, 0) == 0);
}
else
{
throw new ObjectDisposedException
(S._("Exception_Disposed"));
}
}
}
public bool Match(String str, RegexMatchOptions options)
{
if(str == null)
{
throw new ArgumentNullException("str");
}
if((syntax & RegexSyntax.IgnoreCase) != 0)
{
str = str.ToLower();
}
lock(this)
{
if(handle != IntPtr.Zero)
{
options &= RegexMatchOptions.All;
return (RegexpMethods.ExecInternal
(handle, str, (int)options) == 0);
}
else
{
throw new ObjectDisposedException
(S._("Exception_Disposed"));
}
}
}
// Determine if a string matches this regular expression and return
// all of the matches in an array. Returns null if no match.
public RegexMatch[] Match(String str, RegexMatchOptions options,
int maxMatches)
{
if(str == null)
{
throw new ArgumentNullException("str");
}
else if(maxMatches < 0)
{
throw new ArgumentOutOfRangeException
("maxMatches", "Must be non-negative");
}
if((syntax & RegexSyntax.IgnoreCase) != 0)
{
str = str.ToLower();
}
lock(this)
{
if(handle != IntPtr.Zero)
{
options &= RegexMatchOptions.All;
return (RegexMatch[])RegexpMethods.MatchInternal
(handle, str, maxMatches, (int)options,
typeof(RegexMatch));
}
else
{
throw new ObjectDisposedException
(S._("Exception_Disposed"));
}
}
}
// Get the syntax options used by this regex object.
public RegexSyntax Syntax
{
get
{
return syntax;
}
}
// Determine if this regex object has been disposed.
public bool IsDisposed
{
get
{
lock(this)
{
return (handle == IntPtr.Zero);
}
}
}
// Convert a filesystem wildcard into a Posix regex pattern.
private static String FileSystemToPosix(String wildcard)
{
// Special case: match the empty string.
if(wildcard == String.Empty)
{
return "^()$";
}
// Build the new regular expression.
StringBuilder builder = new StringBuilder(wildcard.Length * 2);
char ch;
int posn = 0;
int index, index2;
builder.Append('^');
while(posn < wildcard.Length)
{
ch = wildcard[posn++];
switch(ch)
{
case '*':
{
if((posn + 1) < wildcard.Length &&
wildcard[posn] == '*' &&
(wildcard[posn + 1] == '/' ||
wildcard[posn + 1] == '\\'))
{
// "**/": match arbitrary directory prefixes.
builder.Append("(.*[/\\]|())");
posn += 2;
}
else
{
// Match a sequence of arbitrary characters.
builder.Append('.');
builder.Append('*');
}
}
break;
case '?':
{
// Match an arbitrary character.
builder.Append('.');
}
break;
case '[':
{
// Match a set of characters.
index = wildcard.IndexOf(']', posn);
index2 = wildcard.IndexOf('[', posn);
if(index != -1 &&
(index2 == -1 || index2 > index))
{
// Output the set to the regex.
builder.Append
(wildcard.Substring
(posn - 1, index - (posn - 1) + 1));
posn = index + 1;
}
else
{
// Unmatched '[': treat as a literal character.
builder.Append('\\');
builder.Append(ch);
}
}
break;
case '.': case '^': case '$': case ']':
case '(': case ')':
{
// Escape a special regex character.
builder.Append('\\');
builder.Append(ch);
}
break;
case '/': case '\\':
{
// Match a directory separator, irrespective
// of the type of operating system we are using.
builder.Append('[');
builder.Append('/');
builder.Append('\\');
builder.Append(']');
}
break;
default:
{
builder.Append(ch);
}
break;
}
}
builder.Append('$');
return builder.ToString();
}
}; // class Regex
}; // namespace System.Private
| |
/*
Copyright (C) 2013-2015 MetaMorph Software, Inc
Permission is hereby granted, free of charge, to any person obtaining a
copy of this data, including any software or models in source or binary
form, as well as any drawings, specifications, and documentation
(collectively "the Data"), to deal in the Data without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Data, and to
permit persons to whom the Data 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 Data.
THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using GME.CSharp;
using GME;
using GME.MGA;
using GME.MGA.Core;
using CyPhyGUIs;
using CyPhyClasses = ISIS.GME.Dsml.CyPhyML.Classes;
namespace CyPhy2MfgBom
{
/// <summary>
/// This class implements the necessary COM interfaces for a GME interpreter component.
/// </summary>
[Guid(ComponentConfig.guid),
ProgId(ComponentConfig.progID),
ClassInterface(ClassInterfaceType.AutoDual)]
[ComVisible(true)]
public class CyPhy2MfgBomInterpreter : IMgaComponentEx, IGMEVersionInfo, ICyPhyInterpreter
{
/// <summary>
/// Contains information about the GUI event that initiated the invocation.
/// </summary>
public enum ComponentStartMode
{
GME_MAIN_START = 0, // Not used by GME
GME_BROWSER_START = 1, // Right click in the GME Tree Browser window
GME_CONTEXT_START = 2, // Using the context menu by right clicking a model element in the GME modeling window
GME_EMBEDDED_START = 3, // Not used by GME
GME_MENU_START = 16, // Clicking on the toolbar icon, or using the main menu
GME_BGCONTEXT_START = 18, // Using the context menu by right clicking the background of the GME modeling window
GME_ICON_START = 32, // Not used by GME
GME_SILENT_MODE = 128 // Not used by GME, available to testers not using GME
}
/// <summary>
/// This function is called for each interpreter invocation before Main.
/// Don't perform MGA operations here unless you open a transaction.
/// </summary>
/// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param>
public void Initialize(MgaProject project)
{
if (Logger == null)
Logger = new GMELogger(project, ComponentName);
MgaGateway = new MgaGateway(project);
project.CreateTerritoryWithoutSink(out MgaGateway.territory);
}
#region CyPhyGUIs
/// <summary>
/// ProgId of the configuration class of this interpreter.
/// </summary>
public string InterpreterConfigurationProgId
{
get
{
return (typeof(CyPhyGUIs.NullInterpreterConfiguration).GetCustomAttributes(typeof(ProgIdAttribute), false)[0] as ProgIdAttribute).Value;
}
}
/// <summary>
/// Preconfig gets called first. No transaction is open, but one may be opened.
/// In this function model may be processed and some object ids get serialized
/// and returned as preconfiguration (project-wise configuration).
/// </summary>
/// <param name="preConfigParameters"></param>
/// <returns>Null if no configuration is required by the DoGUIConfig.</returns>
public IInterpreterPreConfiguration PreConfig(IPreConfigParameters preConfigParameters)
{
return null;
}
/// <summary>
/// Shows a form for the user to select/change settings through a GUI. All interactive
/// GUI operations MUST happen within this function scope.
/// </summary>
/// <param name="preConfig">Result of PreConfig</param>
/// <param name="previousConfig">Previous configuration to initialize the GUI.</param>
/// <returns>Null if operation is canceled by the user. Otherwise returns with a new
/// configuration object.</returns>
public IInterpreterConfiguration DoGUIConfiguration(
IInterpreterPreConfiguration preConfig,
IInterpreterConfiguration previousConfig)
{
return new NullInterpreterConfiguration();
}
/// <summary>
/// No GUI and interactive elements are allowed within this function.
/// </summary>
/// <param name="parameters">Main parameters for this run and GUI configuration.</param>
/// <returns>Result of the run, which contains a success flag.</returns>
public IInterpreterResult Main(IInterpreterMainParameters parameters)
{
this.mainParameters = parameters;
//this.runtime = new Queue<Tuple<string, TimeSpan>>();
//this.runtime.Clear();
this.result = new InterpreterResult()
{
Success = true
};
try
{
BOMVisitor visitor = new BOMVisitor()
{
Logger = Logger,
Traceability = this.result.Traceability
};
String nameFCO = null;
int designQuantity = 1;
List<String> listSupplierAffinity = null;
MgaGateway.PerformInTransaction(delegate
{
// Call Elaborator
var elaboratorSuccess = this.CallElaborator(this.mainParameters.Project,
this.mainParameters.CurrentFCO,
this.mainParameters.SelectedFCOs,
this.mainParameters.StartModeParam);
this.UpdateSuccess("Elaborator", elaboratorSuccess);
// Parse design
var tb = CyPhyClasses.TestBench.Cast(parameters.CurrentFCO);
visitor.visit(tb);
nameFCO = this.mainParameters.CurrentFCO.Name;
var propDesignQuantity = tb.Children
.PropertyCollection
.FirstOrDefault(p => p.Name == "design_quantity");
if (propDesignQuantity != null)
{
int val;
if (int.TryParse(propDesignQuantity.Attributes.Value, out val))
{
designQuantity = val;
}
else
{
Logger.WriteWarning("The property <a href=\"mga:{0}\">{1}</a> has a non-integer value of \"{2}\". Setting to default of 1.",
propDesignQuantity.ID,
propDesignQuantity.Name,
propDesignQuantity.Attributes.Value);
}
}
else
{
Logger.WriteWarning("No property named \"design_quantity\" found. Assuming quantity of 1.");
}
var metricPartCostPerDesign = tb.Children
.MetricCollection
.FirstOrDefault(m => m.Name == "part_cost_per_design");
if (metricPartCostPerDesign == null)
{
var manifest = AVM.DDP.MetaTBManifest.OpenForUpdate(this.mainParameters.OutputDirectory);
var metric = new AVM.DDP.MetaTBManifest.Metric()
{
Name = "part_cost_per_design",
DisplayedName = "Part Cost Per Design",
Unit = "USD",
GMEID = null
};
if (manifest.Metrics == null)
{
manifest.Metrics = new List<AVM.DDP.MetaTBManifest.Metric>();
}
manifest.Metrics.Add(metric);
manifest.Serialize(this.mainParameters.OutputDirectory);
}
var propSupplierAffinity = tb.Children
.PropertyCollection
.FirstOrDefault(p => p.Name == "supplier_affinity");
if (propSupplierAffinity != null &&
!String.IsNullOrWhiteSpace(propSupplierAffinity.Attributes.Value))
{
listSupplierAffinity = propSupplierAffinity.Attributes
.Value
.Split(',')
.Select(s => s.Trim())
.ToList();
}
},
transactiontype_enum.TRANSACTION_NON_NESTED,
abort: true);
// Serialize BOM to file
var bom = visitor.bom;
var filenameBom = nameFCO + "_bom.json";
var pathBom = Path.Combine(this.mainParameters.OutputDirectory,
filenameBom);
using (StreamWriter outfile = new StreamWriter(pathBom))
{
outfile.Write(bom.Serialize());
}
// Create CostEstimationRequest
var request = new MfgBom.CostEstimation.CostEstimationRequest()
{
bom = bom,
design_quantity = designQuantity,
supplier_affinity = listSupplierAffinity
};
var filenameRequest = nameFCO + "_cost_estimate_request.json";
var pathRequest = Path.Combine(this.mainParameters.OutputDirectory,
filenameRequest);
using (StreamWriter outfile = new StreamWriter(pathRequest))
{
outfile.Write(request.Serialize());
}
var tbManifest = AVM.DDP.MetaTBManifest.OpenForUpdate(this.mainParameters.OutputDirectory);
tbManifest.AddArtifact(filenameBom, "CyPhy2MfgBom::BOM");
tbManifest.AddArtifact(filenameRequest, "CyPhy2MfgBom::CostEstimationRequest");
tbManifest.Serialize(this.mainParameters.OutputDirectory);
using (var batRunBomCostAnalysis = new StreamWriter(Path.Combine(this.mainParameters.OutputDirectory,
"runBomCostAnalysis.bat")))
{
batRunBomCostAnalysis.Write(CyPhy2MfgBom.Properties.Resources.runBomCostAnalysis);
}
this.result.RunCommand = "runBomCostAnalysis.bat";
if (this.result.Success)
{
Logger.WriteInfo("Generated files are here: <a href=\"file:///{0}\" target=\"_blank\">{0}</a>", this.mainParameters.OutputDirectory);
Logger.WriteInfo("CyPhy2MfgBom has finished. [SUCCESS: {0}, Labels: {1}]", this.result.Success, this.result.Labels);
}
else
{
Logger.WriteError("CyPhy2MfgBom failed! See error messages above.");
}
}
catch (Exception ex)
{
Logger.WriteError("Exception: {0}<br> {1}", ex.Message, ex.StackTrace);
}
return this.result;
}
#endregion
private bool CallElaborator(
MgaProject project,
MgaFCO currentobj,
MgaFCOs selectedobjs,
int param,
bool expand = true)
{
bool result = false;
try
{
this.Logger.WriteDebug("Elaborating model...");
var elaborator = new CyPhyElaborateCS.CyPhyElaborateCSInterpreter();
elaborator.Initialize(project);
int verbosity = 128;
result = elaborator.RunInTransaction(project, currentobj, selectedobjs, verbosity);
if (this.result.Traceability == null)
{
this.result.Traceability = new META.MgaTraceability();
}
if (elaborator.Traceability != null)
{
elaborator.Traceability.CopyTo(this.result.Traceability);
}
this.Logger.WriteDebug("Elaboration is done.");
}
catch (Exception ex)
{
this.Logger.WriteError("Exception occurred in Elaborator : {0}", ex.ToString());
result = false;
}
return result;
}
#region IMgaComponentEx Members
MgaGateway MgaGateway { get; set; }
GMELogger Logger { get; set; }
public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
{
if (!enabled)
{
return;
}
try
{
if (Logger == null)
{
Logger = new GMELogger(project, ComponentName);
}
MgaGateway = new MgaGateway(project);
project.CreateTerritoryWithoutSink(out MgaGateway.territory);
this.mainParameters = new InterpreterMainParameters()
{
Project = project,
CurrentFCO = currentobj as MgaFCO,
SelectedFCOs = selectedobjs,
StartModeParam = param
};
Main(this.mainParameters);
//this.PrintRuntimeStatistics();
}
catch (Exception ex)
{
Logger.WriteError("Exception: {0}<br> {1}", ex.Message, ex.StackTrace);
}
finally
{
if (MgaGateway != null &&
MgaGateway.territory != null)
{
MgaGateway.territory.Destroy();
}
MgaGateway = null;
project = null;
currentobj = null;
selectedobjs = null;
DisposeLogger();
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
public void DisposeLogger()
{
if (Logger != null)
{
Logger.Dispose();
Logger = null;
}
}
//private Queue<Tuple<string, TimeSpan>> runtime = new Queue<Tuple<string, TimeSpan>>();
private DateTime startTime = DateTime.Now;
/*private void PrintRuntimeStatistics()
{
Logger.WriteDebug("======================================================");
Logger.WriteDebug("Start time: {0}", this.startTime);
foreach (var time in this.runtime)
{
Logger.WriteDebug("{0} = {1}", time.Item1, time.Item2);
}
Logger.WriteDebug("======================================================");
}*/
/// <summary>
/// Parameter of this run.
/// </summary>
private IInterpreterMainParameters mainParameters { get; set; }
/// <summary>
/// Result of the latest run of this interpreter.
/// </summary>
private InterpreterResult result = new InterpreterResult();
private void UpdateSuccess(string message, bool success)
{
this.result.Success = this.result.Success && success;
//this.runtime.Enqueue(new Tuple<string, TimeSpan>(message, DateTime.Now - this.startTime));
if (success)
{
Logger.WriteInfo("{0} : OK", message);
}
else
{
Logger.WriteError("{0} : FAILED", message);
}
}
private ComponentStartMode Convert(int param)
{
switch (param)
{
case (int)ComponentStartMode.GME_BGCONTEXT_START:
return ComponentStartMode.GME_BGCONTEXT_START;
case (int)ComponentStartMode.GME_BROWSER_START:
return ComponentStartMode.GME_BROWSER_START;
case (int)ComponentStartMode.GME_CONTEXT_START:
return ComponentStartMode.GME_CONTEXT_START;
case (int)ComponentStartMode.GME_EMBEDDED_START:
return ComponentStartMode.GME_EMBEDDED_START;
case (int)ComponentStartMode.GME_ICON_START:
return ComponentStartMode.GME_ICON_START;
case (int)ComponentStartMode.GME_MAIN_START:
return ComponentStartMode.GME_MAIN_START;
case (int)ComponentStartMode.GME_MENU_START:
return ComponentStartMode.GME_MENU_START;
case (int)ComponentStartMode.GME_SILENT_MODE:
return ComponentStartMode.GME_SILENT_MODE;
}
return ComponentStartMode.GME_SILENT_MODE;
}
#region Component Information
public string ComponentName
{
get { return GetType().Name; }
}
public string ComponentProgID
{
get
{
return ComponentConfig.progID;
}
}
public componenttype_enum ComponentType
{
get { return ComponentConfig.componentType; }
}
public string Paradigm
{
get { return ComponentConfig.paradigmName; }
}
#endregion
#region Enabling
bool enabled = true;
public void Enable(bool newval)
{
enabled = newval;
}
#endregion
#region Interactive Mode
protected bool interactiveMode = true;
public bool InteractiveMode
{
get
{
return interactiveMode;
}
set
{
interactiveMode = value;
}
}
#endregion
#region Custom Parameters
SortedDictionary<string, object> componentParameters = null;
public object get_ComponentParameter(string Name)
{
if (Name == "type")
return "csharp";
if (Name == "path")
return GetType().Assembly.Location;
if (Name == "fullname")
return GetType().FullName;
object value;
if (componentParameters != null && componentParameters.TryGetValue(Name, out value))
{
return value;
}
return null;
}
public void set_ComponentParameter(string Name, object pVal)
{
if (componentParameters == null)
{
componentParameters = new SortedDictionary<string, object>();
}
componentParameters[Name] = pVal;
}
#endregion
#region Unused Methods
// Old interface, it is never called for MgaComponentEx interfaces
public void Invoke(MgaProject Project, MgaFCOs selectedobjs, int param)
{
throw new NotImplementedException();
}
// Not used by GME
public void ObjectsInvokeEx(MgaProject Project, MgaObject currentobj, MgaObjects selectedobjs, int param)
{
throw new NotImplementedException();
}
#endregion
#endregion
#region IMgaVersionInfo Members
public GMEInterfaceVersion_enum version
{
get { return GMEInterfaceVersion_enum.GMEInterfaceVersion_Current; }
}
#endregion
#region Registration Helpers
[ComRegisterFunctionAttribute]
public static void GMERegister(Type t)
{
Registrar.RegisterComponentsInGMERegistry();
}
[ComUnregisterFunctionAttribute]
public static void GMEUnRegister(Type t)
{
Registrar.UnregisterComponentsInGMERegistry();
}
#endregion
}
}
| |
// Copyright (c) 2017 Jan Pluskal, Miroslav Slivka, Viliam Letavay
//
//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.Diagnostics;
using System.IO;
using System.Text;
using Castle.MicroKernel.Handlers;
using Castle.Windsor;
using Netfox.Core.Database;
using Netfox.Core.Models.Exports;
using Netfox.Framework.Models;
using Netfox.Framework.Models.Interfaces;
using Netfox.Framework.Models.Snoopers;
namespace Netfox.Framework.ApplicationProtocolExport.Snoopers
{
public abstract class SnooperBase : ISnooper
{
/// <summary>
/// todo this should be DB collection
/// </summary>
private readonly List<SnooperExportBase> _snooperExportsList = new List<SnooperExportBase>();
protected Boolean ForceExportOnAllConversations;
protected SelectedConversations SelectedConversations;
protected IEnumerable<SnooperExportBase> SourceExports;
private DirectoryInfo _exportBaseDirectory;
private readonly List<SnooperExportBase> _snooperExportCache = new List<SnooperExportBase>();
/// <summary>
/// Parameterless constructor has to be always present in derived classes
/// </summary>
protected SnooperBase()
{
this.IsPrototype = true;
}
protected SnooperBase(
WindsorContainer investigationWindsorContainer,
DirectoryInfo exportDirectory)
{
this.InvestigationWindsorContainer = investigationWindsorContainer;
this.ExportBaseDirectory = new DirectoryInfo(Path.Combine(exportDirectory.FullName, this.Name));
this.SnooperExportCollection = this.InvestigationWindsorContainer.Resolve<VirtualizingObservableDBSetPagedCollection<SnooperExportBase>>();
}
public VirtualizingObservableDBSetPagedCollection<SnooperExportBase> SnooperExportCollection { get; set; }
protected SnooperBase(
WindsorContainer investigationWindsorContainer,
SelectedConversations conversations,
DirectoryInfo exportDirectory,
Boolean ignoreApplicationTags) : this(investigationWindsorContainer, exportDirectory)
{
this.SelectedConversations = conversations;
this.ForceExportOnAllConversations = ignoreApplicationTags;
}
protected SnooperBase(
WindsorContainer investigationWindsorContainer,
IEnumerable<SnooperExportBase> sourceExports,
DirectoryInfo exportDirectory) : this(investigationWindsorContainer, exportDirectory)
{
this.SourceExports = sourceExports;
}
protected SnooperBase(WindsorContainer investigationWindsorContainer, IEnumerable<FileInfo> sourceFiles, DirectoryInfo exportDirectory): this(investigationWindsorContainer, exportDirectory)
{
//this.CreateExportDirectory();
this.SourceFiles = sourceFiles;
}
public WindsorContainer InvestigationWindsorContainer { get; }
public IEnumerable<FileInfo> SourceFiles { get; set; }
protected internal L7Conversation CurrentConversation { get; set; }
protected internal DirectoryInfo ExportBaseDirectory
{
get { return this._exportBaseDirectory; }
private set
{
this._exportBaseDirectory = value;
this.CreateExportDirectory();
}
}
protected SnooperExportBase SnooperExport { get; set; }
private Boolean IsPrototype { get; }
public abstract String Description { get; }
public abstract Int32[] KnownApplicationPorts { get; }
//private string _exportDirectory;
public abstract String Name { get; }
public abstract String[] ProtocolNBARName { get; }
public abstract SnooperExportBase PrototypExportObject { get; }
public void Run()
{
if(this.IsPrototype)
{
Console.WriteLine("Prototype of snooper cannot be used to export data!");
return;
}
// create export directory if it doesn't exist
if(!this.ExportBaseDirectory.Exists) { this.ExportBaseDirectory.Create(); }
try {
this.RunBody();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
this.SnooperExport.AddExportReport(ExportReport.ReportLevel.Error, this.Name, "unexpected exception caught",new []{this.CurrentConversation}, ex);
this.FinalizeExports();
}
this.SnooperExport?.CheckExportState();
this.FlushExportCache();
}
public override String ToString()
{
var sb = new StringBuilder();
sb.AppendLine("Export:");
sb.AppendLine(this.SnooperExport.ToString());
return sb.ToString();
}
protected void CreateExportDirectory()
{
if(!this.ExportBaseDirectory.Exists)
{
Console.WriteLine("creating " + this.ExportBaseDirectory.FullName);
this.ExportBaseDirectory.Create();
return;
}
Console.WriteLine(this.ExportBaseDirectory.Name + "already exists");
}
protected abstract SnooperExportBase CreateSnooperExport();
protected void OnAfterDataExporting() => this.SnooperExport.OnAfterDataExporting();
protected void OnAfterProtocolParsing() => this.SnooperExport.OnAfterProtocolParsing();
protected void OnBeforeDataExporting() => this.SnooperExport.OnBeforeDataExporting();
protected void OnBeforeProtocolParsing() => this.SnooperExport.OnBeforeProtocolParsing();
protected void OnConversationProcessingBegin() => this.SnooperExport = this.CreateSnooperExport();
protected void OnConversationProcessingEnd() { this.FinalizeExports(); }
protected void ProcessAssignedConversations()
{
this.SelectedConversations.LockSelectedConversations();
//Main cycle on all conversations
while(this.SelectedConversations.TryGetNextConversations(this.GetType(), out var currentConversation, out _))
{
var selectedL7Conversations = new List<L7Conversation>();
if(currentConversation is L7Conversation l7Conversation) //todo refactor to SnooperBase.. or make more readable.. to method or somenting...
{
selectedL7Conversations.Add(l7Conversation);
}
else if(currentConversation is L4Conversation l4Conversation) {
selectedL7Conversations.AddRange(l4Conversation.L7Conversations);
}
else if(currentConversation is L3Conversation l3Conversation) { selectedL7Conversations.AddRange(l3Conversation.L7Conversations); }
foreach(var selectedL7Conversation in selectedL7Conversations)
{
this.CurrentConversation = selectedL7Conversation;
if(!this.ForceExportOnAllConversations && !this.CurrentConversation.IsXyProtocolConversation(this.ProtocolNBARName))
{
continue;
}
this.OnConversationProcessingBegin();
this.ProcessConversation();
this.OnConversationProcessingEnd();
}
}
}
private void FlushExportCache()
{
try
{
this.SnooperExportCollection.AddRange(this._snooperExportCache);
}
catch (HandlerException)
{
Debugger.Break();
}
}
protected abstract void ProcessConversation();
protected abstract void RunBody();
private void FinalizeExports()
{
this.SnooperExport.OnAfterDataExporting();
this._snooperExportsList.Add(this.SnooperExport);
this.OnSnooperExport(this.SnooperExport);
}
private void OnSnooperExport(SnooperExportBase snooperExportBase)
{
if(this.SnooperExportCollection.IsNotifyImmidiately)
{
this.SnooperExportCollection.Add(snooperExportBase);
}
else
{
this._snooperExportCache.Add(snooperExportBase);
}
}
}
}
| |
/*
* OANDA v20 REST API
*
* The full OANDA v20 REST API Specification. This specification defines how to interact with v20 Accounts, Trades, Orders, Pricing and more.
*
* OpenAPI spec version: 3.0.15
* Contact: api@oanda.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace Oanda.RestV20.Model
{
/// <summary>
/// A StopOrderRequest specifies the parameters that may be set when creating a Stop Order.
/// </summary>
[DataContract]
public partial class StopOrderRequest : IEquatable<StopOrderRequest>, IValidatableObject
{
/// <summary>
/// The type of the Order to Create. Must be set to \"STOP\" when creating a Stop Order.
/// </summary>
/// <value>The type of the Order to Create. Must be set to \"STOP\" when creating a Stop Order.</value>
[JsonConverter(typeof(StringEnumConverter))]
public enum TypeEnum
{
/// <summary>
/// Enum MARKET for "MARKET"
/// </summary>
[EnumMember(Value = "MARKET")]
MARKET,
/// <summary>
/// Enum LIMIT for "LIMIT"
/// </summary>
[EnumMember(Value = "LIMIT")]
LIMIT,
/// <summary>
/// Enum STOP for "STOP"
/// </summary>
[EnumMember(Value = "STOP")]
STOP,
/// <summary>
/// Enum MARKETIFTOUCHED for "MARKET_IF_TOUCHED"
/// </summary>
[EnumMember(Value = "MARKET_IF_TOUCHED")]
MARKETIFTOUCHED,
/// <summary>
/// Enum TAKEPROFIT for "TAKE_PROFIT"
/// </summary>
[EnumMember(Value = "TAKE_PROFIT")]
TAKEPROFIT,
/// <summary>
/// Enum STOPLOSS for "STOP_LOSS"
/// </summary>
[EnumMember(Value = "STOP_LOSS")]
STOPLOSS,
/// <summary>
/// Enum TRAILINGSTOPLOSS for "TRAILING_STOP_LOSS"
/// </summary>
[EnumMember(Value = "TRAILING_STOP_LOSS")]
TRAILINGSTOPLOSS
}
/// <summary>
/// The time-in-force requested for the Stop Order.
/// </summary>
/// <value>The time-in-force requested for the Stop Order.</value>
[JsonConverter(typeof(StringEnumConverter))]
public enum TimeInForceEnum
{
/// <summary>
/// Enum GTC for "GTC"
/// </summary>
[EnumMember(Value = "GTC")]
GTC,
/// <summary>
/// Enum GTD for "GTD"
/// </summary>
[EnumMember(Value = "GTD")]
GTD,
/// <summary>
/// Enum GFD for "GFD"
/// </summary>
[EnumMember(Value = "GFD")]
GFD,
/// <summary>
/// Enum FOK for "FOK"
/// </summary>
[EnumMember(Value = "FOK")]
FOK,
/// <summary>
/// Enum IOC for "IOC"
/// </summary>
[EnumMember(Value = "IOC")]
IOC
}
/// <summary>
/// Specification of how Positions in the Account are modified when the Order is filled.
/// </summary>
/// <value>Specification of how Positions in the Account are modified when the Order is filled.</value>
[JsonConverter(typeof(StringEnumConverter))]
public enum PositionFillEnum
{
/// <summary>
/// Enum OPENONLY for "OPEN_ONLY"
/// </summary>
[EnumMember(Value = "OPEN_ONLY")]
OPENONLY,
/// <summary>
/// Enum REDUCEFIRST for "REDUCE_FIRST"
/// </summary>
[EnumMember(Value = "REDUCE_FIRST")]
REDUCEFIRST,
/// <summary>
/// Enum REDUCEONLY for "REDUCE_ONLY"
/// </summary>
[EnumMember(Value = "REDUCE_ONLY")]
REDUCEONLY,
/// <summary>
/// Enum DEFAULT for "DEFAULT"
/// </summary>
[EnumMember(Value = "DEFAULT")]
DEFAULT,
/// <summary>
/// Enum POSITIONDEFAULT for "POSITION_DEFAULT"
/// </summary>
[EnumMember(Value = "POSITION_DEFAULT")]
POSITIONDEFAULT
}
/// <summary>
/// Specification of what component of a price should be used for comparison when determining if the Order should be filled.
/// </summary>
/// <value>Specification of what component of a price should be used for comparison when determining if the Order should be filled.</value>
[JsonConverter(typeof(StringEnumConverter))]
public enum TriggerConditionEnum
{
/// <summary>
/// Enum DEFAULT for "DEFAULT"
/// </summary>
[EnumMember(Value = "DEFAULT")]
DEFAULT,
/// <summary>
/// Enum TRIGGERDEFAULT for "TRIGGER_DEFAULT"
/// </summary>
[EnumMember(Value = "TRIGGER_DEFAULT")]
TRIGGERDEFAULT,
/// <summary>
/// Enum INVERSE for "INVERSE"
/// </summary>
[EnumMember(Value = "INVERSE")]
INVERSE,
/// <summary>
/// Enum BID for "BID"
/// </summary>
[EnumMember(Value = "BID")]
BID,
/// <summary>
/// Enum ASK for "ASK"
/// </summary>
[EnumMember(Value = "ASK")]
ASK,
/// <summary>
/// Enum MID for "MID"
/// </summary>
[EnumMember(Value = "MID")]
MID
}
/// <summary>
/// The type of the Order to Create. Must be set to \"STOP\" when creating a Stop Order.
/// </summary>
/// <value>The type of the Order to Create. Must be set to \"STOP\" when creating a Stop Order.</value>
[DataMember(Name="type", EmitDefaultValue=false)]
public TypeEnum? Type { get; set; }
/// <summary>
/// The time-in-force requested for the Stop Order.
/// </summary>
/// <value>The time-in-force requested for the Stop Order.</value>
[DataMember(Name="timeInForce", EmitDefaultValue=false)]
public TimeInForceEnum? TimeInForce { get; set; }
/// <summary>
/// Specification of how Positions in the Account are modified when the Order is filled.
/// </summary>
/// <value>Specification of how Positions in the Account are modified when the Order is filled.</value>
[DataMember(Name="positionFill", EmitDefaultValue=false)]
public PositionFillEnum? PositionFill { get; set; }
/// <summary>
/// Specification of what component of a price should be used for comparison when determining if the Order should be filled.
/// </summary>
/// <value>Specification of what component of a price should be used for comparison when determining if the Order should be filled.</value>
[DataMember(Name="triggerCondition", EmitDefaultValue=false)]
public TriggerConditionEnum? TriggerCondition { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="StopOrderRequest" /> class.
/// </summary>
/// <param name="Type">The type of the Order to Create. Must be set to \"STOP\" when creating a Stop Order..</param>
/// <param name="Instrument">The Stop Order's Instrument..</param>
/// <param name="Units">The quantity requested to be filled by the Stop Order. A posititive number of units results in a long Order, and a negative number of units results in a short Order..</param>
/// <param name="Price">The price threshold specified for the Stop Order. The Stop Order will only be filled by a market price that is equal to or worse than this price..</param>
/// <param name="PriceBound">The worst market price that may be used to fill this Stop Order. If the market gaps and crosses through both the price and the priceBound, the Stop Order will be cancelled instead of being filled..</param>
/// <param name="TimeInForce">The time-in-force requested for the Stop Order..</param>
/// <param name="GtdTime">The date/time when the Stop Order will be cancelled if its timeInForce is \"GTD\"..</param>
/// <param name="PositionFill">Specification of how Positions in the Account are modified when the Order is filled..</param>
/// <param name="TriggerCondition">Specification of what component of a price should be used for comparison when determining if the Order should be filled..</param>
/// <param name="ClientExtensions">ClientExtensions.</param>
/// <param name="TakeProfitOnFill">TakeProfitOnFill.</param>
/// <param name="StopLossOnFill">StopLossOnFill.</param>
/// <param name="TrailingStopLossOnFill">TrailingStopLossOnFill.</param>
/// <param name="TradeClientExtensions">TradeClientExtensions.</param>
public StopOrderRequest(TypeEnum? Type = default(TypeEnum?), string Instrument = default(string), string Units = default(string), string Price = default(string), string PriceBound = default(string), TimeInForceEnum? TimeInForce = default(TimeInForceEnum?), string GtdTime = default(string), PositionFillEnum? PositionFill = default(PositionFillEnum?), TriggerConditionEnum? TriggerCondition = default(TriggerConditionEnum?), ClientExtensions ClientExtensions = default(ClientExtensions), TakeProfitDetails TakeProfitOnFill = default(TakeProfitDetails), StopLossDetails StopLossOnFill = default(StopLossDetails), TrailingStopLossDetails TrailingStopLossOnFill = default(TrailingStopLossDetails), ClientExtensions TradeClientExtensions = default(ClientExtensions))
{
this.Type = Type;
this.Instrument = Instrument;
this.Units = Units;
this.Price = Price;
this.PriceBound = PriceBound;
this.TimeInForce = TimeInForce;
this.GtdTime = GtdTime;
this.PositionFill = PositionFill;
this.TriggerCondition = TriggerCondition;
this.ClientExtensions = ClientExtensions;
this.TakeProfitOnFill = TakeProfitOnFill;
this.StopLossOnFill = StopLossOnFill;
this.TrailingStopLossOnFill = TrailingStopLossOnFill;
this.TradeClientExtensions = TradeClientExtensions;
}
/// <summary>
/// The Stop Order's Instrument.
/// </summary>
/// <value>The Stop Order's Instrument.</value>
[DataMember(Name="instrument", EmitDefaultValue=false)]
public string Instrument { get; set; }
/// <summary>
/// The quantity requested to be filled by the Stop Order. A posititive number of units results in a long Order, and a negative number of units results in a short Order.
/// </summary>
/// <value>The quantity requested to be filled by the Stop Order. A posititive number of units results in a long Order, and a negative number of units results in a short Order.</value>
[DataMember(Name="units", EmitDefaultValue=false)]
public string Units { get; set; }
/// <summary>
/// The price threshold specified for the Stop Order. The Stop Order will only be filled by a market price that is equal to or worse than this price.
/// </summary>
/// <value>The price threshold specified for the Stop Order. The Stop Order will only be filled by a market price that is equal to or worse than this price.</value>
[DataMember(Name="price", EmitDefaultValue=false)]
public string Price { get; set; }
/// <summary>
/// The worst market price that may be used to fill this Stop Order. If the market gaps and crosses through both the price and the priceBound, the Stop Order will be cancelled instead of being filled.
/// </summary>
/// <value>The worst market price that may be used to fill this Stop Order. If the market gaps and crosses through both the price and the priceBound, the Stop Order will be cancelled instead of being filled.</value>
[DataMember(Name="priceBound", EmitDefaultValue=false)]
public string PriceBound { get; set; }
/// <summary>
/// The date/time when the Stop Order will be cancelled if its timeInForce is \"GTD\".
/// </summary>
/// <value>The date/time when the Stop Order will be cancelled if its timeInForce is \"GTD\".</value>
[DataMember(Name="gtdTime", EmitDefaultValue=false)]
public string GtdTime { get; set; }
/// <summary>
/// Gets or Sets ClientExtensions
/// </summary>
[DataMember(Name="clientExtensions", EmitDefaultValue=false)]
public ClientExtensions ClientExtensions { get; set; }
/// <summary>
/// Gets or Sets TakeProfitOnFill
/// </summary>
[DataMember(Name="takeProfitOnFill", EmitDefaultValue=false)]
public TakeProfitDetails TakeProfitOnFill { get; set; }
/// <summary>
/// Gets or Sets StopLossOnFill
/// </summary>
[DataMember(Name="stopLossOnFill", EmitDefaultValue=false)]
public StopLossDetails StopLossOnFill { get; set; }
/// <summary>
/// Gets or Sets TrailingStopLossOnFill
/// </summary>
[DataMember(Name="trailingStopLossOnFill", EmitDefaultValue=false)]
public TrailingStopLossDetails TrailingStopLossOnFill { get; set; }
/// <summary>
/// Gets or Sets TradeClientExtensions
/// </summary>
[DataMember(Name="tradeClientExtensions", EmitDefaultValue=false)]
public ClientExtensions TradeClientExtensions { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class StopOrderRequest {\n");
sb.Append(" Type: ").Append(Type).Append("\n");
sb.Append(" Instrument: ").Append(Instrument).Append("\n");
sb.Append(" Units: ").Append(Units).Append("\n");
sb.Append(" Price: ").Append(Price).Append("\n");
sb.Append(" PriceBound: ").Append(PriceBound).Append("\n");
sb.Append(" TimeInForce: ").Append(TimeInForce).Append("\n");
sb.Append(" GtdTime: ").Append(GtdTime).Append("\n");
sb.Append(" PositionFill: ").Append(PositionFill).Append("\n");
sb.Append(" TriggerCondition: ").Append(TriggerCondition).Append("\n");
sb.Append(" ClientExtensions: ").Append(ClientExtensions).Append("\n");
sb.Append(" TakeProfitOnFill: ").Append(TakeProfitOnFill).Append("\n");
sb.Append(" StopLossOnFill: ").Append(StopLossOnFill).Append("\n");
sb.Append(" TrailingStopLossOnFill: ").Append(TrailingStopLossOnFill).Append("\n");
sb.Append(" TradeClientExtensions: ").Append(TradeClientExtensions).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as StopOrderRequest);
}
/// <summary>
/// Returns true if StopOrderRequest instances are equal
/// </summary>
/// <param name="other">Instance of StopOrderRequest to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(StopOrderRequest other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Type == other.Type ||
this.Type != null &&
this.Type.Equals(other.Type)
) &&
(
this.Instrument == other.Instrument ||
this.Instrument != null &&
this.Instrument.Equals(other.Instrument)
) &&
(
this.Units == other.Units ||
this.Units != null &&
this.Units.Equals(other.Units)
) &&
(
this.Price == other.Price ||
this.Price != null &&
this.Price.Equals(other.Price)
) &&
(
this.PriceBound == other.PriceBound ||
this.PriceBound != null &&
this.PriceBound.Equals(other.PriceBound)
) &&
(
this.TimeInForce == other.TimeInForce ||
this.TimeInForce != null &&
this.TimeInForce.Equals(other.TimeInForce)
) &&
(
this.GtdTime == other.GtdTime ||
this.GtdTime != null &&
this.GtdTime.Equals(other.GtdTime)
) &&
(
this.PositionFill == other.PositionFill ||
this.PositionFill != null &&
this.PositionFill.Equals(other.PositionFill)
) &&
(
this.TriggerCondition == other.TriggerCondition ||
this.TriggerCondition != null &&
this.TriggerCondition.Equals(other.TriggerCondition)
) &&
(
this.ClientExtensions == other.ClientExtensions ||
this.ClientExtensions != null &&
this.ClientExtensions.Equals(other.ClientExtensions)
) &&
(
this.TakeProfitOnFill == other.TakeProfitOnFill ||
this.TakeProfitOnFill != null &&
this.TakeProfitOnFill.Equals(other.TakeProfitOnFill)
) &&
(
this.StopLossOnFill == other.StopLossOnFill ||
this.StopLossOnFill != null &&
this.StopLossOnFill.Equals(other.StopLossOnFill)
) &&
(
this.TrailingStopLossOnFill == other.TrailingStopLossOnFill ||
this.TrailingStopLossOnFill != null &&
this.TrailingStopLossOnFill.Equals(other.TrailingStopLossOnFill)
) &&
(
this.TradeClientExtensions == other.TradeClientExtensions ||
this.TradeClientExtensions != null &&
this.TradeClientExtensions.Equals(other.TradeClientExtensions)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Type != null)
hash = hash * 59 + this.Type.GetHashCode();
if (this.Instrument != null)
hash = hash * 59 + this.Instrument.GetHashCode();
if (this.Units != null)
hash = hash * 59 + this.Units.GetHashCode();
if (this.Price != null)
hash = hash * 59 + this.Price.GetHashCode();
if (this.PriceBound != null)
hash = hash * 59 + this.PriceBound.GetHashCode();
if (this.TimeInForce != null)
hash = hash * 59 + this.TimeInForce.GetHashCode();
if (this.GtdTime != null)
hash = hash * 59 + this.GtdTime.GetHashCode();
if (this.PositionFill != null)
hash = hash * 59 + this.PositionFill.GetHashCode();
if (this.TriggerCondition != null)
hash = hash * 59 + this.TriggerCondition.GetHashCode();
if (this.ClientExtensions != null)
hash = hash * 59 + this.ClientExtensions.GetHashCode();
if (this.TakeProfitOnFill != null)
hash = hash * 59 + this.TakeProfitOnFill.GetHashCode();
if (this.StopLossOnFill != null)
hash = hash * 59 + this.StopLossOnFill.GetHashCode();
if (this.TrailingStopLossOnFill != null)
hash = hash * 59 + this.TrailingStopLossOnFill.GetHashCode();
if (this.TradeClientExtensions != null)
hash = hash * 59 + this.TradeClientExtensions.GetHashCode();
return hash;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.Globalization;
using Common.Logging;
using ToolKit.DirectoryServices.ServiceInterfaces;
namespace ToolKit.DirectoryServices.ActiveDirectory
{
/// <summary>
/// This class represents an ActiveDirectory User.
/// </summary>
public class User : DirectoryObject, IUser
{
private static ILog _log = LogManager.GetLogger<User>();
/// <summary>
/// Initializes a new instance of the <see cref="User"/> class.
/// </summary>
/// <param name="distinguishedName">string representation of the distinguished name.</param>
public User(string distinguishedName)
: base(distinguishedName)
{
CheckType();
}
/// <summary>
/// Initializes a new instance of the <see cref="User"/> class.
/// </summary>
/// <param name="distinguishedName">DistinguishedName object of the distinguished name.</param>
public User(DistinguishedName distinguishedName)
: base(distinguishedName)
{
CheckType();
}
/// <summary>
/// Initializes a new instance of the <see cref="User"/> class.
/// </summary>
/// <param name="result">A SearchResult Object.</param>
public User(SearchResult result)
: base(result)
{
CheckType();
}
/// <summary>
/// Initializes a new instance of the <see cref="User"/> class.
/// </summary>
/// <param name="entry">A DirectoryEntry Object.</param>
public User(DirectoryEntry entry)
: base(entry)
{
CheckType();
}
/// <summary>
/// Initializes a new instance of the <see cref="User"/> class.
/// </summary>
/// <param name="domain">The domain of the user.</param>
/// <param name="userName">SAM Account Name of the user.</param>
public User(string domain, string userName)
{
var context = new DirectoryContext(DirectoryContextType.Domain, domain);
var domainObject = Domain.GetDomain(context);
using (var search = new DirectorySearcher())
{
search.SearchRoot = domainObject.GetDirectoryEntry();
search.Filter = "(samAccountName=" + userName + ")";
var result = search.FindOne();
if (result == null)
{
throw new ArgumentException("User does not exist in this domain!");
}
Initialize(DirectoryServices.DistinguishedName.Parse(result.Path));
}
}
/// <summary>
/// Initializes a new instance of the <see cref="User"/> class.
/// </summary>
/// <param name="properties">A Dictionary of properties.</param>
/// <remarks>This constructor is primarily used for unit tests.</remarks>
internal User(Dictionary<string, object> properties)
: base(properties)
{
CheckType();
}
/// <summary>
/// Initializes a new instance of the <see cref="User"/> class.
/// </summary>
protected User()
{
}
/// <summary>
/// Gets the date and time that this user account expires.
/// </summary>
/// <value>The date and time that this user account expires.</value>
public DateTime AccountExpires
{
get
{
try
{
var expiration = GetNodeValue("//DirectoryObject/accountexpires");
return string.IsNullOrEmpty(expiration)
? DateTime.MaxValue
: DateTime.FromFileTimeUtc(Convert.ToInt64(expiration, CultureInfo.InvariantCulture));
}
catch (ArgumentOutOfRangeException)
{
// Means that the account never expires.
return DateTime.MaxValue;
}
}
}
/// <summary>
/// Gets the bad password count of the user.
/// </summary>
/// <value>The bad password count of the user.</value>
public int BadPasswordCount
{
get
{
return Convert.ToInt32(GetNodeValue("//DirectoryObject/badpwdcount"), CultureInfo.CurrentCulture);
}
}
/// <summary>
/// Gets the bad password time of the user.
/// </summary>
/// <value>The bad password time.</value>
public DateTime BadPasswordTime
{
get
{
var nodeValue = GetNodeValue("//DirectoryObject/badpasswordtime");
return DateTime.FromFileTimeUtc(Convert.ToInt64(nodeValue, CultureInfo.InvariantCulture));
}
}
/// <summary>
/// Gets the category of the user.
/// </summary>
/// <value>The category of the user.</value>
public string Category
{
get
{
return GetNodeValue("//DirectoryObject/objectcategory");
}
}
/// <summary>
/// Gets the date and time that user account was last changed.
/// </summary>
/// <value>The date and time that the user account was last changed.</value>
public DateTime Changed
{
get
{
return Modified;
}
}
/// <summary>
/// Gets the city that the user account is in.
/// </summary>
/// <value>The city that the user account is in.</value>
public string City
{
get
{
return GetNodeValue("//DirectoryObject/l");
}
}
/// <summary>
/// Gets the common name of the computer.
/// </summary>
/// <value>The common name of the computer.</value>
public string CommonName
{
get
{
return GetNodeValue("//DirectoryObject/cn");
}
}
/// <summary>
/// Gets the company that the user account belongs to.
/// </summary>
/// <value>The company that the user account belongs to.</value>
public string Company
{
get
{
return GetNodeValue("//DirectoryObject/company");
}
}
/// <summary>
/// Gets the country that the user account is in.
/// </summary>
/// <value>The country that the user account is in.</value>
public string Country
{
get
{
return GetNodeValue("//DirectoryObject/c");
}
}
/// <summary>
/// Gets the country code for the user account.
/// </summary>
/// <value>The country code for the user account.</value>
public int CountryCode
{
get
{
return Convert.ToInt32(GetNodeValue("//DirectoryObject/countrycode"), CultureInfo.CurrentCulture);
}
}
/// <summary>
/// Gets when the account was created.
/// </summary>
/// <value>When the account was created.</value>
public DateTime Created
{
get
{
return DateTime.Parse(
GetNodeValue("//DirectoryObject/whencreated"),
null,
DateTimeStyles.AdjustToUniversal);
}
}
/// <summary>
/// Gets the department of the user account.
/// </summary>
/// <value>The department of the user account.</value>
public string Department
{
get
{
return GetNodeValue("//DirectoryObject/department");
}
}
/// <summary>
/// Gets the description of the user account.
/// </summary>
/// <value>The description of the user account.</value>
public string Description
{
get
{
return GetNodeValue("//DirectoryObject/description");
}
}
/// <summary>
/// Gets a value indicating whether this <see cref="User"/> is disabled.
/// </summary>
/// <value><c>true</c> if disabled; otherwise, <c>false</c>.</value>
public bool Disabled
{
get
{
return Convert.ToBoolean(UserAccountControl
& (int)ADS_USER_FLAG.ACCOUNTDISABLE);
}
}
/// <summary>
/// Gets the display name of the user account.
/// </summary>
/// <value>The display name of the user account.</value>
public string DisplayName
{
get
{
return GetNodeValue("//DirectoryObject/displayname");
}
}
/// <summary>
/// Gets the distinguished name of the user account.
/// </summary>
/// <value>The distinguished name of the user account.</value>
public string DistinguishedName
{
get
{
return GetNodeValue("//DirectoryObject/distinguishedname");
}
}
/// <summary>
/// Gets the email address of the user account.
/// </summary>
/// <value>The email address of the user account.</value>
public string EmailAddress
{
get
{
return GetNodeValue("//DirectoryObject/mail");
}
}
/// <summary>
/// Gets the fax number for the user account.
/// </summary>
/// <value>The fax number for the user account.</value>
public string Fax
{
get
{
return GetNodeValue("//DirectoryObject/facsimiletelephonenumber");
}
}
/// <summary>
/// Gets the first name of the user account.
/// </summary>
/// <value>The first name of the user account.</value>
public string FirstName
{
get
{
return GetNodeValue("//DirectoryObject/givenname");
}
}
/// <summary>
/// Gets the distinguished name list of groups.
/// </summary>
/// <value>The distinguished name list of groups.</value>
public List<string> Groups
{
get
{
return GetNodeListValues("//DirectoryObject/memberof");
}
}
/// <summary>
/// Gets the GUID of the user object.
/// </summary>
/// <value>The GUID of the user object.</value>
[SuppressMessage(
"Naming",
"CA1720:Identifier contains type name",
Justification = "Too Bad. It is what it is.")]
public Guid Guid
{
get
{
return new Guid(HexEncoding.ToBytes(GetNodeValue("//DirectoryObject/objectguid")));
}
}
/// <summary>
/// Gets the home directory of the user account.
/// </summary>
/// <value>The home directory of the user account.</value>
public string HomeDirectory
{
get
{
return GetNodeValue("//DirectoryObject/homedirectory");
}
}
/// <summary>
/// Gets the home drive of the user account.
/// </summary>
/// <value>The home drive of the user account.</value>
public string HomeDrive
{
get
{
return GetNodeValue("//DirectoryObject/homedrive");
}
}
/// <summary>
/// Gets the home phone of the user account.
/// </summary>
/// <value>The home phone of the user account.</value>
public string HomePhone
{
get
{
return GetNodeValue("//DirectoryObject/homephone");
}
}
/// <summary>
/// Gets the IP phone of the user account.
/// </summary>
/// <value>The IP phone of the user account.</value>
public string IpPhone
{
get
{
return GetNodeValue("//DirectoryObject/ipphone");
}
}
/// <summary>
/// Gets the last logoff date and time of the user account.
/// </summary>
/// <value>The last logoff date and time of the user account.</value>
public DateTime LastLogoff
{
get
{
var nodeValue = GetNodeValue("//DirectoryObject/lastlogoff");
return DateTime.FromFileTimeUtc(Convert.ToInt64(nodeValue, CultureInfo.InvariantCulture));
}
}
/// <summary>
/// Gets the last logon date and time of the user account.
/// </summary>
/// <value>The last logon date and time of the user account.</value>
public DateTime LastLogon
{
get
{
var nodeValue = GetNodeValue("//DirectoryObject/lastlogon");
return DateTime.FromFileTimeUtc(Convert.ToInt64(nodeValue, CultureInfo.InvariantCulture));
}
}
/// <summary>
/// Gets the last logon timestamp of the user account.
/// </summary>
/// <value>The last logon timestamp of the user account.</value>
public DateTime LastLogonTimestamp
{
get
{
var nodeValue = GetNodeValue("//DirectoryObject/lastlogontimestamp");
return DateTime.FromFileTimeUtc(Convert.ToInt64(nodeValue, CultureInfo.InvariantCulture));
}
}
/// <summary>
/// Gets the last name of the user account.
/// </summary>
/// <value>The last name of the user account.</value>
public string LastName
{
get
{
return GetNodeValue("//DirectoryObject/sn");
}
}
/// <summary>
/// Gets the logon count of the user account.
/// </summary>
/// <value>The logon count of the user account.</value>
public int LogonCount
{
get
{
return Convert.ToInt32(GetNodeValue("//DirectoryObject/logoncount"), CultureInfo.CurrentCulture);
}
}
/// <summary>
/// Gets the logon script of the user account.
/// </summary>
/// <value>The logon script of the user account.</value>
public string LogonScript
{
get
{
return GetNodeValue("//DirectoryObject/scriptpath");
}
}
/// <summary>
/// Gets the manager's DistinguishedName for the user account.
/// </summary>
/// <value>The manager's DistinguishedName for the user account.</value>
public string Manager
{
get
{
return GetNodeValue("//DirectoryObject/manager");
}
}
/// <summary>
/// Gets the middle initial of the user account.
/// </summary>
/// <value>The middle initial of the user account.</value>
public string MiddleInitial
{
get
{
return GetNodeValue("//DirectoryObject/initials");
}
}
/// <summary>
/// Gets the mobile phone number of the user account.
/// </summary>
/// <value>The mobile phone number of the user account.</value>
public string MobilePhone
{
get
{
return GetNodeValue("//DirectoryObject/mobile");
}
}
/// <summary>
/// Gets the modified date and time for the user account.
/// </summary>
/// <value>The modified date and time for the user account.</value>
public DateTime Modified
{
get
{
return DateTime.Parse(
GetNodeValue("//DirectoryObject/whenchanged"),
null,
DateTimeStyles.AdjustToUniversal);
}
}
/// <summary>
/// Gets the name of the user account.
/// </summary>
/// <value>The name of the user account.</value>
public string Name
{
get
{
return GetNodeValue("//DirectoryObject/name");
}
}
/// <summary>
/// Gets the notes of the user account.
/// </summary>
/// <value>The notes of the user account.</value>
public string Notes
{
get
{
return GetNodeValue("//DirectoryObject/info");
}
}
/// <summary>
/// Gets the office of the user account.
/// </summary>
/// <value>The office of the user account.</value>
public string Office
{
get
{
return GetNodeValue("//DirectoryObject/physicaldeliveryofficename");
}
}
/// <summary>
/// Gets the pager number of the user account.
/// </summary>
/// <value>The pager number of the user account.</value>
public string Pager
{
get
{
return GetNodeValue("//DirectoryObject/pager");
}
}
/// <summary>
/// Gets the password last set date and time of the user account.
/// </summary>
/// <value>The password last set date and time of the user account.</value>
public DateTime PasswordLastSet
{
get
{
var nodeValue = GetNodeValue("//DirectoryObject/pwdlastset");
return DateTime.FromFileTimeUtc(Convert.ToInt64(nodeValue, CultureInfo.InvariantCulture));
}
}
/// <summary>
/// Gets the PO box of the user account.
/// </summary>
/// <value>The PO box of the user account.</value>
public string PoBox
{
get
{
return GetNodeValue("//DirectoryObject/postofficebox");
}
}
/// <summary>
/// Gets the postal code of the user account.
/// </summary>
/// <value>The postal code of the user account.</value>
public string PostalCode
{
get
{
return GetNodeValue("//DirectoryObject/postalcode");
}
}
/// <summary>
/// Gets the primary group id of the user account.
/// </summary>
/// <value>The primary group id of the user account.</value>
public int PrimaryGroupId
{
get
{
return Convert.ToInt32(GetNodeValue("//DirectoryObject/primarygroupid"), CultureInfo.CurrentCulture);
}
}
/// <summary>
/// Gets the profile path of the user account.
/// </summary>
/// <value>The profile path of the user account.</value>
public string ProfilePath
{
get
{
return GetNodeValue("//DirectoryObject/profilepath");
}
}
/// <summary>
/// Gets the province of the user account.
/// </summary>
/// <value>The province of the user account.</value>
public string Province
{
get
{
return State;
}
}
/// <summary>
/// Gets the region of the user account.
/// </summary>
/// <value>The region of the user account.</value>
public string Region
{
get
{
return Country;
}
}
/// <summary>
/// Gets the SAM Account name of the user account.
/// </summary>
/// <value>The SAM Account name of the user account.</value>
public string SamAccountName
{
get
{
return GetNodeValue("//DirectoryObject/samaccountname");
}
}
/// <summary>
/// Gets the Security ID of the user account.
/// </summary>
/// <value>The Security ID of the user account.</value>
public string Sid
{
get
{
var nodeValue = GetNodeValue("//DirectoryObject/objectsid");
return Security.Sid.ToString(HexEncoding.ToBytes(nodeValue));
}
}
/// <summary>
/// Gets the state of the user account.
/// </summary>
/// <value>The state of the user account.</value>
public string State
{
get
{
return GetNodeValue("//DirectoryObject/st");
}
}
/// <summary>
/// Gets the street address of the user account.
/// </summary>
/// <value>The street address of the user account.</value>
public string StreetAddress
{
get
{
return GetNodeValue("//DirectoryObject/streetaddress");
}
}
/// <summary>
/// Gets the telephone number of the user account.
/// </summary>
/// <value>The telephone number of the user account.</value>
public string TelephoneNumber
{
get
{
return GetNodeValue("//DirectoryObject/telephonenumber");
}
}
/// <summary>
/// Gets the title of the user account.
/// </summary>
/// <value>The title of the user account.</value>
public string Title
{
get
{
return GetNodeValue("//DirectoryObject/title");
}
}
/// <summary>
/// Gets the update sequence number (USN) of the user account when it was created.
/// </summary>
/// <value>The update sequence number (USN) of the user account when it was created.</value>
public long UpdateSequenceNumberCreated
{
get
{
return Convert.ToInt64(GetNodeValue("//DirectoryObject/usncreated"), CultureInfo.CurrentCulture);
}
}
/// <summary>
/// Gets the current update sequence number (USN) of the user account.
/// </summary>
/// <value>The current update sequence number (USN) of the user account.</value>
public long UpdateSequenceNumberCurrent
{
get
{
return Convert.ToInt64(GetNodeValue("//DirectoryObject/usnchanged"), CultureInfo.CurrentCulture);
}
}
/// <summary>
/// Gets the user account control value of the user account.
/// </summary>
/// <value>The user account control value of the user account.</value>
public int UserAccountControl
{
get
{
return Convert.ToInt32(GetNodeValue("//DirectoryObject/useraccountcontrol"), CultureInfo.CurrentCulture);
}
}
/// <summary>
/// Gets the user principal name of the user account.
/// </summary>
/// <value>The user principal name of the user account.</value>
public string UserPrincipalName
{
get
{
return GetNodeValue("//DirectoryObject/userprincipalname");
}
}
/// <summary>
/// Gets the web site of the user account.
/// </summary>
/// <value>The web site of the user account.</value>
public string WebSite
{
get
{
return GetNodeValue("//DirectoryObject/wwwhomepage");
}
}
/// <summary>
/// Gets the zip code of the user account.
/// </summary>
/// <value>The zip code of the user account.</value>
public string Zip
{
get
{
return PostalCode;
}
}
/// <summary>
/// Disables this account in Active Directory.
/// </summary>
public void Disable()
{
using (var de = ToDirectoryEntry())
{
try
{
var uac = (int)de.Properties["userAccountControl"].Value;
de.Properties["userAccountControl"].Value = uac | (int)ADS_USER_FLAG.ACCOUNTDISABLE;
de.CommitChanges();
}
catch (DirectoryServicesCOMException ex)
{
_log.Error($"Unable to Disable Account! {DistinguishedName}", ex);
throw;
}
catch (UnauthorizedAccessException uaex)
{
_log.Error($"Access Denied trying to disable {DistinguishedName}", uaex);
throw;
}
}
}
/// <summary>
/// Determines whether this user is an administrative account.
/// </summary>
/// <returns><c>true</c> if this user is an administrative account; otherwise, <c>false</c>.</returns>
public bool IsAdministrativeAccount()
{
return SamAccountName.EndsWith("-ADM", StringComparison.InvariantCultureIgnoreCase)
|| DistinguishedName.Contains(",OU=Administrative Accounts,");
}
/// <summary>
/// Determines whether this user is an application account.
/// </summary>
/// <returns><c>true</c> if this user is an application account; otherwise, <c>false</c>.</returns>
public bool IsApplicationAccount()
{
return SamAccountName.EndsWith("-APP", StringComparison.InvariantCultureIgnoreCase)
|| DistinguishedName.Contains(",OU=Application Accounts,");
}
/// <summary>
/// Determines whether this user is an regular account.
/// </summary>
/// <returns><c>true</c> if this user is an regular account; otherwise, <c>false</c>.</returns>
public bool IsRegularAccount()
{
return !(IsAdministrativeAccount() || IsApplicationAccount() || IsServiceAccount());
}
/// <summary>
/// Determines whether this user is an service account.
/// </summary>
/// <returns><c>true</c> if this user is an service account; otherwise, <c>false</c>.</returns>
public bool IsServiceAccount()
{
return SamAccountName.EndsWith("-SVC", StringComparison.InvariantCultureIgnoreCase)
|| DistinguishedName.Contains(",OU=Service Accounts,");
}
private void CheckType()
{
// Check to see if this is indeed a User object Computer objects also have "user" in
// it's objectClass attribute...
if ((!GetObjectClass().Contains("user")) || GetObjectClass().Contains("computer"))
{
throw new ArgumentException("The directory object does not represent a user!");
}
}
}
}
| |
// 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.Reflection.Internal;
using System.Reflection.Metadata.Ecma335;
namespace System.Reflection.Metadata
{
public struct SequencePointCollection : IEnumerable<SequencePoint>
{
private readonly MemoryBlock _block;
private readonly DocumentHandle _document;
internal SequencePointCollection(MemoryBlock block, DocumentHandle document)
{
_block = block;
_document = document;
}
public Enumerator GetEnumerator()
{
return new Enumerator(_block, _document);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator<SequencePoint> IEnumerable<SequencePoint>.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<SequencePoint>
{
private BlobReader _reader;
private SequencePoint _current;
private int _previousNonHiddenStartLine;
private ushort _previousNonHiddenStartColumn;
internal Enumerator(MemoryBlock block, DocumentHandle document)
{
_reader = new BlobReader(block);
_current = new SequencePoint(document, -1);
_previousNonHiddenStartLine = -1;
_previousNonHiddenStartColumn = 0;
}
public bool MoveNext()
{
if (_reader.RemainingBytes == 0)
{
return false;
}
DocumentHandle document = _current.Document;
int offset, deltaLines, deltaColumns, startLine;
ushort startColumn;
if (_reader.Offset == 0)
{
// header (skip local signature rid):
_reader.ReadCompressedInteger();
if (document.IsNil)
{
document = ReadDocumentHandle();
}
// IL offset:
offset = _reader.ReadCompressedInteger();
}
else
{
// skip all document records and update the current document accordingly:
int deltaOffset;
while ((deltaOffset = _reader.ReadCompressedInteger()) == 0)
{
document = ReadDocumentHandle();
}
// IL offset:
offset = AddOffsets(_current.Offset, deltaOffset);
}
ReadDeltaLinesAndColumns(out deltaLines, out deltaColumns);
// hidden
if (deltaLines == 0 && deltaColumns == 0)
{
_current = new SequencePoint(document, offset);
return true;
}
// delta Start Line & Column:
if (_previousNonHiddenStartLine < 0)
{
Debug.Assert(_previousNonHiddenStartColumn == 0);
startLine = ReadLine();
startColumn = ReadColumn();
}
else
{
startLine = AddLines(_previousNonHiddenStartLine, _reader.ReadCompressedSignedInteger());
startColumn = AddColumns(_previousNonHiddenStartColumn, _reader.ReadCompressedSignedInteger());
}
_previousNonHiddenStartLine = startLine;
_previousNonHiddenStartColumn = startColumn;
_current = new SequencePoint(
document,
offset,
startLine,
startColumn,
AddLines(startLine, deltaLines),
AddColumns(startColumn, deltaColumns));
return true;
}
private void ReadDeltaLinesAndColumns(out int deltaLines, out int deltaColumns)
{
deltaLines = _reader.ReadCompressedInteger();
deltaColumns = (deltaLines == 0) ? _reader.ReadCompressedInteger() : _reader.ReadCompressedSignedInteger();
}
private int ReadLine()
{
return _reader.ReadCompressedInteger();
}
private ushort ReadColumn()
{
int column = _reader.ReadCompressedInteger();
if (column > ushort.MaxValue)
{
Throw.SequencePointValueOutOfRange();
}
return (ushort)column;
}
private int AddOffsets(int value, int delta)
{
int result = unchecked(value + delta);
if (result < 0)
{
Throw.SequencePointValueOutOfRange();
}
return result;
}
private int AddLines(int value, int delta)
{
int result = unchecked(value + delta);
if (result < 0 || result >= SequencePoint.HiddenLine)
{
Throw.SequencePointValueOutOfRange();
}
return result;
}
private ushort AddColumns(ushort value, int delta)
{
int result = unchecked(value + delta);
if (result < 0 || result >= ushort.MaxValue)
{
Throw.SequencePointValueOutOfRange();
}
return (ushort)result;
}
private DocumentHandle ReadDocumentHandle()
{
int rowId = _reader.ReadCompressedInteger();
if (rowId == 0 || !TokenTypeIds.IsValidRowId(rowId))
{
Throw.InvalidHandle();
}
return DocumentHandle.FromRowId(rowId);
}
public SequencePoint Current
{
get { return _current; }
}
object IEnumerator.Current
{
get { return _current; }
}
public void Reset()
{
_reader.Reset();
_current = default(SequencePoint);
}
void IDisposable.Dispose()
{
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.WinHttpHandlerUnitTests
{
public class WinHttpResponseStreamTest
{
public WinHttpResponseStreamTest()
{
TestControl.ResetAll();
}
[Fact]
public void CanRead_WhenCreated_ReturnsTrue()
{
Stream stream = MakeResponseStream();
bool result = stream.CanRead;
Assert.True(result);
}
[Fact]
public void CanRead_WhenDisposed_ReturnsFalse()
{
Stream stream = MakeResponseStream();
stream.Dispose();
bool result = stream.CanRead;
Assert.False(result);
}
[Fact]
public void CanSeek_Always_ReturnsFalse()
{
Stream stream = MakeResponseStream();
bool result = stream.CanSeek;
Assert.False(result);
}
[Fact]
public void CanWrite_Always_ReturnsFalse()
{
Stream stream = MakeResponseStream();
bool result = stream.CanWrite;
Assert.False(result);
}
[Fact]
public void Length_WhenCreated_ThrowsNotSupportedException()
{
Stream stream = MakeResponseStream();
Assert.Throws<NotSupportedException>(() => stream.Length);
}
[Fact]
public void Length_WhenDisposed_ThrowsObjectDisposedException()
{
Stream stream = MakeResponseStream();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => stream.Length);
}
[Fact]
public void Position_WhenCreatedDoGet_ThrowsNotSupportedException()
{
Stream stream = MakeResponseStream();
Assert.Throws<NotSupportedException>(() => stream.Position);
}
[Fact]
public void Position_WhenDisposedDoGet_ThrowsObjectDisposedException()
{
Stream stream = MakeResponseStream();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => stream.Position);
}
[Fact]
public void Position_WhenCreatedDoSet_ThrowsNotSupportedException()
{
Stream stream = MakeResponseStream();
Assert.Throws<NotSupportedException>(() => stream.Position = 0);
}
[Fact]
public void Position_WhenDisposedDoSet_ThrowsObjectDisposedExceptionException()
{
Stream stream = MakeResponseStream();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => stream.Position = 0);
}
[Fact]
public void Seek_WhenCreated_ThrowsNotSupportedException()
{
Stream stream = MakeResponseStream();
Assert.Throws<NotSupportedException>(() => stream.Seek(0, SeekOrigin.Begin));
}
[Fact]
public void Seek_WhenDisposed_ThrowsObjectDisposedException()
{
Stream stream = MakeResponseStream();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => stream.Seek(0, SeekOrigin.Begin));
}
[Fact]
public void SetLength_WhenCreated_ThrowsNotSupportedException()
{
Stream stream = MakeResponseStream();
Assert.Throws<NotSupportedException>(() => stream.SetLength(0));
}
[Fact]
public void SetLength_WhenDisposed_ThrowsObjectDisposedException()
{
Stream stream = MakeResponseStream();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => stream.SetLength(0));
}
[Fact]
public void Write_WhenCreated_ThrowsNotSupportedException()
{
Stream stream = MakeResponseStream();
Assert.Throws<NotSupportedException>(() => stream.Write(new byte[1], 0, 1));
}
[Fact]
public void Write_WhenDisposed_ThrowsObjectDisposedException()
{
Stream stream = MakeResponseStream();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => stream.Write(new byte[1], 0, 1));
}
[Fact]
public void Read_BufferIsNull_ThrowsArgumentNullException()
{
Stream stream = MakeResponseStream();
Assert.Throws<ArgumentNullException>(() => stream.Read(null, 0, 1));
}
[Fact]
public void Read_OffsetIsNegative_ThrowsArgumentOutOfRangeException()
{
Stream stream = MakeResponseStream();
Assert.Throws<ArgumentOutOfRangeException>(() => stream.Read(new byte[1], -1, 1));
}
[Fact]
public void Read_CountIsNegative_ThrowsArgumentOutOfRangeException()
{
Stream stream = MakeResponseStream();
Assert.Throws<ArgumentOutOfRangeException>(() => stream.Read(new byte[1], 0, -1));
}
[Fact]
public void Read_OffsetPlusCountExceedsBufferLength_ThrowsArgumentException()
{
Stream stream = MakeResponseStream();
Assert.Throws<ArgumentException>(() => stream.Read(new byte[1], int.MaxValue, int.MaxValue));
}
[Fact]
public void Read_WhenDisposed_ThrowsObjectDisposedException()
{
Stream stream = MakeResponseStream();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => stream.Read(new byte[1], 0, 1));
}
[Fact]
public void ReadAsync_OffsetIsNegative_ThrowsArgumentOutOfRangeException()
{
Stream stream = MakeResponseStream();
Assert.Throws<ArgumentOutOfRangeException>(() => { Task t = stream.ReadAsync(new byte[1], -1, 1); });
}
[Fact]
public void ReadAsync_QueryDataAvailableFailsWithApiCall_TaskIsFaultedWithIOException()
{
Stream stream = MakeResponseStream();
TestControl.WinHttpQueryDataAvailable.ErrorWithApiCall = true;
Task t = stream.ReadAsync(new byte[1], 0, 1);
AggregateException ex = Assert.Throws<AggregateException>(() => t.Wait());
Assert.IsType<IOException>(ex.InnerException);
}
[Fact]
public void ReadAsync_QueryDataAvailableFailsOnCompletionCallback_TaskIsFaultedWithIOException()
{
Stream stream = MakeResponseStream();
TestControl.WinHttpQueryDataAvailable.ErrorOnCompletion = true;
Task t = stream.ReadAsync(new byte[1], 0, 1);
AggregateException ex = Assert.Throws<AggregateException>(() => t.Wait());
Assert.IsType<IOException>(ex.InnerException);
}
[Fact]
public void ReadAsync_ReadDataFailsWithApiCall_TaskIsFaultedWithIOException()
{
Stream stream = MakeResponseStream();
TestControl.WinHttpReadData.ErrorWithApiCall = true;
Task t = stream.ReadAsync(new byte[1], 0, 1);
AggregateException ex = Assert.Throws<AggregateException>(() => t.Wait());
Assert.IsType<IOException>(ex.InnerException);
}
[Fact]
public void ReadAsync_ReadDataFailsOnCompletionCallback_TaskIsFaultedWithIOException()
{
Stream stream = MakeResponseStream();
TestControl.WinHttpReadData.ErrorOnCompletion = true;
Task t = stream.ReadAsync(new byte[1], 0, 1);
AggregateException ex = Assert.Throws<AggregateException>(() => t.Wait());
Assert.IsType<IOException>(ex.InnerException);
}
[Fact]
public void ReadAsync_TokenIsAlreadyCanceled_TaskIsCanceled()
{
Stream stream = MakeResponseStream();
var cts = new CancellationTokenSource();
cts.Cancel();
Task t = stream.ReadAsync(new byte[1], 0, 1, cts.Token);
Assert.True(t.IsCanceled);
}
[Fact]
public void ReadAsync_WhenDisposed_ThrowsObjectDisposedException()
{
Stream stream = MakeResponseStream();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => { Task t = stream.ReadAsync(new byte[1], 0, 1); });
}
[Fact]
public void ReadAsync_PriorReadInProgress_ThrowsInvalidOperationException()
{
Stream stream = MakeResponseStream();
TestControl.WinHttpReadData.Pause();
Task t1 = stream.ReadAsync(new byte[1], 0, 1);
Assert.Throws<InvalidOperationException>(() => { Task t2 = stream.ReadAsync(new byte[1], 0, 1); });
TestControl.WinHttpReadData.Resume();
t1.Wait();
}
[Fact]
public void Read_QueryDataAvailableFailsWithApiCall_ThrowsIOException()
{
Stream stream = MakeResponseStream();
TestControl.WinHttpQueryDataAvailable.ErrorWithApiCall = true;
Assert.Throws<IOException>(() => { stream.Read(new byte[1], 0, 1); });
}
[Fact]
public void Read_QueryDataAvailableFailsOnCompletionCallback_ThrowsIOException()
{
Stream stream = MakeResponseStream();
TestControl.WinHttpQueryDataAvailable.ErrorOnCompletion = true;
Assert.Throws<IOException>(() => { stream.Read(new byte[1], 0, 1); });
}
[Fact]
public void Read_ReadDataFailsWithApiCall_ThrowsIOException()
{
Stream stream = MakeResponseStream();
TestControl.WinHttpReadData.ErrorWithApiCall = true;
Assert.Throws<IOException>(() => { stream.Read(new byte[1], 0, 1); });
}
[Fact]
public void Read_ReadDataFailsOnCompletionCallback_ThrowsIOException()
{
Stream stream = MakeResponseStream();
TestControl.WinHttpReadData.ErrorOnCompletion = true;
Assert.Throws<IOException>(() => { stream.Read(new byte[1], 0, 1); });
}
[Fact]
public void Read_NoOffsetAndNotEndOfData_FillsBuffer()
{
Stream stream = MakeResponseStream();
byte[] testData = Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
TestServer.ResponseBody = testData;
byte[] buffer = new byte[testData.Length];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
Assert.Equal(buffer.Length, bytesRead);
for (int i = 0; i < buffer.Length; i++)
{
Assert.Equal(testData[i], buffer[i]);
}
}
[Fact]
public void Read_UsingOffsetAndNotEndOfData_FillsBufferFromOffset()
{
Stream stream = MakeResponseStream();
byte[] testData = Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
TestServer.ResponseBody = testData;
byte[] buffer = new byte[testData.Length];
int offset = 5;
int bytesRead = stream.Read(buffer, offset, buffer.Length - offset);
Assert.Equal(buffer.Length - offset, bytesRead);
for (int i = 0; i < offset; i++)
{
Assert.Equal(0, buffer[i]);
}
for (int i = offset; i < buffer.Length; i++)
{
Assert.Equal(testData[i - offset], buffer[i]);
}
}
internal Stream MakeResponseStream()
{
var state = new WinHttpRequestState();
var handle = new FakeSafeWinHttpHandle(true);
handle.Callback = WinHttpRequestCallback.StaticCallbackDelegate;
handle.Context = state.ToIntPtr();
state.RequestHandle = handle;
return new WinHttpResponseStream(state);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.